@scopetickets/checkout 0.1.0 → 0.1.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/README.md +18 -1
- package/dist/chunk-4BOPQURW.js +1989 -0
- package/dist/chunk-4BOPQURW.js.map +1 -0
- package/dist/index.cjs +13852 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.css.map +1 -0
- package/dist/index.d.cts +3813 -0
- package/dist/index.d.ts +3813 -0
- package/dist/index.js +12004 -0
- package/dist/index.js.map +1 -0
- package/dist/pickers.cjs +1908 -0
- package/dist/pickers.cjs.map +1 -0
- package/dist/pickers.css +1054 -0
- package/dist/pickers.css.map +1 -0
- package/dist/pickers.d.cts +911 -0
- package/dist/pickers.d.ts +911 -0
- package/dist/pickers.js +117 -0
- package/dist/pickers.js.map +1 -0
- package/dist/styles.css +2948 -0
- package/package.json +1 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/island/CarrySlot.tsx","../src/island/IslandCard.tsx","../src/island/IslandHeader.tsx","../src/island/IslandHost.tsx","../src/island/island-geometry.ts","../src/island/island-carry.ts","../src/island/island-transition.ts","../src/island/island-continuity.ts","../src/island/IslandShield.tsx","../src/island/IslandSurface.tsx","../src/island/island-theme.ts","../src/island/IslandPill.tsx","../src/island/CheckoutIsland.tsx","../src/island/ScopeTicketsCheckout.tsx","../src/island/status-glyphs.tsx","../src/domain/auth.ts","../src/domain/auth-copy.ts","../../api/src/types.ts","../../api/src/client.ts","../../api/src/payment-protocol/parent.ts","../../api/src/buyer.ts","../../api/src/email-typos.ts","../src/domain/contact.ts","../src/domain/order-intent.ts","../src/data/useBooking.ts","../src/domain/wire.ts","../src/domain/booking.ts","../src/domain/ticket-code.ts","../src/data/bookingGateway.ts","../src/domain/order-buyer.ts","../src/domain/purchase-steps.ts","../src/domain/order-status.ts","../src/domain/passcode.ts","../src/domain/account-creation.ts","../src/domain/compose-funnel.ts","../src/island/ComposeFunnel.tsx","../src/island/IslandCommitPill.tsx","../src/data/useFeedback.ts","../src/island/StarRating.tsx","../src/domain/feedback.ts","../src/domain/money.ts","../src/domain/auth-actions.ts","../src/domain/flow-walk.ts","../src/data/useCheckoutData.ts","../src/domain/artwork.ts","../src/data/useAccountGateway.ts","../src/domain/session.ts","../src/data/accountGateway.ts","../src/testing/simulate.tsx","../src/data/useSignInGateway.ts","../src/domain/sign-in.ts","../src/data/signInGateway.ts","../src/data/usePasskeySignIn.ts","../src/domain/passkey.ts","../src/data/useAuthFunnel.ts","../src/domain/auth-funnel.ts","../src/data/useSessionGuard.ts","../src/data/usePasskeyRegistration.ts","../src/data/useAccountCreation.ts","../src/data/useAuthSession.ts","../src/island/PasskeyButton.tsx","../src/island/island-passkey-theme.ts","../src/island/PasskeyFrame.tsx","../src/data/useCheckoutOrder.ts","../src/data/purchase-completion.ts","../src/domain/cart.ts","../src/domain/order-fill.ts","../src/domain/product.ts","../src/domain/promo.ts","../src/island/CartLines.tsx","../src/island/ProfilePhotoPicker.tsx","../src/island/FollowList.tsx","../src/island/TextField.tsx","../src/island/ContactSteps.tsx","../src/domain/password.ts","../src/island/PasscodeField.tsx","../src/island/step-cards.tsx","../src/island/brand-marks.tsx","../src/domain/profile-photo.ts","../src/domain/notices.ts","../src/island/CredentialFields.tsx","../src/island/RadioDot.tsx","../src/island/PaymentMethods.tsx","../src/island/island-escrow.ts","../src/island/CountdownTimer.tsx","../src/island/island-hero.tsx","../src/island/RestingIsland.tsx","../src/domain/preflight.ts","../src/domain/checkout-preflight.ts","../src/data/useTicketFacts.ts","../src/island/BookingIsland.tsx","../src/data/useTicketCodes.ts","../src/island/QuickActions.tsx","../src/island/TicketCodes.tsx","../src/island/TicketCode.tsx","../src/island/island-ticket-edge.ts","../src/island/TicketsInBooking.tsx","../src/island/booking-cards.tsx","../src/island/IslandPaymentFrame.tsx","../src/domain/detect-digital-wallet.ts","../src/domain/wallet-report.ts","../src/domain/revolut-journey.ts","../src/provider-return-signal.ts","../src/PaymentReturn.tsx"],"sourcesContent":["import { createContext, useContext, useLayoutEffect, useRef, type ReactNode } from 'react';\nimport type { SlotKey } from './island-geometry';\n\n/** WHEN the overlay takes an element over, rather than leaving it to the planes. */\nexport type CarryTrigger = 'always' | 'resized';\n\n/** WHERE A CARRIED ELEMENT LIVES — one of the two planes, or the chrome. */\nexport type CarryHome = SlotKey | 'chrome';\n\n/** The persistent bar outside both planes. */\nexport const CHROME: CarryHome = 'chrome';\n\n/**\n * What a plane's carried elements report to the host, and what the host tells them\n * back. Null outside an `IslandHost`, so a `CarrySlot` used on its own degrades to a\n * plain span rather than throwing.\n */\nexport type CarryRegistry = {\n register: (\n name: string,\n plane: CarryHome,\n element: HTMLElement | null,\n node: ReactNode,\n carryWhen: CarryTrigger,\n ) => void;\n /** Names the overlay is currently drawing. A plane must not draw these. */\n drawnByOverlay: ReadonlySet<string>;\n};\n\nexport const CarryContext = createContext<CarryRegistry | null>(null);\n\n/** Which plane — or the chrome — the surrounding content is rendered into. */\nexport const PlaneContext = createContext<CarryHome | null>(null);\n\nexport type CarrySlotProps = {\n /**\n * Stable identity of the thing being carried, shared by both steps. The total is\n * `\"total\"` in the compact step and `\"total\"` in the expanded one — that shared name is\n * the entire mechanism.\n */\n name: string;\n /**\n * When the overlay takes this element over — see `CarryTrigger`. Defaults to every\n * move, which is right for a subject and wrong for chrome.\n */\n carryWhen?: CarryTrigger;\n children: ReactNode;\n};\n\n/** Marks content that should survive a step change rather than fade through itself. */\nexport function CarrySlot({ name, carryWhen = 'always', children }: CarrySlotProps) {\n const registry = useContext(CarryContext);\n const plane = useContext(PlaneContext);\n const ref = useRef<HTMLSpanElement | null>(null);\n\n useLayoutEffect(() => {\n if (!registry || !plane) return;\n registry.register(name, plane, ref.current, children, carryWhen);\n });\n\n const hidden = registry?.drawnByOverlay.has(name) ?? false;\n\n return (\n <span\n ref={ref}\n data-scopetickets-island-carry={name}\n className=\"scopetickets-island-carry-slot\"\n style={hidden ? { visibility: 'hidden' } : undefined}\n >\n {children}\n </span>\n );\n}\n","import {\n useCallback,\n useContext,\n useEffect,\n useRef,\n useState,\n type CSSProperties,\n type KeyboardEvent as ReactKeyboardEvent,\n type ReactNode,\n} from 'react';\nimport { PressContext, useIslandPress } from './island-press';\nimport { PRESS_IN_MS } from './island-motion';\n\n/** What a card's button IS, rather than what it looks like. */\nexport type IslandActionRole = 'action' | 'primary' | 'secondary';\n\nexport type IslandAction = {\n /** Stable across renders. Labels repeat — two states both end in \"Close\". */\n readonly key: string;\n readonly role: IslandActionRole;\n readonly label: ReactNode;\n /** A mark beside the label — the provider's logo, the passkey glyph. */\n /** The button is drawn, and it does not act. */\n readonly disabled?: boolean;\n readonly mark?: {\n readonly side: 'leading' | 'trailing';\n readonly node: ReactNode;\n /** Default `separate`. See above. */\n readonly spacing?: 'joined' | 'separate';\n };\n readonly onPress: () => void;\n};\n\nexport type IslandCardProps = {\n /** WHICH CARD THIS IS — Figma's own variant on `CtaCard`. */\n /**\n * NEITHER OF THE TWO BESIDE THE FLOW DRAWS A HEADER — the way out of both is the Back\n * button in the stack. `cart` is that card with the cart screen's own title size;\n * `hold` is the timed-out card, which takes the ordinary one.\n */\n readonly variant?: 'default' | 'hold' | 'cart';\n /**\n * The hero — a `.scopetickets-island-avatar` element, and the same node the collapsed\n * pill shows, which is what lets it be carried between the two.\n *\n * THE HOLD'S CARDS TAKE ONE TOO, and that is the design `3803:7329`: the buyer's own\n * avatar wearing the clock as its ELEMENT, where they used to draw a bare `$25` ring.\n * The clock is the caller's to compose for the same reason every other hero is — the\n * face is the buyer's and this file draws none.\n */\n readonly avatar?: ReactNode;\n /** `heading/xl`, centred — `heading/3xl` on the `cart` variant. */\n readonly title?: ReactNode;\n /** `text/regular/md`, centred, and free to run to several lines. */\n readonly subtitle?: ReactNode;\n /**\n * NO HERO, which is what a picker is: the entry step has already said at full size what\n * the buyer is being asked for, so the card opens on the run itself. `avatar`, `title`\n * and `subtitle` are simply left undrawn — the card is the run, and the chrome is not\n * its to draw.\n */\n /**\n * NO HEADER IS BEING DRAWN OVER THIS CARD, so it pays no reserve for one — see\n * `CheckoutIslandProps.sealed`, which is where the decision is made.\n *\n * PER CARD AND NOT PER ISLAND, which is the whole reason it is a prop rather than a\n * rule hung off the frame's `data-sealed`. Both planes live in that frame while they\n * cross, so a rule there would pull the reserve out from under the card on its way OUT\n * as well — the header would fade while the step beneath it jumped upward to meet it.\n * Held here, the leaving card keeps the room it was laid out with and only the arriving\n * one is short, so the surface morphs between two heights instead of snapping.\n */\n readonly sealed?: boolean;\n /**\n * The step's own controls — `Input` in the design, between the hero and the buttons.\n */\n readonly input?: ReactNode;\n /** The buttons, in reading order. Stacked full-width at `$2` apart. */\n readonly actions: readonly IslandAction[];\n /**\n * A CONTROL OF ITS OWN SHAPE WHERE THE BUTTONS GO — the booking's ticket pager, which is\n * one label between two presses and therefore cannot be an `IslandAction`.\n *\n * IT IS NOT A THIRD KIND OF BUTTON. It stands in the same wrapper, which is what it is\n * for: that wrapper is positioned against the card's bottom edge and its height is what\n * the content reserves room for, so a control drawn anywhere else sits in the scroll and\n * takes the card's gutter twice. Counted with the actions below for exactly that reason.\n */\n readonly footer?: ReactNode;\n};\n\n/** The expanded island — Figma `CtaCard`. */\n/** ITS OWN COMPONENT FOR ONE REASON: its own press. */\n/** How many buttons the card carries, published so CSS can reserve their height. */\nfunction cardActionsStyle(count: number): CSSProperties {\n return { '--scopetickets-island-card-actions': count } as CSSProperties;\n}\n\n/**\n * EXPORTED FOR THE BAY: when the payment frame is visible the card's own buttons\n * ride with it (the form is the card's last content), and the bay draws the same\n * button the card would have — same press, same compression, same disabled read.\n */\nexport function CardAction({ action, tapped = false }: { action: IslandAction; tapped?: boolean }) {\n // `element`, not `island`.\n const press = useIslandPress('element');\n /*\n * A KEYBOARD TAP HAS NO POINTER BEHIND IT, so the hook's own sink never fills — it is\n * driven by `pointerdown`. `tapped` is the card saying this button was activated by\n * Enter, and it takes the SAME attribute, so the compression is the one the design drew\n * rather than a second one that looks like it.\n */\n const held = tapped || press['data-pressed'] !== undefined;\n\n // The glyph is decorative in every case the design draws: the label beside it already\n // says what the button does, and \"Sign in with Apple \" read twice is worse than once.\n const mark =\n action.mark === undefined ? null : (\n <span className=\"scopetickets-island-button__mark\" aria-hidden=\"true\">\n {action.mark.node}\n </span>\n );\n\n return (\n <button\n type=\"button\"\n className={`scopetickets-island-button scopetickets-island-button--${action.role} scopetickets-island-button--block${\n action.mark === undefined\n ? ''\n : ` scopetickets-island-button--marked-${action.mark.spacing ?? 'separate'}`\n }${action.disabled ? ' scopetickets-island-button--disabled' : ''}`}\n // Not the attribute — see `IslandAction.disabled`.\n aria-disabled={action.disabled === true ? true : undefined}\n onClick={action.disabled === true ? undefined : action.onPress}\n {...press}\n data-pressed={held ? '' : undefined}\n >\n {action.mark?.side === 'leading' ? mark : null}\n {action.label}\n {action.mark?.side === 'trailing' ? mark : null}\n </button>\n );\n}\n\n/**\n * ENTER COMMITS THE CARD — the primary button, and only ever that one.\n *\n * A buyer typing an email expects Enter to move them on, and every field here sat in a\n * card with no form around it, so it did nothing at all.\n *\n * ONLY THE PRIMARY. It is the one that means \"I have answered this\"; Order Review's\n * commitment is an `action` and its Pay button is deliberately out of reach of a stray\n * keypress. A card with no primary does nothing, which is the right nothing.\n *\n * AND ONLY IF IT WOULD TAKE A CLICK. `disabled` gates the press exactly as it gates the\n * pointer — a gated Continue draws itself and declines, and Enter has to decline the\n * same way or the keyboard would walk past a step the mouse could not.\n *\n * A BUTTON ALREADY HANDLES ITS OWN ENTER, so a keypress on one is left alone: hijacking\n * it would fire the primary while the buyer was on a secondary, which is the worst\n * possible reading of \"the keyboard works here\".\n */\nfunction useEnterCommits(actions: readonly IslandAction[]) {\n const api = useContext(PressContext);\n const [tapped, setTapped] = useState<string | null>(null);\n const timer = useRef<number | null>(null);\n\n useEffect(\n () => () => {\n if (timer.current !== null) window.clearTimeout(timer.current);\n },\n [],\n );\n\n const onEnter = useCallback(\n (event: ReactKeyboardEvent<HTMLDivElement>) => {\n if (event.key !== 'Enter' || event.shiftKey) return;\n if (event.target instanceof HTMLElement && event.target.closest('button, textarea')) return;\n\n const primary = actions.find((action) => action.role === 'primary');\n if (primary === undefined || primary.disabled === true) return;\n\n event.preventDefault();\n\n /*\n * THE ORDER IS THE POINTER'S. Press, then act — the compression is on screen BEFORE\n * whatever the button does, so if it starts a step change the morph uncoils from a\n * card that is already compressed, exactly as `IslandPressApi.release` describes.\n */\n setTapped(primary.key);\n api?.press('element');\n primary.onPress();\n api?.release();\n\n if (timer.current !== null) window.clearTimeout(timer.current);\n timer.current = window.setTimeout(() => setTapped(null), PRESS_IN_MS);\n },\n [actions, api],\n );\n\n return { tapped, onEnter };\n}\n\nexport function IslandCard({\n avatar,\n title,\n subtitle,\n variant = 'default',\n sealed = false,\n input,\n actions,\n footer,\n}: IslandCardProps) {\n const { tapped, onEnter } = useEnterCommits(actions);\n\n /* THE CARD RESERVES THE HEADER'S ROOM AND NO LONGER DRAWS IT. */\n return (\n <div\n className={[\n 'scopetickets-island-card',\n sealed ? 'scopetickets-island-card--sealed' : '',\n /*\n * NO HEADER, and that is the whole shape of both: neither is a step, so there is\n * nothing to step back from and nothing to close. The way back is a secondary\n * button in the stack, which the caller supplies like any other.\n */\n variant === 'default' ? '' : `scopetickets-island-card--${variant}`,\n ]\n .filter(Boolean)\n .join(' ')}\n style={cardActionsStyle(actions.length + (footer === undefined ? 0 : 1))}\n onKeyDown={onEnter}\n >\n {/*\n * ONE CHILD FOR ALL OF IT. The `$6` that used to be the card's own flex gap is the\n * content's END RESERVE now — see `card__content`.\n */}\n <div className=\"scopetickets-island-card__content\">\n {title === undefined && avatar === undefined ? null : (\n <div className=\"scopetickets-island-card__hero\">\n {avatar === undefined ? null : (\n <div className=\"scopetickets-island-card__avatar-slot\">{avatar}</div>\n )}\n <div className=\"scopetickets-island-card__text\">\n <span className=\"scopetickets-island-card__title\">{title}</span>\n {subtitle === undefined ? null : (\n <span className=\"scopetickets-island-card__subtitle\">{subtitle}</span>\n )}\n </div>\n </div>\n )}\n\n {/*\n * `null` AS WELL AS `undefined`, and the difference cost a step its spacing.\n * `stepInput` answers `null` for every card that IS the step — Review, Processing,\n * More Information — and only `undefined` was being caught, so those cards drew an\n * empty input div. It has no height of its own, but it is a flex ITEM in a `$4`\n * column, so it took a gap at each side: Order Review's subtitle sat `$10` off its\n * buttons where every other card sits at `$6`.\n */}\n {input === undefined || input === null ? null : (\n <div className=\"scopetickets-island-card__input\">{input}</div>\n )}\n </div>\n\n <div className=\"scopetickets-island-card__buttons\">\n {actions.map((action) => (\n <CardAction key={action.key} action={action} tapped={action.key === tapped} />\n ))}\n {footer}\n </div>\n </div>\n );\n}\n","import type { ReactNode } from 'react';\nimport { ArrowLeftIcon, XMarkIcon } from '@scopetickets/icons';\nimport { useIslandPress } from './island-press';\n\n/**\n * `IslandHeaderWrapper` — the way out at the leading edge, the cart summary at the\n * trailing one, and nothing between them.\n */\nexport type IslandHeaderProps = {\n /** What the header button DOES, which decides what it draws. */\n readonly dismiss?: 'back' | 'close';\n readonly onDismiss: () => void;\n /**\n * Overrides the glyph. Defaults to `@scopetickets/icons`, which is STui's own set\n * generated from the file rather than copied by hand. A slot, because a host with its\n * own icon set should not be made to take a second one.\n */\n readonly dismissIcon?: ReactNode;\n /** Names the control for assistive technology. Defaults to the `dismiss`. */\n readonly dismissLabel?: string;\n /**\n * A second pill BESIDE the way out — the leading group the design, `$2` off the cross.\n */\n readonly headerLead?: ReactNode;\n /**\n * A PILL AT THE TRAILING END, and ONE SLOT for whichever of them the step wants.\n *\n * There were two props here and a rule about which won — `summary` outranking\n * `headerTrail`, on the reading that a counting hold outranks a way back. The two could\n * never have collided: the funnel is the half of the purchase before a cart exists and\n * the commit pill is the half after. A precedence rule between two things that cannot\n * meet is a rule nobody can be sure of, so the caller picks and this draws what it is\n * handed.\n */\n readonly headerTrail?: ReactNode;\n /**\n * WHETHER THE WAY OUT IS OFFERED. Defaults to true.\n *\n * DRAWN AND HIDDEN RATHER THAN REMOVED, which is the design's own answer — the abandon\n * card sets the whole row to zero opacity rather than dropping it. The cross has to be\n * in the same place on every card, because carried elements are measured against a\n * header that rides every change in the card's height; taking the button out of the tree\n * would move the row and every element travelling through it.\n */\n readonly closable?: boolean;\n};\n\nexport function IslandHeader({\n dismiss = 'close',\n onDismiss,\n dismissIcon,\n dismissLabel,\n headerLead,\n headerTrail,\n closable = true,\n}: IslandHeaderProps) {\n /* `element`, and it used to be `island`. */\n const dismissPress = useIslandPress('element');\n\n return (\n <div className=\"scopetickets-island-header\">\n {/*\n * The leading group — the way out, and whatever stands beside it. Always present, so\n * the cross is in the same place with or without a second pill; see `headerLead`.\n */}\n <div className=\"scopetickets-island-header-lead\">\n <button\n type=\"button\"\n /* `visibility`, not `hidden` — the row keeps its height. See `closable`. */\n data-withheld={closable ? undefined : ''}\n aria-hidden={closable ? undefined : true}\n tabIndex={closable ? undefined : -1}\n className=\"scopetickets-island-chrome-pill scopetickets-island-header-button scopetickets-island-header__close\"\n onClick={onDismiss}\n aria-label={dismissLabel ?? (dismiss === 'back' ? 'Back' : 'Close')}\n {...dismissPress}\n >\n <span className=\"scopetickets-island-glyph-slot\" aria-hidden=\"true\">\n {/*\n * `fill` and `currentColor`, both: the glyph takes its size from the slot around it and\n * its colour from the button. Left untitled, so it renders `aria-hidden` — the button\n * carries the name.\n */}\n {dismissIcon ??\n (dismiss === 'back' ? (\n <ArrowLeftIcon fill color=\"currentColor\" />\n ) : (\n <XMarkIcon fill color=\"currentColor\" />\n ))}\n </span>\n </button>\n {headerLead}\n </div>\n {headerTrail}\n </div>\n );\n}\n","import {\n useCallback,\n useEffect,\n type CSSProperties,\n useLayoutEffect,\n useMemo,\n useReducer,\n useRef,\n useState,\n type ReactNode,\n} from 'react';\nimport { CardAction, type IslandAction } from './IslandCard';\nimport {\n advanceSlots,\n footprintHeight,\n frameFor,\n surfaceHeight,\n initialSlots,\n otherSlot,\n slotOccupied,\n SPACE,\n alignmentAxes,\n type IslandAlignment,\n type IslandPlacement,\n type IslandPresentation,\n type SlotKey,\n} from './island-geometry';\nimport {\n carryLead,\n toCssInset,\n carryTransform,\n forSurfaceGrowth,\n isResized,\n isStationary,\n carryRaster,\n drawsFromLeaving,\n toCssGrow,\n toCssLift,\n toCssSlide,\n toLocal,\n NO_GROWTH,\n type Rect,\n} from './island-carry';\nimport {\n atRest,\n NO_CARRIES,\n reduceTransition,\n type Carry,\n type IslandTransition,\n} from './island-transition';\nimport { ISLAND_TRANSITION_MS as TRANSITION_MS, PRESS_LETGO_MS } from './island-motion';\nimport {\n CarryContext,\n CHROME,\n PlaneContext,\n type CarryHome,\n type CarryRegistry,\n type CarryTrigger,\n} from './CarrySlot';\nimport { recallIsland, rememberIsland, type IslandMemory } from './island-continuity';\nimport { IslandShield } from './IslandShield';\nimport {\n PressContext,\n type IslandGesture,\n type IslandPressApi,\n type PressPhase,\n} from './island-press';\nimport type { IslandMode } from './island-theme';\nimport { IslandSurface } from './IslandSurface';\n/*\n * BOTH SHEETS, PICKERS FIRST. `pickers.css` carries the token layer the island's own\n * rules resolve through, so it is not optional here and not merely the pickers' own.\n */\nimport './pickers.css';\nimport './island.css';\n\n/**\n * Re-exported for callers. Declared in `island-motion`, where it is DERIVED from the\n * springs rather than typed — so the CSS the surface receives and the moment this\n * component tears the transition down cannot diverge.\n */\nexport const ISLAND_TRANSITION_MS = TRANSITION_MS;\n\nexport type IslandHostProps = {\n /** What shape the island should be. Drives the frame, not the content. */\n presentation: IslandPresentation;\n /**\n * Identity of what is being shown. A CHANGE here starts a transition; the same key\n * re-rendered with different children updates in place. Use the step name, not a value\n * that changes as the buyer types.\n */\n contentKey: string;\n /**\n * WHICH ISLAND THIS HOST IS, ACROSS THE COMPONENT THAT MOUNTS IT.\n *\n * Named, and a host that leaves hands the next one under the same name what it was\n * showing — so a widget whose faces are separate components still MORPHS between them\n * instead of cutting. See `island-continuity`, which is the whole mechanism and the\n * argument for it. Absent means \"only itself\", which is every other mount.\n */\n continuity?: string;\n /** Names the region for assistive technology. */\n label: string;\n /**\n * THE CHROME, WHICH IS NOT CONTENT — a bar drawn over both planes and rebuilt by\n * neither.\n */\n chrome?: ReactNode;\n /**\n * SEALED — nothing anywhere on the page may be pressed. Draws `IslandShield`, and it is\n * taken as a flag rather than a node so the host owns where that sheet sits: it has to\n * hang off the anchor, outside every transform and filter between here and there.\n */\n sealed?: boolean;\n /** Which appearance to render. Defaults to following the viewer's OS. */\n mode?: IslandMode;\n /**\n * Where in its reservation the island sits — see `IslandAlignment`. Defaults to `bottom`,\n * which is where the design docks it.\n */\n align?: IslandAlignment;\n /** Where the reservation is held — see `IslandPlacement`. Defaults to `page`. */\n placement?: IslandPlacement;\n /**\n * THE PROVIDER'S JOURNEY, TAKING THE SCREEN — stamped on the root so the CSS can lift\n * the fullscreen overlay over the host page and the centred island's transform out of\n * the overlay's way. Pass-through to `IslandSurfaceProps.journeyFullscreen`.\n */\n journeyFullscreen?: boolean;\n /*\n * THE BAY — see `IslandSurfaceProps.bay`. Supplied by the CALLER rather than measured\n * here because what lives in the bay is the caller's to own; the HOST adds only the\n * measurement, so every bay of the same content height behaves identically.\n */\n bay?: ReactNode;\n /**\n * NOT A CONTENT CHANGE. A bay that appears, disappears or changes height must not\n * start a step transition or carry anything: the planes do not move, and the payment\n * frame inside the bay must not be re-laid-out by anything but its own resize.\n */\n bayLabel?: string;\n bayVisible?: boolean;\n /**\n * HOW MANY ENTRIES THE BAY HOLDS ROOM FOR, whether or not it has them yet.\n *\n * A bay measures what is in it, which is right for a region whose contents are the\n * caller's — and wrong for two screens that are meant to BE the same card. Review and\n * the card screen hold the same kind of stack in the same place; a buyer crossing\n * between them should see the contents change, not the card resize under their hand,\n * and every entry in that stack is an async arrival (a provider reporting its height,\n * a platform answering whether it can pay) that would otherwise resize it again.\n *\n * So the CALLER says how many rows the pair reserves and both screens ask for the same\n * number. The reserve is a FLOOR, not a height: a bay with more to show than it\n * reserved still grows — see the rule in `island.css`.\n */\n bayRows?: number;\n /**\n * THE BAY'S OWN BUTTONS, drawn beneath the bay's content (form first, CTA last —\n * the SDK selector's own order). Same `CardAction` markup the card plane uses, so\n * the press, the compression and the disabled read match everywhere.\n */\n bayActions?: readonly IslandAction[];\n children: ReactNode;\n};\n\ntype Registration = {\n element: HTMLElement | null;\n node: ReactNode;\n /** When the overlay takes this element over — see `CarryTrigger`. */\n carryWhen: CarryTrigger;\n};\n\nconst asRect = (element: Element): Rect => {\n const { x, y, width, height } = element.getBoundingClientRect();\n return { x, y, width, height };\n};\n\n/**\n * HOW FAR THE PLANE'S BOX IS FROM THE FRAME'S, a side — the frame's own inline inset plus\n * the surface's hairline. See `targetPlaneWidth`, which is the only caller and where the\n * reason this is read rather than assumed is written down.\n */\nconst frameInset = (frameEl: HTMLElement, fallback: number): number => {\n const edge =\n typeof getComputedStyle === 'function'\n ? Number.parseFloat(\n getComputedStyle(frameEl).getPropertyValue('--scopetickets-island-edge-inline'),\n )\n : Number.NaN;\n return (Number.isFinite(edge) ? edge : fallback) + SPACE.s0_25;\n};\n\n/** What every viewport measurement is divided by to come back in LAYOUT space. */\nconst layoutScale = (element: HTMLElement): number => {\n const laidOut = element.offsetWidth;\n if (laidOut === 0) return 1;\n const painted = element.getBoundingClientRect().width;\n return painted > 0 ? painted / laidOut : 1;\n};\n\nconst startAtRest = (contentKey: string): IslandTransition => atRest(initialSlots(contentKey));\n\n/** What the island holds open in the host page, in px. */\nconst COLLAPSED_FOOTPRINT = footprintHeight('compact');\n\n/** And how far off the screen's edge it stands, when it is pinned there. */\nconst COLLAPSED_EDGE = frameFor('compact').edge;\n\n/**\n * The persistent surface, the two content planes inside it, and the carry layer above\n * them.\n */\nexport function IslandHost({\n presentation,\n contentKey,\n continuity,\n label,\n mode,\n align = 'bottom',\n placement = 'page',\n journeyFullscreen,\n chrome,\n bay,\n bayLabel = 'Payment',\n bayVisible = false,\n bayRows = 0,\n bayActions,\n sealed = false,\n children,\n}: IslandHostProps) {\n // Where the move has got to, as one value.\n const [state, dispatch] = useReducer(reduceTransition, contentKey, startAtRest);\n\n const frame = frameFor(presentation);\n /* The only half of the alignment anything in here moves by — see `alignmentAxes`. */\n const { block } = alignmentAxes(align);\n\n // ── The press ───────────────────────────────────────────── Held under the finger,\n // and STILL held when the pointer lifts — it lets go only once something has claimed\n // it.\n const [press, setPress] = useState<PressPhase | null>(null);\n\n /**\n * WHAT LED THE MOVE, held in a ref because the transition reads it during the render\n * that starts the move — after the press has already let go.\n */\n const ledRef = useRef<IslandGesture>('none');\n\n /** Set on release, cancelled by anything that claims the press first. */\n const letGo = useRef<number | null>(null);\n const cancelLetGo = () => {\n if (letGo.current !== null) window.clearTimeout(letGo.current);\n letGo.current = null;\n };\n\n const pressApi = useMemo<IslandPressApi>(\n () => ({\n press: (scope) => {\n cancelLetGo();\n ledRef.current = scope;\n // ONLY THE ISLAND'S PRESS COMPRESSES THE SURFACE.\n if (scope === 'island') setPress('held');\n },\n release: () => {\n cancelLetGo();\n letGo.current = window.setTimeout(() => {\n setPress(null);\n ledRef.current = 'none';\n }, PRESS_LETGO_MS);\n },\n abandon: () => {\n cancelLetGo();\n ledRef.current = 'none';\n setPress(null);\n },\n }),\n [],\n );\n\n useEffect(() => cancelLetGo, []);\n\n // The children rendered LAST time, and the padding they were rendered with.\n const previousChildren = useRef<ReactNode>(children);\n const previousPresentation = useRef(presentation);\n /*\n * AND THE CHROME, FOR THE SAME REASON — the one case where the persistent bar needs an\n * outgoing copy after all.\n */\n const previousChrome = useRef<ReactNode>(chrome);\n\n // Adjusting state during render when a prop changes: React's own documented pattern,\n // and the only way to avoid painting one frame of the wrong slot.\n const nextSlots = advanceSlots(state.slots, contentKey);\n if (nextSlots !== state.slots) {\n // The incoming plane must MOUNT hidden, which is what `PLACED` means.\n dispatch({\n type: 'CONTENT_CHANGED',\n slots: nextSlots,\n outgoing: previousChildren.current,\n outgoingPresentation: previousPresentation.current,\n led: ledRef.current,\n });\n }\n\n /**\n * WHAT THIS HOST WOULD HAND OVER IF IT LEFT NOW — see `island-continuity`. Kept beside\n * the two refs above because it is the same fact: what was last committed.\n */\n const parting = useRef<IslandMemory>({\n contentKey,\n children,\n chrome,\n presentation,\n height: null,\n });\n\n useEffect(() => {\n previousChildren.current = children;\n previousPresentation.current = presentation;\n previousChrome.current = chrome;\n parting.current = { contentKey, children, chrome, presentation, height };\n });\n\n /*\n * THE HANDOVER IS LEFT ON THE WAY OUT, from a LAYOUT cleanup — which is what makes it a\n * handover rather than a cache. React runs an unmounting tree's layout cleanups in the\n * same commit as the mounting tree's layout effects, and this one first, so the host\n * arriving finds it exactly when one left in the same breath. See `island-continuity`.\n */\n useLayoutEffect(() => {\n if (continuity === undefined) return undefined;\n return () => rememberIsland(continuity, parting.current);\n }, [continuity]);\n\n const slots = nextSlots;\n const active = slots.active;\n\n // Everything the render needs, DERIVED from the phase rather than stored beside it.\n const transitioning = state.phase !== 'REST';\n // True at rest, so a first mount appears rather than fading in.\n const painted = state.phase !== 'PLACED';\n const outgoing = state.phase === 'REST' ? null : state.outgoing;\n // The frame the leaving content was laid out in — its padding and its row height both\n // differ from the incoming one's.\n const outgoingFrame = state.phase === 'REST' ? null : frameFor(state.outgoingPresentation);\n const carries = state.phase === 'REST' ? NO_CARRIES : state.carries;\n // How the surface should acknowledge this move: `press` returns a compression that is\n // already on screen, `cold` has none and plays the keyframe instead.\n const gesture = state.phase === 'REST' ? undefined : state.led;\n /*\n * The island's WIDTH moves only between the pill and the card: the frame is a fixed\n * width and the edge inset differs per presentation, so a card becoming another card\n * travels vertically and not at all horizontally. A uniform pop squeezed it sideways at\n * every step for a dimension that was not going anywhere — pop horizontally only to and\n * from the pill.\n */\n const popAxis =\n state.phase !== 'REST' && state.outgoingPresentation === presentation ? 'block' : 'both';\n\n // ── Carry registry ──────────────────────────────────────── A ref, not state: slots\n // register on every render and re-rendering the host in response would not terminate.\n const registry = useRef(new Map<string, Partial<Record<CarryHome, Registration>>>());\n\n const drawnByOverlay = useMemo(() => new Set(carries.map((c) => c.name)), [carries]);\n\n const carryRegistry = useMemo<CarryRegistry>(\n () => ({\n register: (name, plane, element, node, carryWhen) => {\n const entry = registry.current.get(name) ?? {};\n entry[plane] = { element, node, carryWhen };\n registry.current.set(name, entry);\n },\n drawnByOverlay,\n }),\n [drawnByOverlay],\n );\n\n // The CLIP, not the surface.\n const clipRef = useRef<HTMLDivElement | null>(null);\n /* The carry layer — the one box every carried copy is both measured against and drawn\n * in. See the note in the carry effect for what happened when those were two boxes. */\n const layerRef = useRef<HTMLDivElement | null>(null);\n\n /*\n * THE BAY'S OWN HEIGHT, measured by the same contract as the planes': ResizeObserver\n * plus one reading on mount, rounded, and published for the CSS. Kept SEPARATE from\n * `height` — the surface's height is the SUM, composed once below, so a bay growing\n * must not be able to round the plane's own measurement away.\n *\n * MEASURED WHETHER IT IS SHOWN OR NOT. The inner box is always laid out at its natural\n * height (the SECTION around it is what collapses), so this is the height the bay WILL\n * be the moment its content changes — which is what the morph has to know before it\n * starts, not a frame after.\n */\n const bayRef = useRef<HTMLDivElement | null>(null);\n const [bayContent, setBayContent] = useState(0);\n const measureBay = useCallback(() => {\n const node = bayRef.current;\n if (!node) return;\n const next = node.offsetHeight;\n setBayContent((current) => (Math.abs(current - next) < 1 ? current : next));\n }, []);\n\n /** Whether the bay is taking room out of the surface at all. */\n const bayShown = bay !== undefined && bayVisible;\n /** What the bay's box is FOR — 0 when it is closed, whatever it holds when it is open. */\n const bayHeight = bayShown ? bayContent : 0;\n\n /**\n * THE GUTTER A PLANE KEEPS AT ITS BLOCK-END — none, once a bay is drawing one of its\n * own underneath. See the plane's rule in `island.css` for why this is a number from\n * here rather than a `:has()` over there.\n */\n const planeGutter = bayShown ? 0 : frame.padding.block;\n\n // ── Height ────────────────────────────────────────────────\n const [height, setHeight] = useState<number | null>(null);\n /*\n * THE HANDED-OVER HEIGHT IS HELD FOR THE \"BEFORE\" FRAME, and only then.\n *\n * `height` is a CSS transition, so the surface has to be PAINTED at the height it is\n * leaving before it can travel away from it — and a host that has just mounted has no\n * previous frame to have painted one. So a handover seeds the height and this stops\n * `measure` overwriting it until the phase moves off `PLACED`, which is the frame the\n * reducer already holds for exactly this purpose. Every other mount has nothing to hold.\n */\n const holdHandoverHeight = useRef(false);\n\n /**\n * ── CLAIMING A HANDOVER ─────────────────────────────────────────────────────\n *\n * Taken in a LAYOUT EFFECT and not during render, and that is the whole trick: the host\n * that left wrote its memory from a layout CLEANUP, which React runs in the same commit\n * as this and before it. Finding one here therefore means one island became another in\n * one breath — not that a widget was put back on the page later. See `island-continuity`.\n *\n * WHAT IT DOES IS WHAT A CONTENT CHANGE DOES, with the slots wound back one: the leaving\n * key is given the plane this host started in and the current one takes the other, so the\n * ordinary two-plane cross-fade has something to cross FROM. `led` is `none` — nothing was\n * pressed on THIS host, so the surface plays its own keyframe rather than releasing a\n * compression that is not there.\n *\n * MOUNT ONLY. A handover is a thing that happens once, at the moment of arrival.\n */\n useLayoutEffect(() => {\n if (continuity === undefined) return;\n const handover = recallIsland(continuity);\n if (handover === null || handover.contentKey === contentKey) return;\n\n holdHandoverHeight.current = true;\n published.current = handover.height;\n setHeight(handover.height);\n dispatch({\n type: 'CONTENT_CHANGED',\n slots: advanceSlots(initialSlots(handover.contentKey), contentKey),\n outgoing: handover.children,\n outgoingPresentation: handover.presentation,\n led: 'none',\n });\n /* eslint-disable-next-line react-hooks/exhaustive-deps -- arrival, not a subscription. */\n }, []);\n const activePlaneRef = useRef<HTMLDivElement | null>(null);\n const frameRef = useRef<HTMLDivElement | null>(null);\n\n /**\n * THE PLANE'S WIDTH ONCE THE MOVE HAS FINISHED — the frame, less its inline inset and the\n * surface's own hairline either side.\n *\n * THE INSET IS READ OFF THE ELEMENT, NOT TAKEN FROM `frame.edge`. The constant is what\n * the frame is inset by ordinarily; the stylesheet gives that inset up entirely below\n * 432px, and it said so to nobody. On a phone this subtracted 8px a side that was not\n * there, pinned the plane 16px narrow — and a plane pinned narrow is LEFT-ANCHORED,\n * because `inset-inline: 0` loses its end to an explicit width — so every carried\n * element was measured, and therefore drawn, 8px left of where it would land. It eased\n * over there with the morph, sat there, and snapped back the frame the carry was torn\n * down. Measured off a recording at 3x: -8.1px, held for 250ms.\n *\n * A CUSTOM PROPERTY IS NOT INTERPOLATED, which is what makes it readable mid-move: the\n * `padding-inline` it feeds eases between presentations, and this answers the value that\n * padding is easing TOWARD from the first frame. `frame.edge` is the fallback for a\n * renderer with no computed style — a test, SSR — where there is no stylesheet to have\n * overridden anything.\n */\n const targetPlaneWidth = useCallback(() => {\n const frameEl = frameRef.current;\n if (!frameEl) return null;\n const width = frameEl.getBoundingClientRect().width - 2 * frameInset(frameEl, frame.edge);\n return width > 0 ? width : null;\n }, [frame.edge]);\n\n /** READ AT THE WIDTH THE PLANE WILL END AT, not the width it has now. */\n const atFinalWidth = useCallback(\n <T,>(read: () => T): T => {\n const node = activePlaneRef.current;\n const target = node === null ? null : targetPlaneWidth();\n if (node !== null && target !== null) node.style.width = `${target}px`;\n try {\n return read();\n } finally {\n if (node !== null && target !== null) node.style.width = '';\n }\n },\n [targetPlaneWidth],\n );\n\n /**\n * WHAT THE PLANE'S BLOCK-END GUTTER HAS LEFT TO TRAVEL, in layout px.\n *\n * The gutter eases with the morph like everything else, so anything read while it is on\n * its way is read against a box the card does not have yet — the surface sized to a\n * height it never reaches, a carried destination placed a gutter off. It cannot be\n * PINNED for the reading the way the width can: assigning to a property that is midway\n * through a transition re-aims the transition rather than arriving, so the reading\n * would be the same stale number and the animation would be spent. It is corrected\n * for instead.\n *\n * AND NOTHING ELSE WOULD CATCH IT. A `ResizeObserver` watches a CONTENT box, and\n * padding does not move one — the plane's own observer is blind to this by design.\n */\n const gutterTravel = useCallback(() => {\n const node = activePlaneRef.current;\n if (node === null) return 0;\n const now = Number.parseFloat(window.getComputedStyle(node).paddingBlockEnd);\n return Number.isFinite(now) ? planeGutter - now : 0;\n }, [planeGutter]);\n\n /**\n * WHAT WAS LAST PUBLISHED, beside the state that holds it.\n *\n * THE COMPARISON HAS TO HAPPEN BEFORE `setHeight` IS CALLED AT ALL, not inside its\n * updater. React only skips scheduling a render for a state that has not changed while\n * the fiber has no work pending — which is exactly the condition a transition breaks, so\n * during a move an updater returning `current` still scheduled a render. From an effect\n * that runs on EVERY render (see below), that is a loop React stops by throwing.\n */\n const published = useRef<number | null>(null);\n\n /** The incoming plane's natural height, published for the CSS to interpolate. */\n const measure = useCallback(() => {\n if (holdHandoverHeight.current) return;\n const node = activePlaneRef.current;\n if (!node) return;\n // The SURFACE's height, not the plane's: the surface is border-box and carries a\n // hairline, so its content box is two pixels shorter than itself.\n const clip = clipRef.current;\n const painted = atFinalWidth(() => node.getBoundingClientRect().height);\n const next = surfaceHeight(painted / (clip === null ? 1 : layoutScale(clip)) + gutterTravel());\n // Round: sub-pixel jitter from a ResizeObserver would re-render every frame during\n // a transition without changing anything a viewer can see.\n if (published.current !== null && Math.abs(published.current - next) < 1) return;\n published.current = next;\n setHeight(next);\n }, [atFinalWidth, gutterTravel]);\n\n /*\n * READ IN THE SAME LAYOUT PASS THE PLANES ARE READ IN. A ResizeObserver answers a frame\n * later, which is a frame after the morph clock has already started — so a step that\n * opens the bay, or changes what is in it, animated toward a height that was still the\n * last step's. The observer below stays for what changes on its OWN (a payment frame\n * reporting in), which is the only case it was ever needed for.\n */\n useLayoutEffect(measureBay, [measureBay, contentKey, bayShown]);\n\n useLayoutEffect(() => {\n const node = bayRef.current;\n if (!node || typeof ResizeObserver === 'undefined') return undefined;\n const observer = new ResizeObserver(() => measureBay());\n observer.observe(node);\n return () => observer.disconnect();\n }, [measureBay, bay !== undefined]);\n\n useLayoutEffect(() => {\n measure();\n const node = activePlaneRef.current;\n if (!node || typeof ResizeObserver === 'undefined') return undefined;\n /*\n * THE OBSERVER IS FOR CONTENT THAT CHANGES ON ITS OWN — a line added to the cart, a\n * payment frame reporting its height, a run of tickets that could not know its size\n * until it had been laid out.\n *\n * ── IT USED TO BE MUTED FOR THE LENGTH OF A MOVE, AND THAT WAS THE BUG ──────\n *\n * The worry was the host chasing its own tail: the plane is inside a surface whose\n * height is easing, so a reading taken mid-move would be of a box that is going\n * somewhere. It is not. The plane is absolutely positioned with `bottom: 0` and no\n * height of its own, so what is read here is its CONTENT's height — and `measure`\n * pins the final width and corrects the gutter still in flight before reading it, so\n * the number does not move while the surface does.\n *\n * WHAT THE MUTE ACTUALLY COST is every card whose contents settle their own size one\n * render after they mount. React does not re-run a PARENT's effects for a child's\n * state change, so nothing but this observer can see it — and with it muted the morph\n * stayed aimed at the height the plane had before its contents knew theirs, and the\n * card SNAPPED when the move ended and the settle read below finally ran. The codes\n * card is the plainest case: a ticket draws nothing at all until `fitTicketEdge` has a\n * width to answer for, so the card morphed to little more than its pager and then\n * jumped a whole ticket taller.\n *\n * IT IS CHEAP TO LEAVE ARMED. `measure` publishes nothing when the reading has not\n * moved — see `published` — so a fire per frame of the width animation costs a layout\n * read and no render at all.\n */\n const observer = new ResizeObserver(() => measure());\n observer.observe(node);\n return () => observer.disconnect();\n }, [measure, active, contentKey]);\n\n /**\n * THE PHASE'S OWN READING, and the one that ends a handover's hold.\n *\n * The \"before\" frame has been painted by the time this runs for anything but `PLACED`,\n * so the height handed over has done its job and the surface may travel to its own. See\n * `holdHandoverHeight`.\n */\n useLayoutEffect(() => {\n if (state.phase === 'PLACED') return;\n /* `REST` is also the phase a handover is CLAIMED in, and its before-frame has not been\n painted yet — only a move that has started releases the hold. */\n if (state.phase !== 'REST') holdHandoverHeight.current = false;\n measure();\n }, [state.phase, measure]);\n\n /**\n * AND ONE ON EVERY RENDER WHILE THE MOVE IS RUNNING, which closes the other end of what\n * the mute above leaves open.\n *\n * ── THE CARD THAT MORPHS TO THE WRONG HEIGHT ────────────────────────────────\n *\n * Content that has to MEASURE ITSELF settles one render after it mounts, and the incoming\n * plane mounts inside the commit that starts the move. Layout effects run child-first, so\n * a child measuring in one and calling `setState` schedules its correction AFTER the\n * reading above has already been taken — and `measure` does not re-run for it, because\n * its dependencies have not changed. The observer that would have caught it is muted for\n * the length of the move.\n *\n * So the morph was aimed at the height the plane had before its contents knew their own\n * size, and the card snapped to its real height when the move ended. The codes card is\n * the worst of them: a ticket draws NOTHING until `fitTicketEdge` has a width to answer\n * for, so the card morphed to little more than its pager and then jumped a ticket taller.\n *\n * WHY IT IS SAFE TO READ ON EVERY RENDER HERE. The mute exists to stop a ResizeObserver\n * re-aiming the morph at the box's own travel — this reads the plane's NATURAL height\n * (pinned to the final width, corrected for the gutter still in flight), which does not\n * move as the surface eases. Re-reading it costs a layout, so it is spent only while\n * something is actually moving, and it settles because an unchanged height sets no state.\n */\n /**\n * One more reading when the move ends, and it closes what the mute above leaves open.\n */\n useEffect(() => {\n if (transitioning) return;\n measure();\n }, [transitioning, measure]);\n\n // ── Start a carry when the step changes ───────────────────\n useLayoutEffect(() => {\n /*\n * THE BOX THE COPIES ARE MEASURED AGAINST IS THE BOX THEY ARE DRAWN IN, and it is\n * this one — the carry layer itself, which is why it is always mounted rather than\n * raised with the first carry.\n *\n * It was the CLIP, and that was a distinction with no difference for exactly as long\n * as the surface held nothing but the clip: the two boxes had the same edges, so\n * measuring against one and positioning inside the other agreed by accident. The bay\n * ended that. The clip gives up its bottom to the bay while the layer keeps the whole\n * surface, so every `bottom:` the overlay wrote was the bay's own height too low —\n * the carried avatar drawn over the payment entries instead of at the card's head.\n */\n const layer = layerRef.current;\n if (!layer || state.phase !== 'PLACED') return;\n\n const leaving = otherSlot(active);\n // AT THE FINAL WIDTH, for the destinations.\n const next = atFinalWidth(() => {\n const container = asRect(layer);\n const scale = layoutScale(layer);\n /*\n * WHAT THE SURFACE AND ITS CLIP ARE ABOUT TO GAIN, in layout space. Neither has\n * moved yet — this runs in the commit that STARTS the move, before the measured\n * heights have been published back as CSS — so every destination is read against a\n * shape that is one step out of date, and `forSurfaceGrowth` is what closes it.\n *\n * The bay's target is read from the DOM rather than from `bayHeight`, for the same\n * reason: state written in this pass is not on the element until the next one.\n *\n * ALL OF IT IN THE CARRY LAYER'S OWN TERMS, which is the surface inside its hairline:\n * so no `surfaceHeight` here, which adds back a border the layer's box does not have.\n * At rest the clip holds the plane and nothing else, so what the plane will be is\n * what the clip will be.\n */\n const arrivingPlane = activePlaneRef.current;\n const bayTarget = bayShown ? (bayRef.current?.offsetHeight ?? 0) : 0;\n const clipNow = clipRef.current === null ? 0 : asRect(clipRef.current).height / scale;\n const gutter = gutterTravel();\n const growth =\n arrivingPlane === null\n ? NO_GROWTH\n : (() => {\n const planeTarget = arrivingPlane.getBoundingClientRect().height / scale + gutter;\n return {\n surface: planeTarget + bayTarget - container.height / scale,\n clip: planeTarget - clipNow,\n gutter,\n };\n })();\n const found: Carry[] = [];\n\n for (const [name, entry] of registry.current) {\n /* THE CHROME STANDS IN AT WHICHEVER END HAS NO PLANE, and at only one of them. */\n const leavingEntry = entry[leaving] ?? entry[CHROME];\n const arrivingEntry = entry[active] ?? entry[CHROME];\n if (leavingEntry === arrivingEntry) continue;\n\n const from = leavingEntry?.element;\n const arriving = arrivingEntry;\n if (!from || !arriving?.element) continue;\n\n const fromRect = toLocal(asRect(from), container, block, scale);\n const toRect = forSurfaceGrowth(\n toLocal(asRect(arriving.element), container, block, scale),\n growth,\n entry[active] === undefined ? 'CHROME' : 'PLANE',\n block,\n );\n const transform = carryTransform(fromRect, toRect, block);\n // ONE VERSION FOR THE WHOLE FLIGHT, AND IT IS THE LARGER — see `carryRaster`.\n const moving = !isStationary(transform);\n\n /*\n * A REGISTERED ELEMENT THAT DOES NOT MOVE IS STILL CARRIED, and that is the point:\n * leaving a stationary one to the planes means the overlay stops hiding it, so it\n * blinks in with the incoming plane instead of simply being there throughout. Not\n * moving is a reason to skip the ANIMATION, not the carry.\n */\n if (arriving.carryWhen === 'resized' && !isResized(transform)) continue;\n\n const fromLeaving = moving && drawsFromLeaving(fromRect, toRect);\n // WHERE THE OVERLAY DRAWS FROM, named by the HOME the end actually lives in and\n // not by the slot it would have lived in.\n const source: CarryHome = fromLeaving\n ? entry[leaving]\n ? leaving\n : CHROME\n : entry[active]\n ? active\n : CHROME;\n const raster = moving ? carryRaster(fromRect, toRect) : toRect;\n\n found.push({\n name,\n node: (fromLeaving ? leavingEntry?.node : arriving.node) ?? arriving.node,\n source,\n to: toRect,\n box: { width: raster.width, height: raster.height },\n ...(moving\n ? {\n slide: toCssSlide(transform),\n lift: toCssLift(transform),\n grow: toCssGrow(fromRect, raster),\n rest: toCssGrow(toRect, raster),\n lead: carryLead(fromRect, toRect, block),\n }\n : {}),\n });\n }\n\n return found;\n });\n\n if (next.length === 0) return;\n dispatch({ type: 'CARRIES_MEASURED', carries: next });\n }, [active, state.phase, atFinalWidth, gutterTravel, block, bayShown]);\n\n // The second frame.\n useEffect(() => {\n if (state.phase !== 'PLACED') return undefined;\n const frame = requestAnimationFrame(() => dispatch({ type: 'PAINTED' }));\n return () => cancelAnimationFrame(frame);\n }, [state.phase]);\n\n // ── Tear down once the move is over ─────────────────────── Keyed on WHETHER a move\n // is running, not on which phase it is in: the release happens one frame after the\n // start and must not restart the clock.\n useEffect(() => {\n if (!transitioning) return undefined;\n const timer = window.setTimeout(() => {\n dispatch({ type: 'SETTLED' });\n registry.current.clear();\n }, ISLAND_TRANSITION_MS);\n return () => window.clearTimeout(timer);\n }, [transitioning, active]);\n\n /*\n * An element that mounts already carrying its final opacity has no starting style to\n * transition from, so it simply IS visible — the same trap the planes' `painted` flag\n * exists for, and it pops against a card that is cross-fading beneath it.\n */\n const chromeArriving = chrome !== undefined && previousChrome.current === undefined;\n const chromeActive = chrome !== undefined && (painted || !chromeArriving);\n\n const plane = (slot: SlotKey) => {\n if (!slotOccupied(slots, slot)) return null;\n const isActive = slot === active;\n if (!isActive && !transitioning) return null;\n\n return (\n <PlaneContext.Provider value={slot}>\n <div\n ref={isActive ? activePlaneRef : undefined}\n className={`scopetickets-island-plane${isActive && painted ? ' scopetickets-island-plane--active' : ''}`}\n /*\n * The leaving plane keeps the inset it was laid out at, so the step on its way\n * out does not jump to the new one first — AND THE GUTTER IS ONE OF THOSE\n * INSETS, which is why it is declared here per plane rather than selected for\n * on the surface. A `:has()` up there gave the plane on its way out the\n * arriving presentation's gutter, which is the one number it must not have.\n */\n style={\n {\n '--scopetickets-island-plane-gutter': `${\n bayShown\n ? 0\n : (isActive || outgoingFrame === null ? frame : outgoingFrame).padding.block\n }px`,\n ...(isActive || outgoingFrame === null\n ? {}\n : {\n '--scopetickets-island-padding-block': `${outgoingFrame.padding.block}px`,\n '--scopetickets-island-padding-inline': `${outgoingFrame.padding.inline}px`,\n '--scopetickets-island-row': `${outgoingFrame.rowHeight}px`,\n '--scopetickets-island-edge': `${outgoingFrame.edge}px`,\n }),\n } as CSSProperties\n }\n aria-hidden={isActive ? undefined : true}\n // The outgoing plane must not be reachable by keyboard while it fades.\n {...(isActive ? {} : { inert: '' })}\n >\n {isActive ? children : outgoing}\n </div>\n </PlaneContext.Provider>\n );\n };\n\n return (\n <PressContext.Provider value={pressApi}>\n <CarryContext.Provider value={carryRegistry}>\n <IslandSurface\n ref={frameRef}\n clipRef={clipRef}\n radius={frame.radius}\n padding={frame.padding}\n maxWidth={frame.maxWidth}\n rowHeight={frame.rowHeight}\n edge={frame.edge}\n align={align}\n placement={placement}\n journeyFullscreen={journeyFullscreen}\n popAxis={popAxis}\n // Suppressed while moving: the compression is the TRANSITION's to finish now,\n // and leaving `data-press` up would have two rules setting `transform` on the\n // same element.\n press={transitioning ? null : press}\n gesture={gesture}\n footprint={COLLAPSED_FOOTPRINT}\n footprintEdge={COLLAPSED_EDGE}\n transitioning={transitioning}\n /* THE SUM, COMPOSED ONCE AND HERE. The plane's measurement and the bay's are\n * two readings of two boxes; what the surface is told is the one number they\n * add up to, so no rule downstream has to add them again and get it right. */\n height={height === null ? null : height + bayHeight}\n bay={\n bay === undefined ? undefined : (\n <section\n className=\"scopetickets-island-surface__bay\"\n aria-label={bayLabel}\n aria-hidden={!bayVisible}\n {...(bayVisible ? {} : { inert: '' })}\n data-visible={bayVisible ? '' : undefined}\n >\n <div ref={bayRef}>\n {/* The entries, and the room they hold open — see `bayRows`. */}\n <div\n className=\"scopetickets-island-bay__stack\"\n style={{ '--scopetickets-island-bay-rows': bayRows } as CSSProperties}\n >\n {bay}\n {bayActions !== undefined && bayActions.length > 0 && (\n <div className=\"scopetickets-island-bay__buttons\">\n {bayActions.map((action) => (\n <CardAction key={action.key} action={action} />\n ))}\n </div>\n )}\n </div>\n </div>\n </section>\n )\n }\n bayHeight={bayHeight}\n label={label}\n mode={mode}\n overlay={\n /* ALWAYS MOUNTED, EVEN EMPTY. It is the box the carries are measured\n * against, and a box that only exists once there is something to put in it\n * cannot be measured before there is. */\n <div ref={layerRef} className=\"scopetickets-island-carry-layer\" aria-hidden=\"true\">\n {carries.map((carry) => (\n <div\n key={carry.name}\n // A stationary carry never gets the released class, so it never\n // transitions: it is simply the one copy of an element that happens\n // to be in the same place in both states.\n className={`scopetickets-island-carry${carry.slide && painted ? ' scopetickets-island-carry--released' : ''}`}\n data-lead={carry.lead}\n style={{\n left: `${carry.to.x}px`,\n // Against whatever does not move while the card grows — an edge, or\n // the centre line where the island is pinned to neither. See\n // `toCssInset`, which used to be `[align]` and could not stay that.\n ...toCssInset(carry.to.offset, carry.box.height, block),\n width: `${carry.box.width}px`,\n height: `${carry.box.height}px`,\n transform: painted ? undefined : carry.slide,\n }}\n >\n {/*\n * The second box. `transform` is one property, so the other axis needs its own element\n * — but `translate` and `scale` are independent, so its vertical and its size can run\n * on separate clocks without a third. See `toCssLift`.\n */}\n <div\n className=\"scopetickets-island-carry__lift\"\n style={{\n translate: painted ? undefined : carry.lift,\n // Both ends are published: the resting scale is only 1 when the\n // raster IS the destination — see `carryRaster`.\n scale: painted ? carry.rest : carry.grow,\n }}\n >\n {/*\n * THE LIVE NODE, NOT THE ONE THE CARRY WAS MEASURED WITH. `carry.node` is a snapshot\n * taken at `CARRIES_MEASURED` and never refreshed, which is right for the GEOMETRY — an\n * inversion has to be measured once — and wrong for the CONTENT. The escrow ring is a\n * per-frame sweep (`CountdownTimer`: \"a SWEEP, per frame\"), so the overlay drew it frozen\n * for the whole transition and then handed back a ring that had moved all of it in one\n * frame. Reported as the timer being jittery at the start and the end, which is exactly\n * where a freeze and a jump would show. The registry is written in the slots' own\n * layout effect, so this is one commit behind rather than four hundred milliseconds.\n * `carry.node` remains the fallback for a name that has since unregistered.\n */}\n {registry.current.get(carry.name)?.[carry.source]?.node ?? carry.node}\n </div>\n </div>\n ))}\n </div>\n }\n shield={sealed ? <IslandShield /> : undefined}\n sealed={sealed}\n chrome={\n chrome === undefined &&\n !(transitioning && previousChrome.current !== undefined) ? null : (\n /*\n * Outside both planes, so a content change leaves it alone: the dismiss button keeps\n * its focus and its press state, and the escrow ring keeps sweeping instead of being\n * replaced by a new one every step. It is a sibling of the CLIP rather than a child of\n * it, for the reason the bar has always been an overlay — the clip masks the scrolling\n * content, and a header inside that mask fades with the content it is pinned over.\n */\n <PlaneContext.Provider value={CHROME}>\n <div\n className={`scopetickets-island-chrome${chromeActive ? ' scopetickets-island-chrome--active' : ''}`}\n // A bar on its way out is a picture, not a control: the way out it\n // draws belongs to a card that is already leaving.\n aria-hidden={chrome === undefined ? true : undefined}\n {...(chrome === undefined ? { inert: '' } : {})}\n >\n {chrome ?? previousChrome.current}\n </div>\n </PlaneContext.Provider>\n )\n }\n >\n {plane('a')}\n {plane('b')}\n </IslandSurface>\n </CarryContext.Provider>\n </PressContext.Provider>\n );\n}\n","/** The island's shape, as pure data. */\n\nexport type IslandPresentation = 'compact' | 'card' | 'full';\n\n/**\n * Where in its reservation the island sits: a corner, the middle of an edge, or the middle.\n *\n * TWO AXES SPELLED AS ONE WORD, the way a host thinks of a position. Nothing downstream\n * reads the word — see `alignmentAxes`, which is the only thing that does.\n */\nexport type IslandAlignment =\n | 'top-left'\n | 'top'\n | 'top-right'\n | 'left'\n | 'center'\n | 'right'\n | 'bottom-left'\n | 'bottom'\n | 'bottom-right';\n\n/**\n * Where the reservation itself is held: in the host page's flow, or pinned to the screen.\n *\n * `page` is the default and every host before this: the anchor is `position: relative`\n * wherever the host mounted it, so `align` places the island inside a box the page lays\n * out. `screen` pins that box to the viewport, so the same `align` names a corner of the\n * SCREEN — which a host wanting a floating widget could otherwise only get by wrapping it\n * in fixed-position CSS of its own and keeping that in step with `align` by hand.\n */\nexport type IslandPlacement = 'page' | 'screen';\n\n/** Which edge the card grows away from, or `center` for both at once. */\nexport type BlockAlignment = 'top' | 'center' | 'bottom';\n\n/** Which side of a reservation wider than the island's measure it sits against. */\nexport type InlineAlignment = 'left' | 'center' | 'right';\n\nexport type AlignmentAxes = {\n readonly block: BlockAlignment;\n readonly inline: InlineAlignment;\n};\n\n/**\n * THE AXES ARE INDEPENDENT, and the geometry only ever needed one of them.\n *\n * The block axis decides everything that MOVES: which edge stands still while the card\n * grows, and so what every carried element is measured from. The inline axis moves nothing\n * inside the island. The island's measure is capped and the same in every presentation,\n * so a pill and the card it opens into share both side edges however the island is placed,\n * and the carry layer measures from its own left edge, which travels with the frame. So\n * the carry arithmetic takes a `BlockAlignment` and cannot be handed the other half.\n *\n * A RECORD RATHER THAN STRING SURGERY on the hyphen, so a tenth alignment without an entry\n * fails the build instead of splitting into something no rule is written for.\n */\nconst AXES: Record<IslandAlignment, AlignmentAxes> = {\n 'top-left': { block: 'top', inline: 'left' },\n top: { block: 'top', inline: 'center' },\n 'top-right': { block: 'top', inline: 'right' },\n left: { block: 'center', inline: 'left' },\n center: { block: 'center', inline: 'center' },\n right: { block: 'center', inline: 'right' },\n 'bottom-left': { block: 'bottom', inline: 'left' },\n bottom: { block: 'bottom', inline: 'center' },\n 'bottom-right': { block: 'bottom', inline: 'right' },\n};\n\nexport function alignmentAxes(align: IslandAlignment): AlignmentAxes {\n return AXES[align];\n}\n\n/**\n * THE EDGE THAT DOES NOT MOVE while the card grows — `null` where there isn't one.\n *\n * Everything about the island's motion is measured from something that stands still: a\n * bottom-aligned card grows upward, so its bottom edge is the ruler, and the carry layer\n * expresses every position as a distance from it. A CENTRED island grows equally in both\n * directions, so NEITHER edge stands still and the ruler is the container's centre line\n * instead.\n *\n * That is the whole reason this exists rather than the alignment being read directly:\n * `align` used to double as the name of a CSS inset property, which works only while\n * every alignment HAS one. `center` does not, and a value that silently fell through to\n * `bottom` would animate against an edge that was itself travelling.\n */\nexport type PinEdge = 'top' | 'bottom' | null;\n\nexport function pinEdge(block: BlockAlignment): PinEdge {\n return block === 'center' ? null : block;\n}\n\n/** The inset a plane lays its content out at, in px, per axis. */\nexport type PlanePadding = {\n readonly block: number;\n readonly inline: number;\n};\n\nexport type IslandFrame = {\n /** Corner radius in px. `$10` collapsed, `$12` expanded. */\n readonly radius: number;\n /** Padding inside the surface, in px, per axis. */\n readonly padding: PlanePadding;\n /** Max width in px, or `null` to fill the container. */\n readonly maxWidth: number | null;\n /** The height the rows in this presentation are pinned to, in px. */\n readonly rowHeight: number;\n /** The gap between the island and the edge of the box it was mounted into, in px. */\n readonly edge: number;\n};\n\n/** The design system's spacing scale, in px. */\nexport const SPACE = {\n /** `$0.25` — the hairline step. */\n s0_25: 1,\n s2: 8,\n s4: 16,\n /** `$7` — the card's own padding. */\n s7: 28,\n /** `$10` — the header row, and the header button's height. */\n s10: 40,\n /** `$12` — the card's corner radius. */\n s12: 48,\n /**\n * `$100` — the island's width cap, which is also the SDK checkout's own summary column\n * (`@scopetickets/sdk/dist/styles.css:1498`), so the island and the checkout it hands\n * off to are one measure on one page.\n */\n s100: 400,\n} as const;\n\n/**\n * The card in the design is a fixed 326px, which is a phone measurement and meaningless\n * on the web — but the NUMBER is not the rule. The native island is inset from the\n * screen and its width is whatever that leaves; 326 is what an iPhone leaves. So the\n * web ports the rule instead: fill the container, inset by `edge`, capped at `$100`.\n */\nconst ISLAND_MAX_WIDTH = SPACE.s100;\n\n/** Figma `$10` — the header row, sized to the header button that sits in it. */\nconst ISLAND_ROW_HEIGHT = SPACE.s10;\n\n/** `text/bold/md`'s leading — the line box of any button label. */\nconst LABEL_LEADING = 20;\n\n/** The collapsed pill's row, in px — 54, and deliberately NOT a spacing token. */\nconst PILL_ROW_HEIGHT = 2 * SPACE.s4 + LABEL_LEADING + 2 * SPACE.s0_25;\n\n/**\n * The frame, per presentation. Values are `CTA_ISLAND_STATE_GEOMETRY`'s EXCEPT the\n * collapsed inset, which is the in-app frames' — see `IslandFrame.edge`.\n */\nconst FRAMES: Record<IslandPresentation, IslandFrame> = {\n compact: {\n radius: SPACE.s10,\n padding: { block: SPACE.s2, inline: SPACE.s2 },\n edge: SPACE.s4,\n rowHeight: PILL_ROW_HEIGHT,\n maxWidth: ISLAND_MAX_WIDTH,\n },\n card: {\n radius: SPACE.s12,\n padding: { block: SPACE.s7, inline: SPACE.s7 },\n edge: SPACE.s2,\n rowHeight: ISLAND_ROW_HEIGHT,\n maxWidth: ISLAND_MAX_WIDTH,\n },\n full: {\n radius: SPACE.s12,\n padding: { block: SPACE.s7, inline: SPACE.s7 },\n edge: SPACE.s2,\n rowHeight: ISLAND_ROW_HEIGHT,\n maxWidth: null,\n },\n};\n\nexport function frameFor(presentation: IslandPresentation): IslandFrame {\n return FRAMES[presentation];\n}\n\n/**\n * The height a presentation occupies before any content is measured, in px: padding,\n * one row, padding.\n */\nexport function footprintHeight(presentation: IslandPresentation): number {\n const { padding, rowHeight } = FRAMES[presentation];\n return surfaceHeight(padding.block * 2 + rowHeight);\n}\n\n/** The surface's OUTER height for a plane of `planeHeight`, in px. */\nexport function surfaceHeight(planeHeight: number): number {\n return planeHeight + 2 * SPACE.s0_25;\n}\n\n/**\n * How far a plane's content sits from the container's edge, in px: the island's own\n * inset plus its inline padding.\n */\nexport function contentInset(presentation: IslandPresentation): number {\n const { edge, padding } = FRAMES[presentation];\n return edge + padding.inline;\n}\n\n// ── Content slots ────────────────────────────────────────────\n\n/** Two slots. The surface is never unmounted; only which slot is active changes. */\nexport type SlotKey = 'a' | 'b';\n\nexport function otherSlot(slot: SlotKey): SlotKey {\n return slot === 'a' ? 'b' : 'a';\n}\n\nexport type SlotState = {\n readonly active: SlotKey;\n /** The content key occupying each slot, or `null` if it has never been used. */\n readonly a: string | null;\n readonly b: string | null;\n};\n\nexport function initialSlots(contentKey: string): SlotState {\n return { active: 'a', a: contentKey, b: null };\n}\n\n/** Returns the state after `contentKey` is asked for. */\nexport function advanceSlots(state: SlotState, contentKey: string): SlotState {\n if (state[state.active] === contentKey) return state;\n\n const incoming = otherSlot(state.active);\n return { ...state, active: incoming, [incoming]: contentKey };\n}\n\n/** Whether a slot should be painted at all — an unused slot renders nothing. */\nexport function slotOccupied(state: SlotState, slot: SlotKey): boolean {\n return state[slot] !== null;\n}\n","import { pinEdge, type BlockAlignment } from './island-geometry';\n\n/** The carry layer's geometry, as pure functions. */\n\nexport type Rect = {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n};\n\n/** Where a carried element starts, relative to the surface it moves inside. */\nexport type CarryTransform = {\n readonly dx: number;\n readonly dy: number;\n readonly scale: number;\n};\n\nexport const NO_MOVEMENT: CarryTransform = { dx: 0, dy: 0, scale: 1 };\n\n/** A rect expressed against the container's STILL reference. */\nexport type LocalRect = {\n readonly x: number;\n /**\n * How far the element sits from whatever stands still — see `pinEdge`.\n *\n * PINNED TO AN EDGE it is the distance from that edge to the element's matching edge,\n * and it only ever grows away from the pin: both `top` and `bottom` count upward from\n * zero, in opposite directions in screen terms.\n *\n * CENTRED there is no edge to count from, so it is the SIGNED distance between the\n * container's centre line and the element's own, positive downward. The sign is the\n * point: an element above the middle and one below it are both real positions, and a\n * magnitude alone could not tell them apart.\n */\n readonly offset: number;\n readonly width: number;\n readonly height: number;\n};\n\n/** Where the element sits relative to whatever is standing still, in viewport px. */\nfunction stillOffset(rect: Rect, container: Rect, align: BlockAlignment): number {\n switch (align) {\n case 'top':\n return rect.y - container.y;\n case 'bottom':\n return container.y + container.height - (rect.y + rect.height);\n case 'center':\n /* Centre to centre, and SIGNED — see `LocalRect.offset`. */\n return rect.y + rect.height / 2 - (container.y + container.height / 2);\n }\n}\n\n/** A viewport rect expressed against its container's still reference, in LAYOUT space. */\nexport function toLocal(rect: Rect, container: Rect, align: BlockAlignment, scale = 1): LocalRect {\n const s = scale > 0 ? scale : 1;\n\n return {\n x: (rect.x - container.x) / s,\n offset: stillOffset(rect, container, align) / s,\n width: rect.width / s,\n height: rect.height / s,\n };\n}\n\n/**\n * HOW MUCH TALLER THE SURFACE AND THE CLIP INSIDE IT ARE ABOUT TO BE, in layout px.\n *\n * TWO BOXES AND NOT ONE, because a single \"growth\" cannot say where the gain lands. The\n * chrome hangs off the surface's top; the planes hang in the CLIP, which is the top of the\n * surface less whatever the bay takes from its foot. Grow the bay alone and the chrome has\n * not moved while the clip has.\n */\nexport type SurfaceGrowth = {\n /** What the surface's own content box gains. */\n readonly surface: number;\n /**\n * What the clip gains — the box every plane is laid out in.\n *\n * MEASURED, NOT WORKED OUT FROM THE OTHER TWO. At rest the clip is the surface less the\n * bay, and it used to be taken as exactly that. But the bay a pill opens with is taller\n * than the pill, and a box cannot be negative: the clip sits at nothing, the difference\n * put it 144px above that, and every carry into the card landed that far short and\n * snapped when the layer was torn down.\n */\n readonly clip: number;\n /**\n * What the plane's own block-end gutter gains — negative wherever a bay opening takes\n * it away. The plane grows by it at its foot, so content hung from that foot rises by\n * all of it and content hung from the middle by half.\n */\n readonly gutter: number;\n};\n\n/** Nothing is about to change — a move inside one shape. */\nexport const NO_GROWTH: SurfaceGrowth = Object.freeze({ surface: 0, clip: 0, gutter: 0 });\n\n/**\n * WHICH OF THE SURFACE'S TWO BOXES A DESTINATION IS LAID OUT IN, which is the same\n * question as which edge it is pinned to — see `SurfaceGrowth`.\n */\nexport type CarryAnchor = 'CHROME' | 'PLANE';\n\n/**\n * How far a destination's content travels before the move ends, measured DOWNWARD from\n * the surface's top edge.\n *\n * The chrome is pinned to that edge, so it does not move relative to it at all. A plane\n * hangs in the clip, whose top IS that edge, and WHERE in the clip it hangs is the\n * alignment's — the stylesheet anchors the planes with the frame. From the clip's top\n * nothing below can move it; from its foot it travels by everything the clip gains, less\n * the gutter the plane grows underneath; from its middle, by half of both.\n *\n * IT TOOK NO ALIGNMENT, AND EVERY PLANE WAS HUNG FROM THE FOOT. A top-aligned card\n * collapsing to its pill read the pill's avatar as riding the card's foot 412px up, and\n * flew the carry off the top of the screen before it snapped back. Centred, the same\n * error at half the size.\n */\nfunction anchorTravel(growth: SurfaceGrowth, anchor: CarryAnchor, align: BlockAlignment): number {\n if (anchor === 'CHROME') return 0;\n\n switch (align) {\n case 'top':\n return 0;\n case 'bottom':\n return growth.clip - growth.gutter;\n case 'center':\n return (growth.clip - growth.gutter) / 2;\n default: {\n const exhaustive: never = align;\n return exhaustive;\n }\n }\n}\n\n/**\n * A destination corrected for the shape the surface is ABOUT to be.\n *\n * The measurement is taken against the surface as it stands, but the element will be\n * laid out against the surface once it has grown — so the correction is however far the\n * still reference and the element's own box drift apart in between.\n *\n * `offset` is a distance from whatever stands still (see `LocalRect`), and what stands\n * still is the island's ALIGNMENT: the top edge, the bottom edge, or the centre line.\n * TOP counts the content's own travel. BOTTOM counts what is left of the surface's gain\n * once the content has taken its share. CENTRE takes the content's travel less half the\n * gain, because the middle moves by half of everything the surface adds.\n */\nexport function forSurfaceGrowth(\n rect: LocalRect,\n growth: SurfaceGrowth,\n anchor: CarryAnchor,\n align: BlockAlignment,\n): LocalRect {\n const travel = anchorTravel(growth, anchor, align);\n\n switch (align) {\n case 'top':\n return { ...rect, offset: rect.offset + travel };\n case 'bottom':\n return { ...rect, offset: rect.offset + growth.surface - travel };\n case 'center':\n /* Signed and positive downward, so rising by half the gain SUBTRACTS. */\n return { ...rect, offset: rect.offset + travel - growth.surface / 2 };\n default: {\n const exhaustive: never = align;\n return exhaustive;\n }\n }\n}\n\n/**\n * The transform that puts an element drawn at `to` back on top of `from` — the FLIP\n * inversion. Apply it, then remove it with a transition, and the element appears to\n * travel from one to the other.\n */\nexport function carryTransform(\n from: LocalRect,\n to: LocalRect,\n align: BlockAlignment,\n): CarryTransform {\n return {\n dx: from.x - to.x,\n /*\n * BOTTOM IS THE ODD ONE OUT, because its offsets run the other way: pinned to the\n * bottom edge, a LARGER offset is HIGHER up the screen, so the subtraction flips. Top\n * and centre both count downward — centre signed, top from zero — and `dy` is CSS\n * pixels, which are downward too.\n */\n dy: align === 'bottom' ? to.offset - from.offset : from.offset - to.offset,\n scale: to.width === 0 ? 1 : from.width / to.width,\n };\n}\n\n/** Whether a carried element needs ANIMATING. Not whether it needs carrying. */\nexport function isStationary(transform: CarryTransform, tolerance = 0.5): boolean {\n return (\n Math.abs(transform.dx) < tolerance &&\n Math.abs(transform.dy) < tolerance &&\n !isResized(transform)\n );\n}\n\n/** Whether the two ends are different SIZES — a change of ROLE rather than of place. */\nexport function isResized({ scale }: CarryTransform, tolerance = 0.01): boolean {\n return Math.abs(scale - 1) >= tolerance;\n}\n\n/** The horizontal leg, for the outer box. */\nexport function toCssSlide({ dx }: CarryTransform): string {\n return `translateX(${dx}px)`;\n}\n\n/**\n * WHERE A CARRIED ELEMENT IS PUT, as the inset that puts it there.\n *\n * THE PIN EDGE IS THE INSET PROPERTY, and that is not a coincidence — it is the same\n * fact said twice. `offset` is a distance from whatever stands still, and where that is\n * an edge, the CSS inset of the same name is exactly the property that means \"this far\n * from that edge\". So the value and the property came from one word: `[align]: '40px'`.\n *\n * It only worked while every alignment HAD a pin edge. Centred there is none — see\n * `pinEdge`, which returns `null` and makes the gap something you have to answer for\n * rather than something that falls through — so a centred element is placed by its own\n * middle instead: half the container, plus the signed offset, less half the element.\n */\nexport function toCssInset(\n offset: number,\n height: number,\n align: BlockAlignment,\n): Readonly<Record<string, string>> {\n const edge = pinEdge(align);\n\n return edge === null\n ? { top: `calc(50% + ${offset - height / 2}px)` }\n : { [edge]: `${offset}px` };\n}\n\n/**\n * HOW FAR THE ELEMENT REACHES from whatever is standing still — its FAR edge, measured\n * the way `offset` measures its near one.\n *\n * Pinned to an edge, the far edge is simply `offset + height`: the near edge plus the\n * element. Centred, `offset` is a signed centre-to-centre distance, so the far edge is\n * `|offset|` — how far off the middle it sits, whichever side — plus its own half.\n */\nexport function farEdge(rect: LocalRect, align: BlockAlignment): number {\n return align === 'center' ? Math.abs(rect.offset) + rect.height / 2 : rect.offset + rect.height;\n}\n\n/**\n * WHICH AXIS LEADS THE ARC — the one that starts first and gets the lead easing, leaving\n * the other to trail. What decides it is whether the element is moving TOWARD the still\n * reference or away from it: collapsing into the pill draws the eye down, so the\n * vertical leads; opening out of it travels mostly sideways, so the horizontal does.\n *\n * ── IT TAKES `align`, AND IT DID NOT ─────────────────────────────────────────\n *\n * This compared `offset + height` directly and so read `offset` as a distance from an\n * EDGE. That was true while the only alignments had one. A centred island's offset is\n * signed and measured from the middle, and the same expression then compares two numbers\n * that mean something else — quietly, because nothing in the old signature mentioned\n * alignment and a wrong answer here is a plausible-looking arc rather than an error.\n */\nexport function carryLead(from: LocalRect, to: LocalRect, align: BlockAlignment): 'x' | 'y' {\n return farEdge(to, align) < farEdge(from, align) ? 'y' : 'x';\n}\n\n/**\n * The vertical leg, for the inner box — as the INDEPENDENT `translate` property rather\n * than a `transform`.\n */\nexport function toCssLift({ dy }: CarryTransform): string {\n return `0 ${dy}px`;\n}\n\n/** The size leg, as the independent `scale` property. Always with the morph. */\nexport function toCssGrow(rect: LocalRect, raster: LocalRect): string {\n return `${rasterScale(rect, raster)}`;\n}\n\n/** Which END of the move the copy is drawn from — the larger one, always. */\nexport function carryRaster(from: LocalRect, to: LocalRect): LocalRect {\n return drawsFromLeaving(from, to) ? from : to;\n}\n\n/** Whether the larger end — the one the overlay draws — is the one being left. */\nexport function drawsFromLeaving(from: LocalRect, to: LocalRect): boolean {\n return from.width > to.width;\n}\n\n/**\n * What one end of the move is, as a fraction of the raster it is drawn in — so the copy\n * is scaled to `from` at the start and to `to` at rest.\n */\nexport function rasterScale(rect: LocalRect, raster: LocalRect): number {\n return raster.width === 0 ? 1 : rect.width / raster.width;\n}\n","import type { ReactNode } from 'react';\nimport type { CarryHome } from './CarrySlot';\nimport type { LocalRect } from './island-carry';\nimport type { IslandPresentation, SlotState } from './island-geometry';\nimport type { IslandGesture } from './island-press';\n\n/** The host's own state, as ONE value. */\nexport type IslandTransition =\n | { readonly phase: 'REST'; readonly slots: SlotState }\n /**\n * The \"before\" frame. The incoming plane is mounted but not yet revealed and every\n * carried element is drawn back where it came from — a CSS transition needs a starting\n * style to move from, and this is that style, held for exactly one frame.\n */\n | {\n readonly phase: 'PLACED';\n readonly slots: SlotState;\n readonly outgoing: ReactNode;\n /** The presentation the leaving content was laid out in. */\n readonly outgoingPresentation: IslandPresentation;\n /**\n * What led this move — see `IslandGesture`, which is where the three answers and their\n * reasons are.\n */\n readonly led: IslandGesture;\n readonly carries: readonly Carry[];\n }\n /** The inversion has been dropped and everything is on its way. */\n | {\n readonly phase: 'RELEASED';\n readonly slots: SlotState;\n readonly outgoing: ReactNode;\n readonly outgoingPresentation: IslandPresentation;\n readonly led: IslandGesture;\n readonly carries: readonly Carry[];\n };\n\n/**\n * A shared element the overlay has taken over for the length of one step change: laid\n * out at `to` and inverted until it is released.\n */\nexport type Carry = {\n readonly name: string;\n readonly node: ReactNode;\n readonly to: LocalRect;\n /**\n * The size the copy is LAID OUT at, which is the larger of its two ends — see\n * `carryRaster`. The position is still `to`'s; only the raster differs.\n */\n readonly box: { readonly width: number; readonly height: number };\n /**\n * WHERE the node the overlay draws comes from. The LARGER end, so the copy is\n * rasterized at the size it is biggest and only ever scaled down — see `carryRaster`.\n * The two ends are different nodes, not one node at two sizes.\n */\n readonly source: CarryHome;\n readonly slide?: string;\n readonly lift?: string;\n /** The scale at the start of the move, against `box`. */\n readonly grow?: string;\n /** The scale at rest, against `box`. 1 whenever `box` is the destination. */\n readonly rest?: string;\n /** Which axis leads the arc — see `carryLead`. */\n readonly lead?: 'x' | 'y';\n};\n\nexport type IslandTransitionEvent =\n /** A new `contentKey` was rendered. `slots` is the advance it produced. */\n | {\n readonly type: 'CONTENT_CHANGED';\n readonly slots: SlotState;\n readonly outgoing: ReactNode;\n readonly outgoingPresentation: IslandPresentation;\n readonly led: IslandGesture;\n }\n /** Both planes were read in one layout pass. */\n | { readonly type: 'CARRIES_MEASURED'; readonly carries: readonly Carry[] }\n /** The browser has painted the \"before\" frame. */\n | { readonly type: 'PAINTED' }\n /** The whole timeline has run. */\n | { readonly type: 'SETTLED' };\n\n/** One frozen empty list, so a resting host hands out a stable identity. */\nexport const NO_CARRIES: readonly Carry[] = Object.freeze([]);\n\nexport function atRest(slots: SlotState): IslandTransition {\n return { phase: 'REST', slots };\n}\n\nexport function reduceTransition(\n state: IslandTransition,\n event: IslandTransitionEvent,\n): IslandTransition {\n switch (event.type) {\n case 'CONTENT_CHANGED':\n // Interrupting a move that is already running is ordinary — a buyer can change\n // step faster than 550ms.\n return {\n phase: 'PLACED',\n slots: event.slots,\n outgoing: event.outgoing,\n outgoingPresentation: event.outgoingPresentation,\n led: event.led,\n carries: NO_CARRIES,\n };\n\n case 'CARRIES_MEASURED':\n // Only the frame they were measured in can use them.\n return state.phase === 'PLACED' ? { ...state, carries: event.carries } : state;\n\n case 'PAINTED':\n return state.phase === 'PLACED' ? { ...state, phase: 'RELEASED' } : state;\n\n case 'SETTLED':\n // Identity when there was nothing to settle: a no-op event must not cost the host\n // a render.\n return state.phase === 'REST' ? state : atRest(state.slots);\n }\n}\n","import { createContext, useContext, type ReactNode } from 'react';\nimport type { IslandPresentation } from './island-geometry';\n\n/**\n * ONE ISLAND ACROSS TWO COMPONENTS — what the widget was showing at the instant it was\n * replaced by a different face of itself.\n *\n * ── WHY THIS EXISTS AT ALL ───────────────────────────────────────────────────\n *\n * `ScopeTicketsCheckout` has four faces and they are four COMPONENTS: the resting card,\n * the purchase walk, and the booking a purchase ends at. Each mounts its own `IslandHost`,\n * and React swaps one for another by unmounting the first — so the host that knew what was\n * on screen is gone by the time the host that has to move away from it exists. `IslandHost`\n * starts every mount `atRest`, which is the right default and is exactly why the Follow\n * prompt CUT to the booking instead of morphing into it: there was nothing to leave.\n *\n * THE THREE FACES CANNOT SIMPLY SHARE A HOST. Every reading each of them makes is about a\n * state the others do not have — an order, a walk, a hold, a booking — so hoisting the host\n * above them means threading all of that through one component, which is the thing\n * `ScopeTicketsCheckout`'s own note says it split them up to avoid.\n *\n * ── IT IS A HANDOVER, NOT A CACHE ────────────────────────────────────────────\n *\n * The memory is written by a LAYOUT-EFFECT CLEANUP, read by a LAYOUT EFFECT, and thrown\n * away on the next microtask — which together make \"these two are the same island\" a fact\n * rather than a guess. See `rememberIsland`, where that is argued.\n *\n * ── THE NAME IS THE IDENTITY, AND IT IS DELIBERATELY NOT AUTOMATIC ───────────\n *\n * Two islands on one page that both claimed continuity would hand each other their\n * contents. The name comes from `IslandContinuityContext`, which only\n * `ScopeTicketsCheckout` provides — so the three faces it swaps between are one island and\n * a `BookingIsland` a host mounted on its own page is another, with no name and no memory.\n */\nexport type IslandMemory = {\n /** What the leaving host was showing — the key the arriving one moves AWAY from. */\n readonly contentKey: string;\n readonly children: ReactNode;\n readonly chrome: ReactNode;\n readonly presentation: IslandPresentation;\n /**\n * THE SURFACE'S HEIGHT AS IT STOOD, and the morph does not run without it: `height` is a\n * CSS transition, so the arriving host has to PAINT the height it is leaving before it\n * can travel from it. A fresh mount has no previous frame to supply one.\n */\n readonly height: number | null;\n};\n\nconst MEMORY = new Map<string, IslandMemory>();\n\n/**\n * Left behind by a host on its way out, and it expires at the end of the current task.\n *\n * ── THE MICROTASK IS WHAT MAKES \"THE SAME COMMIT\" OBSERVABLE ─────────────────\n *\n * React's commit phase is synchronous: an unmounting tree's layout cleanups and a mounting\n * tree's layout effects run in one uninterrupted block, so a host arriving in the same\n * commit takes this before anything queued here can run. A host that arrives LATER — a page\n * that put the widget back, a test that renders a fresh one after the last was torn down —\n * finds nothing, which is right: it has no previous frame to move away from and should\n * start at rest.\n *\n * A TIMESTAMP CANNOT DRAW THAT LINE. A buyer can sit on the Follow prompt for a minute\n * before pressing anything, so the last thing that island rendered is a minute old by the\n * time it hands over; there is no window that admits that and excludes a remount half a\n * second later. \"Did these two happen without the event loop turning\" is the actual\n * question, and this is how it is asked.\n *\n * Overwrites — the last host standing is the one that left.\n */\nexport function rememberIsland(name: string, memory: IslandMemory): void {\n MEMORY.set(name, memory);\n queueMicrotask(() => {\n /* Only its own: a host that arrived and left again in the meantime owns the slot now. */\n if (MEMORY.get(name) === memory) MEMORY.delete(name);\n });\n}\n\n/** TAKEN, not read: a handover is spent by the host that arrives to answer it. */\nexport function recallIsland(name: string): IslandMemory | null {\n const memory = MEMORY.get(name);\n if (memory === undefined) return null;\n MEMORY.delete(name);\n return memory;\n}\n\n/**\n * Empty the registry. For tests, which mount and unmount islands in one process and would\n * otherwise hand the next test's island the last one's card — the same service\n * `forgetAccessory` does for `@scopetickets/avatar`.\n */\nexport function forgetIslands(): void {\n MEMORY.clear();\n}\n\n/**\n * WHICH ISLAND A HOST IS PART OF, or `undefined` for one that is only itself.\n *\n * A context rather than a prop so it does not reach the public surface: a host mounting\n * `BookingIsland` on its own page is not opting in or out of anything, it simply is not\n * inside the widget that swaps faces.\n */\nexport const IslandContinuityContext = createContext<string | undefined>(undefined);\n\nexport function useIslandContinuity(): string | undefined {\n return useContext(IslandContinuityContext);\n}\n\n/** The one name in this package. See the context's note for why there is exactly one. */\nexport const CHECKOUT_CONTINUITY = 'scopetickets:checkout';\n","import { useIslandPress } from './island-press';\n\n/**\n * NOTHING OUTSIDE THE ISLAND MAY BE PRESSED.\n *\n * A sheet over the whole viewport, for the one state that admits no input at all: the\n * payment is in flight, there is no way out and nothing to go back to, and a buyer who\n * wanders off to press something else on the host's page is doing so while their money\n * moves. `PurchaseStep.collapsed` already says this in words — \"input is blocked\n * entirely\" — and this is that sentence with an element behind it.\n *\n * IT ANSWERS RATHER THAN IGNORING. A dead page is indistinguishable from a frozen one, so\n * a press here compresses the island and lets it spring back: the same gesture the pill\n * uses, on the same clock, saying \"still here, still working\" without a word of copy.\n * `useIslandPress('island')` is the whole implementation — the surface already knows how\n * to be pressed, and this is one more thing pressing it.\n *\n * ── WHERE IT HAS TO LIVE ─────────────────────────────────────────────────────\n *\n * Inside the press context, so it can reach the surface — and OUTSIDE the frame, which\n * is `position: fixed`'s one hard requirement here: a transform or a backdrop filter on\n * an ancestor makes that ancestor the containing block, and the island's frame carries\n * a transform when centred while the surface now carries a filter. Fixed inside either\n * would cover the card rather than the page. The anchor has neither, which is why the\n * shield is handed down to it rather than rendered where it is decided.\n *\n * It is drawn BEFORE the frame and takes no `z-index`: two positioned siblings paint in\n * document order, so the island stays above its own shield without either of them\n * having to name a layer.\n */\nexport function IslandShield() {\n const press = useIslandPress('island');\n\n return (\n <div\n className=\"scopetickets-island-shield\"\n /*\n * Not a control and not a label — there is nothing here to do. It exists to stop\n * presses reaching the page, and announcing it would be announcing an obstacle.\n */\n aria-hidden=\"true\"\n {...press}\n />\n );\n}\n","import { forwardRef, type CSSProperties, type ReactNode, type Ref } from 'react';\nimport {\n ARC_LEAD_EASING,\n ARC_TRAIL_EASING,\n CARRY_MOVE_DELAY_MS,\n CARRY_MOVE_MS,\n CARRY_SPRING,\n INCOMING_FADE_DELAY_MS,\n INCOMING_FADE_MS,\n OUTGOING_FADE_MS,\n POP_MS,\n POP_RETURN_SPRING,\n POP_SCALE,\n SHIELD_POP_SCALE,\n POP_RETURN_MS,\n PRESS_IN_MS,\n SURFACE_MORPH_DELAY_MS,\n SURFACE_MORPH_MS,\n SURFACE_SPRING,\n ISLAND_TRANSITION_MS,\n springEasing,\n} from './island-motion';\n\n/**\n * Sampled once at module load, not per render. A spring curve is forty evaluations of\n * an exponential; recomputing it on every frame of a transition would be the one piece\n * of arithmetic here that could actually be felt.\n */\nconst SURFACE_EASING = springEasing(SURFACE_SPRING);\nconst CARRY_EASING = springEasing(CARRY_SPRING);\nconst POP_RETURN_EASING = springEasing(POP_RETURN_SPRING);\nimport { modeAttribute, type IslandMode } from './island-theme';\nimport {\n alignmentAxes,\n type IslandAlignment,\n type IslandPlacement,\n type PlanePadding,\n} from './island-geometry';\nimport type { IslandGesture, PressPhase } from './island-press';\n\nexport type IslandSurfaceProps = {\n /** Corner radius in px, from `frameFor`. */\n radius: number;\n /** Inner padding in px, per axis, from `frameFor`. */\n padding: PlanePadding;\n /** Max width in px, or `null` to fill the container. */\n maxWidth: number | null;\n /** Shared header-row height in px, from `frameFor`. */\n rowHeight: number;\n /** Inset from the container's edge in px, from `frameFor`. */\n edge: number;\n /**\n * Where in the anchor the frame sits, stamped as ONE ATTRIBUTE PER AXIS —\n * `data-align-block` and `data-align-inline` — because the stylesheet's rules are per\n * axis. The block half moves the frame, the planes and the pop's origin together, and\n * those must never disagree; the inline half only picks the side the frame docks to.\n * See `alignmentAxes`.\n */\n align: IslandAlignment;\n /**\n * Where the ANCHOR is held — see `IslandPlacement`. Stamped on the anchor as\n * `data-placement` only when it is `screen`, with the block half of `align` beside it:\n * the rules that pin the reservation to an edge of the viewport are per block axis,\n * exactly as the frame's are.\n */\n placement: IslandPlacement;\n /**\n * How far a pinned reservation stands off the screen's edge, in px — the COLLAPSED\n * frame's `edge`, for the reason `footprint` is the collapsed height: the reservation is\n * the island at rest, whatever it is showing now.\n */\n footprintEdge: number;\n /**\n * THE PROVIDER'S FULLSCREEN JOURNEY, stamped as `data-journey`. Two rules hang off\n * it, and they hang off the ROOT because both are about what the root's own\n * geometry does to a fixed-position descendant: the journey overlay has to escape\n * the island entirely, and a centred island's `translateY(-50%)` would otherwise\n * become the overlay's containing block instead of the viewport.\n */\n journeyFullscreen?: boolean;\n /**\n * Where the press gesture has got to, or `undefined` when nothing is being pressed.\n * Stamped as `data-press`.\n */\n press?: PressPhase | null;\n /**\n * How the move should be acknowledged, or `undefined` when nothing is moving. Stamped\n * as the VALUE of `data-transitioning`. See `IslandGesture` for the three answers and\n * why a boolean could not hold them.\n */\n gesture?: IslandGesture;\n /** True while a step change is in flight. */\n transitioning?: boolean;\n /** Which appearance to render, or `undefined` to follow the viewer's OS. */\n mode?: IslandMode;\n /**\n * The height the surface is to be, in px — the plane's measurement AND the bay's,\n * already added up by `IslandHost`, which is the one place that knows both. `null`\n * before the first measurement renders at `auto`, because a 0-height first paint would\n * flash an empty box on mount.\n */\n height: number | null;\n /** Names the region for assistive technology. */\n label: string;\n /**\n * The height reserved in the host page's flow, in px — `footprintHeight` of the\n * island's COLLAPSED presentation, not its current one.\n */\n footprint: number;\n /** WHICH AXES THE POP IS SPENT ON — `both`, or `block` alone. */\n popAxis?: 'both' | 'block';\n /**\n * THE BAY — a region that joins and leaves the card WITHOUT belonging to any\n * step, so its contents survive every plane change. The clip tears down and rebuilds\n * both planes on a step change; a payment frame mounted there would be destroyed at\n * the exact moment it must not be. Like `chrome`, the bay is a sibling of the clip\n * inside the surface, but at the other end: it grows the card instead of sitting\n * over its content.\n */\n bay?: ReactNode;\n /**\n * The bay's own box, in px — `0` while it is closed. Published as\n * `--scopetickets-island-bay-height`, which is the bay element's own height and\n * nothing else's: the clip takes what is left of the surface by FLEX rather than by\n * subtracting this var, so the two cannot be told different numbers.\n */\n bayHeight?: number | null;\n /** The element children are actually positioned inside. */\n clipRef?: Ref<HTMLDivElement>;\n children: ReactNode;\n /**\n * The persistent chrome — `IslandHeader`, drawn over both planes and rebuilt by\n * neither.\n */\n chrome?: ReactNode;\n /**\n * Drawn OUTSIDE the clip, as a sibling of it — the carry layer, and so far the only\n * thing that belongs there.\n */\n overlay?: ReactNode;\n /**\n * A sheet over the viewport, for a state that admits no input — see `IslandShield`.\n * Taken HERE rather than anywhere inside the frame because it is `position: fixed` and\n * the frame's transform would become its containing block.\n */\n shield?: ReactNode;\n /**\n * Nothing may be pressed — see `IslandShield`. Softens the pop, because the press it is\n * answering did not do anything.\n */\n sealed?: boolean;\n};\n\n/** The island's own box — fill, stroke, radius, and the frame it animates. */\nexport const IslandSurface = forwardRef<HTMLDivElement, IslandSurfaceProps>(function IslandSurface(\n {\n radius,\n padding,\n maxWidth,\n rowHeight,\n edge,\n align,\n placement,\n journeyFullscreen,\n popAxis = 'both',\n press,\n gesture,\n mode,\n transitioning,\n height,\n label,\n footprint,\n footprintEdge,\n clipRef,\n bay,\n bayHeight,\n children,\n chrome,\n overlay,\n shield,\n sealed = false,\n },\n ref,\n) {\n const axes = alignmentAxes(align);\n /* Only a pinned anchor stamps anything: `page` is the base rule, and has no block. */\n const pinned = placement === 'screen';\n const style = {\n '--scopetickets-island-radius': `${radius}px`,\n '--scopetickets-island-padding-block': `${padding.block}px`,\n '--scopetickets-island-padding-inline': `${padding.inline}px`,\n '--scopetickets-island-max-width': maxWidth === null ? '100%' : `${maxWidth}px`,\n '--scopetickets-island-row': `${rowHeight}px`,\n '--scopetickets-island-edge': `${edge}px`,\n // The whole timeline, published from TypeScript so the CSS and the teardown timer\n // cannot disagree.\n '--scopetickets-island-fade-out-ms': `${OUTGOING_FADE_MS}ms`,\n '--scopetickets-island-morph-delay': `${SURFACE_MORPH_DELAY_MS}ms`,\n '--scopetickets-island-morph-ms': `${SURFACE_MORPH_MS}ms`,\n '--scopetickets-island-fade-in-delay': `${INCOMING_FADE_DELAY_MS}ms`,\n '--scopetickets-island-fade-in-ms': `${INCOMING_FADE_MS}ms`,\n '--scopetickets-island-carry-delay': `${CARRY_MOVE_DELAY_MS}ms`,\n '--scopetickets-island-carry-ms': `${CARRY_MOVE_MS}ms`,\n /* The WHOLE move, which is what the bay's out-and-back keyframe runs over. */\n '--scopetickets-island-swap-ms': `${ISLAND_TRANSITION_MS}ms`,\n // The arc — one window, two curve shapes.\n '--scopetickets-island-arc-lead-ease': ARC_LEAD_EASING,\n '--scopetickets-island-arc-trail-ease': ARC_TRAIL_EASING,\n '--scopetickets-island-spring': SURFACE_EASING,\n '--scopetickets-island-carry-spring': CARRY_EASING,\n // The pop: contract, then spring back.\n '--scopetickets-island-pop-ms': `${POP_MS}ms`,\n '--scopetickets-island-pop-scale': `${sealed ? SHIELD_POP_SCALE : POP_SCALE}`,\n '--scopetickets-island-press-ms': `${PRESS_IN_MS}ms`,\n '--scopetickets-island-pop-return-ms': `${POP_RETURN_MS}ms`,\n '--scopetickets-island-pop-return-spring': POP_RETURN_EASING,\n /*\n * THE SURFACE'S HEIGHT IS A SUM, and it was added up before it got here — see\n * `height`. The bay growing rides the surface's own `height:` transition, which is\n * the island's one height clock, rather than a second one of its own.\n */\n ...(height === null ? {} : { '--scopetickets-island-height': `${height}px` }),\n ...(bayHeight === null || bayHeight === undefined\n ? {}\n : { '--scopetickets-island-bay-height': `${bayHeight}px` }),\n } as CSSProperties;\n\n return (\n // The reservation, and nothing else: it holds the island's collapsed footprint open\n // in the host page's flow — or, placed on the screen, pinned to it — and gives the\n // frame something to be positioned against.\n <div\n data-scopetickets-island-anchor\n data-placement={pinned ? 'screen' : undefined}\n data-align-block={pinned ? axes.block : undefined}\n className=\"scopetickets-island-anchor\"\n style={\n {\n '--scopetickets-island-anchor-height': `${footprint}px`,\n ...(pinned ? { '--scopetickets-island-anchor-inset': `${footprintEdge}px` } : {}),\n } as CSSProperties\n }\n >\n {/* Before the frame, so the island paints over it without either naming a layer. */}\n {shield}\n <div\n ref={ref}\n /*\n * THE ISLAND'S OWN SCOPE, AND ONLY ITS OWN — never the host's picker attribute,\n * which this wore once and leaked a host's theme in through. See `pickers.css`.\n */\n data-scopetickets-island\n data-mode={modeAttribute(mode)}\n data-align-block={axes.block}\n data-align-inline={axes.inline}\n data-journey={journeyFullscreen ? 'fullscreen' : undefined}\n // Only the narrowing case is stamped: `both` is the default the token already\n // holds, and an attribute asserting a default is one more thing that can\n // disagree with it.\n data-pop-axis={popAxis === 'block' ? 'block' : undefined}\n data-press={press ?? undefined}\n data-sealed={sealed ? '' : undefined}\n data-transitioning={transitioning ? (gesture ?? 'none') : undefined}\n className=\"scopetickets-island-frame\"\n style={style}\n >\n <div className=\"scopetickets-island-surface\">\n <div\n ref={clipRef}\n className=\"scopetickets-island-surface__clip\"\n role=\"region\"\n aria-label={label}\n >\n {children}\n </div>\n {bay}\n {chrome}\n {overlay}\n </div>\n </div>\n </div>\n );\n});\n","/** How the island is told which appearance to render. */\n\n/**\n * Three states, not two — matching the SDK's own `ThemeSelectionMode`, so a consumer\n * that already holds one can pass it straight through.\n */\nexport type IslandMode = 'light' | 'dark' | 'system';\n\n/** The `data-mode` attribute to stamp on the surface, or `undefined` to stamp none. */\nexport function modeAttribute(mode: IslandMode = 'system'): 'light' | 'dark' | undefined {\n return mode === 'system' ? undefined : mode;\n}\n","import type { ReactNode } from 'react';\nimport { useIslandPress } from './island-press';\n\nexport type IslandPillProps = {\n /**\n * The round preview at the leading edge — a\n * `.scopetickets-island-avatar.scopetickets-island-avatar--sm` element, `$10` across.\n */\n readonly avatar?: ReactNode;\n /**\n * The quiet line above the title. Optional — the design ships it hidden, which is what\n * makes it optional rather than empty.\n */\n readonly subtitle?: ReactNode;\n /** The line that carries the number. `heading/lg`. */\n readonly title?: ReactNode;\n /** The label on the action. `text/bold/md`, e.g. Figma's \"Get Ticket\". */\n readonly actionLabel: ReactNode;\n readonly onAction: () => void;\n};\n\n/** The collapsed island — Figma `CtaCollapsedGetTicket`. */\nexport function IslandPill({ avatar, subtitle, title, actionLabel, onAction }: IslandPillProps) {\n // The pill's action opens the island, so it compresses the whole surface.\n const press = useIslandPress('island');\n\n return (\n <div className=\"scopetickets-island-pill\">\n <div className=\"scopetickets-island-pill__preview\">\n {avatar}\n {/*\n * THE WHOLE COLUMN GOES, not just the empty spans — otherwise the row keeps the gap it\n * was leaving for words that are not there.\n */}\n {subtitle === undefined && title === undefined ? null : (\n <span className=\"scopetickets-island-pill__text\">\n {subtitle === undefined ? null : (\n <span className=\"scopetickets-island-pill__subtitle\">{subtitle}</span>\n )}\n {title === undefined ? null : (\n <span className=\"scopetickets-island-pill__title\">{title}</span>\n )}\n </span>\n )}\n </div>\n\n {/*\n * PRIMARY, not Action: this is forward progress into the island, not the commitment at\n * the end of it. NearWhite100 on BlackNear100 text, which is `ButtonPrimaryBackground`\n * over `ButtonPrimaryText`.\n */}\n <button\n type=\"button\"\n className=\"scopetickets-island-button scopetickets-island-button--primary scopetickets-island-pill__action\"\n onClick={onAction}\n {...press}\n >\n {actionLabel}\n </button>\n </div>\n );\n}\n","import type { ReactNode } from 'react';\nimport { CarrySlot } from './CarrySlot';\nimport { IslandCard, type IslandAction } from './IslandCard';\nimport { IslandHeader } from './IslandHeader';\nimport { IslandHost } from './IslandHost';\nimport { useIslandContinuity } from './island-continuity';\nimport { IslandPill } from './IslandPill';\nimport type { IslandAlignment, IslandPlacement } from './island-geometry';\nimport type { IslandMode } from './island-theme';\n\nexport type CheckoutIslandProps = {\n /** Collapsed is the pill; expanded is the card. */\n readonly expanded: boolean;\n /** WHICH CARD is showing, when \"the card\" is not specific enough. */\n readonly contentKey?: string;\n /** The pill's action opens it; the card's header button closes it. */\n readonly onToggle: () => void;\n /**\n * The hero. This component supplies the SIZE the current state calls for — `$10` in the\n * pill, 100 in the card — and the carry identity that moves it between them. It does\n * NOT supply a shape.\n */\n readonly avatar?: ReactNode;\n /** `heading/lg` in the pill, `heading/xl` and centred in the card. */\n /**\n * The card's own title. A PICKER passes none: the entry step has already said at full\n * size what is being asked for, so the card opens on the run. The pill's line is\n * `IslandPillProps.title`, which is always drawn.\n */\n readonly title?: ReactNode;\n /** Above the title in the pill, below it in the card. */\n readonly subtitle?: ReactNode;\n /**\n * THE PILL'S OWN TWO LINES, which are NOT the card's.\n *\n * They were, and it read as nonsense: a card's copy is written for a card, and the pill\n * is one row that truncates — \"Already Have An Account?\" over \"You may qualify for\n * better pricing.\" came out as \"Already Hav…\" over \"You may qual…\", which says nothing\n * and looks broken. The pill's job is to state the price and the way in, not to\n * summarise the card behind it.\n *\n * ONE OBJECT, AND ITS PRESENCE IS THE DECISION. Supplying it means \"the pill's copy is\n * mine\", and EMPTY FIELDS INSIDE IT MEAN THE PILL SAYS NOTHING — which is a real answer\n * and the whole reason this is not two optional props. Two would have fallen back\n * field-by-field, so a caller with no price would have been handed the card's title\n * again, which is the thing being fixed.\n *\n * Omitting it entirely keeps the card's copy for both, so `CheckoutIsland` stays usable\n * on its own by a caller with one thing to say.\n */\n readonly pillCopy?: {\n readonly title?: ReactNode;\n readonly subtitle?: ReactNode;\n };\n /**\n * The card's own controls, between the hero and the buttons. The pill has no\n * counterpart — it is one row, and a collapsed island asking a question would be a\n * card.\n */\n readonly input?: ReactNode;\n /** Persistent content outside the replaceable step planes. */\n readonly bay?: ReactNode;\n readonly bayVisible?: boolean;\n /** How many entries the bay holds room for — see `IslandHostProps.bayRows`. */\n readonly bayRows?: number;\n /** Which card the expanded island is showing — see `IslandCardProps.variant`. */\n readonly variant?: 'default' | 'hold' | 'cart';\n /**\n * NOTHING MAY BE PRESSED, HERE OR ANYWHERE ELSE ON THE PAGE — one state, two\n * consequences, and they are the same sentence twice.\n *\n * The card loses its header, because the header IS the way out: a cross that cannot\n * close and a trailing pill that opens a view the buyer must not leave for. And the page gets\n * `IslandShield` over it, which answers a press with the island's own pop instead of\n * ignoring it.\n *\n * `PurchaseStep.collapsed` is where this comes from — a step declaring `NONE` says\n * \"input is blocked entirely; there is no way out and nothing to collapse to\".\n */\n readonly sealed?: boolean;\n /**\n * WHETHER THE HEADER DRAWS A WAY OUT. Defaults to true.\n *\n * SEPARATE FROM `sealed`, and it has to be. `sealed` is \"no header at all, and the\n * host's page is held\" — right while money moves, and wrong everywhere else, because the\n * header is not only the cross: it carries the compose funnel before there is a cart and\n * the cart-and-promo pill after, and a card that cannot be left still has both.\n */\n readonly closable?: boolean;\n /** The pill's action. */\n readonly actionLabel: ReactNode;\n /**\n * THE BUTTONS, SPLIT BY THE BAY. `actions` is what the card plane draws; when the\n * payment form is visible its card rides the form in the bay, and the card that acts\n * on the field — Confirm, Try Again — belongs BENEATH it, not above it. `bayActions`\n * draws there (same `CardAction`, same press); `actions` keeps only what stays\n * upstairs, which with the form showing is nothing.\n */\n readonly actions: readonly IslandAction[];\n /** A control of the card's own shape where the buttons go — see `IslandCardProps.footer`. */\n readonly footer?: ReactNode;\n readonly bayActions?: readonly IslandAction[];\n /**\n * Whether the card's header button steps BACK or closes the island. Drives the glyph,\n * which is the only thing telling a buyer which it is.\n */\n readonly dismiss?: 'back' | 'close';\n readonly dismissIcon?: ReactNode;\n readonly dismissLabel?: string;\n /** A second pill beside the card's way out — see `IslandCardProps.headerLead`. */\n readonly headerLead?: ReactNode;\n /** A pill at the OTHER end — the compose funnel, or the commit pill. See `IslandHeaderProps`. */\n readonly headerTrail?: ReactNode;\n /** Which appearance to render. Defaults to following the viewer's OS. */\n readonly mode?: IslandMode;\n /**\n * Where the island sits. The vertical half is which way it grows — away from its edge,\n * or both ways at once from the middle — and the horizontal half is which side of a\n * reservation wider than the card it docks to. Defaults to `bottom`.\n */\n readonly align?: IslandAlignment;\n /** Where the reservation is held — see `IslandPlacement`. Defaults to `page`. */\n readonly placement?: IslandPlacement;\n /**\n * THE PROVIDER'S FULLSCREEN JOURNEY IS OVER EVERYTHING, and stamping the root lets\n * the CSS both lift the journey over the host page and lift the centred island's\n * own transform out of the way of it. See `IslandSurfaceProps.journeyFullscreen`.\n */\n readonly journeyFullscreen?: boolean;\n};\n\n/** The island, as the design draws it: a pill that becomes a card. */\nexport function CheckoutIsland({\n expanded,\n contentKey,\n onToggle,\n avatar,\n title,\n subtitle,\n pillCopy,\n input,\n bay,\n bayVisible = false,\n bayRows,\n variant = 'default',\n sealed = false,\n closable = true,\n actionLabel,\n actions,\n footer,\n bayActions,\n dismiss,\n dismissIcon,\n dismissLabel,\n headerLead,\n headerTrail,\n mode,\n align,\n placement,\n journeyFullscreen,\n}: CheckoutIslandProps) {\n /*\n * THE TWO CARDS BESIDE THE FLOW FADE THEIR HERO RATHER THAN FLYING IT.\n *\n * A carry is for an element the buyer is FOLLOWING — the same avatar answering the next\n * question. The cart is a detour, opened from the header and left by one button, and the\n * timed-out card is news; both arrive wearing a different element than the step left with,\n * so flown it read as the avatar being thrown across the card to pick up a new badge.\n * Withholding the slot is the whole mechanism — the host finds no pair and leaves it to\n * the planes.\n */\n const flies = !(variant === 'hold' || variant === 'cart');\n\n /* `lg` is the hero's 100; the pill has no room for it and draws `$10`. */\n const hero =\n avatar === undefined ? undefined : (\n <span\n className={`scopetickets-island-avatar scopetickets-island-avatar--${expanded ? 'lg' : 'sm'}`}\n >\n {avatar}\n </span>\n );\n\n /* Carried where it should be, and bare where it should fade — never named for one of them. */\n const heroSlot =\n hero === undefined ? undefined : flies ? <CarrySlot name=\"avatar\">{hero}</CarrySlot> : hero;\n\n /*\n * COMPOSED, never substituted: the state leads, the caller's name only says WHICH card.\n * See `contentKey`'s own note for what substituting it cost.\n */\n const named = contentKey ?? 'island';\n const showing = expanded ? `card:${variant}:${named}` : `pill:${named}`;\n\n /*\n * Handed to the HOST rather than to the card, so it lives outside both planes and\n * survives every content change. `IslandHeader` has the measurements; the short version\n * is that a header inside a plane is rebuilt at every step, and a rebuilt header drops\n * the focus a keyboard buyer was holding.\n */\n /*\n * NEITHER CARD BESIDE THE FLOW DRAWS A HEADER: the cart is reached from the header\n * itself, and the timed-out card is what the header was counting down TO. Both hand the\n * way back to a button in the stack, and a cross on either would be a second way out of\n * a card that already has one.\n */\n const chrome =\n expanded && variant === 'default' && !sealed ? (\n <IslandHeader\n closable={closable}\n dismiss={dismiss}\n dismissIcon={dismissIcon}\n dismissLabel={dismissLabel}\n headerLead={headerLead}\n headerTrail={headerTrail}\n onDismiss={onToggle}\n />\n ) : undefined;\n\n /*\n * WHETHER THIS CARD IS PART OF A BIGGER ISLAND — see `island-continuity`. Read from\n * context rather than taken as a prop: a caller mounting one of these does not decide\n * whether it is the same island as something else, the thing that swaps them does.\n */\n const continuity = useIslandContinuity();\n\n return (\n <IslandHost\n // `compact` is the pill and `card` is the opened island.\n presentation={expanded ? 'card' : 'compact'}\n contentKey={showing}\n continuity={continuity}\n label=\"Your order\"\n mode={mode}\n align={align}\n placement={placement}\n journeyFullscreen={journeyFullscreen}\n chrome={chrome}\n bay={bay}\n bayActions={bayActions}\n bayVisible={expanded && bayVisible}\n bayRows={bayRows}\n /*\n * AND THE HOST'S PAGE IS HELD WITH IT. `IslandCard` takes this to drop its header\n * reserve; `IslandHost` takes it to draw `IslandShield`, which is the sheet over\n * the viewport. Passing it to the card alone seals the card and leaves the page\n * behind it live — a buyer could wander off and press something on the host's own\n * site while their money moves.\n */\n sealed={sealed}\n >\n {expanded ? (\n <IslandCard\n variant={variant}\n avatar={heroSlot}\n title={title}\n subtitle={subtitle}\n sealed={sealed}\n input={input}\n actions={actions}\n footer={footer}\n />\n ) : (\n <IslandPill\n avatar={heroSlot}\n subtitle={pillCopy === undefined ? subtitle : pillCopy.subtitle}\n title={pillCopy === undefined ? title : pillCopy.title}\n actionLabel={actionLabel}\n onAction={onToggle}\n />\n )}\n </IslandHost>\n );\n}\n","/**\n * SCOPETICKETSCHECKOUT — the widget a host mounts.\n *\n * Hand it an app key, what is being bought into, and whatever of the order is already\n * known. It works out which steps that leaves unanswered, asks them in order, and hands\n * back a complete intent.\n *\n * THE HOST SUPPLIES NO COPY, NO STYLING AND NO STEPS. That is the whole point of\n * deferring one: a host that did not want to build a calendar cannot then be asked what\n * the calendar's card should say. Everything drawn below comes from this package.\n *\n * OR HAND IT NOTHING TO SELL. `intent` is optional, and absent it mounts UNASSOCIATED:\n * one card about the buyer's account and no purchase at all, which is what belongs on a\n * page that is not selling anything. See `ScopeTicketsCheckout` below, which is the whole\n * of that decision.\n *\n * `CheckoutIsland` is the surface underneath — the morphing card and its motion. It\n * takes a title and some actions and knows nothing about purchases. This decides what\n * to put on it.\n */\n\nimport {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n type RefObject,\n} from 'react';\nimport { Avatar, defaultAvatarValue } from '@scopetickets/avatar';\nimport { ProcessingSlowIcon } from './status-glyphs';\nimport {\n ANONYMOUS_SESSION,\n authPrompt,\n buyerAvatarValue,\n type Account,\n type AuthSession,\n} from '../domain/auth';\nimport {\n answeredBuyer,\n excusedByIntent,\n intentHeadcount,\n refuseIntent,\n type OrderIntent,\n} from '../domain/order-intent';\nimport type { BookingOccasion, BookingRecord, TicketAttribution } from '../domain/booking';\nimport { useBookingGateway } from '../data/useBooking';\nimport { buyerDetails, orderBuyer } from '../domain/order-buyer';\nimport {\n cartIsHeld,\n orderStatusAt,\n pressCreatesOrder,\n timeoutTakesOver,\n} from '../domain/order-status';\nimport {\n DEFAULT_DIAL_CODE,\n e164,\n isCompleteName,\n isValidEmail,\n type PhoneValue,\n} from '../domain/contact';\nimport {\n accountFromCreation,\n chosenPhoto,\n addressForAccount,\n ACCOUNT_CREATION_ORDER,\n} from '../domain/account-creation';\nimport { answeredByReading, purchaseStep, type PurchaseStepId } from '../domain/purchase-steps';\nimport { clearedAfter, composeAnswered, composeFunnel } from '../domain/compose-funnel';\nimport { ComposeFunnel } from './ComposeFunnel';\nimport { IslandCommitPill } from './IslandCommitPill';\nimport type { FeedbackRating } from '../domain/feedback';\nimport { useFeedback } from '../data/useFeedback';\nimport { StarRating } from './StarRating';\nimport { formatMoney, quoteLines, type Quote } from '../domain/money';\nimport { stopIndex, walkPurchase, type FlowSituation, type RoutePlan } from '../domain/flow-walk';\nimport { useCheckoutClient, useCheckoutData, type CheckoutSource } from '../data/useCheckoutData';\nimport { useAccountGateway } from '../data/useAccountGateway';\nimport { useSignInGateway } from '../data/useSignInGateway';\nimport { usePasskeySignIn } from '../data/usePasskeySignIn';\nimport { useAuthFunnel } from '../data/useAuthFunnel';\nimport { useSessionGuard } from '../data/useSessionGuard';\nimport { usePasskeyRegistration } from '../data/usePasskeyRegistration';\nimport { useAccountCreation } from '../data/useAccountCreation';\nimport { useAuthSession, type AuthSessionStore } from '../data/useAuthSession';\nimport { PasskeyButton } from './PasskeyButton';\n\nimport type { PasskeyCeremony, PasskeyResult } from '../domain/passkey';\nimport { passkeySignInCeremony } from '../domain/sign-in';\nimport { funnelOpen, funnelOpenedBy } from '../domain/auth-funnel';\nimport { AUTH_COPY } from '../domain/auth-copy';\nimport { useCheckoutOrder } from '../data/useCheckoutOrder';\nimport { CheckoutIsland } from './CheckoutIsland';\nimport { PartyStepper, SOLO_KEY, type PartyUserTypeOption } from './PartyStepper';\nimport { partyTypes, type PartyTypes } from '../domain/user-types';\nimport { CartLines } from './CartLines';\nimport { ProfilePhotoPicker, type ProfilePhotoOption } from './ProfilePhotoPicker';\nimport { FollowList, type FollowEntity } from './FollowList';\nimport { TextField } from './TextField';\nimport { ConfirmEmailStep, EmailStep, NameStep, PasswordStep, PhoneStep } from './ContactSteps';\nimport { VerifyEmailStep } from './PasscodeField';\nimport {\n AUTH_CARDS,\n PICKER_LAYOUT,\n STEP_ACCESSORY,\n statusAccessory,\n CREATE_ORDER_LABEL,\n COMPOSE_FUNNEL_LABEL,\n PASSKEY_BUTTON_LABEL,\n POWERED_BY,\n STEP_CARD_ACTIONS,\n STEP_CARD_COPY,\n STEP_DISMISS,\n CART_VIEW,\n cartViewProps,\n holdBadge,\n NOTICE_STATUS,\n funnelViewProps,\n noticeViewProps,\n statusBadge,\n timedOutViewProps,\n accountCreatedTitle,\n paymentSuccessSubtitle,\n PROFILE_PHOTO_COPY,\n PROMO_COPY,\n OPENING_LABEL,\n UNCLOSABLE_STEPS,\n FEEDBACK_COPY,\n type CardAction,\n} from './step-cards';\nimport {\n defaultProfilePhotos,\n photoRefusal,\n type PhotoRefusalCode,\n type ProfilePhoto,\n} from '../domain/profile-photo';\nimport { promoApplied, promoSaved, promoSendable, type PromoWrite } from '../domain/promo';\nimport { avatarAssetsFor, heroAccessory, HERO_TRANSITION_KEY } from './island-hero';\nimport { RestingIsland } from './RestingIsland';\nimport { BookingIsland } from './BookingIsland';\nimport { CHECKOUT_CONTINUITY, IslandContinuityContext } from './island-continuity';\nimport {\n raiseFor,\n raiseForAccount,\n raiseForFeedback,\n raiseForSignIn,\n type NoticeAction,\n type NoticeId,\n} from '../domain/notices';\nimport type { IslandAlignment, IslandPlacement } from './island-geometry';\nimport type { IslandMode } from './island-theme';\nimport {\n ACCOUNT_CREATING_FLOOR_MS,\n HOLD_TICK_MS,\n PAID_GRACE_MS,\n PROCESSING_FLOOR_MS,\n} from './island-motion';\nimport { EyeToCenterIcon, EyeToCenterWithStrikethroughIcon } from '@scopetickets/icons';\nimport { formatHold, holdExpired, holdSince, sameHold, type EscrowHold } from './island-escrow';\nimport { cartLines as cartLinesFrom, type CartLine } from '../domain/cart';\nimport { DayPicker } from './DayPicker';\nimport { TimePicker } from './TimePicker';\nimport { eventKeyForDay, formatWeekdayAndDate, soonestRelevantDay } from './island-calendar';\nimport type { CalendarSeries } from './island-calendar';\nimport {\n formatSlotRange,\n timeslotRequest,\n withSelectedDay,\n withSelectedTime,\n type Timeslot,\n} from './island-timeslots';\nimport {\n ENVIRONMENT_URLS,\n type PaymentMethodStatus,\n type QuestionnaireQuestion,\n} from '@scopetickets/api';\nimport { IslandPaymentFrame, isWalletFrameMethod, type FrameFailure } from './IslandPaymentFrame';\nimport {\n detectDigitalWallet,\n walletFrameMethod,\n walletHostMethod,\n type DigitalWalletKind,\n} from '../domain/detect-digital-wallet';\nimport {\n walletInPlay,\n walletLabel,\n walletReport,\n type WalletReport,\n} from '../domain/wallet-report';\nimport { journeyPresentation, revolutStatus, type RevolutJourney } from '../domain/revolut-journey';\nimport { parseProviderReturnSignal, type ProviderReturnSignal } from '../provider-return-signal';\n\n/**\n * WHAT IS ON SALE AND WHEN. Everything the two pickers draw from, and all of it the\n * platform's: the widget owns their layout and none of their content.\n *\n * THE CLOCK IS THE VENUE'S, NEVER THE DEVICE'S, which is why both readings are handed in\n * rather than taken. A run sold in Dublin does not change what day it is because the\n * buyer is in Sydney, and a picker that read `new Date()` would grey out tonight's show\n * for half the world.\n */\n/**\n * WHAT A PROVIDER BUTTON IS TALL, AND WHY THE ISLAND MAY KNOW IT IN ADVANCE.\n *\n * The payment host mounts both provider buttons at a stated height — `buttonStyle.height:\n * '52px'` — `$13`, the island's own button height — on the Revolut mount and on the wallet's, in `payment-host/src/routes/Checkout`.\n * Neither is content whose size depends on what is inside it, so neither has to be\n * MEASURED: the frame is given its height at mount and is right the first time.\n *\n * THAT IS WHAT LETS THE MORPH KNOW WHERE IT IS GOING. The destination height is\n * calculated before the move begins; a frame that opens at a bootstrap height and\n * corrects when the host reports is the opposite of that, and the correction is a settle\n * the buyer watches. Only the CARD field is genuinely unmeasurable in advance, and it is\n * the one frame still waited on.\n *\n * IT MUST MATCH THE HOST. Disagree and the button is clipped or floats in a taller box —\n * two halves of one number, in two documents that cannot share a token.\n */\nconst PROVIDER_BUTTON_HEIGHT = 52;\n\n/**\n * THE STEP WHOSE ARRIVAL CONFIRMS THE ACCOUNT'S ADDRESS — whatever `ACCOUNT_CREATION_ORDER`\n * puts after Confirm Email, which is Verify Email where the passcodes work and Add Password\n * where they do not. Read from the order so the two cannot come apart.\n */\nconst CONFIRMS_ADDRESS: PurchaseStepId | undefined =\n ACCOUNT_CREATION_ORDER[ACCOUNT_CREATION_ORDER.indexOf('CONFIRM_EMAIL') + 1];\n\nexport type CheckoutSchedule = {\n /** The run being picked from. Every month it touches is drawn. */\n readonly series: CalendarSeries;\n /** `YYYY-MM-DD` on the venue's calendar. */\n readonly today: string;\n /** `HH:MM` on the venue's clock — see `timeOfDayInZone`. */\n readonly nowTime: string;\n /** One ticket's slots, by `YYYY-MM-DD`. A day with none simply offers none. */\n readonly slotsByDay?: Readonly<Record<string, readonly Timeslot[]>>;\n /** Per-day `Remaining`, 0..1, keyed by `YYYY-MM-DD`. */\n readonly remaining?: Readonly<Record<string, number>>;\n};\n\n/**\n * WHAT A PAYMENT DID, in the platform's own three words.\n *\n * THE CHAIN, WHICH IS THE WHOLE POINT: the status endpoint's `completed` means the\n * PROVIDER took the money — lowercase because it is the platform API's own enum literal,\n * not ours. The frame's SUCCESS means the payment host then finalized it\n * (`convertToTransaction` succeeded), so the tickets exist. `PLACED` is what this widget\n * publishes, and it is set from SUCCESS alone — never from `completed`, which can arrive\n * while finalization is still pending or has failed.\n */\nexport type PaymentOutcome =\n /** Declined, with the provider's own words for why. */\n | { readonly kind: 'FAILED'; readonly reason: string }\n /**\n * Taken but not finalized. The recovery view's state: no pay button, no resubmit —\n * a second charge against a completed order is the one mistake this flow must not\n * offer.\n */\n | { readonly kind: 'PAID' }\n /** Taken. The tickets are the buyer's and nothing can change. */\n | {\n readonly kind: 'PLACED';\n /**\n * WHICH TICKET THE PAYMENT MADE — the first of them, and the one the rating card\n * rates. The payment host reads it off the transaction it has just converted and\n * names it on the frame's SUCCESS, which is the only moment it is knowable: there is\n * no attendee ticket until the money is finalized.\n *\n * OPTIONAL BECAUSE A HOST MAY ASSERT THIS OUTCOME ITSELF and have no ticket to name\n * — see `CheckoutProps.payment`. Nothing else in the flow reads it, so an outcome\n * without one is a complete answer to every question but the rating's.\n */\n readonly attendeeTicketKey?: string;\n };\n\n/**\n * WHAT A FINISHED PURCHASE HANDS THE BOOKING.\n *\n * THE CART KEY AND NOT THE TRANSACTION'S: `Transactions/ByKey` takes the cart's, and the\n * transaction's own comes back inside the response — see `bookingGateway`.\n *\n * THE OCCASION TRAVELS WITH IT because the platform does not answer for it, and the flow is\n * the one place that holds every field: it has just walked a buyer through choosing the run,\n * the day and the session. See `BookingOccasion`.\n */\nexport type PlacedBooking = {\n readonly cartKey: string;\n readonly occasion: BookingOccasion;\n readonly attribution: TicketAttribution;\n /**\n * THE TICKETS, ALREADY READ — and this is why the handover is asynchronous.\n *\n * The island fetches its incoming content BEFORE it transitions, then morphs, then fades\n * in. Swapping to the booking and letting IT fetch puts a fifth card between the last step\n * of the purchase and the tickets: the buyer watches \"Opening Your Booking\" appear from\n * nothing and then transition again, which is two moves where the design draws one. So\n * the flow stays on the card the buyer just pressed until the read lands, and the swap is\n * the transition.\n *\n * ABSENT WHERE THE READ FAILED OR FOUND NOTHING, which is the one case the booking has to\n * work that out for itself — it has the notice and the Try Again, and this does not.\n */\n readonly record?: BookingRecord;\n};\n\nexport type CheckoutProps = {\n /**\n * WHICH IMPLEMENTATION IS ASKING. Held rather than read here: the data layer\n * authenticates with it, and a widget that drew a card without one would be drawing\n * somebody's checkout with no idea whose.\n */\n readonly appKey: string;\n /**\n * WHICH PLATFORM, and nothing else — the app key above is what authenticates. Optional\n * in every field: absent means production.\n *\n * THIS IS WHAT `appKey` WAS ALWAYS FOR. The prop above has said since the first commit\n * that the data layer authenticates with it, and there was no data layer — every fact\n * arrived as a prop, which is right for a host already holding them and wrong for the\n * case this widget exists to serve: an implementation that will not engage with the SDK,\n * drops the island onto a page and expects it to work.\n *\n * WHAT A HOST PASSES STILL WINS. `schedule` and `userTypes` are checked first, so a host\n * with its own calendar keeps it and nothing is fetched twice.\n */\n readonly source?: CheckoutSource;\n /**\n * WHAT THE HOST ALREADY KNOWS ABOUT THE ORDER. Partial is the normal case.\n *\n * ABSENT IS A MOUNT WITH NO ORDER AT ALL, which is a different thing from a partial one\n * — and it is why the absence is modelled HERE rather than by making `OrderSubject`\n * optional a level down. An intent with no subject is not an order half-composed; it is\n * nothing to sell, which is what that field's own note says and which stays true.\n *\n * The island then draws the `IDLE` checkpoint and nothing else: no walk, no steps, no\n * cart and nothing fetched. That is what a host mounts on a page which is not selling\n * anything — a header, a landing page, an account corner — and it hands in an intent the\n * moment there is something to buy.\n */\n readonly intent?: OrderIntent;\n /**\n * The user types the event offers, for the party step. Empty draws the single\n * unnamed line, which is what an event with no discount types wants.\n */\n readonly userTypes?: readonly PartyUserTypeOption[];\n /** The ticket's ceiling, across the whole party. */\n readonly maxParty?: number;\n /**\n * A CART THE HOST ALREADY OPENED — adopted, never duplicated.\n *\n * A host that composes the order itself holds a cart before this widget mounts: it made\n * one to price the order and to hold the stock. Without this the widget opened a SECOND\n * for the same purchase, so the items went in twice, the payment settled against the\n * widget's, and the host's went on holding stock nobody would ever buy.\n *\n * Given a key the cart is READ and never created or filled — what is in it is the\n * host's statement, not this widget's guess.\n */\n readonly cart?: { readonly key: string };\n /**\n * WHAT IS ON SALE AND WHEN — everything the day and time pickers draw from.\n *\n * REQUIRED BY A HOST THAT DEFERS THOSE STEPS, and there is no way around it: the widget\n * owns the calendar's LAYOUT and none of its CONTENT. Which days a run touches, which\n * slots a day holds and what the venue's clock says are all the platform's, and the\n * widget has no data layer to ask.\n *\n * Absent, the pickers cannot be drawn — and the steps then GATE rather than pass. See\n * `stepAnswered`: a card that cannot collect its answer must not let a buyer past it,\n * or the order goes out without the day it was supposed to carry.\n */\n readonly schedule?: CheckoutSchedule;\n /**\n * THE STOCK PHOTOS THE PROFILE PHOTO STEP OFFERS, in the order the grid draws them.\n *\n * AN OVERRIDE, NOT A REQUIREMENT — `defaultProfilePhotos` is the platform's own set and\n * is what this falls back to. It was required once, on the reading that the faces are\n * content the widget has nowhere to fetch; but the ids are not the host's to choose\n * (see `ProfilePhoto`), so every integration was being asked to copy the same constant\n * and none of them did. The step was dark everywhere, and so was a returning buyer's\n * stored face, which resolves through the same set — see `avatarAssetsFor`.\n *\n * PASSED EMPTY, THE STEP IS STILL EXCUSED. A host that genuinely has no faces to offer\n * says so with `[]`, and an account can be made without a photo: a card asking for one\n * it cannot offer is worse than no card at all.\n */\n readonly profilePhotos?: readonly ProfilePhoto[];\n /**\n * WHAT IS IN THE CART, for the screen the header's summary opens.\n *\n * Derived from the cart itself where the widget opened one — see `cartLines`, which\n * groups the platform's own items and money into rows a buyer recognises. A host that\n * knows better says so here: it may hold the user-type split, or artwork, or a line the\n * cart cannot describe.\n */\n readonly cartLines?: readonly CartLine[];\n /**\n * WHO THE BUYER IS WHEN THE WIDGET MOUNTS, and nothing after that.\n *\n * A SEED AND NOT A CONTROL. It is read once, into the widget's own store, because the\n * widget is the only thing that knows whether a passkey ceremony finished or a call was\n * refused — a prop that could overwrite that would be a second authority over the one\n * thing that must have exactly one. See `useAuthSession`.\n */\n readonly session?: AuthSession;\n /** What is owed, as the pill and the commitment button say it. */\n readonly quote?: Quote;\n /** The reservation, once there is an order to hold. */\n readonly hold?: EscrowHold;\n /**\n * WHAT THE PAYMENT DID, once it has been attempted. Absent until it has.\n *\n * A HOST SAYS SO because nothing here can know. There is no payment integration, and\n * the widget must not invent one — so both cards are built and the event that reaches\n * them comes from outside, exactly as `hold` and `quote` do. When payments are wired\n * this becomes something the widget observes rather than is told.\n *\n * ONE PROP FOR BOTH OUTCOMES, and that is the point of it. Processing draws no buttons\n * — there is nothing for a buyer to press while money moves — so NEITHER outcome is\n * reachable from inside the flow, and a host told to report only failures would have\n * had no way to say a payment worked.\n */\n readonly payment?: PaymentOutcome;\n /**\n * RUN THE ACCOUNT SUB-FLOW AGAINST A DOUBLE, and nothing else. This once stood in for\n * the payment too; payments are real now, and an outcome a caller wants to state is\n * `payment` above. What is left is the account: eight calls the platform does not\n * answer yet, so without this the sub-flow has nothing to run against. See\n * `simulatedAccountGateway`.\n */\n readonly simulate?: boolean;\n /** Called with the completed intent when the last step is answered. */\n readonly onCommit?: (intent: OrderIntent) => void;\n /**\n * WHICH STATE THE HOST'S PAGE LOADS ON — the pill, or the card already open.\n *\n * The state, not the only state: the island collapses and expands either way, and a\n * buyer who closes the card gets the pill back whichever this says. It names the\n * OPENING position, which is a page-layout decision and therefore the host's — a\n * dedicated checkout route wants the card standing open, a product page under a\n * \"Get Tickets\" button wants the pill until it is asked for.\n */\n /**\n * WHICH FACE THE ISLAND RESTS ON — the purchase, or the cart the host is still filling.\n *\n * `flow` is the default and is what every host has had: the widget opens on the first\n * step the intent has not answered, and a host that preloaded the whole order opens on\n * Order Review.\n *\n * `cart` is for a host that is STILL COMPOSING — the SDK has put a product in a cart and\n * the buyer may add more. The island draws the cart instead of a step, follows it as it\n * changes, and hands over to the flow when Check Out is pressed. It is a prop rather\n * than something derived from `cart` being present, because a host resuming a purchase\n * across pages passes a cart on every page and means the opposite by it — see the\n * multi-page guide.\n *\n * A SIBLING OF `initialPresentation` AND NOT A REPLACEMENT: that one says pill or card,\n * this one says which card. Both are page-layout decisions and therefore the host's.\n */\n readonly opensOn?: 'flow' | 'cart';\n readonly initialPresentation?: 'pill' | 'card';\n /**\n * WHAT THE OPENING PILL SAYS, where the host's page has its own word for it — \"Book Santo\n * Panto\" on a page selling one show. Absent, or blank, is `OPENING_LABEL`.\n *\n * THE ONE PIECE OF COPY A HOST MAY SUPPLY, and only this one: it names what is on sale,\n * which the page knows and the widget does not. Every later pill names the step behind\n * it, and those stay the widget's own.\n */\n readonly openingLabel?: string;\n readonly mode?: IslandMode;\n /**\n * Where in its reservation the island sits — a corner, the middle of an edge, or the\n * middle. Defaults to `bottom`.\n *\n * THE RESERVATION IS THE SAME EVERY WAY: the host's page has the island's COLLAPSED\n * footprint held open for it, and an opened card grows out of that — upward from any\n * `bottom` alignment, downward from any `top` one, and both ways at once from `left`,\n * `center` and `right`, which therefore need room above AND below.\n *\n * LEFT AND RIGHT ONLY SHOW IN A RESERVATION WIDER THAN THE CARD, whose measure is capped\n * at `$100`. In a narrower one the island fills it, and every horizontal choice draws\n * the same. See `island.css`'s alignment blocks.\n */\n readonly align?: IslandAlignment;\n /**\n * WHERE THE RESERVATION ITSELF IS HELD. Defaults to `page`.\n *\n * `page` holds it in the host's flow, wherever the widget was mounted, and `align` places\n * the island inside that box. `screen` pins the box to the viewport, so `align` names a\n * corner of the SCREEN — a floating widget, with no fixed-position wrapper of the host's\n * own to keep in step with it.\n *\n * A TRANSFORMED ANCESTOR STILL WINS: a `transform`, `filter` or `contain` anywhere above\n * the widget makes that ancestor the containing block of anything fixed, and a pinned\n * island then sits in it instead of on the screen. Mount a pinned widget at the end of\n * `<body>`, out of reach of the page's own wrappers.\n */\n readonly placement?: IslandPlacement;\n};\n\n/** The answers this widget has collected, before they are folded back into the intent. */\ntype Collected = {\n readonly composition: Record<string, number>;\n /**\n * WHICH WAY OF PAYING IS CHOSEN — the ones the platform takes, and nothing until the\n * buyer says one. NOT A FREE STRING: the fold and the frames read it, and a value\n * nobody mounts a frame for would be a method that charges nothing. The wallets are\n * EXPLICIT (never a bare `wallet`): the device's one wallet was named when its frame\n * was mounted, and everything downstream — the frame key, the fold, the retry — reads\n * the same word. See `detect-digital-wallet`.\n */\n readonly paymentMethodKey: '' | 'card' | 'revolut_pay' | 'apple_pay' | 'google_pay';\n /**\n * THE AVATAR VALUE THE BUYER PICKED for the account they are making — `default:<id>`\n * off the stock set, or an uploaded photo's own url — and empty until they pick. The\n * hero wears it from the moment it is set, which is the preview.\n */\n readonly photo: string;\n /**\n * The url of the photo they uploaded, which the grid draws as a cell of its own.\n * Empty before any upload; a second upload REPLACES it rather than adding another.\n */\n readonly uploadedPhoto: string;\n /** The event's own questions, by question id. */\n readonly answers: Readonly<Record<string, string>>;\n /** Who the buyer has chosen to follow. */\n readonly following: readonly string[];\n /**\n * HOW THE BUYER RATED THE PURCHASE, or `null` while they have rated nothing — which is\n * the state the card opens in and the state Skip leaves it in. Not `0`: zero stars is a\n * rating this flow does not offer, and a number that means \"unanswered\" is the thing a\n * nullable type is for.\n */\n readonly rating: FeedbackRating | null;\n /** `YYYY-MM-DD`, or empty for a day not yet chosen. */\n readonly day: string;\n /** The slot's `startTime`, or empty for a time not yet chosen. */\n readonly timeslot: string;\n /** Null means untouched; an empty string is an explicit edit. */\n readonly firstName: string | null;\n readonly lastName: string | null;\n readonly email: string;\n /*\n * THE TWO FIELDS THE BUYER TYPED, not the one string the platform takes: the step\n * collects a country and a national number, and which plan the digits belong to is\n * half of what makes them valid. The one string is written at the fold, below.\n */\n readonly phone: PhoneValue;\n};\n\nconst NOTHING_COLLECTED: Collected = {\n composition: {},\n /*\n * Empty until the buyer says one — Review's buttons and the detour's rows are where\n * a method is chosen, and the two frames mount off it.\n */\n paymentMethodKey: '',\n photo: '',\n uploadedPhoto: '',\n answers: {},\n following: [],\n rating: null,\n day: '',\n timeslot: '',\n firstName: null,\n lastName: null,\n email: '',\n phone: { dialCode: DEFAULT_DIAL_CODE, national: '' },\n};\n\n/**\n * Fold collected answers into the callback intent. Only the host intent determines\n * excusal; editing an answer must not rewrite the walk.\n */\nfunction foldIntent(intent: OrderIntent, collected: Collected): OrderIntent {\n const composition = { ...(intent.composition ?? {}), ...collected.composition };\n /*\n * E.164 AT THE BOUNDARY, and only once the two fields make a whole number — a\n * half-typed one folds as nothing rather than as a string the platform would read\n * as a claim. The step's own gate stops the walk before an invalid one can be\n * committed; this is the safety under it.\n */\n const phone =\n collected.phone.national === ''\n ? null\n : e164(collected.phone.dialCode, collected.phone.national);\n /*\n * THE HOST'S OWN FIELDS GO THROUGH THE SAME GATE the collected ones do — see\n * `answeredBuyer`. Folding `intent.buyer` raw is what carried an unchecked address and\n * an unnormalised phone all the way to the provider, and `excusedByIntent` reads the\n * narrowed buyer too, so the step for anything dropped here is one the buyer is asked.\n */\n const buyer = {\n ...answeredBuyer(intent.buyer),\n ...(collected.firstName === null ? {} : { firstName: collected.firstName }),\n ...(collected.lastName === null ? {} : { lastName: collected.lastName }),\n ...(collected.email === '' ? {} : { email: collected.email }),\n ...(phone === null ? {} : { phone }),\n };\n /*\n * THE METHOD, FOLDED ONCE CHOSEN AND NOT BEFORE — an empty key folds as nothing\n * rather than as a claim, and the intent the host gets back names what charged it.\n */\n return {\n ...intent,\n ...(collected.paymentMethodKey === '' ? {} : { paymentMethodKey: collected.paymentMethodKey }),\n ...(Object.keys(composition).length === 0 ? {} : { composition }),\n ...(Object.keys(buyer).length === 0 ? {} : { buyer }),\n ...(collected.day === '' ? {} : { day: collected.day }),\n ...(collected.timeslot === '' ? {} : { timeslot: collected.timeslot }),\n };\n}\n\n/**\n * HOW LONG THE PAYMENT HAS BEEN WATCHED, as the two answers that change what is drawn.\n *\n * `settled` is whether the card has been up long enough to be read, which is what an\n * outcome has to wait for. `waiting` is whether it has been up long enough that the buyer\n * deserves to be told what is being waited ON.\n *\n * BOTH RESET WHEN THE FLOW LEAVES, so a buyer who reaches Processing twice — a declined\n * payment, then a retry — gets the same floor under the second attempt as under the first.\n */\nfunction usePaymentDwell(processing: boolean) {\n const [settled, setSettled] = useState(false);\n\n useEffect(() => {\n if (!processing) {\n setSettled(false);\n return;\n }\n const floor = window.setTimeout(() => setSettled(true), PROCESSING_FLOOR_MS);\n return () => window.clearTimeout(floor);\n }, [processing]);\n\n return { settled };\n}\n\n/**\n * A HOST'S OWN HOLD, COUNTED DOWN FROM THE MOMENT THEY ASSERTED IT — see `holdSince`,\n * which is where the snapshot-against-deadline argument lives.\n *\n * THE RING USED TO SIT STILL, in the header and over the avatar both, because a host that\n * computes a snapshot and renders it keeps asserting the same number. It was explicitly\n * not counted down, on the argument that advancing somebody else's number would be\n * inventing seconds nobody said had passed. That had it backwards: holding the number\n * still is what makes it false. Reported as the timer not moving.\n *\n * THE STAMP IS THE WHOLE MECHANISM, and it is keyed on the VALUE rather than on the\n * object. A host rebuilding `{ secondsLeft: 540, ... }` every render is repeating one\n * assertion, not making a new one — stamping on identity would reset the clock on every\n * render and freeze it exactly as before. A host that ticks its own hold changes the value,\n * re-stamps, and its clock wins; one that asserts once is counted down from that once.\n *\n * SET DURING RENDER, which is React's own answer for state derived from a prop — the\n * alternative is an effect, and an effect would draw one frame of the stale clock every\n * time the assertion changed.\n */\nfunction useAssertedHold(hold: EscrowHold | undefined, now: number): EscrowHold | undefined {\n const [stamp, setStamp] = useState<{ hold: EscrowHold; at: number } | null>(null);\n\n if (hold === undefined) {\n if (stamp !== null) setStamp(null);\n return undefined;\n }\n if (stamp === null || !sameHold(stamp.hold, hold)) {\n setStamp({ hold, at: now });\n return hold;\n }\n return holdSince(stamp.hold, stamp.at, now);\n}\n\n/**\n * THE WIDGET A HOST MOUNTS, and the two decisions it makes before anything else: is there\n * an order, and has the buyer said they are checking out.\n *\n * FOUR FACES, ONE MOUNT. `RestingIsland` is the widget at rest — the account card, or the\n * cart once there is something in it. `PurchaseIsland` is the walk, which is everything this\n * file was. `BookingIsland` is what the walk ends at: the tickets it bought. A host that\n * hands in an order and says nothing gets the walk, exactly as before; a host that says\n * `opensOn=\"cart\"` gets the cart until the buyer presses Check Out.\n *\n * TWO COMPONENTS AND NOT ONE WITH GUARDS. Every reading the flow makes — the excusal, the\n * refusal, the cart it opens, the fold `onCommit` hands back — is about an order it is\n * holding. Threading an absent one through all of them would put a `?.` on each and leave\n * the subject's requiredness true in the type and untrue in the code. Answering the\n * question once, here, keeps `PurchaseIsland` exactly as strict as it was.\n */\nexport function ScopeTicketsCheckout({\n intent,\n opensOn = 'flow',\n session: seed = ANONYMOUS_SESSION,\n ...props\n}: CheckoutProps) {\n /**\n * WHERE THE CHECKS SENT THE BUYER, and `null` until they have run — which is also what\n * \"still resting\" means, so there is one value and not a flag beside it.\n *\n * IT IS A ONE-WAY DOOR. Nothing sets it back: a buyer who checked out and closed the\n * card gets the pill of the flow they are in, not the cart they left, because the flow\n * may by then have opened a cart, taken a name, or charged a card. Adding more is what\n * the host's own page is for.\n */\n const [opensAt, setOpensAt] = useState<PurchaseStepId | null>(null);\n\n /**\n * THE TICKETS, ONCE THERE ARE ANY — and the fourth face of the widget.\n *\n * IT IS A ONE-WAY DOOR LIKE `opensAt` ABOVE, and more so: the money has moved, the order\n * is closed, and there is nothing behind this to go back to. Nothing sets it back.\n *\n * WHY IT IS HELD HERE. `PurchaseIsland` cannot draw the booking itself — it is holding an\n * order, a walk and a hold that are all over — and `BookingIsland` cannot be mounted\n * beside it without two islands on one page. Which island is showing is this component's\n * one job, and this is the last of its four answers.\n */\n const [booked, setBooked] = useState<PlacedBooking | null>(null);\n\n /*\n * WHO IS BUYING, HELD ABOVE ALL THREE FACES — and this is the level it has to be at,\n * not a convenience. The resting island signs a buyer in; pressing Check Out then\n * REPLACES it with the purchase island. A store owned by each face would be built fresh\n * from the host's seed at that moment, and the buyer who just proved who they are would\n * arrive at the flow as a stranger. One store, mounted once, survives the swap.\n */\n const auth = useAuthSession(seed);\n\n /*\n * THE TICKETS OUTRANK EVERYTHING, including a host that changes the intent underneath a\n * finished purchase: a buyer looking at what they bought must not be handed a new order.\n */\n const face =\n booked !== null ? (\n <BookingIsland\n appKey={props.appKey}\n source={props.source}\n cartKey={booked.cartKey}\n occasion={booked.occasion}\n attribution={booked.attribution}\n seed={booked.record}\n /*\n * WHOSE BOOKING IT IS, for the collapsed pill. Read from the same store the\n * purchase island draws its hero from, so a buyer who signed in during the flow is\n * the face on the pill afterwards rather than the guest they arrived as.\n */\n buyerAvatar={buyerAvatarValue(auth.session.auth)}\n buyerAvatarAssets={avatarAssetsFor(defaultProfilePhotos(props.source?.environment))}\n mode={props.mode}\n align={props.align}\n placement={props.placement}\n />\n ) : /* Nothing to sell, so nothing to check out: the account card, and no cart face. */\n intent === undefined ? (\n <RestingIsland {...props} auth={auth} />\n ) : opensOn === 'cart' && opensAt === null ? (\n <RestingIsland {...props} auth={auth} intent={intent} onCheckOut={setOpensAt} />\n ) : (\n <PurchaseIsland\n {...props}\n auth={auth}\n intent={intent}\n opensAt={opensAt ?? undefined}\n onPlaced={setBooked}\n />\n );\n\n /*\n * ── THE FOUR FACES ARE ONE ISLAND, AND THIS IS WHAT SAYS SO ─────────────────\n *\n * They are separate components on purpose — see this function's own note — so React\n * unmounts one to mount the next, and the host that knew what was on screen is gone\n * before the host that must move away from it exists. Every swap therefore CUT: the\n * Follow prompt vanished and the booking appeared in its place, where every other step\n * of the same widget morphs.\n *\n * The name is what lets the leaving host hand the arriving one its card, its chrome and\n * the height it stood at. `island-continuity` is the mechanism and the argument; what is\n * decided HERE is only that these four are the same island, which is a fact this\n * component is uniquely placed to know.\n */\n return (\n <IslandContinuityContext.Provider value={CHECKOUT_CONTINUITY}>\n {face}\n </IslandContinuityContext.Provider>\n );\n}\n\n/** The purchase, with the order in hand. */\ntype PurchaseIslandProps = Omit<CheckoutProps, 'intent' | 'session'> & {\n readonly intent: OrderIntent;\n /** Who is buying — the widget's own store, held above both faces. See `RestingIslandProps`. */\n readonly auth: AuthSessionStore;\n /**\n * WHERE THE CHECKS SAID TO OPEN, for a flow reached by pressing Check Out — see\n * `runCheckoutPreflight`. Absent is a flow mounted directly, which opens at the start of\n * the walk exactly as it always has.\n */\n readonly opensAt?: PurchaseStepId;\n /**\n * THE PURCHASE IS OVER AND THERE ARE TICKETS TO SHOW. Reported to\n * `ScopeTicketsCheckout`, which swaps this island for the booking's — see `BookingIsland`,\n * and see `onCommit`, which is the HOST's signal and fires beside this one.\n */\n readonly onPlaced?: (placed: PlacedBooking) => void;\n};\n\nfunction PurchaseIsland({\n appKey,\n source,\n intent,\n userTypes = [],\n maxParty = 20,\n cart,\n schedule,\n profilePhotos,\n cartLines,\n auth,\n quote,\n hold,\n payment,\n simulate = false,\n onCommit,\n initialPresentation = 'card',\n openingLabel,\n mode = 'system',\n align = 'bottom',\n placement = 'page',\n opensAt,\n onPlaced,\n}: PurchaseIslandProps) {\n /*\n * WHAT THE PLATFORM SAYS, where a host has not said it. Skipped entirely when both are\n * already in hand — a widget handed everything makes no request at all.\n */\n /*\n * THE PLATFORM'S FACES WHERE THE HOST NAMED NONE, and `[]` is a host saying it wants the\n * step gone rather than a host that forgot — `??` and not `||` for exactly that reason.\n */\n const photos = useMemo(\n () => profilePhotos ?? defaultProfilePhotos(source?.environment),\n [profilePhotos, source?.environment],\n );\n\n const client = useCheckoutClient(appKey, source);\n /*\n * THE ACCOUNT OPERATIONS, on the widget's own client. A gateway of named calls rather\n * than the client itself: nothing above the data layer reaches the platform directly.\n */\n const accounts = useAccountGateway(client, simulate);\n /*\n * AND THE WAY BACK INTO ONE THAT EXISTS — its twin, kept apart because they answer to\n * different cards: this one runs in front of the order and the account gateway runs\n * behind it, after the money.\n */\n const signIns = useSignInGateway(client, simulate);\n /*\n * WHERE THE CEREMONY DOCUMENT LIVES AND WHAT RP IT SPEAKS FOR — read once, because both\n * halves are spent in two places each and the pair only means anything together: a\n * credential is bound to the RP id and only a document whose origin ends in that id may\n * ask for one. See `ENVIRONMENT_URLS`.\n */\n const passkeyEnvironment = ENVIRONMENT_URLS[source?.environment ?? 'production'];\n /*\n * THE ACCOUNT SUB-FLOW'S OWN CALLS. It holds the progress and makes the requests; the\n * cards below hand it presses and read back what it knows.\n */\n const accountFlow = useAccountCreation(accounts);\n /*\n * AND THE BOOKING'S, on the same client. The flow reads the tickets it made before handing\n * the buyer to them — see the effect beside the cart's own booking, and `PlacedBooking`.\n */\n const bookings = useBookingGateway(client);\n /*\n * WHO IS BUYING — handed down rather than made here. `ScopeTicketsCheckout` owns the\n * store so identity survives the swap between the resting island and this one; see\n * `useAuthSession` for why nothing outside the widget can drive it.\n */\n const session = auth.session;\n\n const [collected, setCollected] = useState<Collected>(NOTHING_COLLECTED);\n /**\n * WHERE THE BUYER HAS WALKED TO, or `null` for one who has not moved yet.\n *\n * A STEP AND NOT AN OFFSET, because the walk is re-planned from the session on every\n * render and the session moves during a purchase. Making an account bypasses the\n * OrderSuccess offer and answers the name, the email and the phone, so up to four stops\n * vanish from BEHIND the buyer — and an offset into a list that shrinks quietly means a\n * different card. It meant exactly that: `ACCOUNT_CREATING` carried the buyer to the\n * welcome the moment the account came back, so the three-second floor written under that\n * card was never served. `stopIndex` is the rule for reading this back.\n *\n * NOT THE FIRST STEP, because \"the first step\" is an answer and \"has not moved\" is not\n * one: a flow reached by pressing Check Out opens where the checks sent it, and seeding\n * this with that would need the walk, which is not built until well below here. `null`\n * defers the question to the one place that can answer it.\n */\n const [at, setAt] = useState<PurchaseStepId | null>(null);\n /**\n * THE WALK HAS RUN OUT. A flag and not a callback fired on the spot, because what the\n * booking needs — the run's name, its artwork, the session — is composed a long way below\n * `forward`, and hoisting all of it above one press would be reordering the file around a\n * single line. Read by the effect beside the cart's own booking, which is where those\n * facts already are.\n */\n const [finished, setFinished] = useState(false);\n const [answered, setAnswered] = useState(false);\n /*\n * WHERE THE ISLAND IS, not where it started. `initialPresentation` seeds this once and\n * then has no further say — a buyer who opens the pill has moved the island, and a prop\n * that kept overriding that would be a widget arguing with the person using it.\n */\n const [expanded, setExpanded] = useState(initialPresentation === 'card');\n /**\n * THE MONTH ON SCREEN, which is the PICKER's to say and not the flow's — a run that\n * crosses New Year says 2026 over December and 2027 over January, and only the thing\n * doing the paging knows which. Both pickers publish it; the header spends it.\n */\n\n /** Whether the cart's screen — the one card beside the flow — is the one showing. */\n const [cartOpen, setCartOpen] = useState(false);\n /*\n * THE CLOCK THE HOLD IS READ AGAINST, and the only reason it is state: `order.hold` is\n * worked out from the cart's expiry against `Date.now()` AT RENDER, so without\n * something to re-render the island the countdown is whatever it said when the buyer\n * last pressed anything — and a hold nobody re-read never reaches `00:00` at all.\n */\n const [, setClock] = useState(0);\n /**\n * A PARTY OVER THE TICKET'S CEILING WAS ASKED FOR. The step is not answered while it\n * stands: a card showing a refusal beside a live Continue would be telling a buyer both\n * that they cannot have it and that they may proceed.\n */\n const [partyRefused, setPartyRefused] = useState<number | null>(null);\n /**\n * The detour standing in front of the walk, or `null` for the walk itself.\n *\n * A DETOUR IS NOT A STOP — `walkPurchase` skips every step with a `detourFrom`,\n * because nothing walks to one. It is reached by pressing a control on the card it\n * hangs off and left by finishing with it, so the flow's own position does not move\n * while one is open.\n */\n const [detour, setDetour] = useState<PurchaseStepId | null>(null);\n\n const fetched = useCheckoutData(\n intent.subject.key,\n intent.subject.kind === 'series',\n client,\n /*\n * FETCHED WHENEVER SOMETHING IS MISSING, and sessions count as missing.\n *\n * \"The host supplied a schedule\" is not \"the host supplied everything\": `slotsByDay` is\n * optional, and a host that maps the days of a run and stops has said nothing about the\n * sessions on them. Keying only on the schedule's PRESENCE meant such a host got no\n * fetch, so there was nothing to fill the gap with — a picker with no sessions in it and\n * no way to find any.\n *\n * AND THE CART'S ARTWORK IS MISSING TOO, which is the third thing this gate has had to\n * learn. There is no `artwork` prop: the run's picture is not something a host CAN hand\n * in, so a host holding a schedule and its user types does not hold everything after\n * all — it was getting no fetch, and every cart row drew an empty ticket. The one way\n * to hold the artwork is to hold the whole cart, so `cartLines` is what excuses it.\n */\n schedule?.slotsByDay === undefined || userTypes.length === 0 || cartLines === undefined,\n /*\n * THE DAY WHOSE SESSIONS ARE WANTED. Sessions are fetched for one day, not for every\n * night of a run — see the hook. Before a day is chosen, the soonest is the one the\n * calendar opens on and therefore the one about to be asked for.\n */\n collected.day === '' ? intent.day : collected.day,\n source?.environment,\n );\n\n /*\n * A SIMULATED RUN WHERE THE HOST GAVE NONE — and without this, `simulate` was half a\n * switch. It answered the payment and left the calendar empty, so a demo of\n * `compose=\"widget\"` reached Select Day, found nothing to pick from and stopped at the\n * gate: the pickers were mounted and had no run to draw.\n *\n * THE HOST'S OWN SCHEDULE ALWAYS WINS, so a demo can hand in real days and still\n * simulate the payment — the two are separate things being stood in for.\n */\n const drawnSchedule = useMemo(() => {\n const own = schedule ?? fetched.schedule;\n if (own === undefined) return undefined;\n if (own.slotsByDay !== undefined || fetched.schedule?.slotsByDay === undefined) return own;\n return { ...own, slotsByDay: fetched.schedule.slotsByDay };\n }, [schedule, fetched.schedule]);\n\n /* The run's own user types, where the host did not name them — or not yet. */\n const partyAsking = client !== null && fetched.error === null;\n const party = useMemo(\n () => partyTypes(userTypes, fetched.userTypes, partyAsking),\n [userTypes, fetched.userTypes, partyAsking],\n );\n\n /** The intent including everything asked for so far. */\n const standing = useMemo(() => foldIntent(intent, collected), [intent, collected]);\n\n /*\n * WHO THE ORDER IS NAMED FOR, ASKED ONCE — the host's fields, what the buyer has typed\n * over them, and what their ACCOUNT answers for whatever neither holds. See `orderBuyer`,\n * which is the same reading the walk makes when it decides whether to ask at all.\n *\n * IT WAS `standing.buyer` AT FOUR SITES, and the account was in none of them: signing in\n * skipped Name, Email and Phone and then sent `Email: ''`, so the platform refused the\n * order on Review with \"Email is not a valid email address\" — a buyer who had given us\n * their details being told they had not.\n */\n const orderedBuyer = useMemo(() => orderBuyer(standing, session.auth), [standing, session.auth]);\n\n /*\n * THE SITUATION IS THE INTENT, RESTATED. Everything the host answered is a step this\n * widget must not ask, which is exactly what `excused` means to the walk — so the\n * bridge between an order and a flow is one function call and no special cases.\n */\n const situation: FlowSituation = useMemo(\n () => ({\n name: 'The host composes what it holds',\n basis: 'Whatever the OrderIntent already carries is excused; the widget collects the rest.',\n /*\n * THE HOST'S INTENT, NOT THE STANDING ONE — and the difference is the whole stability\n * of the walk.\n *\n * `standing` folds in what the BUYER has answered so far. Excusing from it made the\n * walk rewrite itself under the person walking it: choosing a day excused DATE, the\n * step dropped out of the stops, and the index — which had not moved — was suddenly\n * pointing at Select Time. The buyer never pressed Continue and the card changed\n * anyway; on Party it would have jumped the moment the first guest was added.\n *\n * A HOST'S ANSWERS EXCUSE A STEP; A BUYER'S ANSWER IT. The first decides which steps\n * exist and is fixed before the widget opens. The second moves through them, which is\n * what `forward` is for. `standing` is still what `onCommit` hands back.\n */\n excused: [\n ...excusedByIntent(\n /*\n * WHAT THE EVENT ACTUALLY ASKS, where the platform said. `asksQuestions` is a\n * host's claim; the tickets carry the questions, so a run that asks none excuses\n * the step without anybody having to remember to say so.\n */\n fetched.questions.length > 0 ? { ...intent, asksQuestions: true } : intent,\n ),\n /*\n * AND A RUN THAT SELLS NO SESSIONS IS NOT ASKED FOR ONE. `HasTimeslot` is the\n * platform saying so, and without reading it the widget put an empty Select Time in\n * front of every run that has none — a card asking a question with no answers on it.\n * The SDK's own selector skips the step for the same reason.\n */\n ...(fetched.hasTimeslots === false ? (['TIME'] as const) : []),\n /*\n * AND NOBODY IS ASKED FOR A FACE THERE ARE NO FACES TO PICK FROM. The platform's\n * own set is the default now, so this is reached only where a host passed `[]` on\n * purpose — and there the grid would be an empty well under a card that says\n * \"Select an avatar\", so the step drops out of the walk instead. See\n * `CheckoutProps.profilePhotos`.\n */\n ...(photos.length === 0 ? (['PROFILE_PHOTO'] as const) : []),\n ],\n savedPaymentMethod: intent.paymentMethodKey !== undefined,\n devicePasskey: false,\n }),\n [intent, fetched.questions.length, fetched.hasTimeslots, photos.length],\n );\n\n /*\n * GUEST until there is an account service to route into. The walk needs an account to\n * reason about what signing in would answer; with nothing to sign into, an empty one\n * is the honest input — it answers nothing, which is the truth.\n *\n * THIS IS NOT WHAT THE HERO DRAWS, and the empty avatar on it is not why the island\n * would ever be faceless. The island's avatar is `buyerAvatarValue(session.auth)`,\n * which a host supplies today and which resolves to the guest placeholder when it\n * supplies nothing. The two absences look alike and are unrelated.\n */\n /*\n * GUEST UNTIL THE BUYER SAYS OTHERWISE. The walk needs a route per checkpoint, and\n * until the offer is answered there is nothing to sign into — so guest is the honest\n * input, exactly as before.\n *\n * WHAT CHANGED is that the offer's Create Account can now say otherwise. Pressing it\n * takes the account route at `ORDER_SUCCESS` alone, which is what turns\n * `makingAccount` on and unskips the five steps behind it. Every earlier checkpoint\n * stays guest: this is a decision made AFTER paying and it cannot reach back.\n */\n const [accountChosen, setAccountChosen] = useState(false);\n /* Add Password's reveal — the card owns it; the button that flips it is the card's. */\n const [passwordRevealed, setPasswordRevealed] = useState(false);\n const route: RoutePlan = useMemo(\n () =>\n accountChosen\n ? /*\n * EVERY CHECKPOINT NAMED, and that is not verbosity. `routeFor` defaults a\n * partial plan to ACCOUNT, so `{ ORDER_SUCCESS: 'ACCOUNT' }` alone silently\n * took the account route at the EARLIER checkpoint too — the buyer was signed\n * in at OrderCreated, which makes the offer bypass (\"already on the buyer's\n * account\") and skips the whole sub-flow it was meant to open.\n */\n {\n IDLE: 'GUEST' as const,\n ORDER_CREATED: 'GUEST' as const,\n ORDER_SUCCESS: 'ACCOUNT' as const,\n }\n : 'GUEST',\n [accountChosen],\n );\n const account: Account = useMemo(\n () => ({ avatar: null, name: null, email: null, phone: null, userTypeKey: null }),\n [],\n );\n /*\n * AND THE WALK IS TOLD THE OFFER WAS TAKEN, not left to infer it. Creating the account\n * signs the buyer in, which makes `ORDER_SUCCESS` bypass — so a walk left to read the\n * press would decide, the instant the account existed, that nobody was making one, and\n * drop the welcome and the passkey from under a buyer standing between them.\n */\n const walk = useMemo(\n () => walkPurchase(session, situation, route, account, accountChosen),\n [session, situation, route, account, accountChosen],\n );\n\n /*\n * WHERE THE BUYER HAS WALKED TO, before any outcome is allowed to move them. Read first\n * because the dwell below depends on it and the outcome depends on the dwell: an\n * outcome that decided its own starting point would be a circle.\n */\n const last = Math.max(0, walk.stops.length - 1);\n /*\n * WHERE THE FLOW OPENS — the step the checks resolved to, as a position in this walk.\n *\n * `-1` IS NOT AN ERROR AND IS NOT HONOURED. A destination the walk does not stop at is a\n * step this order does not need, which is the checks and the excusal disagreeing; the\n * walk wins, because it is what the buyer is about to be shown. Opening at the start is\n * then right rather than merely safe: the first stop is the first thing still unanswered.\n */\n const opened =\n opensAt === undefined\n ? 0\n : Math.max(\n 0,\n walk.stops.findIndex((stop) => stop.step === opensAt),\n );\n const from = at === null ? opened : stopIndex(walk.stops, at);\n const standingAt = walk.stops[Math.min(from, last)]?.step;\n const { settled } = usePaymentDwell(standingAt === 'PROCESSING');\n\n /*\n * THE ORDER ITSELF, once the flow is past Add to Cart. `quote` and `hold` stop being\n * things a host asserts and become what the cart says: what is owed, and how long it is\n * held for.\n */\n /*\n * THE DAY THE ORDER IS FOR, and the one every reading of it comes from.\n *\n * A ONE-NIGHT RUN NEVER ASKS. The walk skips Select Day when there is only one, so\n * nothing writes `collected.day` and a host that composed no day leaves this undefined\n * — which reached `timeslotRequest` as \"no day\", came back undefined, and put an item\n * on the wire with no `Timeslot` on it. The platform answers `TimeslotTicket`, \"the\n * ticket requires a timeslot\", and the buyer is told the order could not be started:\n * a refusal earned by the widget failing to say something it knew.\n *\n * SO THE RUN ANSWERS WHERE NOBODY ELSE HAS. The buyer's choice first, then the host's,\n * then the soonest night the run still has — which for a run of one night is that night.\n */\n const runDay =\n drawnSchedule === undefined\n ? undefined\n : (soonestRelevantDay(drawnSchedule.series, drawnSchedule.today) ?? undefined);\n const chosenDay = collected.day !== '' ? collected.day : (intent.day ?? runDay);\n const chosenTime = collected.timeslot === '' ? intent.timeslot : collected.timeslot;\n /*\n * WHAT THE HOST ASSERTED, CHECKED. `excusedByIntent` stops the widget ASKING for a\n * field the host filled; nothing read that field as correct. An unresolvable timeslot\n * used to reach the cart as no timeslot at all — the right day at no particular time —\n * and a party over the ceiling reached it as that many line items.\n */\n const askedTimeslot = chosenTime === '' ? undefined : chosenTime;\n /*\n * WHAT THE PLATFORM WILL SELL IN ONE TRANSACTION, which is a different question from\n * what the buyer may ASK for. It bounds the order, never the stepper: a party of seven\n * is a valid thing to say to a venue that sells five at a time, and the honest answer\n * is that this order cannot be placed — not a number quietly capped on the way in.\n */\n const partyCeiling = fetched.limits?.max ?? maxParty;\n const refusal = refuseIntent({\n headcount: intentHeadcount(standing.composition),\n minParty: fetched.limits?.min ?? 1,\n maxParty: partyCeiling,\n timeslot: askedTimeslot,\n slotsKnown: chosenDay !== undefined && drawnSchedule?.slotsByDay?.[chosenDay] !== undefined,\n timeslotResolved: timeslotRequest(chosenDay, chosenTime, drawnSchedule) !== undefined,\n });\n\n useEffect(() => {\n if (refusal === null || typeof console === 'undefined') return;\n console.warn(\n `[ScopeTicketsCheckout] the order cannot be placed as given: ${refusal}. ` +\n 'No cart is opened — see the `intent` prop.',\n );\n }, [refusal]);\n\n /*\n * BOTH KEYINGS, because a cart line is labelled from what the REQUEST carried and that\n * is the resolved assignment, not the name the rows are keyed by. The platform's go\n * first so a host, which keys its composition however it likes, wins on its own key.\n */\n const userTypeNames = useMemo(\n () => ({\n ...fetched.userTypeNames,\n ...Object.fromEntries(\n (party.status === 'KNOWN' ? party.types : []).map((type) => [type.key, type.name]),\n ),\n }),\n [party, fetched.userTypeNames],\n );\n\n const order = useCheckoutOrder(\n client,\n {\n /*\n * THE RUN'S OWN ANSWER FIRST, because the fetched map can be empty by design: the\n * gate above skips the fetch for a host that hands in a schedule AND its user types,\n * which is what `compose=\"widget\"` does. So there was a day, no event key, `load`\n * returning early and no cart — and no cart is no quote and no hold, which is no\n * summary in the header and neither screen beside the flow reachable.\n */\n eventKey:\n intent.subject.kind === 'event'\n ? intent.subject.key\n : chosenDay === undefined\n ? undefined\n : (eventKeyForDay(drawnSchedule?.series, chosenDay) ??\n fetched.eventKeyByDay[chosenDay]),\n composition: standing.composition ?? {},\n timeslot: timeslotRequest(chosenDay, chosenTime, drawnSchedule),\n },\n /* The product's, then its event's, then the run's — see `CheckoutData.currency`. */\n fetched.currency,\n /*\n * SEAM 4 — NO ORDER WHEN SIMULATING, which is what every other seam here already\n * assumes. The pay button says it plainly: the call would \"open a payment against a\n * cart the demo never created\". The demo DID create one, or tried to — the flow\n * reaching Order Review opened a cart on the platform, against an event key a\n * simulated run invents and an app key a demo does not have, and the refusal raised\n * ORDER_NOT_OPENED over the whole harness before anybody could press anything.\n *\n * A REFUSAL ABOUT AN ABSENT BACKEND IS NOT NEWS ABOUT THE ORDER, and the failure card\n * cannot say which it is: \"Something went wrong before we could hold your tickets\" is\n * true of a sold-out night and of a demo with nothing behind it, and only one of them\n * is worth showing. A widget asked to pretend asks the platform for nothing.\n *\n * AND A DEMO POINTED AT A REAL EVENT IS THE WORSE CASE, not the exception that argues\n * for keeping this: the button that charges refuses while simulating, so a cart opened\n * here would be filled, never paid for, and left holding stock nobody will buy.\n */\n !simulate &&\n client !== null &&\n standingAt !== undefined &&\n orderStatusAt(standingAt) !== 'NONE' &&\n refusal === null,\n cart?.key,\n /*\n * THE USER TYPES BY KEY, so the cart's own lines can say who each ticket is for —\n * \"Peak (Child)\". The names are the platform's; the keys are what the widget sent.\n */\n userTypeNames,\n );\n\n /*\n * A CART THAT FAILED AND A FLOW WITH NO HEADER LOOK IDENTICAL, and are not the same\n * thing — the argument the tickets warning makes one layer down.\n *\n * The summary is drawn only where there is a hold, a hold only where there is a cart,\n * and the cart is three calls that catch into `order.error`, which nothing reads: a\n * refused bulk add is a header that never arrives, with nothing saying why. NOT A NOTICE\n * because the island has no failure card yet — the notices module is in\n * `@scopetickets/sdk`, which this package cannot reach.\n */\n\n useEffect(() => {\n if (order.fill.status !== 'FAILED' || typeof console === 'undefined') return;\n console.warn(\n '[ScopeTicketsCheckout] the order could not be opened, so the header carries no ' +\n 'summary and neither the hold nor the cart screen can be reached.',\n order.fill.error,\n );\n }, [order.fill]);\n\n /*\n * THE GRID'S CELLS — the platform's stock set, and then the face the buyer made.\n *\n * TWO SOURCES, ONE LIST, and the upload goes LAST: it appears the moment it exists,\n * where a new cell reads as something added rather than as one of the stock faces\n * having changed. A second upload REPLACES it, which is why the list never grows past\n * one of them.\n */\n const photoOptions: readonly ProfilePhotoOption[] = useMemo(\n () => [\n ...photos.map((photo, index) => ({\n value: defaultAvatarValue(photo.id),\n url: photo.url,\n label: PROFILE_PHOTO_COPY.photo(index + 1),\n })),\n ...(collected.uploadedPhoto === ''\n ? []\n : [\n {\n value: collected.uploadedPhoto,\n url: collected.uploadedPhoto,\n label: PROFILE_PHOTO_COPY.uploaded,\n },\n ]),\n ],\n [photos, collected.uploadedPhoto],\n );\n\n const avatarAssets = useMemo(() => avatarAssetsFor(photos), [photos]);\n\n /*\n * THE HERO WEARS WHAT THE BUYER JUST PICKED — the preview, and the only one worth\n * having: an avatar is a hundred pixels of round photo, so the way to show somebody what\n * theirs will look like is to put it where theirs goes.\n *\n * IT OUTRANKS THE SESSION'S OWN VALUE FROM THE TAP ONWARDS, not only while the photo\n * card is up: the account is made with it a step later, so a hero that reverted to the\n * guest placeholder on the way would be showing something about to stop being true.\n *\n * DECLARED WITH THE ASSETS rather than beside the hero it feeds, because the cart's own\n * screen draws a hero of its own and returns before that point.\n */\n const heroAvatar = collected.photo === '' ? buyerAvatarValue(session.auth) : collected.photo;\n\n /*\n * THE UPLOAD. `uploads` on the card's own button opens this input — see `pressFor` —\n * because the button the design draws is under Continue and the input belongs to the\n * grid.\n */\n const photoInput = useRef<HTMLInputElement>(null);\n const [photoRefused, setPhotoRefused] = useState<PhotoRefusalCode | null>(null);\n /*\n * THE LIVE OBJECT URL, HELD OUTSIDE THE STATE IT NAMES. Revoking is a side effect and a\n * state updater may be replayed, so the url to withdraw is read from here rather than\n * from the previous `collected` — and the same ref is what the unmount below revokes.\n */\n const uploadedUrl = useRef('');\n\n /*\n * AND THE BYTES, WHICH AN OBJECT URL IS NOT. `URL.createObjectURL` gives this page a\n * handle it can draw; it means nothing to anyone else and cannot be sent. The platform's\n * `ImageRequest` takes the picture ITSELF for an upload — see `AccountPhoto` — so the\n * file is read once, here, and the result is what goes out when the account is made.\n */\n const uploadedEncoded = useRef('');\n\n /*\n * THE FACE THE ACCOUNT IS MADE WITH, named once because it is asked for TWICE — the\n * first attempt and the retry behind `ACCOUNT_NOT_CREATED`. Written out at both, the day\n * one of them gained a fallback the buyer would be offered one face and given another.\n *\n * A CALLBACK AND NOT A VALUE, because the upload's bytes live in a ref: read at press\n * time, a file chosen a moment before the retry is still the file that goes.\n */\n const photoForAccount = useCallback(\n () => chosenPhoto(collected.photo, photoOptions, uploadedEncoded.current),\n [collected.photo, photoOptions],\n );\n\n const chooseFile = useCallback((file: File) => {\n const refused = photoRefusal(file);\n setPhotoRefused(refused);\n if (refused !== null) return;\n\n /* One upload at a time: the cell it drew is about to be replaced by this one. */\n if (uploadedUrl.current !== '') URL.revokeObjectURL(uploadedUrl.current);\n const url = URL.createObjectURL(file);\n uploadedUrl.current = url;\n uploadedEncoded.current = '';\n setCollected((was) => ({ ...was, uploadedPhoto: url, photo: url }));\n\n /*\n * READ ALONGSIDE rather than instead: the cell draws from the object url the moment it\n * is made, and this arrives a tick later. A buyer who presses Continue before it lands\n * gets an account with no face rather than a card that waited — which is the right way\n * round for the one thing here the account can live without.\n */\n const reader = new FileReader();\n reader.onload = () => {\n if (typeof reader.result === 'string') uploadedEncoded.current = reader.result;\n };\n reader.readAsDataURL(file);\n }, []);\n\n /*\n * AN OBJECT URL OUTLIVES THE ELEMENT THAT DREW IT and holds the file in memory until it\n * is revoked, which in a widget mounted inside somebody else's page means until they\n * navigate away.\n */\n useEffect(\n () => () => {\n if (uploadedUrl.current !== '') URL.revokeObjectURL(uploadedUrl.current);\n },\n [],\n );\n\n /*\n * THE OUTCOME WAITS FOR THE FLOOR. Everything downstream reads this rather than the\n * raw state, so a payment that resolved in 200ms is held behind the card that says it\n * is happening — see `PROCESSING_FLOOR_MS`.\n *\n * A HOST'S OWN `payment` WINS over the order's. That is real news from an integration\n * that took the charge itself, and the order's own answer must not argue with it.\n */\n const reported = payment ?? order.payment;\n /*\n * AND THE POLL'S \"PAID\" WAITS FOR THE FRAME — see `PAID_GRACE_MS`, which is where the\n * whole argument is. The short version: `completed` is the money and `SUCCESS` is the\n * tickets, the poll usually learns the first before the frame says the second, and the\n * card for the gap between them says the order could not be placed.\n *\n * ONLY THE POLL'S. A host that reports `PAID` itself is making a statement about a\n * charge it took, not racing our frame, and it is not made to wait for a word that is\n * never coming.\n */\n const pollSaysPaid = payment === undefined && order.payment?.kind === 'PAID';\n /*\n * UNLESS THE FRAME ALREADY SAID SO. `PAID` has two sources and only one of them is a\n * race: the poll INFERS it from `completed` and knows nothing about the tickets, while\n * the host's `TransactionError` is the payment host reporting that finalization itself\n * failed — the answer, not the absence of one. Waiting six seconds to repeat news we\n * have already been given would be the fix taking something from the buyer it was meant\n * to give them.\n *\n * A FLAG HERE AND NOT A FOURTH `PaymentOutcome`, deliberately. That union is a PUBLIC\n * type — a host asserts one through `CheckoutProps.payment` — and splitting `PAID` in\n * two would break every integration that constructs it, to record something no host can\n * tell us anyway: this is about which of OUR two voices spoke, and both speak here.\n */\n const [finalizationRefused, setFinalizationRefused] = useState(false);\n const [paidAged, setPaidAged] = useState(false);\n useEffect(() => {\n if (!pollSaysPaid) {\n setPaidAged(false);\n return;\n }\n const timer = window.setTimeout(() => setPaidAged(true), PAID_GRACE_MS);\n return () => window.clearTimeout(timer);\n }, [pollSaysPaid]);\n /*\n * NOTHING IS SEALED LATER FOR THIS. `terminalPayment` and every guard that stops a\n * second charge read `reported`, which says PAID the instant the poll does — it is the\n * CARD that waits, not the knowledge. Delaying the knowledge would open exactly the\n * double-charge window the poll exists to close.\n */\n const outcome =\n (standingAt === 'PROCESSING' && !settled) || (pollSaysPaid && !paidAged && !finalizationRefused)\n ? undefined\n : reported;\n\n /*\n * A PLACED PAYMENT MOVES THE FLOW, rather than standing in front of it. The\n * acknowledgement is a real stop with a Continue on it, so pinning the card there would\n * strand the buyer on the one screen whose whole job is to be left — the outcome sets a\n * FLOOR under the walk instead, which Continue then advances past and nothing can\n * reverse. Money does not un-move.\n */\n const placed = walk.stops.findIndex((stop) => stop.step === 'PAYMENT_SUCCESS');\n const floor = outcome?.kind === 'PLACED' && placed !== -1 ? placed : 0;\n const index = Math.min(Math.max(from, floor), last);\n const walked: PurchaseStepId = walk.stops[index]?.step ?? 'REVIEW';\n /*\n * THE ORDER MATTERS. A failure stands in front of the walk for as long as the host says\n * so — but a DETOUR still wins over it, because the way off the failure card is\n * \"Change Payment Method\", and a failure that outranked the detour would slam the door\n * it had just opened.\n */\n const stepId: PurchaseStepId = detour ?? (outcome?.kind === 'FAILED' ? 'PAYMENT_FAILED' : walked);\n\n /*\n * THE PASSKEY STEP'S TWO CALLS, opened only once the card is up: a challenge is spent\n * whether or not the buyer uses it, so one is not asked for on the buyer's behalf until\n * they are looking at the offer.\n */\n const passkeyRegistration = usePasskeyRegistration(accounts, stepId === 'PASSKEY');\n const step = purchaseStep(stepId);\n\n /*\n * THE TICKET THE RATING CARD RATES, read off the outcome that made it — see\n * `PaymentOutcome`. There is no second source and deliberately so: the transaction\n * could be read back off the cart, and that would be a second answer to a question the\n * payment has already answered, differing only in which one arrives first.\n */\n const ratedTicket = outcome?.kind === 'PLACED' ? outcome.attendeeTicketKey : undefined;\n const feedback = useFeedback(client, ratedTicket);\n\n /*\n * SAID TO THE INTEGRATOR AND NOT TO THE BUYER. A placed payment that named no ticket\n * leaves the rating card with nowhere to send what it collects — which is a fault in\n * the integration rather than news about the order, so it goes where the person who can\n * fix it is looking. The buyer still gets the card: a rating they can give and we cannot\n * file is a worse trade than one nobody asked for.\n */\n useEffect(() => {\n if (stepId !== 'FEEDBACK' || ratedTicket !== undefined) return;\n if (typeof console === 'undefined') return;\n console.warn(\n '[ScopeTicketsCheckout] the payment is placed but named no attendee ticket, so the ' +\n 'rating has nowhere to go — see `PaymentOutcome.attendeeTicketKey`.',\n );\n }, [stepId, ratedTicket]);\n\n /*\n * ARRIVING AT THE CARD FORM IS CHOOSING THE CARD. A list used to say which method was\n * chosen; there is no list, and \"Pay with Card\" is the only thing that opens this step\n * — so being here IS the answer. The frame in the bay mounts off `cardChosen`, and\n * without this it would never appear and the step could never be answered.\n */\n const [revolutCart, setRevolutCart] = useState<string | null>(null);\n const [savedRevolutCart, setSavedRevolutCart] = useState<string | null>(null);\n /*\n * THE WALLET'S OWN PAIR, the same two states the Revolut frame keeps: the cart its\n * frame is mounted against (prewarmed from the moment the review card is up, so\n * `canMakePayment()` has answered before the buyer looks at the buttons), and the\n * cart the buyer has been SAVED against — the gate that keeps an unsaved buyer off a\n * charge whose conversion needs them. See `selectMethod`.\n */\n const [walletCart, setWalletCart] = useState<string | null>(null);\n const [savedWalletCart, setSavedWalletCart] = useState<string | null>(null);\n /*\n * WHAT THE WALLET FRAME HAS SAID ABOUT ITSELF — checking until it speaks, and from\n * then on the fold `walletReport` keeps: availability words move it, charge words\n * leave it alone. Gates both the Review button and the method list's row.\n */\n const [walletAvailability, setWalletAvailability] = useState<WalletReport>({\n kind: 'checking',\n });\n const [journey, setJourney] = useState<RevolutJourney>({ kind: 'idle' });\n const journeyRef = useRef(journey);\n const updateJourney = (next: RevolutJourney) => {\n journeyRef.current = next;\n setJourney(next);\n };\n const [cancelSignal, setCancelSignal] = useState(0);\n /*\n * THE INLINE JOURNEY'S FRAME EPOCH. When the provider redirects the frame itself away\n * (the inline journey's failure/cancel landing), the host page is destroyed with it —\n * and no message can reach a destroyed page. Bumping this counter changes the frame's\n * URL (`paymentRetry=1`), which is the iframe's React key: the dead document is\n * replaced by a fresh host page that mints a NEW order for the SAME cart. This is the\n * island's only way to resurrect a dead journey; see `handleProviderReturnSignal`.\n */\n const [revolutFrameEpoch, setRevolutFrameEpoch] = useState(0);\n /*\n * THE UNRESOLVED WARNING WAITS ITS TURN. A closed popup is followed by a moment\n * where cancellation cannot be confirmed while the payment itself is being checked\n * and converted — and that moment resolves to success almost always. Telling the\n * buyer \"we could not confirm\" for those seconds reads as a failure that then\n * un-fails, so the warning is held back for this long and the wait is shown as a\n * wait: a spinner and the words below, until the grace expires or the journey moves.\n */\n const UNRESOLVED_GRACE_MS = 6000;\n const [unresolvedAged, setUnresolvedAged] = useState(false);\n useEffect(() => {\n if (journey.kind !== 'unresolved') {\n setUnresolvedAged(false);\n return;\n }\n const timer = window.setTimeout(() => setUnresolvedAged(true), UNRESOLVED_GRACE_MS);\n return () => window.clearTimeout(timer);\n }, [journey.kind]);\n /*\n * THE POLL'S FAILURE STANDS THE JOURNEY DOWN TOO. The frame's own `onError` resets\n * the journey before it fails the payment, but the poll can say `FAILED` with no\n * frame word at all — the inline page's own close terminalises the attempt and the\n * poll is the only voice that hears it — and a `processing` journey keeps the\n * FULLSCREEN OVERLAY standing over the failure card it just answered for. Whichever\n * way the failure is learned, the buyer must be able to see it, so the journey goes\n * idle the moment a failure stands. (PAID and PLACED already take the overlay down\n * through `terminalPayment` in `revolutVisible`.)\n */\n useEffect(() => {\n if (order.payment?.kind === 'FAILED' && journeyRef.current.kind === 'processing')\n updateJourney({ kind: 'idle' });\n }, [order.payment]);\n const selectionRequest = useRef(0);\n /*\n * THE DEVICE'S ONE WALLET — ASKED FOR, NOT GUESSED AT.\n *\n * The sniff decides ONE thing: which slot the single wallet frame mounts in\n * (`apple_pay`/`google_pay`), a word fixed for the life of the frame because it is in\n * the frame's URL and the URL is its key. Nothing downstream is told to be that wallet:\n * the payment host passes Revolut no `preferredPaymentMethod`, so the device answers\n * with whatever it actually has, and `walletInPlay` is that answer everywhere the wallet\n * has to be named — the button's words and the method a charge is recorded under.\n *\n * IT USED TO BE A DEMAND, and the demand was a guess. See `detect-digital-wallet`.\n */\n const sniffedWallet = useMemo<DigitalWalletKind>(() => detectDigitalWallet(), []);\n const sniffedWalletHostMethod = useMemo(() => walletHostMethod(), []);\n /*\n * AND THE WALLET THAT CHARGES, in the payment host's spelling. This is what goes into\n * `collected.paymentMethodKey` and therefore into the intent the host gets back on\n * `onCommit` — so it has to be the wallet that actually took the money, not the slot its\n * frame happens to sit in. They are the same word on most devices and were reported as\n * the same word on all of them, which is how a Google Pay charge was handed back as\n * `apple_pay`.\n */\n const walletCharging = walletFrameMethod(walletInPlay(walletAvailability, sniffedWallet));\n const selectMethod = (method: 'card' | 'revolut_pay' | 'apple_pay' | 'google_pay') => {\n if (\n journeyRef.current.kind !== 'idle' ||\n reported?.kind === 'PAID' ||\n reported?.kind === 'PLACED'\n )\n return;\n const request = ++selectionRequest.current;\n setCollected((was) => ({ ...was, paymentMethodKey: method }));\n if (method === 'card') return;\n /*\n * THE EXTERNAL METHODS — Revolut Pay and the wallet — share one shape: the choice\n * stands on Review, the frame is mounted against the cart, and the buyer is SAVED\n * before the charge can be pressed, because a cart nobody is named on converts to\n * nothing. The save's answer arms the entry; see `savedRevolutCart` and\n * `savedWalletCart`.\n */\n setDetour(null);\n const key = order.cart?.Key;\n if (!key) return;\n const wallet = isWalletFrameMethod(method);\n if (wallet) {\n setWalletCart(key);\n setSavedWalletCart(null);\n } else {\n setRevolutCart(key);\n setSavedRevolutCart(null);\n }\n void order.saveBuyer(buyerDetails(orderedBuyer)).then((saved) => {\n if (!saved || selectionRequest.current !== request) return;\n if (wallet) setSavedWalletCart(key);\n else setSavedRevolutCart(key);\n });\n };\n\n /*\n * PAID, NOT PLACED — the recovery view's flag. The money is taken and finalization\n * did not finish, so the honest card says what happened and asks for nothing: no\n * Try Again (a second charge against a completed payment), no method change, no\n * pay button.\n */\n const paidRecovery = outcome?.kind === 'PAID';\n const prompt = step.checkpoint ? authPrompt(step.checkpoint, session) : null;\n const authCard = prompt?.kind === 'CARD' ? AUTH_CARDS[prompt.card] : null;\n\n /*\n * THE PASSKEY SIGN-IN, opened only once the card that offers it is up — the same rule\n * the registration step above follows, and the same reason: a challenge is spent\n * whether or not the buyer uses it.\n *\n * THE CARD DECIDES, NOT THE STEP. `SIGN_IN_RECOGNISED` is one node drawn at two\n * checkpoints, so this is keyed on which card `authPrompt` chose rather than on where\n * the walk is standing.\n */\n /* Asked once and spent three times — the hook, the button, and the stack it comes out of. */\n const offersPasskeySignIn = prompt?.kind === 'CARD' && prompt.card === 'SIGN_IN_RECOGNISED';\n const signIn = usePasskeySignIn(\n signIns,\n passkeyEnvironment.passkeyRpId,\n offersPasskeySignIn,\n auth,\n );\n /*\n * AND THE OTHER DOOR. The funnel is not a step and has no stop in the walk — it stands in\n * front of whichever checkpoint summoned it, the way the notice does.\n */\n const funnel = useAuthFunnel(signIns, auth);\n\n /* A refused call is the only signal a session has that it is over. */\n useSessionGuard(client, auth);\n\n /*\n * WHAT THE ORDER RAISES, and one place decides it — see `raiseFor`. A shortfall is an\n * order the buyer HAS and outranks a failure on the same state; both stand in front of\n * the flow until they are answered.\n */\n /*\n * THREE SOURCES, ONE CARD. The order's failures come first, and the three can barely\n * collide: everything `raiseFor` raises happens before a payment, everything\n * `raiseForAccount` raises happens after one, and the passkey route is only walked at a\n * checkpoint standing in front of the order. The order is stated anyway, because a card\n * that picked whichever it noticed first would be deciding by accident.\n */\n const raised = useMemo(\n () =>\n raiseFor(order.fill) ??\n raiseForAccount(accountFlow.progress, accountFlow.outcome) ??\n raiseForSignIn(signIn.state, funnel.state) ??\n /*\n * THE RATING LAST, because it is the least of them. Everything above is about the\n * order or the way into an account; a rating that did not send is news about a\n * courtesy, and a buyer holding both should be told about the one that matters.\n */\n raiseForFeedback(feedback.submission),\n [\n order.fill,\n accountFlow.progress,\n accountFlow.outcome,\n signIn.state,\n funnel.state,\n feedback.submission,\n ],\n );\n /* Put away, by id — a notice answered does not come back on the next render. */\n const [noticeAnswered, setNoticeAnswered] = useState<NoticeId | null>(null);\n const notice = raised === null || noticeAnswered === raised.id ? null : raised;\n\n /*\n * WHAT EACH BUTTON DOES, and the notice's own vocabulary is what it is wired to: the\n * labels are copy and will change, the ids are the contract — see `NoticeActionId`.\n */\n const pressNotice = useCallback(\n (action: NoticeAction) => () => {\n /*\n * A RETRY IS NOT AN ANSWER. Putting the notice away by id would silence the SECOND\n * failure of the same kind; the retry takes it away by changing the state that\n * raised it, and it comes back if that state says so again.\n */\n setNoticeAnswered(action.id === 'RETRY' ? null : (raised?.id ?? null));\n /* Back to the party, which is the one lever a buyer has over what the order asks for. */\n if (action.id === 'CHANGE_ORDER') setAt(walk.stops[0]?.step ?? null);\n if (action.id === 'CLOSE') setExpanded(false);\n /*\n * WHAT IS RETRIED DEPENDS ON WHAT FAILED, and the notice already says which — so\n * this reads the id rather than keeping a second record of where the buyer is.\n */\n if (action.id === 'RETRY') {\n if (raised?.id === 'ACCOUNT_CODE_NOT_SENT') accountFlow.resend();\n /* Another challenge, and the button comes back armed with it. */\n if (raised?.id === 'SIGN_IN_NOT_COMPLETED') signIn.retry();\n /* Reopened on the address alone: `FAILED` carries no password, deliberately. */\n if (raised?.id === 'SIGN_IN_UNREACHABLE') funnel.open(standing.buyer?.email ?? '');\n /* The rating is still in hand — `FAILED` keeps it, so this needs no argument. */\n if (raised?.id === 'FEEDBACK_NOT_SENT') feedback.retry();\n if (raised?.id === 'ACCOUNT_NOT_CREATED') {\n accountFlow.create(\n {\n firstName: collected.firstName ?? '',\n lastName: collected.lastName ?? '',\n phone: e164(collected.phone.dialCode, collected.phone.national),\n },\n photoForAccount(),\n );\n }\n }\n /*\n * GIVING UP ON THE ACCOUNT TAKES ITS STEPS BACK OUT OF THE WALK — the exact reverse\n * of the offer's Create Account, which put them in. The buyer lands on whatever\n * comes after them, which is their ticket, and the order is untouched: this is only\n * reachable once it is paid for.\n */\n if (action.id === 'SKIP_ACCOUNT') setAccountChosen(false);\n },\n [\n raised,\n accountFlow,\n signIn,\n funnel,\n feedback,\n standing.buyer?.email,\n collected.firstName,\n collected.lastName,\n collected.phone,\n walk.stops,\n ],\n );\n\n const forward = useCallback(() => {\n setAnswered(false);\n setAt((was) => {\n /*\n * FROM WHERE THE BUYER ACTUALLY IS, which is not always where `at` says. A placed\n * payment puts a FLOOR under the walk without moving `at`, so advancing from the raw\n * value would step from behind the acknowledgement to the acknowledgement — and the\n * Continue on it would appear to do nothing.\n */\n const here = Math.max(was === null ? opened : stopIndex(walk.stops, was), floor);\n const next = walk.stops[here + 1];\n if (next === undefined) {\n /* SET EVERY TIME, unlike the publication below: the once-marker is about not telling\n a host the same news twice, and showing a buyer their own tickets is not news. */\n setFinished(true);\n /*\n * THE ONCE-MARKER'S VETO. This browser already finalized a purchase against the\n * cart — the completion is old news here, whatever the walk just said — so\n * nothing is published a second time.\n */\n if (!order.completedPreviously) onCommit?.(standing);\n return was;\n }\n return next.step;\n });\n }, [walk.stops, floor, opened, onCommit, standing, order.completedPreviously]);\n\n /**\n * STRAIGHT TO A NAMED STEP — what the header's funnel presses.\n *\n * NOT `forward`/`back`, which count from where the buyer is: this is a jump, and the\n * funnel has already decided it is a legal one. `setAnswered(false)` for the same reason\n * every other move clears it — the flag belongs to the card being left.\n */\n const goToStep = useCallback((step: PurchaseStepId) => {\n setAnswered(false);\n setAt(step);\n }, []);\n\n const back = useCallback(\n () =>\n setAt((was) => {\n const here = was === null ? opened : stopIndex(walk.stops, was);\n return walk.stops[Math.max(floor, here - 1)]?.step ?? was;\n }),\n [walk.stops, floor, opened],\n );\n\n /*\n * THE ADDRESS THE ACCOUNT WILL BE MADE ON — the buyer's correction where they made one,\n * and otherwise the order's own, which a host that composed the order may have supplied\n * without this flow ever asking. Read once because two effects below spend it, and a\n * second copy of this expression is a second thing to keep in step.\n */\n const accountAddress =\n collected.email.trim() === '' ? (standing.buyer?.email ?? '') : collected.email;\n\n /*\n * ARRIVING AT THE STEP AFTER CONFIRM EMAIL IS WHAT CONFIRMS THE ADDRESS, because\n * arriving is what that card's one button DOES — it says Confirm. Keyed on the step\n * rather than wired to the button so a buyer who comes back does not confirm twice:\n * `confirmEmail` remembers the address it last sent to.\n *\n * WHICH STEP THAT IS COMES FROM THE ORDER rather than being named here. With the passcode\n * endpoints live it is Verify Email, and arriving there sends the code; with them down\n * Verify Email is not in the walk at all and the next card is Add Password — so naming\n * the step would have left the address unconfirmed for ever and stopped the sub-flow on\n * its first card. See `UNBUILT_ACCOUNT_STEPS`.\n */\n useEffect(() => {\n if (standingAt !== CONFIRMS_ADDRESS || accountAddress === '') return;\n accountFlow.confirmEmail(accountAddress);\n }, [standingAt, accountAddress, accountFlow]);\n\n /*\n * AND ARRIVING AT THE BOXES IS WHAT SENDS THE CODE — the other half of what used to be\n * one call, split when the step it belongs to could be absent.\n *\n * INERT TODAY, and deliberately kept: `VERIFY_EMAIL` is out of the walk while the\n * passcode endpoints are down, so `standingAt` cannot be it. The day the step returns\n * this fires on the same arrival as the confirm above — which is exactly the behaviour\n * it replaced. See `UNBUILT_ACCOUNT_STEPS`.\n */\n useEffect(() => {\n if (standingAt !== 'VERIFY_EMAIL' || accountAddress === '') return;\n accountFlow.requestCode(accountAddress);\n }, [standingAt, accountAddress, accountFlow]);\n\n /*\n * WHEN THE ACCOUNT IS ACTUALLY MADE. The card draws no buttons and takes no input, so\n * arriving on it is the whole trigger.\n */\n /*\n * ONCE PER ARRIVAL, AND THE LATCH IS LOAD-BEARING — it is not tidiness, it is the\n * difference between a card and a locked browser tab.\n *\n * `useAccountCreation` returns a fresh object every render, so this effect runs on every\n * render. `create` guards against a second call while one is in flight or has already\n * succeeded, but deliberately NOT against one after a FAILURE, because the notice's\n * Retry has to be able to try again. Those two facts multiply: a refusal sets a FAILED\n * outcome, the new object re-runs this effect, the unguarded call sets another FAILED\n * outcome with a new identity so React cannot bail out, and the render loop never ends.\n *\n * It went unseen because nothing had ever reached this card against a platform that\n * could refuse: `simulate` used to return before the call, so the only walk that got\n * here made no account at all. It does now — see `simulatedAccountGateway`.\n *\n * CLEARED BY LEAVING, so Retry still works: it calls `create` directly rather than\n * through this, and a buyer who walks back round gets a fresh attempt.\n */\n const attemptedCreate = useRef(false);\n useEffect(() => {\n if (standingAt !== 'ACCOUNT_CREATING') {\n attemptedCreate.current = false;\n return;\n }\n if (attemptedCreate.current) return;\n attemptedCreate.current = true;\n accountFlow.create(\n {\n firstName: collected.firstName ?? '',\n lastName: collected.lastName ?? '',\n phone: e164(collected.phone.dialCode, collected.phone.national),\n },\n photoForAccount(),\n );\n }, [\n standingAt,\n collected.firstName,\n collected.lastName,\n collected.phone,\n collected.photo,\n photoOptions,\n accountFlow,\n ]);\n\n /*\n * THE ACCOUNT JUST MADE BECOMES THE BUYER. `createAccount` mints a session and the\n * gateway hands it straight to the client, so the CALLS after this point were already\n * authenticated — this is where the FLOW finds out, which is what makes the cards after\n * it draw an account holder instead of the guest who started.\n *\n * ONCE, AND ONLY ONCE. `CREATED` is terminal, but the details it is built from are not:\n * without the latch, a later keystroke in a collected field would deposit a second\n * session over the first for no reason anybody asked for.\n */\n const deposited = useRef(false);\n useEffect(() => {\n if (accountFlow.outcome.status !== 'CREATED' || deposited.current) return;\n deposited.current = true;\n auth.signedIn(\n accountFromCreation(\n {\n firstName: collected.firstName ?? '',\n lastName: collected.lastName ?? '',\n phone: e164(collected.phone.dialCode, collected.phone.national),\n },\n /* The address the code was verified at, which is the one the account was made on. */\n addressForAccount(accountFlow.progress) ?? '',\n collected.photo === '' ? null : collected.photo,\n ),\n accountFlow.outcome.session,\n );\n }, [accountFlow.outcome, accountFlow.progress, collected, auth]);\n\n /*\n * AND THE FLOOR IS UNDER THE ANSWER, not instead of it. It used to be all that advanced\n * this card; now the call has to have succeeded too, and the floor is what stops a fast\n * one flashing past. Measured from ARRIVAL rather than from the answer, so a slow call\n * does not serve the wait twice.\n */\n const creatingSince = useRef<number | null>(null);\n useEffect(() => {\n if (standingAt !== 'ACCOUNT_CREATING') {\n creatingSince.current = null;\n return;\n }\n creatingSince.current ??= Date.now();\n if (accountFlow.outcome.status !== 'CREATED') return;\n const left = Math.max(0, creatingSince.current + ACCOUNT_CREATING_FLOOR_MS - Date.now());\n const done = window.setTimeout(forward, left);\n return () => window.clearTimeout(done);\n }, [standingAt, accountFlow.outcome.status, forward]);\n\n /**\n * WHETHER THE WAY OUT STEPS BACK OR CLOSES. Read here rather than at the call site\n * because `onToggle` has to know which it is: the same control does both, and what it\n * DOES has to match the glyph it draws.\n */\n const dismiss =\n detour === null ? (STEP_DISMISS[stepId] ?? (index === 0 ? 'close' : 'back')) : 'back';\n\n /*\n * THE HOST'S PAGE IS HELD TOO, which is the stronger of the two statements a step can\n * make about its way out. `PurchaseStep.collapsed` is `NONE` for exactly the cards that\n * must not be left AND must not let the buyer wander off behind them — the payment in\n * flight, and the card asking whether to give the order up.\n */\n const sealed = step.collapsed.kind === 'NONE';\n\n /*\n * AND THESE DRAW NO WAY OUT, without holding the page. The money has moved and what is\n * left is the buyer's to read — see `UNCLOSABLE_STEPS`, where the line is drawn and\n * argued.\n */\n\n /*\n * THE ISLAND'S ONE CONTROL, in both states. Collapsed it is the pill's action and the\n * only thing it can mean is \"open\". Expanded it is the header's way out, which steps\n * back where there is a step behind and otherwise closes.\n *\n * CLOSING IS WHAT THE PILL IS FOR. Until there was one to close to, `close` was wired\n * to `back`, which clamps at zero — so the first step drew a cross that did nothing.\n */\n /*\n * READ AT PRESS TIME, not closed over: `held` is computed further down from the quote\n * and the clock, and `toggle` is declared above it. A ref is the whole of what this\n * callback needs — whether there was something to lose at the moment the cross was\n * pressed — and it cannot go stale the way a captured value would.\n */\n const holdingRef = useRef(false);\n /* Declared below with `startAgain`, and read at press time for the same reason. */\n const leaveRef = useRef<() => void>(() => undefined);\n\n const toggle = useCallback(() => {\n if (!expanded) {\n setExpanded(true);\n return;\n }\n /* A detour's way out is back to the card it hangs off, never out of the island. */\n if (detour !== null) {\n setDetour(null);\n return;\n }\n /*\n * AND IT ASKS FIRST ONCE THERE IS SOMETHING TO LOSE. In Compose the cross costs\n * nothing — no cart is open, nothing is held, and closing gives nothing back. Past the\n * accepted OrderIntent it is stock taken off sale on this buyer's behalf, and closing\n * the card releases it. `held` is that distinction and already exists: it is defined\n * exactly while a quote and a running hold are the buyer's.\n *\n * ONLY WHERE THE CROSS CLOSES. A `back` steps within the flow and takes nothing away,\n * so it is left alone — the question is about leaving, not about moving.\n */\n if (dismiss === 'close' && holdingRef.current) {\n setDetour('ABANDON');\n return;\n }\n /*\n * AND THERE IS NO COLLAPSING MID-FLOW. A buyer is either buying a ticket or out of the\n * flow; a pill in between is a third state that has to be reasoned about at every step\n * and answers a question nobody asked — \"pause this purchase\" is not something the\n * platform can honour, because the hold does not pause with it.\n *\n * OUT IS BACK TO WHAT THE HOST OPENED IN. Where they asked for a pill that looks like\n * a collapse and is not: the order is released and the walk is at its first step, so\n * pressing Get Tickets again starts rather than resumes. `leaveOrder` is the one act.\n */\n if (dismiss === 'close') {\n leaveRef.current();\n return;\n }\n back();\n }, [expanded, detour, dismiss, back]);\n\n /*\n * THE WAY OUT OF A STOPPED CLOCK, which is the way back IN to a purchase.\n *\n * Three things, and they are one act: the reservation is thrown away (the old cart's\n * stock is somebody else's now), the walk goes back to the stop this widget opens on,\n * and the island collapses to the pill that stop draws. Pressing that pill is then an\n * ordinary first press — it opens a cart when the walk reaches a step that needs one,\n * because `restart` has forgotten the one that lapsed.\n *\n * WHAT THE BUYER ANSWERED SURVIVES. `collected` is not touched: they said two adults for\n * Saturday and gave their email, and none of that stopped being true when the clock did.\n * Making them type it again would be the widget punishing them for its own countdown.\n */\n const startAgain = useCallback(() => {\n order.restart();\n setAt(null);\n setDetour(null);\n setExpanded(false);\n }, [order]);\n\n /*\n * THE SAME RESET, STAYING OPEN — the timed-out card's Try Again. A buyer who wants these\n * tickets should not have to press the pill the closing answer leaves them on; the walk\n * is back at its first stop either way, and the only difference is whether they are\n * looking at it.\n */\n const tryHoldAgain = useCallback(() => {\n order.restart();\n setAt(null);\n setDetour(null);\n setExpanded(true);\n setTimeoutRetried(true);\n }, [order]);\n\n /*\n * LEAVING ON PURPOSE, which is `startAgain` plus the one thing that separates it from a\n * stopped clock: where the island LANDS.\n *\n * BACK TO WHAT THE HOST ASKED FOR. A page that mounts this as a card wants a card back\n * when the purchase is abandoned — collapsing to a pill would leave its layout holding a\n * hole where a card was.\n *\n * EXCEPT FROM THE ENTRY, where the card IS what the host asked for: re-expanding would\n * redraw the one the buyer just closed. The pill is the only somewhere left.\n *\n * AND NOT FOR THE TIMEOUT, which shares everything else. A host's own expired hold is\n * not ours to renew — see the timed-out card — so re-expanding there would draw the same\n * \"Your Order Timed Out\" the buyer just closed, and Close would appear to do nothing.\n * The clock ejects a buyer; this is a buyer leaving, and only the second has somewhere\n * to land.\n */\n const leaveOrder = useCallback(() => {\n startAgain();\n setExpanded(initialPresentation === 'card' && index !== 0);\n }, [startAgain, initialPresentation, index]);\n leaveRef.current = leaveOrder;\n\n /**\n * WHAT A BUTTON DOES, and the order matters.\n *\n * A button that OPENS A DETOUR does that and nothing else, whatever its role. Then, on\n * a detour, every button is the way back — the detour's own primary finishes with it\n * rather than advancing a walk that has not moved. Otherwise the flow's own rules\n * apply.\n *\n * THE FALL-THROUGH IS WHY THIS EXISTS. A button with no handler advanced the flow, and\n * on the last card advancing IS committing — so \"Select Payment Method\", a secondary on\n * Order Review that had nowhere to send anybody, placed the order instead of opening\n * the list.\n */\n const pressFor = useCallback(\n (action: CardAction) => {\n /*\n * THE AUTH-CARD PRESSES, matched on the LABEL because that is what those buttons\n * carry — `AUTH_CARD_ACTIONS` is keyed by copy.\n */\n if (funnelOpenedBy(action.label)) {\n return () => funnel.open(standing.buyer?.email ?? '');\n }\n /*\n * AND SIGN OUT SIGNS OUT, which it did not: the button fell through to \"advance the\n * walk\", so the buyer stayed signed in and the card moved. Both halves of the store\n * go — see `signOut` in `./domain/auth`, which keeps the guest choice.\n */\n /* Both halves: a session nobody ended is good for a year — see `Session`. */\n if (action.label === AUTH_COPY.SIGN_OUT) {\n return () => {\n void signIns?.signOut();\n auth.signedOut();\n };\n }\n /*\n * AND THE GUEST CHOICE IS RECORDED, which it was not: the press advanced the walk and\n * left the session saying the buyer had decided nothing, so every later checkpoint\n * asked again. It still advances — a press that only changed state reads as a button\n * that did nothing.\n */\n if (action.label === AUTH_COPY.CONTINUE_AS_GUEST) {\n return () => {\n auth.continuedAsGuest();\n forward();\n };\n }\n if (action.picks !== undefined)\n return () => {\n /* `'wallet'` IS THE DEVICE'S ONE WALLET, named here rather than in the static\n * data — see `CardAction.picks`. */\n selectMethod(action.picks === 'wallet' ? walletCharging : action.picks!);\n if (action.opens !== undefined) setDetour(action.opens);\n };\n const opens = action.opens;\n if (opens !== undefined) return () => setDetour(opens);\n /*\n * TRY AGAIN. The failure is dropped and the buyer is back on Review's card —\n * the frame's field is still there, still theirs to correct, and the next Pay\n * press is a new attempt. Nothing here retries the charge itself.\n *\n * BACK, NOT JUST CLEARED: the walk stood on PROCESSING when the failure arrived,\n * and clearing the outcome without stepping back leaves `at` there — the buyer\n * would be shown a fresh Processing card with NOBODY watching the payment (the\n * poll only runs while a charge is in flight), stuck until the tab died. The\n * step back is what makes the next Pay press a real charge: it re-runs the save,\n * bumps the signal, and starts the poll.\n */\n if (action.retries === true)\n return () => {\n updateJourney({ kind: 'idle' });\n order.retryPayment();\n setAt('REVIEW');\n if (collected.paymentMethodKey === 'revolut_pay' && savedRevolutCart !== order.cart?.Key)\n selectMethod('revolut_pay');\n /* THE WALLET RETRIES THE SAME WAY — the failure terminalised its order, and a\n * fresh button on a fresh order is the only honest retry. */\n if (\n isWalletFrameMethod(collected.paymentMethodKey) &&\n savedWalletCart !== order.cart?.Key\n )\n selectMethod(collected.paymentMethodKey);\n };\n /*\n * UPLOAD OPENS THE DEVICE'S OWN DIALOG, and that is all it does — what comes back is\n * `chooseFile`'s. A button cannot open a file picker declaratively, so the input the\n * grid renders is clicked through its ref; see `CardAction.uploads`.\n */\n if (action.uploads === true) return () => photoInput.current?.click();\n /*\n * THE OFFER'S CREATE ACCOUNT. It takes the account route, which is what puts the\n * five steps behind the offer into the walk. Declared on the action; see\n * `CardAction.takesAccount`.\n *\n * AND IT OPENS THE SUB-FLOW BY NAME rather than advancing one stop. This press is\n * what creates those stops, so \"the next one\" would still be read off a plan that\n * does not have them yet — the destination is the sub-flow's own first step, which\n * `ACCOUNT_CREATION_ORDER` already names.\n */\n if (action.takesAccount === true) {\n return () => {\n setAccountChosen(true);\n setAnswered(false);\n setAt(ACCOUNT_CREATION_ORDER[0]!);\n };\n }\n /*\n * THE BUTTON THAT CHARGES. It puts the buyer on the cart first — a payment\n * cannot be attempted against a cart nobody is named on — and only a save that\n * succeeded authorizes the submit signal: a failed one leaves the failure card up\n * and the frame untouched. THE PRESS IS NOT THE CHARGE: the walk advances (and the\n * status poll arms) when the payment host accepts the submission and asks for the\n * buyer — see the card frame's `onSubmitRequested` — so a host that refuses an\n * empty or unready field leaves the buyer on the form instead of on a processing\n * card with nothing on the wire.\n */\n if (action.pays === true) {\n return () => {\n void order.saveBuyer(buyerDetails(orderedBuyer)).then((saved) => {\n if (!saved) return;\n setSubmitSignal((was) => was + 1);\n });\n };\n }\n /*\n * THE RATING GOES, AND THE BUYER DOES NOT WAIT FOR IT. The card advances on the\n * press: the buyer has said their piece, the tickets are already theirs, and\n * holding them on a card while a courtesy crosses the network would make the\n * optional thing the slow thing. A send that then fails raises its own notice in\n * front of wherever they have got to — see `raiseForFeedback`.\n *\n * NOTHING TO SEND IS A NO-OP AND STILL ADVANCES, which is the same press either\n * way as far as the buyer can tell. See `useFeedback`.\n */\n if (action.rates === true) {\n return () => {\n if (collected.rating !== null) feedback.send(collected.rating);\n forward();\n };\n }\n /*\n * AN ACTION THAT SAYS WHAT IT DOES, DOES IT — and this has to be asked BEFORE the\n * detour rule below, which it was not.\n *\n * Every button on a detour went \"back to the card this hangs off\", which was true of\n * every detour there was: the payment list's buttons pick a method and are caught\n * above, and the failure card's retry likewise. The promo card is the first detour\n * with a button of its OWN, and Apply was being swallowed — the card closed, the\n * walk went back to the checkpoint behind it, and nothing was ever sent.\n */\n if (action.onPress !== undefined) return action.onPress;\n if (detour !== null) return () => setDetour(null);\n return forward;\n },\n [\n detour,\n forward,\n order,\n orderedBuyer,\n walletCharging,\n /* The funnel's prefill is the address TYPED, not the order's — see its press below. */\n standing.buyer?.email,\n funnel,\n auth,\n signIns,\n feedback,\n collected.rating,\n selectMethod,\n collected.paymentMethodKey,\n savedRevolutCart,\n savedWalletCart,\n ],\n );\n\n /*\n * WHAT THE CART SAYS, WHERE THE HOST DID NOT. All three were props a host asserted; two\n * of them are answers the platform gives, and the third is news about a charge the widget\n * now opens itself. A host that passes its own still wins — it may know something the\n * cart does not, and it is not this widget's place to argue.\n */\n const drawnQuote = quote ?? order.quote;\n /*\n * AND A HOST'S HOLD RUNS, rather than standing still at whatever it was asserted as —\n * see `useAssertedHold`, which is where that whole argument is. The cart's own hold is a\n * deadline and has always counted itself down.\n */\n const drawnHold = useAssertedHold(hold, Date.now()) ?? order.hold;\n\n /*\n * WHAT CONFIRM EMAIL REPORTS BACK. The three collection steps are controlled and write\n * through `setCollected` at their call sites; this one offers an address the buyer may\n * correct, so it still reports the corrected one here.\n *\n * STABLE, because the step reports through an effect and a fresh callback each render\n * would make that effect run forever.\n */\n const collectEmail = useCallback(\n (email: string) => setCollected((was) => ({ ...was, email })),\n [],\n );\n\n const openCart = useCallback(() => setCartOpen(true), []);\n /*\n * A DETOUR AND NOT A SCREEN. The cart is an overlay on the card; the promo step is a\n * CARD, reached the way the payment list is — so the way out is the header's own back,\n * which `toggle` already sends to `setDetour(null)`.\n */\n const openPromo = useCallback(() => setDetour('PROMO'), []);\n /*\n * WHAT IS TYPED, WHICH IS NOT WHAT IS APPLIED. The order's own code is `cart.PromoCode`\n * and survives everything; this is the field, and it opens showing whatever is on the\n * order so the card's first frame is not a blank box under \"€4.60 Saved\".\n */\n const appliedPromo = promoApplied(order.cart);\n const [promoTyped, setPromoTyped] = useState('');\n useEffect(() => {\n setPromoTyped(appliedPromo ?? '');\n }, [appliedPromo]);\n /* What the code took off, already written — `null` until one has taken anything. */\n const promoSaving =\n order.cart === null || order.quote === undefined || order.quote.kind === 'NONE'\n ? null\n : promoSaved(order.cart, order.quote.currency);\n /*\n * A REFUSED CODE LEAVES THE FIELD AS THE BUYER TYPED IT. The card says why beside it and\n * they correct a character; clearing what they wrote would make them start again for a\n * mistyped letter.\n */\n const applyPromoCode = useCallback(() => order.applyPromo(promoTyped), [order, promoTyped]);\n const closeCart = useCallback(() => setCartOpen(false), []);\n\n /*\n * THE BOOKING EVERY LINE SHARES — the run, the session and the day, off the standing\n * intent rather than off the cart, because the cart's own items say none of it. One\n * cart, one event: what a buyer chose is what every line of it is for.\n */\n const cartDayKey = standing.day ?? '';\n const cartSubject = drawnSchedule?.series.events.find(\n (event) => cartDayKey === '' || event.day === cartDayKey,\n )?.name;\n const cartTimeslot =\n standing.timeslot === undefined\n ? undefined\n : formatSlotRange(\n standing.timeslot,\n drawnSchedule?.slotsByDay?.[cartDayKey]?.find(\n (slot) => slot.startTime === standing.timeslot,\n )?.endTime ?? null,\n );\n const cartDay = cartDayKey === '' ? undefined : formatWeekdayAndDate(cartDayKey);\n\n /*\n * THE DAY THE BOOKING IS FOR — the buyer's own choice where the walk made one, and the\n * SUBJECT EVENT'S OWN DATE where the host settled the day before the island ever saw\n * it, which is every event-subject host: the DATE step is excused for one, so nothing\n * in the walk ever writes a day. Reading the handover's day off the buyer's choice\n * alone mistook that for “no day is known”, and a buyer who had paid was left on the\n * flow's last card pressing a Continue with nothing left to continue to.\n */\n const occasionDayKey =\n standing.day ??\n (standing.subject.kind === 'event'\n ? drawnSchedule?.series.events.find((event) => event.eventKey === standing.subject.key)?.day\n : undefined);\n\n /*\n * ── AND ON TO MY BOOKING ────────────────────────────────────────────────────\n *\n * The last Continue in the walk hands the buyer their tickets. Three things have to hold\n * and each says something different: the walk is over (`finished`), the money actually\n * moved (`PLACED` — a flow abandoned at Review has no booking behind it), and there is a\n * cart for the read to be addressed to.\n *\n * THE OCCASION IS THE CART'S OWN, read off exactly the values the cart screen above draws\n * from. One event, one day, one session: what every line of this order was for is what the\n * booking is for, and building it twice from two places is how the two come to disagree.\n *\n * THE ATTRIBUTION CARRIES THE PRODUCT AND NOT THE USER TYPES, and that is the platform's\n * limit rather than a gap here — see `TicketAttribution`, where the missing join is\n * written down.\n */\n useEffect(() => {\n const key = order.cart?.Key;\n if (!finished || onPlaced === undefined || outcome?.kind !== 'PLACED') return undefined;\n if (key === undefined || occasionDayKey === undefined) return undefined;\n\n const placed = {\n cartKey: key,\n occasion: {\n name: cartSubject ?? '',\n day: occasionDayKey,\n artwork: fetched.artwork ?? null,\n startTime: standing.timeslot ?? null,\n endTime:\n drawnSchedule?.slotsByDay?.[occasionDayKey]?.find(\n (slot) => slot.startTime === standing.timeslot,\n )?.endTime ?? null,\n },\n attribution: { product: order.productName ?? null },\n };\n\n if (bookings === null) {\n onPlaced(placed);\n return undefined;\n }\n\n /*\n * THE READ COMES FIRST AND THE SWAP IS THE TRANSITION — see `PlacedBooking.record`. The\n * buyer stays on the card they just pressed while this is in flight, which is what\n * \"fetch the incoming content before the transition\" means.\n *\n * AND IT HANDS OVER EITHER WAY. A read that failed or found nothing must not strand\n * somebody on the last step of a purchase they have paid for: the booking is opened\n * without a record and says so itself, with the notice and the Try Again this has\n * neither of.\n */\n let live = true;\n bookings\n .read(key)\n .then((record) => {\n if (live) onPlaced(record === null ? placed : { ...placed, record });\n })\n .catch(() => {\n if (live) onPlaced(placed);\n });\n return () => {\n live = false;\n };\n }, [\n bookings,\n finished,\n onPlaced,\n outcome?.kind,\n order.cart?.Key,\n order.productName,\n cartSubject,\n occasionDayKey,\n fetched.artwork,\n standing.timeslot,\n drawnSchedule,\n ]);\n\n /*\n * WHAT THE CART SCREEN LISTS. A host's own wins, as it does for the quote and the hold —\n * it may know the user-type split the wire does not carry. Otherwise the cart's own\n * items are grouped into lines: real names, real counts, the platform's own money.\n *\n * EVERY LINE SHARES THE ORDER'S OWN BOOKING, ITS ARTWORK AND ITS PRODUCT, said once here\n * rather than per row: the cart holds one event filled from one product, and the day, the\n * session, the picture and the name on it are the ones the buyer chose.\n */\n const drawnCartLines = useMemo(\n () =>\n cartLines ??\n cartLinesFrom(order.items, {\n ...(fetched.artwork === undefined ? {} : { artwork: fetched.artwork }),\n /* What the cart was filled with — the items do not reliably name it. */\n ...(order.productName === undefined ? {} : { productName: order.productName }),\n ...(cartSubject === undefined ? {} : { subject: cartSubject }),\n ...(cartTimeslot === undefined ? {} : { timeslot: cartTimeslot }),\n ...(cartDay === undefined ? {} : { day: cartDay }),\n }),\n [\n cartLines,\n order.items,\n fetched.artwork,\n order.productName,\n cartSubject,\n cartTimeslot,\n cartDay,\n ],\n );\n\n /*\n * THE HOLD HAS RUN OUT AND THIS IS A STEP IT INTERRUPTS. `holdExpired` reads the clock;\n * `timeoutTakesOver` decides whether the clock is the buyer's problem where they are\n * standing, and protects a step on each side of the payment.\n */\n /*\n * AND A BUYER WHO HAS ASKED TO START AGAIN IS NOT SHOWN IT AGAIN.\n *\n * `restart` throws away the cart THIS widget opened, which is enough where the hold was\n * ours. Where it came from the host's own prop there is nothing to throw away: the\n * reading stays expired, `timedOut` stays true, and Try Again drew the card it was\n * pressed on. A button that redraws its own card is broken however true the reading\n * behind it.\n *\n * SO THE LATCH IS ABOUT THE BUYER, NOT ABOUT THE HOLD. They have read the news and said\n * what they want to do about it; re-asserting a reservation they have already given up\n * on is the widget arguing with them. It lifts the moment a hold that is NOT expired\n * arrives — that is a new reservation, and the old one has nothing left to say.\n */\n const [timeoutRetried, setTimeoutRetried] = useState(false);\n const holdRunning = drawnHold !== undefined && !holdExpired(drawnHold);\n useEffect(() => {\n if (holdRunning) setTimeoutRetried(false);\n }, [holdRunning]);\n\n const timedOut =\n !timeoutRetried &&\n drawnHold !== undefined &&\n holdExpired(drawnHold) &&\n timeoutTakesOver(stepId);\n\n /*\n * THE HEADER'S TRAILING PILL, AND THE CART SCREEN BEHIND IT — one value, so the two\n * cannot come apart. It answers the three questions that used to be asked separately at\n * the header and again at the screen:\n *\n * IS THERE A HOLD LEFT TO COUNT. `cartIsHeld` says no once the order is PAID — the\n * design drops the summary on the success card, and a timer for a paid order counts\n * nothing.\n *\n * IS THERE MONEY TO DRAW. The pill states a total and the screen is a statement of\n * account; neither is a smaller version of itself without one. A `NONE` quote has no\n * currency either, and money with the wrong symbol in front of it is worse than none.\n *\n * IS THERE A CLOCK. The screen's hero IS the ring and its subtitle IS the countdown, so\n * a cart with no hold behind it would be that card with its hero and its sentence\n * missing.\n */\n const held =\n drawnHold !== undefined &&\n drawnQuote !== undefined &&\n drawnQuote.kind !== 'NONE' &&\n cartIsHeld(orderStatusAt(stepId))\n ? { hold: drawnHold, quote: drawnQuote }\n : undefined;\n\n holdingRef.current = held !== undefined;\n\n /* The same reading as the header draws it: the ring, and what the cart comes to. */\n const summary =\n held === undefined\n ? undefined\n : { hold: held.hold, total: formatMoney(held.quote.minorUnits, held.quote.currency) };\n\n /*\n * AND WHAT MAKES THE MOMENT ARRIVE — the island re-reads the clock while a hold runs,\n * and stops once there is nothing left to count. EVERY hold, the host's included: see\n * `useAssertedHold`.\n *\n * IT DEPENDS ON WHETHER THERE IS A HOLD AND NOT ON THE HOLD ITSELF, which is the\n * difference between an interval and a thing that keeps being thrown away. Both holds\n * are rebuilt on every render — one from `Date.now()`, the other from a fresh object —\n * so an effect keyed on either tore the interval down and started a new 500ms wait every\n * time anything re-rendered. It survived only because nothing else rendered that often;\n * a boolean cannot be starved that way at all.\n */\n const holding = drawnHold !== undefined && !timedOut;\n useEffect(() => {\n if (!holding) return;\n const tick = window.setInterval(() => setClock(Date.now()), HOLD_TICK_MS);\n return () => window.clearInterval(tick);\n }, [holding]);\n const [reviewCartKey, setReviewCartKey] = useState<string | null>(null);\n /*\n * WHAT THE PAYMENT FRAME SAYS IT NEEDS, or `null` before it has said anything. Held\n * here rather than inside the frame because the card that opens the bay is what has to\n * wait for it — see `frameVisible`.\n */\n const [frameHeight, setFrameHeight] = useState<number | null>(null);\n /*\n * ONE SAVE FOR BOTH, AT REVIEW. See the mount effect above for why the frames start\n * earlier than this does.\n */\n /*\n * THE FRAMES MOUNT THE MOMENT THERE IS A CART, WHICH IS THE EARLIEST THERE CAN BE ONE.\n *\n * Not when the island opens: the frame URL is keyed on the cart, and no cart exists\n * until the press at the end of the funnel mints one. That press is a step or two\n * ahead of Review, and that gap is the whole point — three provider documents, each\n * booting the Revolut SDK, take seconds to become a button. Started on ARRIVAL at\n * Review those seconds are a card with nothing on it; started here they run behind the\n * steps in front, and Review opens on entries that are already drawn.\n *\n * THE SAVE STAYS AT REVIEW, and the distinction cost a crash to learn. Moving the save\n * here too put it in front of the steps that collect the buyer, so it went out with\n * empty strings and the platform answered `400` on `Buyer`. Mounting early is safe;\n * naming a buyer who has not been asked yet is not.\n */\n useEffect(() => {\n if (expanded && order.cart !== null) {\n setReviewCartKey(order.cart.Key);\n }\n }, [expanded, order.cart]);\n /*\n * THE SUBMIT SIGNAL. Zero means \"no attempt has been asked for\"; every press of Pay\n * bumps it, and the frame sends one TRIGGER_SUBMIT per bump. Callbacks are held\n * stable here so the frame's listener is not torn down mid-handshake.\n */\n const [submitSignal, setSubmitSignal] = useState(0);\n /*\n * THE BUYER FOR THE CHARGE, in the shape the payment host's card submit reads —\n * camelCase, and no phone: the phone goes to the cart via the platform's own\n * `setBuyer`, not into the frame.\n */\n const buyerForFrame = useCallback((): {\n firstName: string;\n lastName: string;\n email: string;\n } | null => {\n const buyer = order.cart === null ? undefined : orderedBuyer;\n /*\n * THE ADDRESS IS CHECKED, not merely non-empty. This is the last hop before the card\n * field submits it to Revolut, and `''` was the only shape it refused — every other\n * malformed address went through and came back as \"PaymentError Invalid email\n * format\", a declined card for a typo. Every source upstream now narrows it — the\n * host's, the buyer's and the account's, all through `orderBuyer` — so refusing here\n * should be unreachable; it is the floor under them, and a refusal returns the buyer to\n * a form rather than to a decline.\n */\n if (buyer === undefined || buyer.email === undefined || !isValidEmail(buyer.email)) {\n return null;\n }\n return {\n firstName: buyer.firstName ?? '',\n lastName: buyer.lastName ?? '',\n email: buyer.email,\n };\n }, [order.cart, orderedBuyer]);\n\n /*\n * WHICH PROVIDER IS ACTUALLY CHARGING, WRITTEN AT THE MOMENT IT STARTS.\n *\n * `paymentMethodKey` used to be a CHOICE — set by pressing an island button, before\n * anything happened. There is no such press: the provider's own button is the entry, so\n * the island learns which method is in play only when that provider asks for the buyer,\n * which it does when the buyer clicks it. An outcome, not a precondition.\n *\n * IT HAS TO BE WRITTEN, AND THIS IS WHY. The frame's `active` follows `revolutLive` /\n * `walletLive`, and on Review those are true for both. The flow then moves to\n * PROCESSING — off Review — and without a method recorded both frames go inactive\n * mid-charge: the host's inactive-frame guard kills the order creation and the buyer's\n * payment dies between the press and the answer. Recording it here is what keeps the\n * charging frame armed for the whole journey.\n */\n const recordCharging = (method: 'revolut_pay' | 'apple_pay' | 'google_pay') =>\n setCollected((was) =>\n was.paymentMethodKey === method ? was : { ...was, paymentMethodKey: method },\n );\n const chargingWith = (method: 'revolut_pay' | 'apple_pay' | 'google_pay') => () => {\n recordCharging(method);\n return buyerForFrame();\n };\n /*\n * THE BAY — the frame lives here for the whole purchase once a method is chosen,\n * and stays VISIBLE wherever the buyer must see it: the method list, where the row\n * expands into the form; a provider's inline journey; and a failure, where the buyer\n * corrects the same field and tries again. On Review the form stays mounted but\n * hidden — the buyer has seen it, and the card is the review, not the form's\n * container — and Processing hides it for the reason `frameVisible` states. The\n * hold's own view hides it too: it is pre-payment.\n */\n /*\n * EVERY PROVIDER IS ON THE REVIEW CARD AT ONCE, so \"chosen\" is no longer what decides\n * whether a frame is alive there.\n *\n * The card used to name three methods and open a list; picking one armed its frame and\n * hid the other two. There is no list any more and nothing to pick — the wallet button,\n * the Revolut button and the card field are all on the card together, each drawn by the\n * provider that will honour it. A frame that is not armed paints its button and then\n * refuses the press (`createOrder blocked from inactive frame`), so being VISIBLE and\n * being ARMED have to arrive together.\n *\n * ARMING ALL THREE COSTS NOTHING, which is what makes this shape possible at all:\n * `createOrder` is a PROVIDER CALLBACK fired by the buyer's click, not by activation —\n * see the payment host's own `createOrder` guards. Three armed frames mint no orders;\n * the first press mints one, and the host's single-flight guard holds the rest.\n *\n * `paymentMethodKey` still answers which method the buyer ACTUALLY used, written when a\n * frame reports back. It is an outcome now, not a precondition.\n */\n /*\n * TWO SCREENS, AND EACH FRAME BELONGS TO ONE OF THEM.\n *\n * Review carries the two PROVIDER entries — the device's wallet and Revolut Pay — both\n * live, both armed, each a painted button inside its own document. Typing a card is the\n * one method with no such button, so it has a screen of its own behind \"Pay with Card\",\n * and the card frame lives there.\n *\n * ALL THREE STAY MOUNTED THROUGHOUT. Only which is SHOWN moves with the screen: a frame\n * that unmounted on the way to its own card would be a fresh document with none of the\n * provider state the last one built.\n */\n const onReview = stepId === 'REVIEW';\n const cardChosen = collected.paymentMethodKey === 'card';\n const frameActive = expanded && !cartOpen && cardChosen;\n /*\n * AND THERE HAS TO BE A BAY TO BE VISIBLE IN. `frameVisible` moves the card's buttons\n * out of the plane and into the bay, so asserting it without a frame mounted sends\n * Confirm somewhere that is not drawn and the buyer is left on a card with no way\n * forward. The frame needs a cart of its own; until there is one the buttons stay put.\n */\n const frameMounted = order.cart !== null && reviewCartKey === order.cart.Key;\n /*\n * AND NOT UNTIL THE FRAME HAS SAID HOW TALL IT IS.\n *\n * The bay's growth IS the morph — the surface's own height clock animates it — so a bay\n * opened before the height is known opens to a bootstrap value and then CORRECTS, and\n * the correction is a collapse the buyer watches. The payment host reports its height\n * once its field is mounted; this waits for that, so the card grows once, to the right\n * number, and the buttons move with it rather than a frame later.\n */\n const terminalPayment = reported?.kind === 'PAID' || reported?.kind === 'PLACED';\n const revolutChosen = collected.paymentMethodKey === 'revolut_pay';\n const walletChosen = isWalletFrameMethod(collected.paymentMethodKey);\n /* The provider entries stand on Review itself — nothing is chosen to reach them. */\n const revolutLive = revolutChosen || onReview;\n const walletLive = walletChosen || onReview;\n /*\n * THE INLINE JOURNEY'S FAILURE COMES HOME AS A SIGNAL, NOT A FRAME EVENT. When the\n * provider's UI runs as an iframe inside the bay, a failed or cancelled payment ends\n * with that iframe landing on the site's own return page — and the SDK's events never\n * fire, because its iframe navigated away from under it. The return page says so\n * itself, same origin (see `provider-return-signal`), and the island answers by\n * REPLACING THE DEAD FRAME: the provider's redirect destroyed the host page, so no\n * `CANCEL_REQUESTED` could reach it — the only live move is a fresh host page, which\n * the epoch bump mounts with `paymentRetry=1` so it mints a new order for the same\n * cart. A failure stands the PAYMENT_FAILED card up first; a cancel walks calmly back\n * to the review step, whose armed bay now holds a fresh provider button; a success is\n * the finalized word itself (see below). Nothing navigates the buyer away.\n */\n const handleProviderReturnSignal = (signal: ProviderReturnSignal) => {\n if (signal.payload.cartKey !== order.cart?.Key) return;\n /*\n * SUCCESS IS THE FINALIZED WORD. The framed return page is the inline journey's\n * only converter (the host page died at the redirect), and it says so only AFTER\n * the transaction exists — so this is the frame's SUCCESS in signal form: placed,\n * not merely paid. It deliberately answers even a `PAID` outcome, exactly as the\n * frame's own SUCCESS does: the received card is the safe word for money taken\n * without the finalized one, and this is that word arriving late.\n */\n if (signal.payload.status === 'success') {\n order.settledFromFrame();\n return;\n }\n if (terminalPayment) return;\n const kind = journeyRef.current.kind;\n if (kind === 'idle' || kind === 'unresolved') return;\n setRevolutFrameEpoch((value) => value + 1);\n if (signal.payload.status === 'cancel') {\n updateJourney({ kind: 'idle' });\n order.retryPayment();\n setDetour(null);\n setAt('REVIEW');\n } else {\n updateJourney({ kind: 'idle' });\n order.failedFromFrame('Payment was not completed');\n }\n };\n const providerReturnRef = useRef(handleProviderReturnSignal);\n providerReturnRef.current = handleProviderReturnSignal;\n useEffect(() => {\n const onMessage = (event: MessageEvent) => {\n const signal = parseProviderReturnSignal(event, window.location.origin);\n if (signal !== null) providerReturnRef.current(signal);\n };\n window.addEventListener('message', onMessage);\n return () => window.removeEventListener('message', onMessage);\n }, []);\n /*\n * THE ROOM THE INLINE JOURNEY TAKES — derived from the viewport, not a guessed 480.\n * The 480 box clipped the provider's own checkout page into a scrolled window (the\n * 2026-09-11 screenshot), so now: mobile takes the screen with the island's hero and\n * title suppressed, and desktop grows the island to most of the viewport, capped.\n * `journeyPresentation` owns the arithmetic and its tests.\n */\n const journeyInline =\n journey.kind === 'processing' && journey.mode === 'inline_provisional' && !terminalPayment;\n const [viewport, setViewport] = useState(() => ({\n width: window.innerWidth,\n height: window.innerHeight,\n }));\n useEffect(() => {\n if (!journeyInline) return;\n const read = () => setViewport({ width: window.innerWidth, height: window.innerHeight });\n window.addEventListener('resize', read);\n return () => window.removeEventListener('resize', read);\n }, [journeyInline]);\n const journeyRoom = journeyInline ? journeyPresentation(viewport) : undefined;\n const journeyFullscreen = journeyRoom?.fullscreen === true;\n /*\n * ACTIVATION OUTLIVES VISIBILITY. Revolut calls `createOrder` only after the\n * popup page has finished loading — by which time the `away` presentation has\n * already hidden the bay (`revolutVisible` drops with `journeyInline`). If\n * activation followed visibility, the frame would deactivate mid-attempt, the\n * host's inactive-frame guard would kill the in-flight order creation, and the\n * popup would report the order as not valid. So `active` follows the attempt,\n * not the layout: the frame stays the selected method until the journey ends in\n * recovery, resolution, or a terminal state.\n */\n const revolutActive =\n frameMounted &&\n revolutLive &&\n savedRevolutCart === order.cart.Key &&\n !terminalPayment &&\n journey.kind !== 'recovering' &&\n journey.kind !== 'unresolved' &&\n (stepId === 'REVIEW' || stepId === 'PAYMENT_FAILED' || stepId === 'PROCESSING');\n const revolutVisible =\n frameMounted &&\n revolutLive &&\n savedRevolutCart === order.cart.Key &&\n expanded &&\n !cartOpen &&\n !terminalPayment &&\n journey.kind !== 'recovering' &&\n journey.kind !== 'unresolved' &&\n /*\n * NOT THE FAILURE CARD — that card's two buttons are the whole UI there. The bay\n * stays MOUNTED (see `revolutActive` above, which keeps the fresh provider button\n * alive behind the failure) but hidden: showing a provider button beside its own\n * failure's retry controls is the doubled choice the design does not make.\n */\n (stepId === 'REVIEW' || (stepId === 'PROCESSING' && journeyInline));\n /*\n * THE WALLET'S OWN ACTIVATION AND VISIBILITY, the same rules the Revolut frame lives\n * by, with the one difference the wallet's own nature makes: it has no inline journey.\n * The provider's sheet is a native overlay over the whole page, not a page inside the\n * bay, so there is no PROCESSING visibility to hold and no fullscreen room to ask for\n * — the frame is shown on Review, where its button is the entry, and mounted\n * everywhere else its attempt can still be in flight.\n */\n const walletActive =\n frameMounted &&\n walletLive &&\n savedWalletCart === order.cart.Key &&\n !terminalPayment &&\n journey.kind !== 'recovering' &&\n journey.kind !== 'unresolved' &&\n (stepId === 'REVIEW' || stepId === 'PAYMENT_FAILED' || stepId === 'PROCESSING');\n /*\n * A WALLET THE DEVICE CANNOT PAY WITH IS NOT DRAWN AT ALL.\n *\n * The host answers `canMakePayment()` and, when it is no, renders its own sentence in\n * the frame — \"Apple Pay is not available on this device.\" That was the right thing\n * when the wallet was a ROW in a list of methods: the row had to stay so the list did\n * not silently change length, and the note said why it could not be pressed.\n *\n * It is not a row any more, it is one of three ways to pay standing on the card, and a\n * paragraph of apology where a button belongs is worse than the button's absence. The\n * buyer has two other ways to pay and no decision to make about this one. `checking`\n * keeps it hidden too — a wallet that may yet appear must not flash an empty slot.\n */\n const walletVisible =\n frameMounted &&\n walletLive &&\n walletAvailability.kind === 'available' &&\n savedWalletCart === order.cart.Key &&\n expanded &&\n !cartOpen &&\n !terminalPayment &&\n journey.kind !== 'recovering' &&\n journey.kind !== 'unresolved' &&\n stepId === 'REVIEW';\n /*\n * ── THE BAY BELONGS TO THE SCREEN, NOT TO WHAT IS STANDING IN IT ────────────\n *\n * It used to open when the first frame was ready to be seen in it, which reads\n * backwards the first time a buyer reaches Pay: the card arrives built around a bay\n * that does not exist yet, so it opens SHORT — and the hero flies to the middle of a\n * card that is about to be a hundred pixels taller. The cart resolves, the frames\n * mount, the bay appears, and the card corrects underneath an avatar that has already\n * landed. Measured off a recording of the first arrival: the card opened 113px under\n * its own resting height and grew back over the next 600ms.\n *\n * The Pay card's SHAPE is not a fact about whether Revolut has answered. Both payment\n * screens are built around a stack of ways to pay, and the room for it is reserved by\n * the screen (`PAY_SCREEN_ROWS`) — so the bay is open from the card's first frame,\n * empty, at its full height, and the entries fade in where they were always going to\n * be. Nothing moves when they arrive.\n *\n * IT IS ALSO WHAT MAKES THE BUTTONS STAY PUT. `frameVisible` decides whether the\n * card's own actions ride in the bay or upstairs in the plane, so a bay that opened\n * late moved them mid-journey; the old note here warned about the other direction —\n * asserting it with NO bay drawn sends Confirm somewhere the buyer cannot press — and\n * both are answered by there being a bay for the whole of both screens.\n */\n const payScreen = stepId === 'REVIEW' || stepId === 'PAYMENT';\n const bayOpen =\n payScreen &&\n expanded &&\n !cartOpen &&\n !terminalPayment &&\n journey.kind !== 'recovering' &&\n journey.kind !== 'unresolved';\n /*\n * ── THE TYPED FIELD DOES NOT FOLLOW THE BUYER INTO PROCESSING ───────────────\n *\n * It used to, and the argument was 3DS: the card host renders a challenge inside the\n * same frame, so hiding the frame there would hide something the buyer has to see and\n * click. That is still true of a challenge — and it was being paid for by every payment\n * that has none, which is nearly all of them. The buyer presses Pay and the card they\n * have just finished typing sits under the processing card: live, editable, and\n * describing work that has already left the browser.\n *\n * MOUNTED, NOT DRAWN. The frame stays in the bay — the charge is in flight inside it and\n * `frameActive` is what keeps it armed — exactly as the Revolut frame stays mounted\n * behind its own failure card. Only the room it takes is given up.\n *\n * WHAT THIS COSTS, SAID OUT LOUD: a card host that renders a 3DS challenge in-frame has\n * nowhere to draw it. The protocol already has the word for that — `SCOPE_PAYMENT_\n * PRESENTATION` carrying `inline_provisional`, which is what `journeyInline` reads and\n * what keeps the Revolut journey visible here through PROCESSING. The card route in\n * `packages/payment-host` does not send it — only `initializeRevolutPay` wires a\n * presentation detector — so the day a challenge needs the room, the fix is there and\n * the rule below already reads it.\n */\n const frameVisible =\n !terminalPayment &&\n (bayOpen ||\n revolutVisible ||\n walletVisible ||\n (frameMounted && frameActive && frameHeight !== null && stepId === 'PAYMENT_FAILED'));\n const recoveryReady = () => {\n if (journeyRef.current.kind === 'recovering') updateJourney({ kind: 'idle' });\n };\n /*\n * THE FRAME THEME, in the words the payment host's own `parseTheme` reads. The\n * island's mode may be `system`, and a system mode is the SURFACE's CSS that resolves\n * it — but a frame is a separate document that cannot inherit the attribute, so the\n * resolution happens here, once, and the provider's own buttons (whose variant is\n * light or dark) match the surface they sit in.\n */\n const frameTheme = useMemo<Record<string, string>>(\n () => ({\n themeMode:\n mode === 'system'\n ? window.matchMedia('(prefers-color-scheme: light)').matches\n ? 'light'\n : 'dark'\n : mode,\n }),\n [mode],\n );\n /*\n * THE TWO OUTCOMES EVERY EXTERNAL METHOD SHARES — Revolut Pay and the wallet both\n * recover from a cancellation by standing the buyer back on Review with a fresh\n * attempt behind them, and both fail a charge into the failure card. One definition,\n * because these are the words of the provider journey rather than of any one method,\n * and a copy that drifted would make cancelling one method mean something else than\n * cancelling the other.\n */\n const providerCancelled = () => {\n /* A FAILED outcome stands until the buyer retries or changes method; the\n * host's cancellation housekeeping (fresh order, fresh button) must not\n * walk the island back over the failure it just reported. */\n if (terminalPayment || order.payment?.kind === 'FAILED') return;\n if (journeyRef.current.kind === 'unresolved') return;\n updateJourney({ kind: 'recovering' });\n order.retryPayment();\n setDetour(null);\n setAt('REVIEW');\n };\n const providerFailed = (failure: FrameFailure) => {\n if (journeyRef.current.kind === 'unresolved' || terminalPayment) return;\n /*\n * MONEY TAKEN, TICKETS NOT FINALIZED — the host's own TransactionError, whose words\n * say \"payment was received\". The worst move available is the failure card, which\n * offers Try Again and method switching against an order that was already charged;\n * the recovery card is the honest answer, and the charge's own words never resubmit.\n */\n if (failure.code === 'TransactionError') {\n /* SAID, NOT INFERRED — so the recovery card does not wait to be contradicted. */\n setFinalizationRefused(true);\n order.paidWithoutFinalizing();\n return;\n }\n updateJourney({ kind: 'idle' });\n order.failedFromFrame(failure.words);\n };\n /*\n * THE REVOLUT FRAME PREWARMS AT THE REVIEW CARD. The provider's own button takes the\n * best part of a second to paint after its frame mounts — a wait the buyer paid in\n * full between choosing Revolut Pay and seeing anything to press. Mounting the frame\n * the moment the review card is up arms nothing (`active` is false until the choice\n * is made, so the host gets no `selectedMethod` and can create no order) and costs no\n * platform traffic beyond the shared attempt the card frame already minted — it only\n * has the provider's button painted before the choice, so the chooser's press\n * REVEALS a button instead of waiting for one to be built. The card frame was already\n * this way; the Revolut one was only ever mounted on choice.\n */\n /*\n * BOTH EXTERNAL FRAMES ARE MOUNTED AND ARMED THE MOMENT REVIEW HAS A CART.\n *\n * They used to be mounted here and armed by the press that chose them. There is no\n * such press any more — the provider's own button IS the entry — so the arming has to\n * happen without one, and it cannot simply be moved into the mount: an external frame\n * can only charge a cart the buyer is NAMED on, because a cart nobody is named on\n * converts to nothing. That is what `selectMethod`'s save was for.\n *\n * IT WAITS FOR REVIEW BECAUSE IT NEEDS A BUYER. Saving on the cart instead put the\n * call in front of the steps that collect the name and the address, so it went out\n * with empty strings and the platform answered `400` on `Buyer` — and the charge\n * behind it `400`ed in turn.\n *\n * ONE SAVE FOR BOTH, ONCE PER CART. The buyer is the same person whichever button they\n * reach for, so saving per method would be the same call twice and a race between its\n * two answers. The save's answer arms both entries together.\n *\n * IT MINTS NOTHING. Arming sends the frame a `selectedMethod` and no more; the order is\n * minted by the provider's `createOrder` callback, which fires on the buyer's click.\n */\n useEffect(() => {\n const key = order.cart?.Key;\n if (stepId !== 'REVIEW' || key === undefined || revolutCart === key) return;\n setRevolutCart(key);\n setWalletCart(key);\n const request = ++selectionRequest.current;\n void order.saveBuyer(buyerDetails(orderedBuyer)).then((saved) => {\n if (!saved || selectionRequest.current !== request) return;\n setSavedRevolutCart(key);\n setSavedWalletCart(key);\n });\n /* `order` and the buyer are read at the moment the cart appears; re-running on their\n * identity would re-save the same buyer against the same cart on every render. */\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [stepId, order.cart?.Key, revolutCart]);\n /*\n * THE CARD FIELD'S OWN WORDS, as the host reports them on every change: whether the\n * field is ready and whether what is in it can be charged. The Pay button reads this\n * — a charge pressed on a field the host would only refuse is a buyer marched to the\n * processing card with nothing on the wire (see the accepted-submission comment at\n * the frame below). `null` is \"the field has not spoken yet\", and holds the button\n * shut: a slow provider init leaves the field empty, and empty is not payable.\n */\n const [cardStatus, setCardStatus] = useState<PaymentMethodStatus | null>(null);\n /*\n * THE ISLAND'S OWN IDENTITY FOR THIS CART, minted once per cart and carried in every\n * frame URL. The host puts it on the provider's return URLs (a mobile redirect back\n * to the merchant's checkout needs something to resume by), and without it the host\n * says `unknown` — a resume that can identify its cart by nothing. Changing the id\n * remounts the frames (the URL is the iframe's key), which is exactly why it is\n * per-cart: the identity must survive the whole life of one reservation and never\n * change under a mounted frame.\n */\n const checkoutSessionId = useMemo(() => crypto.randomUUID(), [order.cart?.Key]);\n /*\n * THE ENTRIES, WHICH NEED A CART BEFORE THEY CAN EXIST — every one of them is a frame\n * minted against it. The WRAPPER does not (see `bay` below): the room they will stand\n * in is the screen's, and it is held open before they arrive.\n */\n /*\n * THEY COULD NOT BE IN `IslandCard`'s `__buttons`, and the reason is structural, not\n * stylistic. Both `__input` and `__buttons` are rendered by `IslandCard`, which is the\n * PLANE's children, and `IslandHost` swaps planes on every step change — new subtree,\n * fresh mount. Content does not care; an iframe does. Remounting the frame that is\n * handling a charge as the flow moves Review → Processing hands the provider's callback\n * a dead document, mid-payment.\n *\n * So the bay is the persistent twin: `bay__buttons` already existed for exactly this —\n * \"the card's buttons riding with the form\" — and carries `__buttons`'s own rules, a\n * full-width column at `$2`. The entries go in it; it is the one parented where they\n * survive.\n */\n const payEntries = frameMounted ? (\n <>\n {/*\n * THE TYPED CARD IS THE ONE SURFACE WITH NO PROVIDER CHROME OF ITS OWN.\n *\n * The wallet and Revolut each arrive as a painted button that says what it is. The\n * card frame is a bare field on the card's own ground, so with all three stacked\n * together it read as loose text between two buttons. The wrapper gives it the\n * FIELD's own clothes — `InputBackground`, `InputStroke`, the field radius — so the\n * three entries read as three things of the same kind.\n */}\n {/*\n * AND IT IS NOT SHOWN UNTIL IT HAS BEEN MEASURED. The frame opens at\n * `MOUNTING_HEIGHT` — a bootstrap box, because the payment host will not mount its\n * field into one with no size — and that used to be invisible for free: the bay\n * stayed shut until the card frame reported, and the card frame was all the bay\n * held.\n *\n * It holds three now, and the other two have a height the moment they mount, so the\n * bay opens immediately for them. That exposed the card frame mid-bootstrap: 280px\n * of empty bordered box, sitting there for as long as the host took to answer, then\n * collapsing to the real field height. The wait has to be the FRAME's own now, not\n * the bay's.\n */}\n <div className=\"scopetickets-island-bay__field\" hidden={!cardChosen || frameHeight === null}>\n <IslandPaymentFrame\n key={order.cart.Key}\n hostUrl={ENVIRONMENT_URLS[source?.environment ?? 'production'].paymentHostUrl}\n cartKey={order.cart.Key}\n apiKey={appKey}\n checkoutSessionId={checkoutSessionId}\n method=\"card\"\n active={frameActive && !terminalPayment}\n submitSignal={submitSignal}\n cancelSignal={0}\n onStatusChange={setCardStatus}\n onSubmitRequested={() => {\n /*\n * THE CHARGE BEGINS WHERE THE HOST ACCEPTED IT, not where the buyer pressed.\n * The press saves the buyer and bumps the submit signal; this callback is the\n * host saying the submission is real — the field was valid and ready, and the\n * card is about to go on the wire. Advancing (and arming the status poll)\n * only here means a refused submission — an empty field, a host still\n * resetting after the last attempt — leaves the buyer standing on the form\n * they can fix, instead of on a processing card that nothing can end.\n */\n const buyer = buyerForFrame();\n if (buyer === null) return null;\n order.chargeAttempted();\n setDetour(null);\n forward();\n return buyer;\n }}\n onSuccess={order.settledFromFrame}\n onError={providerFailed}\n /* MEASURED ONLY — see `onHeight`. The bootstrap sizes nothing here; revealing on\n * it is what put an empty 280px box on the card for five seconds. */\n onHeight={(h, measured) => {\n if (measured) setFrameHeight(h);\n }}\n theme={frameTheme}\n />\n </div>\n {walletCart === order.cart.Key && (\n /*\n * THE WALLET STANDS ABOVE REVOLUT PAY, which is the order the design draws and the\n * order the buyer wants: one press on a device that already holds the card, then\n * the account button, then the field for typing one out. The bay is a flex column,\n * so this is the stack.\n *\n * OFFSTAGE LIKE THE REVOLUT FRAME BELOW IT, for the same reason: the provider's\n * wallet button has to be laid out to paint and to run `canMakePayment()`, and a\n * box with no size gives it neither. The chooser's press drops the class for the\n * reveal, exactly as the Revolut prewarm does.\n *\n * NO EPOCH AND NO PRESENTATION: the wallet's sheet is native and in-frame — it\n * never redirects the frame away, so the host page never dies and there is no\n * dead attempt to resurrect. A cancel or a decline is the host's own\n * cancellation housekeeping, which re-arms the button itself.\n */\n <div className={walletVisible ? undefined : 'scopetickets-island-bay__offstage'}>\n <IslandPaymentFrame\n key={`wallet:${order.cart.Key}`}\n hostUrl={ENVIRONMENT_URLS[source?.environment ?? 'production'].paymentHostUrl}\n cartKey={order.cart.Key}\n apiKey={appKey}\n checkoutSessionId={checkoutSessionId}\n method={sniffedWalletHostMethod}\n /* Named for what is IN it, which the slot does not know — see `label`. */\n label={walletLabel(walletAvailability, sniffedWallet)}\n heightOverride={PROVIDER_BUTTON_HEIGHT}\n active={walletActive}\n submitSignal={0}\n /* Zero by design: the host honours a parent-driven cancel for `revolut_pay`\n * only, and the wallet's own sheet is the buyer's way out. */\n cancelSignal={0}\n theme={frameTheme}\n onSubmitRequested={chargingWith(walletCharging)}\n /* THE FRESH BOOT ENDS A RECOVERY, as it does for the Revolut frame: the host's\n * cancellation housekeeping re-arms its own button, and this word is how the\n * island learns the journey is over. */\n onReady={recoveryReady}\n onHeight={recoveryReady}\n onStatusChange={(status) => {\n /* AVAILABILITY FIRST, UNCONDITIONALLY: the fold only moves on the host's\n * availability words, and the gate on the buttons below must not go stale\n * because a charge happened to be in flight. */\n setWalletAvailability((was) => walletReport(was, status, sniffedWallet));\n /* AND THE JOURNEY, shared with Revolut Pay — a wallet charge reports\n * itself through the same `METHOD_STATUS` processing words, and the same\n * machine answers. See `revolutStatus`. */\n if (terminalPayment || order.payment?.kind === 'FAILED') return;\n const before = journeyRef.current;\n const next = revolutStatus(before, status);\n /* The wallet records itself the same way the Revolut frame does, and for\n * the same reason — see `chargingWith`. */\n if (next.kind === 'processing') recordCharging(walletCharging);\n updateJourney(next);\n if (\n (next.kind === 'processing' && before.kind !== 'processing') ||\n (next.kind === 'unresolved' && before.kind !== 'unresolved')\n ) {\n order.chargeAttempted();\n setDetour(null);\n setAt('PROCESSING');\n }\n }}\n onCancelled={providerCancelled}\n onSuccess={order.settledFromFrame}\n onError={providerFailed}\n />\n </div>\n )}\n {revolutCart === order.cart.Key && (\n <div\n /*\n * OFFSTAGE, NOT `hidden`. The prewarmed frame has to keep a real viewport for\n * the provider's button to paint into, and `hidden` is display:none — a\n * zero-size box. Offstage takes the frame out of flow (the bay measures only\n * what is really shown) while it stays laid out at full width, invisible and\n * untouchable, and the chooser's press drops the class for the reveal.\n *\n * THE INLINE JOURNEY IS THE THIRD STATE, and it is not a bay state at all:\n * the provider's page goes fixed over the whole screen (see the CSS), because\n * no room the bay can grow to is one the provider's own page did not choose.\n */\n className={\n journeyInline && journeyFullscreen\n ? 'scopetickets-island-bay__journey'\n : revolutVisible\n ? undefined\n : 'scopetickets-island-bay__offstage'\n }\n >\n <IslandPaymentFrame\n /*\n * THE EPOCH IS PART OF THE KEY, NOT ONLY THE URL. Every provider return\n * that destroyed the host page bumps the epoch, and the remount is the whole\n * point — a fresh host document is the only live move when the old one died\n * at the provider's redirect. `retry` alone could not do it: it changes the\n * frame URL once (false to true) and then every later return left the URL,\n * the key, and the dead document exactly as they were. The epoch in the key\n * remounts on EVERY bump, and `retry` keeps telling each fresh page that the\n * stored attempt is dead and a new order must be minted.\n */\n key={`revolut:${revolutFrameEpoch}:${order.cart.Key}`}\n hostUrl={ENVIRONMENT_URLS[source?.environment ?? 'production'].paymentHostUrl}\n cartKey={order.cart.Key}\n apiKey={appKey}\n checkoutSessionId={checkoutSessionId}\n method=\"revolut_pay\"\n active={revolutActive}\n submitSignal={0}\n cancelSignal={cancelSignal}\n retry={revolutFrameEpoch > 0}\n /*\n * THE FULLSCREEN JOURNEY FILLS ITS OVERLAY BY PERCENTAGE. `journeyRoom`'s\n * own arithmetic is the island's room in pixels, but a real phone's viewport\n * is fractional, and `innerHeight` is an integer — an iframe sized to the\n * rounded number inside the true viewport is a subpixel mismatch, and on a\n * real device that mismatch is the one-pixel scroll. `100%` of the fixed\n * overlay is exact at any height.\n */\n heightOverride={\n journeyInline && journeyFullscreen\n ? '100%'\n : (journeyRoom?.height ?? PROVIDER_BUTTON_HEIGHT)\n }\n onSubmitRequested={chargingWith('revolut_pay')}\n onReady={recoveryReady}\n onHeight={recoveryReady}\n theme={frameTheme}\n onStatusChange={(status) => {\n if (terminalPayment || order.payment?.kind === 'FAILED') return;\n const before = journeyRef.current;\n const next = revolutStatus(before, status);\n /*\n * PROCESSING IS ALSO A CHARGE STARTING. `onSubmitRequested` is the other\n * signal and the earlier one, but a provider does not always ask for the\n * buyer before it begins — Revolut's popup journey reports processing\n * first. Both write the method for the same reason: see `chargingWith`.\n */\n if (next.kind === 'processing') recordCharging('revolut_pay');\n updateJourney(next);\n if (\n (next.kind === 'processing' && before.kind !== 'processing') ||\n (next.kind === 'unresolved' && before.kind !== 'unresolved')\n ) {\n order.chargeAttempted();\n setDetour(null);\n setAt('PROCESSING');\n }\n }}\n onPresentation={(presentation) => {\n if (!terminalPayment && journeyRef.current.kind === 'processing')\n updateJourney({ kind: 'processing', mode: presentation.mode });\n }}\n onCancelled={providerCancelled}\n onSuccess={order.settledFromFrame}\n onError={providerFailed}\n />\n </div>\n )}\n </>\n ) : null;\n\n /*\n * AND THE WRAPPER STANDS WHETHER THEY DO OR NOT — see `bayOpen`, which is the whole\n * argument. An empty stack at its reserved height is the Pay card's own shape; the\n * entries fade into it where they were always going to be.\n */\n const bay =\n frameMounted || bayOpen ? (\n <div className=\"scopetickets-island-bay__buttons\">{payEntries}</div>\n ) : undefined;\n\n /*\n * THE CART'S OWN SCREEN — the whole island, not a card inside the current one. It takes\n * no header, no step and no title of the flow's, so it is reached by REPLACING the\n * step's props rather than by adding to them; `cartViewProps` is that swap, written\n * where the rest of the card copy lives.\n *\n * Same component in the same position, so React keeps the island and only the\n * `contentKey` changes — which is exactly the morph, rather than a remount.\n *\n * A NOTICE STANDS IN FRONT OF IT, and of the timed-out card. It is the only card here\n * that is NEWS: the cart is somewhere a buyer chose to go, and one who has just been\n * told they hold four of six tickets must not have that answered for them by a clock or\n * by a press from a moment ago.\n */\n if (notice !== null) {\n return (\n <CheckoutIsland\n mode={mode}\n align={align}\n placement={placement}\n contentKey={`NOTICE:${notice.id}`}\n avatar={\n <Avatar\n subject={{ kind: 'user', avatar: heroAvatar, assets: avatarAssets }}\n size={25}\n fill\n /* The severity's own status, so the badge and the lead button agree. */\n accessory={statusBadge(NOTICE_STATUS[notice.severity], 25)}\n transitionKey={HERO_TRANSITION_KEY}\n />\n }\n {...noticeViewProps(notice, pressNotice)}\n />\n );\n }\n\n /*\n * THE CART BEFORE THE CLOCK STOPPING, so a buyer who opened it is not overruled by a\n * timer mid-read — and after the notice, because a lapsed hold takes over from the flow\n * rather than from a screen somebody asked for.\n */\n if (cartOpen && held !== undefined) {\n return (\n <CheckoutIsland\n mode={mode}\n align={align}\n placement={placement}\n contentKey=\"CART\"\n /*\n * THE FRAME COMES WITH, HIDDEN. This screen replaces the whole island rather than\n * drawing a card inside it, so a bay left behind would UNMOUNT the payment frame\n * and take the provider's session with it — the buyer opens the cart to check the\n * total and comes back to a form that has forgotten them. It is not drawn here:\n * the cart is pre-payment, which is the same reason the hold's own view hid it.\n */\n bay={bay}\n bayVisible={false}\n avatar={\n <Avatar\n subject={{ kind: 'user', avatar: heroAvatar, assets: avatarAssets }}\n size={25}\n fill\n /* The clock over the buyer's face — see `holdBadge`. */\n accessory={holdBadge(held.hold)}\n transitionKey={HERO_TRANSITION_KEY}\n />\n }\n {...cartViewProps(\n <CartLines\n lines={drawnCartLines}\n totalMinorUnits={held.quote.minorUnits}\n currency={held.quote.currency}\n totalLabel={CART_VIEW.total}\n />,\n held.hold,\n closeCart,\n )}\n />\n );\n }\n\n /*\n * AND BEHIND THE NOTICE: a card that could not reach the platform has nothing to type\n * into. The way out is the header's back arrow, onto the card the buyer pressed.\n */\n if (funnelOpen(funnel.state)) {\n return (\n <CheckoutIsland\n mode={mode}\n align={align}\n placement={placement}\n /*\n * ONE KEY FOR THE WHOLE FUNNEL. Its states change the subtitle, and a key per state\n * would cross-fade the card to itself on every one of them.\n */\n contentKey=\"FUNNEL\"\n avatar={\n <Avatar\n subject={{ kind: 'user', avatar: heroAvatar, assets: avatarAssets }}\n size={25}\n fill\n transitionKey={HERO_TRANSITION_KEY}\n />\n }\n {...funnelViewProps(funnel.state, {\n onChange: funnel.change,\n onSubmit: funnel.submit,\n onClose: funnel.close,\n })}\n />\n );\n }\n\n /*\n * THE STOPPED CLOCK TAKES THE OPEN CARD, AND NOT THE PILL.\n *\n * It used to take both, so the island sat on the buyer's page saying \"Your Order Timed\n * Out\" over \"Your tickets have been released\" — a card's two sentences squeezed into one\n * truncating row — and the only thing pressing it did was say them again at full size.\n *\n * COLLAPSING IS STARTING AGAIN. The flow is returned to the stop this widget opens on and\n * the reservation is thrown away, so the pill behind the card is the ordinary entry pill\n * and its action opens a purchase with a new cart. See `startAgain`.\n *\n * A HOST'S OWN HOLD IS NOT OURS TO RESTART, and this does not pretend otherwise: nothing\n * here can renew somebody else's reservation, so a host asserting a hold that has run out\n * gets the news back when the card is opened again. That is the truth about their hold\n * rather than a state this widget is stuck in.\n */\n if (timedOut && expanded && drawnHold !== undefined) {\n return (\n <CheckoutIsland\n mode={mode}\n align={align}\n placement={placement}\n contentKey=\"HOLD_TIMED_OUT\"\n avatar={\n <Avatar\n subject={{ kind: 'user', avatar: heroAvatar, assets: avatarAssets }}\n size={25}\n fill\n /* The clock over the buyer's face — see `holdBadge`. */\n accessory={holdBadge(drawnHold)}\n transitionKey={HERO_TRANSITION_KEY}\n />\n }\n {...timedOutViewProps(expanded, tryHoldAgain, startAgain)}\n />\n );\n }\n\n /*\n * THE RECOGNISED CARD'S PRIMARY IS AN IFRAME, exactly as the passkey STEP's is — and for\n * exactly the same reason: only a document under the RP id may ask for a credential, and\n * transient user activation does not cross a frame boundary. So the button stands here,\n * as the card's own content, and comes out of the action stack below.\n *\n * IT IS NOT A `stepInput` CASE, because this is not a step. `SIGN_IN_RECOGNISED` is a\n * CARD drawn at two checkpoints, and the step underneath it is whatever the walk is\n * standing on.\n */\n /*\n * THE UNRESOLVED WAIT DRAWS ITSELF, as the card's own content: the bay is hidden for\n * an away journey, so without this the card would say only what its subtitle says. The\n * spinner is the busy button's own — the wait is the same word in a bigger slot. It is\n * not a `stepInput` case for the same reason as the passkey button below: this is not\n * a step, it is where the journey has left the card while the platform answers.\n */\n const waitingOnPayment =\n stepId === 'PROCESSING' && journey.kind === 'unresolved' && !terminalPayment;\n const input = offersPasskeySignIn ? (\n <PasskeyButton\n hostUrl={passkeyEnvironment.passkeyHostUrl}\n ceremony={passkeySignInCeremony(signIn.state)}\n label={AUTH_COPY.USE_PASSKEY}\n onResult={signIn.onResult}\n />\n ) : waitingOnPayment ? (\n <div className=\"scopetickets-island-payment-waiting\">\n <ProcessingSlowIcon\n className=\"scopetickets-island-payment-waiting-glyph\"\n style={{ width: 32, height: 32 }}\n />\n </div>\n ) : (\n stepInput(stepId, {\n account: {\n verify: accountFlow.verify,\n refused: accountFlow.refused,\n setPassword: accountFlow.setPassword,\n },\n passkey: {\n hostUrl: passkeyEnvironment.passkeyHostUrl,\n ceremony: passkeyRegistration.ceremony,\n onResult: passkeyRegistration.onResult,\n },\n promo: {\n typed: promoTyped,\n onTyped: setPromoTyped,\n applied: appliedPromo,\n write: order.promo,\n },\n collected,\n setCollected,\n party,\n maxParty: partyCeiling,\n onAnsweredChange: setAnswered,\n schedule: drawnSchedule,\n onPartyRefused: setPartyRefused,\n partyRefused,\n questions: fetched.questions,\n follow: fetched.follow,\n buyerEmail: standing.buyer?.email,\n scheduleDay: chosenDay,\n buyerName: {\n firstName: standing.buyer?.firstName ?? '',\n lastName: standing.buyer?.lastName ?? '',\n },\n passwordRevealed,\n onEmailChange: collectEmail,\n photos: photoOptions,\n photoInputRef: photoInput,\n onFileChosen: chooseFile,\n photoRefused,\n })\n );\n\n /*\n * WHETHER THIS STEP HAS ITS ANSWER. Two shapes report it differently and both are\n * right: a controlled step is answered when the value says so, and a step holding its\n * own fields tells us. A card with no control at all is answered by being read.\n */\n /**\n * WHAT COMPOSE HAS COLLECTED, as one value — the gate below and the header's funnel both\n * read it, so a step cannot be dimmed in one place and open in the other.\n */\n const composeAnswers = {\n composition: collected.composition,\n day: collected.day,\n timeslot: collected.timeslot,\n partyRefused,\n };\n\n const stepAnswered =\n stepId === 'PARTY'\n ? /* The funnel dims the same mark this gate shuts, so both ask `composeAnswered`. */\n composeAnswered('PARTY', composeAnswers)\n : /*\n * A DAY AND A TIME ARE ANSWERS, NOT CARDS READ. The general rule below counts a\n * card with no control as answered — right for Order Review, which IS the step, and\n * wrong for a picker, whose whole job is to collect something.\n *\n * IT WAS THE SECOND, AND AN ORDER WENT OUT SHORT. Nothing mounted a picker, so\n * both steps drew a bare card with a Continue on it, and a host deferring Compose\n * to the widget got a completed intent carrying no day and no timeslot — silently,\n * because every gate in the flow was satisfied. Gating on the answer itself means a\n * step that cannot collect one cannot be walked past, which turns a silent wrong\n * order into an obvious missing picker.\n */\n stepId === 'DATE'\n ? composeAnswered('DATE', composeAnswers)\n : stepId === 'TIME'\n ? composeAnswered('TIME', composeAnswers)\n : /*\n * THE PAYMENT LIST OPENS ON NOTHING, so Confirm waits for the tap that picks a\n * row. It opened on a chosen row while the rows were fixtures and choosing was\n * cosmetic; a row now mounts the card form beneath it, so a step confirmed\n * without one would be a buyer confirming a method they have not given.\n */\n stepId === 'PAYMENT'\n ? collected.paymentMethodKey !== ''\n : /*\n * A FACE IS AN ANSWER, and this grid opens on none chosen — unlike the payment\n * list, which opens on a row. The card asks for a photo and offers no way to\n * decline one, so Continue waits for the tap that picks it.\n */\n stepId === 'PROFILE_PHOTO'\n ? collected.photo !== ''\n : /*\n * A STAR IS AN ANSWER, and the card opens on none — the same rule as the\n * photo grid above it. Continue is what SENDS, so a Continue that could be\n * pressed with nothing chosen would send a rating of nothing; the way past\n * without rating is the Skip beside it, which is a secondary and is not\n * gated on this.\n */\n stepId === 'FEEDBACK'\n ? collected.rating !== null\n : /*\n * A CODE IS AN ANSWER, and this card opens on none — so its own button is\n * the gate rather than this one. `promoSendable` already says whether\n * there is anything to send AND whether the button is Apply or Remove,\n * and the general rule below would have shut BOTH of them: a primary on a\n * card with a control is disabled until this says otherwise, which is how\n * Apply came to be inert on a card where the code was typed and ready.\n */\n stepId === 'PROMO'\n ? true\n : /* Answered by being read, though it draws a list — see the predicate. */\n answeredByReading(stepId)\n ? true\n : /*\n * THE THREE CONTACT STEPS ANSWER FOR THEMSELVES, from what has been typed\n * rather than from the step's own `answered` flag: the cards are rebuilt on\n * every step and a flag held in one does not survive being left and returned\n * to. See `NameStep` and its siblings, which are controlled for the same\n * reason.\n */\n stepId === 'NAME'\n ? isCompleteName(\n standing.buyer?.firstName ?? '',\n standing.buyer?.lastName ?? '',\n )\n : stepId === 'EMAIL'\n ? isValidEmail(collected.email)\n : stepId === 'PHONE'\n ? e164(collected.phone.dialCode, collected.phone.national) !== null\n : input === null || answered;\n\n /*\n * WHOSE NAME GOES ON THE THANKS — the name THE ORDER CARRIES, because that is the person\n * who bought it. A guest declined to give one, so there is none to use; a buyer who never\n * reached the Name step has not given one either, and both read the same way, which is\n * what `paymentSuccessSubtitle` is written around.\n *\n * It used to read the intent and then unpick the account's stored name itself, a third\n * hand-rolled copy of `orderBuyer`'s composition — and one that could greet a buyer by a\n * different name than the one on their tickets.\n */\n const buyerFirstName = session.guest === 'TAKEN' ? null : (orderedBuyer.firstName ?? null);\n\n /*\n * AND WHOSE NAME GOES ON THE WELCOME, which is a different question with a different\n * answer. The guest clause above is about a buyer who declined to give a name; this card\n * exists only because they made an ACCOUNT, and an account is made with the name the\n * order carries. Reading `buyerFirstName` here welcomed \"Alex Whelan\" as nobody.\n */\n const accountFirstName = orderedBuyer.firstName ?? null;\n\n /** Whether this step wears the picker layout — no hero, no title, the run itself. */\n const picker = PICKER_LAYOUT[stepId] === true;\n\n const copy = authCard?.copy ?? STEP_CARD_COPY[stepId];\n\n /*\n * THE TWO CARDS WHOSE SUBTITLE IS NOT A CONSTANT. The failure's is the provider's own\n * sentence and the success's carries a name, so both are written over the static copy\n * rather than declared beside it — `STEP_CARD_COPY` holds what each can say with\n * nothing to hand.\n */\n const subtitle = paidRecovery\n ? 'Your payment was received, but we could not finish placing your order.\\nOur support team will complete it for you.'\n : stepId === 'PAYMENT_FAILED' && outcome?.kind === 'FAILED'\n ? outcome.reason\n : stepId === 'PAYMENT_SUCCESS'\n ? paymentSuccessSubtitle(buyerFirstName)\n : /*\n * THE PAY CARDS COUNT THE HOLD DOWN, in the words the cart screen used to carry\n * — and over the same ring, which they already wear on their hero. The clock\n * belongs where the buyer decides to pay rather than where they check what they\n * are buying.\n *\n * BOTH OF THEM, AND THAT IS THE POINT OF THE PLURAL. The card screen is the same\n * purchase under the same hold — a buyer typing a card is the buyer most likely\n * to run out of time, and it was the one screen that stopped telling them. Saying\n * it on both also makes the pair the same SHAPE: two cards that differ by a line\n * of copy differ by a line of height, and these two are meant to be one card with\n * its contents changed. See `PAY_SCREEN_ROWS` for the other half of that.\n *\n * AND THE CREDIT STANDS WHERE THERE IS NOTHING TO COUNT — see `POWERED_BY`, whose\n * own note says why it came back: without it nothing on the card says whose\n * checkout this is. A card with no hold has the room for it; one with a hold has\n * something more useful to say in the only line it has.\n */\n stepId === 'REVIEW' || stepId === 'PAYMENT'\n ? drawnHold === undefined\n ? POWERED_BY\n : CART_VIEW.remaining(formatHold(drawnHold))\n : copy?.subtitle;\n const lines = drawnQuote === undefined ? null : quoteLines(drawnQuote);\n /*\n * THE THREE CARDS WHOSE TITLE IS NOT A CONSTANT, in the order they outrank each other.\n *\n * PAID READS FIRST, because it overwrites whatever step the buyer is standing on.\n *\n * \"Welcome, Alex!\" is the design's, and the name is the whole of what it adds over \"your\n * account has been made\" — see `accountCreatedTitle`, where the nameless reading lives.\n *\n * AND THE REVIEW CARD'S TITLE IS THE QUOTE'S OWN MONEY, with nothing invented where\n * there is no quote to read: `STEP_CARD_COPY.REVIEW` holds the neutral title a\n * quote-less card falls back to, the same way it holds what the outcome cards overwrite.\n */\n const title = paidRecovery ? (\n 'Payment Received'\n ) : stepId === 'ACCOUNT_CREATED' ? (\n accountCreatedTitle(accountFirstName)\n ) : stepId === 'REVIEW' && lines !== null ? (\n `Pay ${lines.headline}`\n ) : /*\n * AND THE PROMO CARD'S TITLE IS WHAT THE CODE TOOK OFF, once one has. It is the\n * MONEY and not a percentage — see `promoSaved`, where the reason no endpoint\n * can answer for a rate is written down.\n */\n stepId === 'PROMO' && promoSaving !== null ? (\n <span className=\"scopetickets-island-promo__saved\">{PROMO_COPY.saved(promoSaving)}</span>\n ) : (\n copy?.title\n );\n /*\n * THE CARDS WHOSE BUTTONS SAY SOMETHING THAT CHANGES WHILE THEY ARE ON SCREEN.\n * Everything else takes its stack straight off `STEP_CARD_ACTIONS`.\n */\n const baseActions = authCard?.actions ?? STEP_CARD_ACTIONS[stepId];\n /*\n * AND THE ONE PRESS THAT OPENS THE CART SAYS SO, rather than reading as one more step\n * of composing. Which card that is depends on the event — see `pressCreatesOrder` —\n * so it is decided from the walk here and not declared beside the step's own buttons.\n */\n const creatingOrder = pressCreatesOrder(stepId, walk.stops[index + 1]?.step);\n const cardActions: readonly CardAction[] = ((): readonly CardAction[] => {\n /* PAID READS, AND OFFERS NOTHING: both buttons on the walk's card would be a charge. */\n if (paidRecovery) return [];\n if (journey.kind === 'unresolved') return [];\n if (stepId === 'PROCESSING' && journey.kind === 'processing' && !terminalPayment)\n return [\n {\n role: 'secondary',\n label: 'Cancel',\n onPress: () => setCancelSignal((value) => value + 1),\n },\n ];\n if (creatingOrder) {\n return baseActions.map((action) =>\n action.role === 'primary' ? { ...action, label: CREATE_ORDER_LABEL } : action,\n );\n }\n /*\n * ONE BUTTON, AND WHICH ONE DEPENDS ON WHAT THE ORDER CARRIES.\n *\n * APPLY while the field holds something that is not already on the order — which is\n * the design's own reading of its dim state: empty is nothing to send, and unchanged\n * is a round trip that can only answer with what is already on screen.\n *\n * REMOVE once a code is applied and the field still shows it, because the design draws\n * no other way back to full price and a buyer who applied the wrong one would\n * otherwise have to abandon the cart to fix it. Editing the field turns it back into\n * Apply, which is why this is read off `promoSendable` rather than off the cart alone.\n */\n /*\n * THE TWO ANSWERS TO \"ARE YOU SURE?\". Confirm IS `startAgain` — the same act the\n * stopped clock performs, reached deliberately instead of by running out: the\n * reservation goes back on sale, the walk returns to the stop this widget opens on,\n * and what the buyer ANSWERED survives, so pressing Get Tickets again is quick.\n *\n * Return to Order is the detour's own way back and nothing more.\n */\n if (stepId === 'ABANDON') {\n return [\n { role: 'primary' as const, label: 'Confirm', onPress: leaveOrder },\n { role: 'secondary' as const, label: 'Return to Order', onPress: () => setDetour(null) },\n ];\n }\n if (stepId === 'PROMO') {\n const sendable = promoSendable(promoTyped, appliedPromo);\n const busy = order.promo.status === 'SAVING';\n return [\n sendable\n ? {\n role: 'primary' as const,\n label: PROMO_COPY.apply,\n disabled: busy,\n onPress: () => void applyPromoCode(),\n }\n : {\n role: 'primary' as const,\n label: PROMO_COPY.remove,\n /* Nothing to remove is the design's dim Apply, wearing the other word. */\n disabled: busy || appliedPromo === null,\n onPress: () => void order.removePromo(),\n },\n ];\n }\n /*\n * THE PASSKEY CARD KEEPS ONLY ITS SKIP. Its primary is drawn by the ceremony document\n * as the step's own content — a credential can only be made by a page under the RP id,\n * so the press has to land there and activation does not cross a frame. Stripped here\n * rather than left out of `STEP_CARD_ACTIONS`, so the table still says what the card\n * offers and the words have one home.\n */\n if (stepId === 'PASSKEY') {\n return baseActions.filter((action) => action.role !== 'primary');\n }\n /*\n * AND THE RECOGNISED CARD LOSES ITS \"USE PASSKEY\" FOR THE SAME REASON — the frame above\n * is drawing it. What is left is the way to a password and the way out, which is what a\n * buyer whose device cannot or will not needs.\n */\n if (offersPasskeySignIn) {\n return baseActions.filter((action) => action.label !== AUTH_COPY.USE_PASSKEY);\n }\n if (stepId === 'PASSWORD') {\n /* A button on the card with the eye beside it — `AddPasswordQuestion`'s shape. */\n return baseActions\n .map((action) => (action.role === 'secondary' ? action : action))\n .concat([\n {\n role: 'secondary',\n label: passwordRevealed ? 'Hide Entered Text' : 'Show Entered Text',\n mark: {\n side: 'leading',\n node: passwordRevealed ? (\n <EyeToCenterWithStrikethroughIcon size={14} color=\"currentColor\" />\n ) : (\n <EyeToCenterIcon size={14} color=\"currentColor\" />\n ),\n },\n onPress: () => setPasswordRevealed((was) => !was),\n },\n ]);\n }\n if (stepId === 'VERIFY_EMAIL') {\n /*\n * It says how long it is shut for: a disabled button that does not explain itself\n * reads as broken. THE COUNTDOWN AND THE REFUSAL ARE READ SEPARATELY, because a code\n * still in flight counts down from nothing — see `canResend`.\n */\n const left = accountFlow.resendSeconds;\n return baseActions.map((action) =>\n action.label === 'Re-send'\n ? {\n ...action,\n label: left > 0 ? `Re-send (${left}s)` : 'Re-send',\n disabled: !accountFlow.canResend,\n onPress: accountFlow.resend,\n }\n : action,\n );\n }\n /*\n * THE BUTTON THAT CHARGES SAYS THE MONEY, AND IT IS THE CARD FORM'S. Review's three\n * buttons name METHODS — they are the choice, not the commitment — and the one that\n * takes the money is the one under the field the card is typed into.\n *\n * NEVER A CARD'S OWN NAME. Saved payment methods do not exist, so a button reading\n * \"Pay with Mastercard • 1123\" would be naming one the buyer has never given us. The\n * quote's own headline is the one thing that is true in every state.\n */\n /*\n * REVIEW'S ONE BUTTON IS THE CARD FIELD'S, and it carries the money in words.\n *\n * The three method buttons are gone with the list they opened — each provider now\n * draws its own control in the bay. What is left is the press the card field has no\n * provider to draw for it, so the gate is the FIELD's readiness, exactly as it was\n * when this button lived a card later: the host reports the field's state as it\n * changes, and a Pay that could only be refused is the stuck-processing card in\n * button form.\n */\n if (stepId === 'PAYMENT') {\n if (!cardChosen) return [];\n return baseActions.map((action) =>\n action.pays === true\n ? {\n ...action,\n /* THE DESIGN'S OWN WORDS, not the quote's. The total is already on the hero\n * above the field and in the header pill; a third statement of it on the\n * button is the same number said three times. */\n label: 'Pay Now',\n /*\n * AND IT IS SHUT WITH NO ORDER UNDER IT, OR NO FIELD TO CHARGE. The charge\n * saves the buyer against the cart and does nothing at all when there is no\n * cart to save them to — `saveBuyer` answers false and the press falls\n * silently on the floor, which is the one thing a button that commits money\n * must never do. A widget with no platform behind it says so by being\n * unpressable, as the wallets do. THE FIELD'S OWN READINESS GATES IT TOO:\n * the host reports the card field's state as it changes, and a Pay that\n * could only be refused — an empty field, a provider still initializing —\n * is the stuck-processing card in button form.\n */\n disabled:\n order.cart === null ||\n cardStatus === null ||\n cardStatus.ready !== true ||\n cardStatus.valid !== true,\n }\n : action,\n );\n }\n /* The way back to the list is the design's own — the retry clears the failure. */\n if (stepId === 'PAYMENT_FAILED') {\n return baseActions.map((action) =>\n action.retries === true ? { ...action, label: 'Try Again' } : action,\n );\n }\n return baseActions;\n })();\n\n /*\n * WHERE THE BUTTONS SIT. With the frame visible the card's own buttons ride WITH the\n * form in the bay (the SDK selector's own order: the chosen row expands into the\n * field, the CTA sits beneath it, at the card's bottom) — a Confirm left upstairs\n * would sit ABOVE the field it confirms and read upside down. Processing draws no\n * buttons at all, so the split is empty there and the bay is the frame alone.\n */\n const frameUpstairs = !frameVisible;\n const bayActions = frameUpstairs ? [] : cardActions;\n const planeActions = frameUpstairs ? cardActions : [];\n\n /*\n * ── THE TWO PAYMENT SCREENS ARE ONE CARD ────────────────────────────────────\n *\n * Review and the card screen hold the same stack in the same place and differ only in\n * what is standing in it: Review has a way to pay per provider — the card field once\n * the buyer has chosen one, Revolut Pay, the device's wallet where there is one — and\n * the door to the card screen; the card screen has the field, Pay Now and Back.\n *\n * MEASURED, THEY ARE NEVER THE SAME HEIGHT TWICE. Every entry in that stack arrives on\n * somebody else's clock: the payment host reports the field's height when its provider\n * has mounted one, the platform answers whether the wallet can pay whenever it answers,\n * and pressing \"Pay with Card\" puts the field on Review too. So the card resized under\n * the buyer's hand on the way into the screen, again on the way back out of it, and\n * again a second later when a frame changed its mind.\n *\n * BOTH SCREENS RESERVE THE TALLER ARRANGEMENT and neither one moves. The count is what\n * crosses — the row's own height is `$13` and belongs to the stylesheet, which draws\n * it. It is a FLOOR: a frame with more to show than this (a provider's 3DS challenge)\n * still grows the card, on the morph's own clock like everything else.\n */\n /*\n * THREE, FLAT — the three ways to pay this card offers, which is the same three on both\n * screens: Review draws the wallet, Revolut Pay and the door to the card; the card screen\n * draws the field, Pay Now and Back.\n *\n * IT WAS `3 + walletRow`, AND THE RESERVE MOVED. The fourth row was the card field\n * standing on Review beside the other three, which only happens to a buyer who has been\n * to the card screen and come back — and buying room for it cost every buyer an empty\n * row, on a card whose whole point is that it does not move. Worse, `walletRow` came\n * from an answer that arrives late, so the reserve itself grew a row the moment the\n * wallet reported: the one thing this number exists to prevent.\n *\n * A FLOOR, NOT A CEILING — the note above still holds. The returning buyer's fourth row\n * grows the card on the morph's own clock, exactly as a provider's 3DS challenge does.\n */\n const PAY_SCREEN_ROWS = 3;\n const bayRows = payScreen ? PAY_SCREEN_ROWS : 0;\n\n /*\n * CARD ACTION TO ISLAND ACTION, shared by both homes: the card plane and the bay\n * draw the same buttons, and the primary's gate on the step's own answer applies\n * wherever the button sits — a Confirm beneath the form is as unable to advance an\n * unanswered step as one above it.\n */\n const toIslandActions = (actions: readonly CardAction[]) =>\n actions.map((action, position) => ({\n key: `${stepId}-${position}`,\n role: action.role,\n mark: action.mark,\n label: action.label,\n disabled: action.disabled === true || (action.role === 'primary' && !stepAnswered),\n onPress: pressFor(action),\n }));\n\n /*\n * THE HERO — the buyer, badged with whatever the step is asking for.\n *\n * A CARD'S OWN BADGE WINS OVER THE STEP'S, which is the rule `STEP_BADGES` is written\n * against: Create Account carries its badge on `AUTH_CARDS` and deliberately has no\n * entry there, and the sign-in cards that want NO badge have neither, so `??` reaching\n * `null` is the design and not a gap.\n *\n * A STATUS SITS BETWEEN THE TWO. It outranks the step's own badge because it reports\n * what is HAPPENING rather than what is being asked for, and it yields to a card that\n * brought its own — no step does both today, and the order says which way it would go.\n */\n /*\n * `size` PICKS THE GEOMETRY; `fill` ONLY HANDS OVER THE BOX. They are separate props and\n * the package says why: \"fill is not a third size\". The proportions inside the box\n * differ between the two designs — the photo is 84% of the box at `$25` and 80% at\n * `$10`, the notch cutout 56% against 60%, the badge slot 48% against 50% — so one is\n * not the other scaled up.\n *\n * Omitting it took the default, `10`, and drew the small avatar's proportions at 100px:\n * a badge two pixels too big with a corner two pixels too tight, and a photo four too\n * small. The island's own markup is the package README's example of this mode, and it\n * carries `size={25}`.\n */\n const heroSize = expanded ? 25 : 10;\n /*\n * THE CLOCK OVER THE BUYER'S FACE, on the two cards where the money is. The design draws\n * the pay card's hero wearing the escrow timer — the same ring the cart screen and the\n * timed-out card carry, reading the same hold the header's pill counts.\n *\n * BOTH CARDS AND NOT JUST THE FIRST: the hold keeps running while the card number is\n * typed, and a ring that vanished on the way into the form would say the opposite.\n *\n * IT STANDS WHERE A STEP BADGE WOULD, and yields to one. Neither of these two declares\n * a badge of its own, so nothing is displaced — but a card that later does keeps it,\n * because what a step is ASKING for outranks how long is left to ask it in.\n */\n /*\n * A WAY OUT ON EVERY STEP A BUYER MAY LEAVE, the entry included — see `UNCLOSABLE_STEPS`\n * for the ones they may not. A card-mode entry used to draw none, because leaving\n * redrew the card the buyer was on; `leaveOrder` lands that one on the pill instead.\n */\n const closable = !UNCLOSABLE_STEPS.has(stepId);\n\n const payHoldBadge =\n (stepId === 'REVIEW' || stepId === 'PAYMENT') && drawnHold !== undefined\n ? holdBadge(drawnHold)\n : null;\n const hero = (\n <Avatar\n subject={{ kind: 'user', avatar: heroAvatar, assets: avatarAssets }}\n size={heroSize}\n fill\n accessory={\n authCard?.accessory === undefined\n ? (statusAccessory(stepId, heroSize) ??\n heroAccessory(STEP_ACCESSORY[stepId]) ??\n payHoldBadge)\n : heroAccessory(authCard.accessory)\n }\n transitionKey={HERO_TRANSITION_KEY}\n />\n );\n\n return (\n <CheckoutIsland\n mode={mode}\n align={align}\n placement={placement}\n expanded={expanded}\n /*\n * THE INLINE JOURNEY STAMPS THE ROOT — a fullscreen overlay is fixed to the\n * viewport, which the centred island's own `translateY(-50%)` would otherwise\n * hijack as its containing block. See the CSS for what the stamp does.\n */\n journeyFullscreen={journeyInline && journeyFullscreen}\n contentKey={`${detour === null ? '' : 'detour:'}${stepId}:${prompt?.kind === 'CARD' ? prompt.card : ''}`}\n onToggle={toggle}\n dismiss={dismiss}\n sealed={sealed}\n closable={closable}\n bay={bay}\n /*\n * THE BAY'S BUTTONS: when the form shows, the card's own actions ride with it —\n * `bayActions` — and the card plane keeps only the secondaries that open the\n * detour (none, once the detour is open, because `bayActions` holds them all).\n * With the form hidden the split is empty and the card draws every action\n * itself, as it always did.\n */\n /*\n * THE BAY SHOWS WHEREVER THE BUYER MUST SEE THE FORM: the method list it expands\n * under, a provider's own inline journey, and a failure, which keeps the field for\n * the corrected retry. Review keeps it mounted but hidden — the form is behind its\n * own step, not sprawled under the Pay — and so does Processing, where the card has\n * already gone. See `frameVisible`.\n */\n bayVisible={frameVisible}\n /* THE PAIR IS ONE HEIGHT — see `PAY_SCREEN_ROWS`. */\n bayRows={bayRows}\n /* A PICKER HAS NO HERO: the entry step has already said at full size what is being\n * asked for, so the card opens on the run itself. */\n avatar={picker || journeyFullscreen ? undefined : hero}\n /*\n * A PICKER PASSES NO TITLE, which is `CheckoutIslandProps.title`'s own rule and was\n * going unread: the entry step has already said at full size what is being asked for,\n * so the card opens on the RUN. Handing it \"Select Day\" put a heading over a calendar\n * that is already a calendar, and pushed the run down the card to make room for it.\n */\n title={picker || journeyFullscreen ? undefined : title}\n subtitle={\n picker || journeyFullscreen\n ? undefined\n : journey.kind === 'unresolved' && !terminalPayment\n ? unresolvedAged\n ? 'We could not confirm cancellation. We are checking your payment. If this continues, contact support before trying another payment.'\n : 'Checking your payment…'\n : journey.kind === 'processing' &&\n journey.mode === 'external_handoff' &&\n !terminalPayment\n ? 'Complete your payment in the Revolut window or app.'\n : subtitle\n }\n /*\n * AND THE PERIOD GOES IN THE HEADER, as two pills beside the way out — the month, and\n * the year beside it. `CalendarGrainButton` has been built and measured (it shortens\n * `December` to `Dec.` against a probe, and a year never shortens because `'26` is a\n * different claim) and nothing was mounting it.\n */\n /*\n * THE COMPOSE STEPS, AT THE TRAILING END — the design's\n * `HeaderButtons-TicketSelectionFunnel`, and the way back into a question already\n * answered. Drawn from the WALK's own stops, so a step this order excuses is not\n * offered; empty past Compose, where the cart summary takes the slot instead.\n */\n headerTrail={\n /*\n * ONE SLOT, TWO OCCUPANTS, AND THE ORDER DECIDES WHICH. Before there is one the\n * funnel holds the questions Compose asks; after, the commit pill holds the cart\n * and the promo code. `summary` used to be a prop of its own with a precedence\n * rule against this one — see `IslandHeaderProps.headerTrail`, where that is\n * argued away.\n *\n * `summary` IS STILL THE READING, under its own name: it is defined exactly when\n * there is a held order, which is what the buyer's Order intent creates and what a\n * placed payment takes away again. So the pill arrives and leaves on its own.\n */\n /*\n * AND NOTHING AT ALL INSIDE THE PROMO CARD, the same way the cart screen draws no\n * pill: both are what the pill OPENS, and a control that re-opens the card you are\n * standing on is a control that does nothing. The way out is the header's back.\n */\n detour === 'PROMO' || cartOpen ? undefined : summary === undefined ? (\n <ComposeFunnel\n stops={composeFunnel(\n walk.stops.map((stop) => stop.step),\n composeAnswers,\n stepId,\n )}\n onGo={goToStep}\n label={COMPOSE_FUNNEL_LABEL}\n />\n ) : (\n <IslandCommitPill\n onOpenCart={openCart}\n cartLabel={CART_VIEW.label(summary.total)}\n onOpenPromo={openPromo}\n promoLabel={PROMO_COPY.open}\n />\n )\n }\n /*\n * ── NO SECOND PILL BESIDE THE WAY OUT ───────────────────────────────────\n *\n * `CalendarGrainButton` stood here on both pickers: the YEAR over a month grid, the\n * MONTH over a week strip, and pressing the second went up to the first. The design's\n * Compose header has two things in it and that is not one of them — the way out\n * leads, the steps trail, and a third pill between them is a period nobody asked\n * about sitting where the buyer looks for the way back.\n *\n * WHAT IT ANSWERED IS STILL ANSWERED. The month grid names its own months down the\n * run, and the week strip names the month it is showing above the row — see the\n * pickers, which draw it either way. The pill was a second voice for both.\n *\n * The component and its measuring hook stay where they are; a host mounting a picker\n * on its own page may still want a period named over it. Nothing in this widget\n * mounts one.\n */\n /*\n * THE PILL SAYS THE PRICE, NOT THE CARD. `QuoteLines` calls itself \"the two lines\n * the pill shows\" and it always meant these two: the qualifier over the money —\n * \"From\" over \"€56.00\", or \"Save €4.00\". Handing the card's copy down instead put a\n * sentence written for a card into one truncating row.\n *\n * NO QUOTE, NO LINES, and the pill drops the whole text column rather than\n * inventing something — there is no price to state, and the action still says what\n * pressing it does.\n */\n pillCopy={{ title: lines?.headline, subtitle: lines?.qualifier ?? undefined }}\n /*\n * THE CARD SCREEN DRAWS NO SELECTOR.\n *\n * This prop carried `PaymentMethods` for `PAYMENT` — a list of SAVED methods over a\n * single live row, from when the step was called Select Payment Method. There are no\n * saved methods, and the two provider entries are frames on the card BEHIND this one.\n * What belongs here is the field, which is the payment host's and lives in the bay,\n * so this step's own region is empty. `stepInput` says the same thing from the other\n * side, and is now the only thing that answers.\n */\n input={input}\n /*\n * THE STEP'S OWN COLLAPSED LABEL — \"Select Party\", \"Review Order\". The price was\n * here, which put the money on the button and left the pill's two lines to the\n * card; both belong the other way round.\n */\n /*\n * THE FIRST PRESS OF A NEW SESSION SAYS WHAT THE WIDGET IS FOR. Every other stop's\n * pill names the question behind it — \"Select Day\", \"Review Order\" — which is right\n * once a buyer is inside something, and wrong as the very first thing they see: the\n * opening pill was \"Select Party\", a step's name offered to somebody who has not\n * agreed to buy anything yet.\n *\n * POSITIONAL AND NOT PER-STEP, because which step opens depends on what the event\n * excuses — a run with one session opens on the calendar, one with no user types on\n * the day. Whichever it is, the first press is Get Tickets.\n */\n actionLabel={\n detour === null && index === 0\n ? openingLabel?.trim() || OPENING_LABEL\n : step.collapsed.kind === 'PILL'\n ? step.collapsed.actionLabel\n : step.name\n }\n actions={toIslandActions(planeActions)}\n bayActions={toIslandActions(bayActions)}\n />\n );\n}\n\n/** Everything a step's control needs to draw itself and report an answer. */\ntype StepInputContext = {\n readonly collected: Collected;\n readonly setCollected: (update: (was: Collected) => Collected) => void;\n readonly party: PartyTypes;\n readonly maxParty: number;\n readonly onAnsweredChange: (answered: boolean) => void;\n readonly schedule: CheckoutSchedule | undefined;\n readonly onPartyRefused: (asked: number | null) => void;\n readonly partyRefused: number | null;\n readonly questions: readonly QuestionnaireQuestion[];\n readonly follow: readonly FollowEntity[];\n /**\n * @Zsolt — AUTH SURFACE. The address the order was placed with, which Confirm Email\n * opens on. Absent where the host composed the order without one.\n */\n readonly buyerEmail: string | undefined;\n readonly buyerName: { readonly firstName: string; readonly lastName: string };\n /** The day the order is for — see `chosenDay`, which resolves it once. */\n readonly scheduleDay: string | undefined;\n readonly passwordRevealed: boolean;\n /** Where a corrected address goes — see `collectEmail`. */\n readonly onEmailChange: (email: string) => void;\n /** The photo grid's cells — SEE `photoOptions`. Empty where the step is excused. */\n readonly photos: readonly ProfilePhotoOption[];\n readonly photoInputRef: RefObject<HTMLInputElement>;\n readonly onFileChosen: (file: File) => void;\n /** Why the last file was refused, or `null` while none was. */\n readonly photoRefused: PhotoRefusalCode | null;\n /**\n * THE PASSKEY STEP'S BUTTON, which is not one this package can draw — see\n * `PasskeyButton`. The ceremony is `null` while a challenge is being opened, or where\n * one could not be, and the card keeps its Skip either way.\n */\n /**\n * THE ACCOUNT SUB-FLOW, as the three cards that drive it need it. Handed down rather\n * than reached for: a step that held the gateway itself would be a component talking to\n * the platform.\n */\n readonly account: {\n readonly verify: (code: string) => void;\n readonly refused: boolean;\n readonly setPassword: (password: string) => void;\n };\n readonly passkey: {\n readonly hostUrl: string;\n readonly ceremony: PasskeyCeremony | null;\n readonly onResult: (result: PasskeyResult) => void;\n };\n /**\n * THE PROMO CARD'S FIELD. What is TYPED is the card's own state and what is APPLIED is\n * the cart's — see `domain/promo`, where that split is argued — so this carries both and\n * the card never has to ask which of them it is looking at.\n */\n readonly promo: {\n readonly typed: string;\n readonly onTyped: (value: string) => void;\n readonly applied: string | null;\n readonly write: PromoWrite;\n };\n};\n\n/**\n * WHICH CONTROL A STEP DRAWS, or null where the card IS the step.\n *\n * Review, Processing and More Information have no control by design: the first is the\n * quote, the second takes no input at all, and the third is a gate onto questions that\n * vary in number and height per event and so cannot sit in a card of fixed height.\n */\nfunction stepInput(stepId: PurchaseStepId, context: StepInputContext): ReactNode {\n const {\n account,\n passkey,\n collected,\n setCollected,\n party,\n maxParty,\n onAnsweredChange,\n schedule,\n onPartyRefused,\n partyRefused,\n questions,\n follow,\n buyerEmail,\n buyerName,\n scheduleDay,\n passwordRevealed,\n onEmailChange,\n photos,\n photoInputRef,\n onFileChosen,\n photoRefused,\n } = context;\n\n switch (stepId) {\n /*\n * THE CARD FORM DRAWS ITSELF, IN THE BAY. This step was a list of methods with a\n * Confirm under it; there is nothing to list, because there is nothing saved and card\n * is the one thing the platform takes. The buyer arrives by pressing \"Pay with Card\",\n * and what they need here is the field — which is the payment host's, inside its own\n * frame, mounted in the bay so no card number is ever in this bundle or the host's\n * page. The card's own region is empty on purpose.\n */\n case 'PAYMENT':\n return null;\n /*\n * THE TWO PICKERS. Both were unreachable: `stepInput` answered `null` for them, so the\n * cards drew nothing and the steps were walked past. `DayPicker` and `TimePicker` have\n * been built and tested the whole time — what was missing is the schedule they draw\n * from, which is the platform's and had nowhere to arrive.\n */\n case 'DATE':\n return schedule === undefined ? null : (\n <DayPicker\n series={schedule.series}\n today={schedule.today}\n selectedDay={collected.day === '' ? null : collected.day}\n onSelectDay={(day) => setCollected((was) => ({ ...was, day, ...clearedAfter('DATE') }))}\n remaining={schedule.remaining}\n />\n );\n case 'TIME': {\n if (schedule === undefined) return null;\n /*\n * THE DAY THE TIMES BELONG TO, READ ONCE — and not the buyer's own today, which is\n * the mistake the calendar made and which is worse here.\n *\n * A ONE-NIGHT RUN NEVER ASKS FOR A DAY: the walk skips Select Day, so nothing ever\n * writes `collected.day`, and this fell back to a date the run does not play.\n * `slotsByDay` is keyed by day, so the lookup missed and the list drew EMPTY — a\n * dead card with the sessions sitting in the schedule under a key nobody asked for.\n *\n * ONCE, BECAUSE IT WAS TWICE. The strip's own day and the day its times are looked\n * up under were separate expressions saying the same thing, and fixing one left the\n * other reading the clock — a list of times for a day the picker is not showing.\n * It is now the SAME day the order is built from — see `chosenDay`, which is where\n * the question is answered and the only place it should be.\n */\n const day = scheduleDay ?? schedule.today;\n return (\n <TimePicker\n series={schedule.series}\n today={schedule.today}\n nowTime={schedule.nowTime}\n selection={{\n day,\n startTime: collected.timeslot === '' ? null : collected.timeslot,\n }}\n onSelectDay={(next) =>\n setCollected((was) => {\n const moved = withSelectedDay({ day: was.day, startTime: null }, next);\n return { ...was, day: moved.day, ...clearedAfter('DATE') };\n })\n }\n slots={schedule.slotsByDay?.[day] ?? []}\n onSelectTime={(startTime) =>\n setCollected((was) => {\n const next = withSelectedTime({ day: was.day, startTime: null }, startTime);\n return { ...was, timeslot: next.startTime ?? '' };\n })\n }\n remaining={schedule.remaining}\n />\n );\n }\n /*\n * THE EVENT'S OWN QUESTIONS. The card was a gate onto nothing: `DETAILS` had no case\n * here, so it drew a sentence about needing details and no way to give any. The\n * questions ride on the tickets, so they are already in hand by the time this is asked.\n */\n case 'DETAILS':\n return questions.length === 0 ? null : (\n <div className=\"scopetickets-island-card__fields\">\n {questions.map((question) => (\n <TextField\n key={question.QuestionId}\n label={question.Question}\n value={collected.answers[String(question.QuestionId)] ?? ''}\n onChange={(value) =>\n setCollected((was) => ({\n ...was,\n answers: { ...was.answers, [String(question.QuestionId)]: value },\n }))\n }\n type={question.Type === 'date' ? 'text' : 'text'}\n enterKeyHint=\"done\"\n />\n ))}\n </div>\n );\n /*\n * WHO TO HEAR FROM AGAIN. `FollowList` was built and tested and mounted by nothing —\n * the organiser and the venue are on every event, and they are who a buyer would\n * follow.\n */\n case 'FOLLOW':\n return follow.length === 0 ? null : (\n <FollowList\n entities={follow}\n selectedKeys={collected.following}\n onToggle={(key) =>\n setCollected((was) => ({\n ...was,\n following: was.following.includes(key)\n ? was.following.filter((held) => held !== key)\n : [...was.following, key],\n }))\n }\n />\n );\n /*\n * FIVE STARS. It draws whatever the buyer has chosen and reports the change; which\n * TICKET the number ends up against is the widget's business and not this card's.\n */\n case 'FEEDBACK':\n return (\n <StarRating\n value={collected.rating}\n onChange={(rating) => setCollected((was) => ({ ...was, rating }))}\n label={FEEDBACK_COPY.group}\n />\n );\n case 'PARTY':\n /* The single line says \"no types\", which nobody has said yet. See `partyTypes`. */\n if (party.status === 'ASKING') return null;\n return (\n <PartyStepper\n onRefuse={onPartyRefused}\n refused={partyRefused}\n userTypes={party.types}\n counts={collected.composition}\n max={maxParty}\n /*\n * AND WHAT THE CHANGE COSTS. A day and a session were chosen for a party of two;\n * neither has been checked against three. See `clearedAfter`, which is the rule\n * for all three of these steps and is why it is not written out here.\n */\n onChange={(key, count) =>\n setCollected((was) => ({\n ...was,\n composition: { ...was.composition, [key === SOLO_KEY ? SOLO_KEY : key]: count },\n ...clearedAfter('PARTY'),\n }))\n }\n />\n );\n case 'NAME':\n return (\n <NameStep\n value={buyerName}\n onChange={(next) =>\n setCollected((was) => ({ ...was, firstName: next.firstName, lastName: next.lastName }))\n }\n onAnsweredChange={onAnsweredChange}\n />\n );\n case 'EMAIL':\n return (\n <EmailStep\n value={collected.email}\n onChange={(next) => setCollected((was) => ({ ...was, email: next }))}\n onAnsweredChange={onAnsweredChange}\n />\n );\n case 'PHONE':\n return (\n <PhoneStep\n value={collected.phone}\n onChange={(next) => setCollected((was) => ({ ...was, phone: next }))}\n onAnsweredChange={onAnsweredChange}\n />\n );\n /*\n * THE ADDRESS GOES WITH IT — the account the password belongs to, for the browser's\n * own save prompt. See `PasswordStep`'s hidden username.\n */\n case 'PASSWORD':\n return (\n <PasswordStep\n revealed={passwordRevealed}\n accountEmail={buyerEmail}\n onAnsweredChange={onAnsweredChange}\n onPasswordChange={account.setPassword}\n />\n );\n case 'CONFIRM_EMAIL':\n return (\n <ConfirmEmailStep\n initialEmail={buyerEmail ?? ''}\n onAnsweredChange={onAnsweredChange}\n /*\n * THE ADDRESS THE ACCOUNT WILL BE MADE ON. It goes to the same place the order's\n * own email step writes, because it IS that address — corrected here if the\n * buyer wants the account somewhere else.\n */\n onEmailChange={onEmailChange}\n />\n );\n case 'VERIFY_EMAIL':\n return (\n <VerifyEmailStep\n onAnsweredChange={onAnsweredChange}\n onVerify={account.verify}\n invalid={account.refused}\n />\n );\n /*\n * THE BUTTON IS AN IFRAME, and it stands here rather than in the card's action stack\n * because a passkey can only be made by a document under the RP id — the press has to\n * land over there, and activation does not cross a frame. `STEP_CARD_ACTIONS` keeps\n * only the Skip for this step; see `cardActions`.\n */\n case 'PASSKEY':\n return (\n <PasskeyButton\n hostUrl={passkey.hostUrl}\n ceremony={passkey.ceremony}\n label={PASSKEY_BUTTON_LABEL}\n onResult={passkey.onResult}\n />\n );\n /*\n * THE FACES ARE THE PLATFORM'S, and a host that offers none excuses the step rather\n * than drawing it empty — so this case is only ever reached with a set in hand. See\n * `CheckoutProps.profilePhotos`.\n */\n case 'PROFILE_PHOTO':\n return photos.length === 0 ? null : (\n <ProfilePhotoPicker\n photos={photos}\n selectedValue={collected.photo}\n onSelect={(value) => setCollected((was) => ({ ...was, photo: value }))}\n label={PROFILE_PHOTO_COPY.group}\n inputRef={photoInputRef}\n onFileChosen={onFileChosen}\n refusal={photoRefused === null ? null : PROFILE_PHOTO_COPY.refusal[photoRefused]}\n />\n );\n /*\n * THE FIELD, AND WHAT THE ORDER ALREADY CARRIES IN IT. An applied code is shown and\n * marked accepted rather than cleared: the card's whole subject is the code on the\n * order, and a blank field over \"€4.60 Saved\" would be the card contradicting itself.\n */\n case 'PROMO': {\n const { typed, onTyped, applied, write } = context.promo;\n const refused = write.status === 'REFUSED';\n\n return (\n <>\n <TextField\n id=\"promo-code\"\n label={PROMO_COPY.field}\n value={typed}\n onChange={onTyped}\n /* A code is a token, not prose: the same reading Add Password's field takes. */\n monospace\n autoCapitalize=\"none\"\n prose={false}\n enterKeyHint=\"go\"\n flag={refused ? 'error' : applied !== null && typed === applied ? 'success' : undefined}\n flagTitle={refused ? undefined : PROMO_COPY.accepted}\n />\n {/*\n * UNDER THE FIELD, which is where a buyer who has just mistyped something is\n * looking — and `role=\"status\"` for the same reason the photo step's refusal has\n * one: it arrives without the buyer moving focus. Why this is not a notice is\n * argued where that is decided, in `useCheckoutOrder`.\n */}\n {refused ? (\n <p className=\"scopetickets-island-promo__refusal\" role=\"status\">\n {write.reason}\n </p>\n ) : null}\n </>\n );\n }\n default:\n return null;\n }\n}\n","/**\n * THE GLYPHS THE DESIGN DRAWS THAT `@scopetickets/icons` DOES NOT HAVE.\n *\n * PROCESSING-SLOW — the mark on the design's `PaymentConfirming` card.\n *\n * ── THE ARTWORK IS THE FILE'S, UNTOUCHED ─────────────────────────────────────\n *\n * The path below is the export from `2990:10303` byte for byte, in the viewBox it was\n * exported at. It is not redrawn, not simplified and not rescaled — an earlier version\n * scaled it to the 20x20 the icon set authors on so it could go through `IconGlyph`, and\n * scaling is still touching it. Nothing here touches it. `status-glyphs.test.tsx` holds\n * the same string and fails if the two ever differ.\n *\n * Which is also why this does not use `IconGlyph`: that renderer assumes the set's own\n * 20x20 grid, and meeting it would mean changing the artwork to suit the renderer. The\n * eleven lines below are the price of not doing that.\n *\n * IT BELONGS IN THE ICON SET. When it gets there this file goes and one import changes.\n * Until then it is here rather than approximated with a glyph that merely looks close —\n * `ArrowsCircling` is the near miss, it is what `Processing` itself draws, and the two\n * were compared coordinate by coordinate before this was written.\n */\n\nimport type { CSSProperties } from 'react';\n\n/** `2990:10303`, exported at 32. */\nconst PROCESSING_SLOW_VIEWBOX = '0 0 32 32';\nconst PROCESSING_SLOW_PATH =\n 'M16 0C6.95655 0 -0.334526 7.50281 0.0118514 16.6234C0.326786 24.9161 7.08393 31.6732 15.3766 31.9881C24.1542 32.3215 31.4335 25.581 31.9685 17.0124C32.0028 16.4629 31.5584 16 31.0078 16H29.7246C29.2174 16 28.8039 16.3954 28.7687 16.9014C28.2857 23.8451 22.2644 29.2633 15.0921 28.7686C8.78029 28.3333 3.66668 23.2197 3.23137 16.9079C2.71549 9.42802 8.63043 3.2 16 3.2C19.5168 3.2 23.0752 4.4601 25.5104 7.05529C25.984 7.5609 26.416 8.11131 26.8032 8.6873L22.1664 8.4249C21.2288 8.4249 20.48 9.23131 20.5696 10.1849C20.6496 11.0201 21.3984 11.6313 22.2336 11.6313H30.64C31.3911 11.6313 32 11.0224 32 10.2713V1.8617C32 1.0265 31.3888 0.277693 30.5568 0.197693C29.6 0.108102 28.7968 0.856893 28.7968 1.79449C28.7968 1.81371 28.9856 5.17689 29.1008 7.2409C28.6144 6.5209 28.0704 5.8393 27.4752 5.2057C24.1728 1.6441 20.0448 0.0320128 16 0Z';\n\nexport type ProcessingSlowIconProps = {\n /** Fill the parent instead of sizing itself — the avatar's badge slot does the sizing. */\n readonly fill?: boolean;\n /** Defaults to `currentColor`; the badge passes its tone's foreground. */\n readonly color?: string;\n readonly className?: string;\n readonly style?: CSSProperties;\n};\n\nexport function ProcessingSlowIcon({\n fill = false,\n color = 'currentColor',\n className,\n style,\n}: ProcessingSlowIconProps) {\n return (\n <svg\n data-scopetickets-glyph=\"ProcessingSlow\"\n className={className}\n viewBox={PROCESSING_SLOW_VIEWBOX}\n aria-hidden\n focusable={false}\n style={{\n display: 'block',\n ...(fill ? { width: '100%', height: '100%' } : { width: 20, height: 20 }),\n ...style,\n }}\n >\n <path d={PROCESSING_SLOW_PATH} fill={color} />\n </svg>\n );\n}\n\n/**\n * ── THE THREE MARKS THAT ARE THE WHOLE BADGE ─────────────────────────────────\n *\n * Failed `3671:38706`, Warning `3671:38727`, Success `2988:9615` — the design's own three\n * CtaCard variants, and one drawing between them: a disc that fills its 48, painted in the\n * tone's full-strength colour, with the mark KNOCKED OUT of it.\n *\n * WHICH IS A DIFFERENT COMPOSITION FROM THE ONE THEY REPLACE, and the only thing about\n * this worth reading twice. A status badge used to be a pale wash of the tone with a glyph\n * of the tone drawn on top, inset by a ring. These are not glyphs: the disc IS the badge,\n * and the tick, the cross and the bang are holes in it showing whatever the badge sits on.\n * So `statusBadge` draws them edge to edge with no ground and no ring — see the `mark`\n * lookup there, whose presence is the whole decision.\n *\n * THE COLOUR IS ALREADY THE TONE'S. Figma paints these `#F67679`, `#FDDF44` and `#4AD968`,\n * which are exactly `STATUS_TONES.dark[tone].foreground` — so the badge hands each mark its\n * own tone's foreground and the light appearance follows the token rather than the export.\n * Nothing here hardcodes a colour.\n *\n * THE ARTWORK IS THE EXPORT, byte for byte, in the viewBox it came out at, for the reasons\n * the header above gives. `status-glyphs.test.tsx` holds the same strings.\n */\nconst STATUS_MARK_VIEWBOX = '0 0 48 48';\n\n/** The three tones that draw a solid mark, and the path each one is. */\nexport type StatusMarkTone = 'success' | 'warning' | 'error';\n\nconst STATUS_MARK_PATHS: Readonly<Record<StatusMarkTone, string>> = {\n /* `2988:9615` — the tick. */\n success:\n 'M24 0C37.2548 0 48 10.7452 48 24C48 37.2548 37.2548 48 24 48C10.7452 48 1.2679e-05 37.2548 0 24C0 10.7452 10.7452 0 24 0ZM32.2641 13.9641C31.3535 13.715 30.3856 14.1027 29.8148 14.8547L29.8125 14.857C25.9306 19.9132 21.5481 27.6637 21.5086 27.7336C21.5086 27.7336 20.1722 25.4782 18.1453 22.9453L18.1359 22.9336C18.0981 22.8867 18.0583 22.84 18.0164 22.7953C17.0534 21.7686 15.3997 21.7758 14.4492 22.8633C13.6336 23.7966 13.7157 25.2293 14.5617 26.1352C16.5329 28.2453 18.2953 30.5682 19.8047 33.0586L19.8469 33.1289C20.6646 34.477 22.6371 34.4276 23.3859 33.0398L23.4094 32.9953C26.271 27.6077 29.6821 22.5233 33.5648 17.85C33.5823 17.8288 33.6067 17.7992 33.6234 17.7773C34.6262 16.4701 34.0759 14.4597 32.2641 13.9641Z',\n /* `3671:38727` — the bang. */\n warning:\n 'M24 0C37.2546 0 47.9995 10.7456 48 24C48 37.2548 37.2548 48 24 48C10.7452 48 0 37.2548 0 24C0.000467456 10.7456 10.7454 1.93266e-07 24 0ZM23.6086 31.3172C21.6399 31.3172 20.6019 32.4695 20.6016 34.2867C20.6016 36.1832 21.6395 37.3359 23.6086 37.3359C25.5412 37.3358 26.618 36.1831 26.618 34.2867C26.6176 32.4696 25.5408 31.3173 23.6086 31.3172ZM23.6109 10.6641C22.2859 10.6641 21.2092 11.7391 21.2086 13.0641C21.2086 13.0854 21.2149 13.1062 21.2156 13.1273H21.2109C21.3371 17.9256 21.4623 22.7269 21.5695 26.8055H21.5742C21.6033 27.9063 22.5009 28.7923 23.6086 28.793C24.717 28.793 25.6162 27.9067 25.6453 26.8055H25.65C25.7573 22.7269 25.8824 17.9256 26.0086 13.1273H26.0039C26.0046 13.1062 26.0109 13.0854 26.0109 13.0641C26.0104 11.7395 24.9355 10.6647 23.6109 10.6641Z',\n /* `3671:38706` — the cross. */\n error:\n 'M24 0C37.2546 0 47.9995 10.7456 48 24C48 37.2548 37.2548 48 24 48C10.7452 48 0 37.2548 0 24C0.000467456 10.7456 10.7454 1.93266e-07 24 0ZM31.6805 13.9219C30.9889 13.9219 30.37 14.218 29.932 14.6859L29.9273 14.6813C27.2866 17.5031 25.8964 18.9899 24 21.0164C22.1036 18.9899 20.7134 17.5031 18.0727 14.6813L18.068 14.6859C17.63 14.218 17.0111 13.9219 16.3195 13.9219C14.9942 13.9221 13.9195 14.9966 13.9195 16.3219C13.9198 17.0125 14.2163 17.6303 14.6836 18.068L14.6813 18.0727C17.5027 20.7131 18.9878 22.1039 21.0141 24C18.9877 25.8962 17.5024 27.2872 14.6813 29.9273L14.6836 29.932C14.2157 30.3699 13.9196 30.9892 13.9195 31.6805C13.9195 33.0058 14.9942 34.0802 16.3195 34.0805C17.0111 34.0805 17.63 33.7844 18.068 33.3164L18.0727 33.3211C20.7136 30.4991 22.1036 29.0125 24 26.9859C25.8964 29.0125 27.2864 30.4991 29.9273 33.3211L29.932 33.3164C30.37 33.7844 30.989 34.0805 31.6805 34.0805C33.0058 34.0802 34.0805 33.0058 34.0805 31.6805C34.0804 30.9892 33.7843 30.3699 33.3164 29.932L33.3188 29.9273C30.4976 27.2872 29.0123 25.8962 26.9859 24C29.0122 22.1039 30.4973 20.7131 33.3188 18.0727L33.3164 18.068C33.7837 17.6303 34.0802 17.0125 34.0805 16.3219C34.0805 14.9966 33.0058 13.9221 31.6805 13.9219Z',\n};\n\n/** Figma's own names for the three, so the DOM says which mark it is drawing. */\nconst STATUS_MARK_GLYPH: Readonly<Record<StatusMarkTone, string>> = {\n success: 'StatusMarkSuccess',\n warning: 'StatusMarkWarning',\n error: 'StatusMarkError',\n};\n\n/**\n * ONE COMPONENT PER TONE, BOUND ONCE — because `statusBadge` takes a component and not a\n * tone, and a new function identity on every render is a remount of the badge under the\n * avatar's carry.\n */\nexport const STATUS_MARK: Readonly<\n Record<StatusMarkTone, (props: ProcessingSlowIconProps) => JSX.Element>\n> = {\n success: (props) => <StatusMark tone=\"success\" {...props} />,\n warning: (props) => <StatusMark tone=\"warning\" {...props} />,\n error: (props) => <StatusMark tone=\"error\" {...props} />,\n};\n\n/**\n * THE SOLID MARK FOR A TONE, or nothing where the design still draws a glyph on a wash —\n * `processing`, which turns, and `draft`, which the flow never reaches.\n *\n * NARROWED RATHER THAN CAST. The caller has a tone from the status package, whose set is\n * wider than the three drawn here, and a lookup written as an assertion would answer\n * `undefined` while claiming it could not.\n */\nconst isStatusMarkTone = (tone: string): tone is StatusMarkTone => tone in STATUS_MARK_PATHS;\n\nexport function statusMark(\n tone: string,\n): ((props: ProcessingSlowIconProps) => JSX.Element) | undefined {\n return isStatusMarkTone(tone) ? STATUS_MARK[tone] : undefined;\n}\n\nfunction StatusMark({\n tone,\n fill = false,\n color = 'currentColor',\n className,\n style,\n}: ProcessingSlowIconProps & { readonly tone: StatusMarkTone }) {\n return (\n <svg\n data-scopetickets-glyph={STATUS_MARK_GLYPH[tone]}\n className={className}\n viewBox={STATUS_MARK_VIEWBOX}\n aria-hidden\n focusable={false}\n style={{\n display: 'block',\n ...(fill ? { width: '100%', height: '100%' } : { width: 20, height: 20 }),\n ...style,\n }}\n >\n {/*\n * `evenodd` IS THE MARK. The path is the disc followed by the tick, the bang or the\n * cross, and the fill rule is what turns the second into a hole in the first. Drop it\n * and the badge is a plain filled circle — the mark does not go wrong, it goes\n * MISSING, which is the kind of break a screenshot catches and a renderer does not.\n */}\n <path fillRule=\"evenodd\" clipRule=\"evenodd\" d={STATUS_MARK_PATHS[tone]} fill={color} />\n </svg>\n );\n}\n","import { GUEST_AVATAR_VALUE } from '@scopetickets/avatar';\nimport { AUTH_COPY } from './auth-copy';\nimport { isValidEmail, normalizeE164, splitFullName } from './contact';\n\n/** WHO IS BUYING, WHERE THE FLOW ASKS, AND WHAT THE ANSWER COSTS IT. */\n\n// ── WHO ──────────────────────────────────────────────────────\n\n/** What a Scope Tickets account carries that this flow spends. */\nexport type Account = {\n /**\n * The stored avatar VALUE, exactly as the profile carries it — a URI, or one of\n * `@scopetickets/avatar`'s prefixed forms. `null` is a real account that has never set\n * one, which is a fact about the ACCOUNT and not a treatment: what gets drawn for it is\n * `buyerAvatarValue`'s decision, and that is the placeholder.\n */\n readonly avatar: string | null;\n readonly name: string | null;\n readonly email: string | null;\n readonly phone: string | null;\n /** The type this account holder IS, or `null`. Not a composition key — see `user-types`. */\n readonly userTypeKey: string | null;\n};\n\n/** The three ways a buyer arrives, as ONE value. */\nexport type AuthState =\n /**\n * Nobody. No account stored, no session — the first visit from this browser, or a buyer\n * who signed out. Carries no account, because there is none to carry: that absence is\n * the union's whole point.\n */\n | { readonly status: 'UNRECOGNISED' }\n /** An account we hold, without a live session. */\n | { readonly status: 'RECOGNISED'; readonly avatar: string | null }\n /** Authenticated. Nothing further is asked; the account is spendable. */\n | { readonly status: 'AUTHENTICATED'; readonly account: Account };\n\nexport type AuthStatus = AuthState['status'];\n\n/** Whether the buyer has taken the guest route for this order. */\nexport type GuestChoice = 'NOT_TAKEN' | 'TAKEN';\n\n/** The session, as the flow sees it — everything a checkpoint decides from. */\nexport type AuthSession = {\n readonly auth: AuthState;\n readonly guest: GuestChoice;\n};\n\n/**\n * A buyer nobody has met, who has not declined anything either. The state the flow must\n * handle without help, and the default everywhere.\n */\nexport const ANONYMOUS_SESSION: AuthSession = {\n auth: { status: 'UNRECOGNISED' },\n guest: 'NOT_TAKEN',\n};\n\n// ── WHERE ────────────────────────────────────────────────────\n\n/** The three points in a purchase at which the flow asks about an account. */\nexport type AuthCheckpoint =\n /** The resting island, before anything has been added to a cart. */\n | 'IDLE'\n /** An OrderIntent has been accepted — \"Add to Cart\" has been pressed. */\n | 'ORDER_CREATED'\n /** The order is paid for. */\n | 'ORDER_SUCCESS';\n\n// ── WHICH CARD ───────────────────────────────────────────────\n\n/**\n * The five cards the three checkpoints draw between them, named by what each SAYS\n * rather than by where it appears — `SIGN_IN_RECOGNISED` is one node at two\n * checkpoints, and naming it twice is how two copies of one card fall out of step.\n */\nexport type AuthCardId =\n /**\n * the design `Login-Idle-Unrecognised`. \"Already Have An Account?\" over the guest\n * placeholder, with Sign in with ▮ and Create Account.\n */\n | 'SIGN_IN_UNRECOGNISED'\n /**\n * the design. The same card with `CONTINUE_AS_GUEST` added beneath — the\n * `ORDER_CREATED` reading, where there IS an order and guest checkout is therefore a\n * real route.\n */\n | 'SIGN_IN_UNRECOGNISED_GUEST'\n /**\n * the design `Login-Idle-Recognised`. The buyer's own face under a keyhole badge,\n * \"Welcome Back!\", and the two ways back in — passkey first.\n */\n | 'SIGN_IN_RECOGNISED'\n /**\n * the design `Login-Idle-SignedIn`. \"Welcome Back! / You're ready to go.\" and a single\n * `SIGN_OUT`.\n */\n | 'ACCOUNT_READY'\n /**\n * the design `SignupPrompt`. \"Add to Account / Enjoy faster checkout and access to\n * discounts.\" — Create Account, Sign In, Skip.\n */\n | 'ADD_TO_ACCOUNT';\n\n/** What a checkpoint does about a session. */\nexport type AuthPrompt =\n | { readonly kind: 'BYPASS'; readonly reason: string }\n | { readonly kind: 'CARD'; readonly card: AuthCardId };\n\nconst card = (id: AuthCardId): AuthPrompt => ({ kind: 'CARD', card: id });\nconst bypass = (reason: string): AuthPrompt => ({ kind: 'BYPASS', reason });\n\n/**\n * WHICH CARD A CHECKPOINT DRAWS, or why it draws none. The whole policy, as one pure\n * function.\n */\nexport function authPrompt(checkpoint: AuthCheckpoint, session: AuthSession): AuthPrompt {\n const { auth, guest } = session;\n\n if (checkpoint === 'ORDER_SUCCESS') {\n /*\n * THE OFFER IS FOR PEOPLE WITHOUT AN ACCOUNT, and a guest is precisely that: taking the\n * guest route is what QUALIFIES a buyer for this card, not what excuses them from it.\n * This is the one checkpoint where `guest: 'TAKEN'` does not bypass.\n */\n if (auth.status === 'UNRECOGNISED') return card('ADD_TO_ACCOUNT');\n if (auth.status === 'AUTHENTICATED') {\n return bypass('The order is already on the buyer’s account; there is nothing to add it to.');\n }\n /*\n * \"not relevant, authenticated or guest chosen upstream\". A buyer cannot still be\n * merely RECOGNISED here — reaching payment meant resolving it one way or the other —\n * so this is unreachable rather than allowed, and it says so instead of drawing a card\n * nobody designed.\n */\n return bypass(\n 'Unreachable: recognition is resolved at OrderCreated, either by signing in or by taking the guest route.',\n );\n }\n\n /*\n * DECLINED ONCE IS DECLINED. A buyer who chose guest has answered this question for the\n * order; asking again at every checkpoint is nagging, and at ORDER_CREATED it would sit\n * between them and paying. OrderSuccess is handled above and deliberately ignores this.\n */\n if (guest === 'TAKEN') {\n return bypass('The buyer chose to continue as a guest; the order does not need an account.');\n }\n\n switch (auth.status) {\n case 'UNRECOGNISED':\n /*\n * THE ONLY DIFFERENCE BETWEEN THE TWO CARDS IS THE GUEST BUTTON, and it turns on\n * whether an order exists to check out.\n */\n return card(\n checkpoint === 'ORDER_CREATED' ? 'SIGN_IN_UNRECOGNISED_GUEST' : 'SIGN_IN_UNRECOGNISED',\n );\n case 'RECOGNISED':\n /* ONE NODE, BOTH CHECKPOINTS — the design. */\n return card('SIGN_IN_RECOGNISED');\n case 'AUTHENTICATED':\n /*\n * THE ONE CELL WHERE THE CHECKPOINT DECIDES AND THE STATE DOES NOT. Idle offers;\n * OrderCreated interrupts, and there is nothing to interrupt an authenticated buyer\n * for.\n */\n return checkpoint === 'IDLE'\n ? card('ACCOUNT_READY')\n : bypass('The buyer is already authenticated; the identity is inherent to the account.');\n }\n}\n\n/**\n * THE PILL'S OWN WORD FOR AN ACCOUNT AT REST — a SUBJECT, as the cart screen's \"My Cart\"\n * is, and not a verb: the card behind it says \"You're ready to go\" and offers only the way\n * out, so there is no action left for the pill to name.\n *\n * NOT IN `AUTH_COPY`, whose keys are the vocabulary of BUTTONS — every one of them has an\n * entry in `AUTH_ACTION_OUTCOME` saying what pressing it does, and nothing presses this.\n */\nexport const ACCOUNT_AT_REST = 'My Account';\n\n/** An island with nothing to sell, as the two things it has to draw. */\nexport type UnassociatedPrompt = {\n readonly card: AuthCardId;\n /** The pill's action, standing in for a step's `collapsed.actionLabel`. */\n readonly actionLabel: string;\n};\n\n/**\n * WHAT AN ISLAND MOUNTED WITH NO ORDER DRAWS: the `IDLE` card, and what the pill that\n * opens it says.\n *\n * ONE VALUE RATHER THAN TWO LOOKUPS, because both answers come from the same auth state,\n * and a card reading \"Welcome Back!\" under a pill reading \"Sign In\" would be the island\n * arguing with itself. `PURCHASE_STEPS` keeps each step's pill label beside the step for\n * the same reason.\n *\n * AND ALWAYS A CARD, WHICH `authPrompt` ON ITS OWN CANNOT PROMISE. A bypass at a step\n * means \"walk past it\"; here the card IS the whole widget, so a mount that resolved to one\n * would draw nothing at all. The only thing that bypasses `IDLE` is a guest choice — an\n * answer about ONE ORDER, offered by the one card that exists because there is an order to\n * check out; see `chooseGuest`. A mount with no order cannot have made that choice, so it\n * is not carried in, and this is total. The throw is the proof, not a fallback.\n */\nexport function unassociatedPrompt(auth: AuthState): UnassociatedPrompt {\n const prompt = authPrompt('IDLE', { auth, guest: 'NOT_TAKEN' });\n if (prompt.kind === 'BYPASS') {\n throw new Error(`IDLE drew no card for an unassociated ${auth.status} buyer: ${prompt.reason}`);\n }\n return { card: prompt.card, actionLabel: unassociatedLabel(auth.status) };\n}\n\nfunction unassociatedLabel(status: AuthStatus): string {\n switch (status) {\n /* Both cards are a way INTO an account, whether or not we know whose it is. */\n case 'UNRECOGNISED':\n case 'RECOGNISED':\n return AUTH_COPY.SIGN_IN;\n case 'AUTHENTICATED':\n return ACCOUNT_AT_REST;\n }\n}\n\n/** Whether a checkpoint STANDS IN THE WAY, or merely offers. */\nexport function checkpointGates(checkpoint: AuthCheckpoint): boolean {\n return checkpoint === 'ORDER_CREATED';\n}\n\n// ── WHAT IT COSTS THE FLOW ───────────────────────────────────\n\n/**\n * The avatar value the island draws — session-wide, and read from exactly here.\n *\n * A FACE NOBODY SET IS THE PLACEHOLDER, not the unset tier. The package draws five\n * treatments and two of them mean \"no picture\": the guest sentinel, and a fallback for a\n * value it was handed nothing for. This used to pass `null` straight through on the\n * reading that a real account which has never set a photo is a different thing from a\n * stranger — true of the ACCOUNT, and not a difference the buyer can read. What they saw\n * was a second empty state that looks like neither a person nor a guest.\n *\n * There is nothing behind it either: the two tiers between a photo and the placeholder —\n * initials and a stock face — are both reached through a value, so a `null` here has\n * already exhausted everything that could have drawn something.\n */\nexport function buyerAvatarValue(auth: AuthState): string {\n switch (auth.status) {\n case 'UNRECOGNISED':\n return GUEST_AVATAR_VALUE;\n case 'RECOGNISED':\n return auth.avatar ?? GUEST_AVATAR_VALUE;\n case 'AUTHENTICATED':\n return auth.account.avatar ?? GUEST_AVATAR_VALUE;\n }\n}\n\n/** The order requirements an account can answer on the buyer's behalf. */\nexport type OrderRequirementId = 'NAME' | 'EMAIL' | 'PHONE';\n\n/**\n * Whether a requirement is already answered, AND WHAT WITH.\n *\n * `value` IS THE VALUE THAT GOES OUT. `orderBuyer` spends it as the field itself, so the\n * gate narrows what it accepts to what an order can actually carry — see below.\n */\nexport type RequirementGate =\n | { readonly kind: 'ANSWERED'; readonly value: string }\n | { readonly kind: 'REQUIRED'; readonly reason: string };\n\n/** What the session can say about one order requirement. */\nexport function requirementGate(auth: AuthState, requirement: OrderRequirementId): RequirementGate {\n if (auth.status !== 'AUTHENTICATED') {\n return {\n kind: 'REQUIRED',\n reason:\n auth.status === 'RECOGNISED'\n ? 'The buyer is recognised but not authenticated; a lapsed session’s details are not spendable.'\n : 'Nothing is known about the buyer.',\n };\n }\n\n const value = accountField(auth.account, requirement);\n /*\n * AN EMPTY STRING IS NOT AN ANSWER. An account created from a purchase can carry a\n * field the platform stored blank, and treating that as answered is how a step gets\n * excused and a requirement goes out unmet.\n */\n if (value === null || value.trim() === '') {\n return { kind: 'REQUIRED', reason: `The account holds no ${requirement.toLowerCase()}.` };\n }\n /*\n * AND NEITHER IS A VALUE THE ORDER COULD NOT CARRY. `answeredBuyer` drops a HOST's\n * malformed field so the widget asks for it instead; a STORED one is the same fact from\n * a different drawer, and an account is no more authoritative about the shape of an\n * address than someone else's page is. Refusing here is what sends the buyer to the step\n * — the only place with anybody who can correct it.\n *\n * CHECKED AT THE GATE rather than at the order, because the gate is what excuses the\n * step: catching it later would mean noticing a field is unusable after deciding never to\n * ask for it, which is exactly how an empty `Email` reached the platform.\n */\n const sendable = sendableAccountValue(value.trim(), requirement);\n if (sendable === null) {\n return {\n kind: 'REQUIRED',\n reason: `The account's ${requirement.toLowerCase()} (“${value.trim()}”) ${UNSENDABLE[requirement]}.`,\n };\n }\n return { kind: 'ANSWERED', value: sendable };\n}\n\n/**\n * WHAT AN ACCOUNT'S FIELD HAS TO BE TO BE SPENT, and it is the wire's rule in each case\n * rather than a second opinion about it: `BuyerDetails` takes `FirstName` and `LastName`\n * apart and requires both, the address is the one a charge is named for, and a phone\n * number leaves as E.164 or not at all.\n *\n * THE NUMBER IS NORMALISED, not merely judged — `+353 85 123 4567` and `+353851234567` are\n * one number and only one of them can be sent, so the sendable spelling is what comes back\n * and what `orderBuyer` puts on the order. Same argument as `answeredBuyer`'s.\n */\nfunction sendableAccountValue(value: string, requirement: OrderRequirementId): string | null {\n switch (requirement) {\n case 'NAME':\n return splitFullName(value) === null ? null : value;\n case 'EMAIL':\n return isValidEmail(value) ? value : null;\n case 'PHONE':\n return normalizeE164(value);\n }\n}\n\n/** Why a stored field cannot be spent, as the sentence the skip reason ends with. */\nconst UNSENDABLE: Readonly<Record<OrderRequirementId, string>> = {\n NAME: 'does not give both a first and a last name',\n EMAIL: 'is not an address a payment provider would accept',\n PHONE: 'cannot be written as an E.164 number',\n};\n\nfunction accountField(account: Account, requirement: OrderRequirementId): string | null {\n switch (requirement) {\n case 'NAME':\n return account.name;\n case 'EMAIL':\n return account.email;\n case 'PHONE':\n return account.phone;\n }\n}\n\n/** The user type this buyer is associated with, or `null`. */\nexport function accountUserTypeKey(auth: AuthState): string | null {\n return auth.status === 'AUTHENTICATED' ? auth.account.userTypeKey : null;\n}\n\n// ── TRANSITIONS ──────────────────────────────────────────────\n\n/** Signing out. Every card that offers it lands here. */\nexport function signOut(session: AuthSession): AuthSession {\n return { auth: { status: 'UNRECOGNISED' }, guest: session.guest };\n}\n\n/**\n * Authenticating — passkey, password, federated, newly created, however the platform\n * gets there. All of them end in one account.\n */\nexport function signIn(account: Account): AuthSession {\n return { auth: { status: 'AUTHENTICATED', account }, guest: 'NOT_TAKEN' };\n}\n\n/**\n * A session lapsing — the only thing in this module that produces `RECOGNISED`, and\n * what a \"Remember me\" control governs.\n */\nexport function expireSession(session: AuthSession, remembered: boolean): AuthSession {\n if (session.auth.status !== 'AUTHENTICATED') return session;\n return {\n auth: remembered\n ? { status: 'RECOGNISED', avatar: session.auth.account.avatar }\n : { status: 'UNRECOGNISED' },\n /*\n * The guest choice is about THIS ORDER and says nothing about the session ending,\n * exactly as with `signOut`.\n */\n guest: session.guest,\n };\n}\n\n/**\n * Taking the guest route. Available only where a card offers it, which is only where an\n * order exists — see `SIGN_IN_UNRECOGNISED_GUEST`.\n */\nexport function chooseGuest(session: AuthSession): AuthSession {\n return { auth: session.auth, guest: 'TAKEN' };\n}\n","/** The words the flow uses about accounts, declared once. */\n\n/**\n * `as const` so each is a literal type: a mistyped key fails the typecheck rather than\n * rendering `undefined` into a button.\n */\nexport const AUTH_COPY = {\n /** the design. The sign-in action, standing alone. */\n SIGN_IN: 'Sign In',\n /**\n * the design — and it is HALF A LABEL. The Scope Tickets wordmark completes it, which\n * is why the two set as one phrase at `$1.5` rather than the `$3` a glyph beside a\n * label takes (see `IslandAction.mark.spacing`), and why the mark carries the\n * accessible name.\n */\n SIGN_IN_WITH: 'Sign in with',\n /**\n * the design. The way out of a recognised or authenticated session — and, at\n * `ORDER_CREATED`, how a recognised buyer reaches guest checkout: it drops them to\n * unrecognised, whose card there carries `CONTINUE_AS_GUEST`. See `authPrompt`.\n */\n SIGN_OUT: 'Sign Out',\n /**\n * the design. The preferred route, and the only thing in the widget that calls WebAuthn\n * — the passkey check is explicit opt-in.\n */\n USE_PASSKEY: 'Use Passkey',\n /**\n * the design. For a recognised buyer whose passkey is not to hand, or who never made\n * one. Opens the sign-in funnel.\n */\n ENTER_PASSWORD: 'Enter Password',\n /** See the note above for why this spelling and not \"Create an Account\". */\n CREATE_ACCOUNT: 'Create Account',\n /** the design. */\n CONTINUE_AS_GUEST: 'Continue as Guest',\n /**\n * the design. Declining the OrderSuccess offer, which costs the buyer nothing. Not \"No\n * Thanks\" and not a cross — the card already has a cross in its header, and the node\n * draws three buttons.\n */\n SKIP: 'Skip',\n /**\n * the design. The only word here that appears on no checkpoint card — it is the\n * funnel's secondary — and it lives here anyway, because \"Sign In\" must not become \"Log\n * in\" anywhere a buyer can read it. Keeps its question mark, which the node draws.\n */\n FORGOT_PASSWORD: 'Forgot Password?',\n} as const;\n\nexport type AuthCopyKey = keyof typeof AUTH_COPY;\n\n/** Spellings that must never reach a buyer, with what to write instead. */\nexport const BANNED_AUTH_SPELLINGS: readonly (readonly [banned: string, instead: string])[] = [\n ['Log Out', AUTH_COPY.SIGN_OUT],\n ['Logout', AUTH_COPY.SIGN_OUT],\n ['Log In', AUTH_COPY.SIGN_IN],\n ['Login', AUTH_COPY.SIGN_IN],\n ['Signin', AUTH_COPY.SIGN_IN],\n ['Sign-in', AUTH_COPY.SIGN_IN],\n ['Sign Up', AUTH_COPY.CREATE_ACCOUNT],\n ['Signup', AUTH_COPY.CREATE_ACCOUNT],\n ['Register', AUTH_COPY.CREATE_ACCOUNT],\n];\n\n/**\n * The first banned spelling in `text`, or `null`. A function rather than a regex at the\n * test, so \"clean\" has one definition.\n */\nexport function bannedAuthSpelling(text: string): { banned: string; instead: string } | null {\n const haystack = text.toLowerCase();\n for (const [banned, instead] of BANNED_AUTH_SPELLINGS) {\n if (haystack.includes(banned.toLowerCase())) return { banned, instead };\n }\n return null;\n}\n","// =============================================================================\n// API Response Types - matches Scope v2 API (PascalCase)\n// =============================================================================\n\n// Nested types used in Event and Series\n\n/** @internal */\nexport interface Theme {\n Backgrounds: string[] | null;\n Cover: string | null;\n ColourPrimary: string | null;\n ColourSecondary: string | null;\n ColourBackground: string | null;\n ColourDetail: string | null;\n SystemColour: string | null;\n}\n\n/** @internal */\nexport interface Venue {\n Key: string;\n Name: string;\n TimeZone: string;\n}\n\n/** @internal */\nexport interface Organisation {\n Key: string;\n Name: string;\n LegalName: string | null;\n Logo: string | null;\n}\n\n// User type (available on EventInfoResponse, per-Event and per-Ticket)\n/**\n * WHO A TICKET IS FOR — \"Child\", \"Student\".\n *\n * `AssignmentKey` IDENTIFIES THE ASSIGNMENT, NOT THE TYPE. One entry is this type\n * assigned to one product on one event, so the same \"Child\" appears once per product per\n * night, each with its own key, its own discount and its own conditions. `Name` is the\n * only field that identifies what a buyer is choosing — see `groupUserTypes`, which is\n * the only thing that should be building rows out of these.\n *\n * @internal\n */\nexport interface UserType {\n AssignmentKey: string;\n Name: string;\n DiscountNominal: number;\n DiscountRate: number;\n /** The organiser's own condition on choosing it, drawn under the name at `PARTY`. */\n Note?: string | null;\n /** Whether the buyer must show ID. Varies BY PRODUCT under one name — see `agreed`. */\n IdRequired?: boolean;\n AgeMinimum?: number | null;\n AgeMaximum?: number | null;\n}\n\n// =============================================================================\n// Display Events - lean navigation list from /api/v2/EventSummaries\n// =============================================================================\n\nexport type DisplayEventType = 'event' | 'series';\n\nexport interface DisplayEvent {\n Type: DisplayEventType;\n Name: string;\n Key: string;\n /** ISO date — present for standalone events, absent for series */\n Date?: string;\n /** First event date in a series (series only) */\n StartDate?: string;\n /** Last event date in a series (series only) */\n EndDate?: string;\n Venue: { Name: string };\n}\n\n/** @internal */\nexport interface DisplayEventsResponse {\n Events: DisplayEvent[];\n}\n\n// =============================================================================\n// Event Info - full detail from /api/v2/EventInformation\n// =============================================================================\n\nexport interface Event {\n /** @deprecated Legacy numeric ID — populated from v1 for cart compat, remove when v2 cart ships */\n ID?: number;\n Key: string;\n Name: string;\n Description: string;\n Date: string;\n Starts: string;\n Ends: string;\n LocalStartTime: string;\n LocalEndTime: string;\n Currency: string;\n /** NOT SENT by `EventInformation` in either mode, measured 2026-09-10 — the run states it. */\n PaymentPlatform?: string | null;\n Capacity: number | null;\n Theme: Theme;\n Venue: Venue;\n Organisation: Organisation;\n UrgencyTags: string[];\n /** Legacy event questionnaire fallback; the dedicated endpoint remains authoritative. */\n Questions?: QuestionnaireQuestion[] | null;\n /**\n * The types THIS night offers, un-grouped — see `UserType`.\n *\n * SERIES-ONLY. `?type=series` carries it on every event; `?type=event` omits the field\n * from the event object entirely, so a standalone event has none of these and the\n * response's own `UserTypes` is all there is.\n */\n UserTypes?: UserType[] | null;\n}\n\nexport interface Series {\n Key: string;\n Name: string;\n Title: string | null;\n /** The run's artwork, repeated from `Theme.Backgrounds`. `runArtwork` reads the Theme. */\n Backgrounds?: string[] | null;\n Description: string | null;\n Capacity: number;\n DatePickerType: string | null;\n IsJointEvent: boolean;\n Currency: string | null;\n PaymentPlatform: string | null;\n Theme: Theme;\n Venue: Venue;\n Organisation: Organisation;\n}\n\n/** @internal */\nexport interface EventInfoResponse {\n HasAvailableTickets: boolean;\n Series: Series | null;\n Events: Event[];\n /**\n * NULL, NOT AN EMPTY LIST, when the run names none of its own — observed on the wire.\n * The types said otherwise and a `.length` on it took down the whole read.\n */\n UserTypes: UserType[] | null;\n}\n\n// =============================================================================\n// Ticket - from /api/v2/Events/{eventKey}/Tickets\n// =============================================================================\n\nexport interface Ticket {\n /** @deprecated Legacy numeric ID — populated from v1 for cart compat, remove when v2 cart ships */\n ID?: number;\n Key: string;\n Name: string;\n Note: string | null;\n BasePrice: number;\n SalePrice: number;\n Fees: number;\n Total: number;\n /**\n * The product's own currency, where it states one — the most specific of the three\n * places this is set, above its event's and the run's. Optional because it is not on\n * every response, and a caller that finds it absent falls up rather than guessing.\n */\n Currency?: string | null;\n Remaining: number;\n Available: boolean;\n Status: string | null;\n Starts: string | null;\n Ends: string | null;\n LocalStartTime: string | null;\n LocalEndTime: string | null;\n MinPerTransaction: number;\n MaxPerTransaction: number;\n PaymentsEnabled: boolean;\n AttendeeDetailsRequired: boolean;\n HasTimeslot: boolean;\n Questions: QuestionnaireQuestion[] | null;\n Timeslots: EventTimeslot[] | null;\n UrgencyTags: string[];\n /** Nullable for the same reason as the run's — see `EventInfoResponse`. */\n UserTypes: UserType[] | null;\n}\n\n/** @internal */\nexport interface TicketsResponse {\n EventKey: string;\n Tickets: Ticket[];\n}\n\n// =============================================================================\n// Questionnaire Types\n// =============================================================================\n\n/** @internal */\nexport interface QuestionnaireQuestion {\n Question: string;\n QuestionId: number;\n Type: 'text' | 'date' | 'checkbox' | string;\n}\n\n/** @internal */\nexport interface QuestionnaireResponseValue {\n QuestionId: number;\n Value: string;\n}\n\n/** @internal */\nexport interface SubmitQuestionnaireResponsesRequest {\n ItemKey: string;\n Values: QuestionnaireResponseValue[];\n}\n\n// =============================================================================\n// Timeslot Types\n// =============================================================================\n\n/** @internal */\nexport interface EventTimeslot {\n LocalStartTime: string;\n LocalEndTime: string;\n Total: number;\n Remaining: number;\n}\n\n/**\n * The session an item is bought for. BOTH ENDS ARE TIMES OF DAY — `18:00:00`, which is\n * what the platform deserialises them into (`System.TimeSpan`) and the shape a ticket's\n * own `Timeslots` come back in. A full local timestamp is refused: `The JSON value could\n * not be converted to System.TimeSpan`. The date is not missing from this — it is the\n * event the cart was opened on.\n */\nexport interface TimeslotRequest {\n LocalStartTime: string;\n LocalEndTime: string;\n}\n\n// =============================================================================\n// Cart Types\n// =============================================================================\n\nexport interface CartItem {\n Key: string;\n Type: string;\n Name?: string; // Optional display name (v2 bulk-add may provide Name instead of Type)\n ItemId: number;\n TotalAmount: number;\n OrganisationAmount: number;\n ScopeAmount: number;\n BrokerAmount: number;\n DiscountAmount: number;\n}\n\n/**\n * `GET /api/PromoCode/Check` — whether a code may be used, and the platform's own words\n * for why not. `Reason` is prose, so a caller drawing it bounds it first.\n */\nexport interface PromoCodeCheck {\n IsValid: boolean;\n Reason: string | null;\n}\n\nexport interface Cart {\n Key: string;\n EventId: number;\n TotalAmount: number;\n OrganisationAmount: number;\n ScopeAmount: number;\n BrokerAmount: number;\n DiscountAmount: number;\n Items: CartItem[];\n PromoCode: string | null;\n /** UTC timestamp when cart escrow expires (ISO 8601 string). Anticipated BE field — currently injected client-side. */\n ExpirationTime?: string | null;\n}\n\n// Response when adding item to cart (v1)\n/** @internal */\nexport interface CartAddItemResponse {\n Item: CartItem;\n Cart: Cart;\n}\n\n// v2 bulk add items to cart\n/** @internal */\nexport interface BulkAddItemRequest {\n ProductKey: string;\n UserTypeAssignmentKey?: string | null;\n Timeslot?: TimeslotRequest;\n}\n\n/** @internal */\nexport interface BulkAddItemsRequest {\n Items: BulkAddItemRequest[];\n /**\n * FILL WHAT YOU CAN, RATHER THAN NOTHING. Six where four remain used to answer\n * `400 NoTicketsAvailable` and leave the cart EMPTY — a dead end carrying no count, so\n * nothing could offer the four. OPT-IN: a caller filling a cart it has priced elsewhere\n * would rather be refused than be short.\n */\n AllowPartialFulfillment?: boolean;\n}\n\n/**\n * `Items` is what was RESERVED, which on a partial fill is fewer than asked.\n *\n * `UnavailableItems` IS WHAT COULD NOT BE, and it is the platform's own statement rather\n * than a count to be inferred: each entry echoes the request line it stands for, so it\n * says WHICH user types went unfilled and not merely how many. Always present — `[]` on a\n * full fill, with or without the flag.\n *\n * IT IS ALSO THE ONLY WAY TO KNOW. A returned `CartItem` carries a key and amounts and no\n * `ProductKey` or `Timeslot`, so nothing in `Items` says which request line it answers.\n * @internal\n */\nexport interface BulkAddItemResponse {\n Items: CartItem[];\n UnavailableItems: BulkAddItemRequest[];\n Cart: Cart;\n}\n\n// =============================================================================\n// Buyer / User Types\n// =============================================================================\n\nexport interface BuyerDetails {\n FirstName: string;\n LastName: string;\n Email: string;\n Phone?: string;\n}\n\n/** @internal */\nexport interface BuyerFormValues extends BuyerDetails {\n /** Local checkout field. Country is local checkout state until the cart buyer API accepts it. */\n Country: string;\n Phone: string;\n}\n\n/** @internal */\nexport interface BuyerResponse extends BuyerDetails {\n Photo?: string;\n}\n\n// Attendee - for saving/fetching attendee details on purchased tickets\n/** @internal */\nexport interface Attendee {\n ID: number;\n FirstName: string;\n LastName: string;\n Email: string;\n Phone?: string;\n Photo?: string;\n}\n\n/**\n * WHO A TICKET IS FOR, AS `PUT /api/v2/Transactions/{transaction_key}/Items/{item_key}/Attendee`\n * TAKES IT.\n *\n * ADDRESSED BY KEYS AND NOT BY IDS, which is the point of the v2 call: the route names the\n * transaction and the item by the tokens the platform issued, so there is no attendee id\n * to have read first, nothing integer-shaped on the wire, and nothing a buyer with dev\n * tools open could enumerate. The platform creates the attendee and binds it to the\n * ticket, and re-addressing the same item is how a holder is changed.\n *\n * `Photo` IS ECHOED RATHER THAN INVENTED: an absent photo on a save means no photo, so a\n * caller that wants the face a read already carried sends it back as it came.\n */\nexport interface SetItemAttendeeRequest {\n FirstName: string;\n LastName: string;\n Email: string;\n Phone?: string;\n /** The face the platform already holds, as the read returned it. Omitted for none. */\n Photo?: string;\n}\n\n// =============================================================================\n// Payment Types\n// =============================================================================\n\n/** @internal */\nexport interface PaymentIntent {\n PaymentPlatform: string | null;\n ClientSecret: string;\n PublicKey: string;\n StripeClientSecret?: string;\n StripePublicKey?: string;\n}\n\n/** @internal */\nexport type PaymentFlowStatus =\n | 'awaiting_payment'\n | 'requires_new_payment'\n | 'processing'\n | 'completed';\n\n/** @internal */\nexport interface PaymentStatusResponse {\n CartKey: string;\n PaymentPlatform: string | null;\n PaymentStatus: PaymentFlowStatus | string;\n FailureReason?: string | null;\n ClientSecret?: string | null;\n}\n\n// =============================================================================\n// Transaction Types\n// =============================================================================\n\nexport interface AttendeeTicket {\n ID: number;\n AttendeeTicketKey: string;\n AttendeeID: number;\n TicketID: number | null;\n TransactionID: number;\n Status: string;\n TotalAmount: number;\n Currency: string;\n TimeBooked: string;\n OrganisationAmount: number;\n ScopeAmount: number;\n BrokerAmount: number;\n DiscountAmount: number;\n}\n\n/** @internal */\nexport interface Transaction {\n ID: number;\n TransactionKey: string;\n Items: AttendeeTicket[];\n}\n\n/**\n * `POST /api/Feedback` — how the buyer rated a ticket they bought.\n *\n * ONE TICKET, NOT ONE ORDER. The platform hangs feedback off an attendee ticket, so an\n * order of four has four things that could be rated and the caller says which.\n *\n * `Rating` IS 1..5, the five stars the card draws. The spec types it as a bare `int32`\n * and states no range, so the range is the design's — see `FeedbackRating` in\n * `@scopetickets/checkout`, which is where it is narrowed and where it is checked.\n */\nexport interface FeedbackRequest {\n /** The ticket being rated. `maxLength: 50` on the platform's own model. */\n AttendeeTicketKey: string;\n Rating: number;\n}\n\n// Response from /api/Transactions/ByKey/{cartKey}\n// Different structure than Transaction - includes full Attendee object per item\n/** @internal */\n/** @internal */\nexport interface TransactionByKeyResponse {\n ID: number;\n TransactionKey: string;\n StripeStatus: string;\n TotalAmount: number;\n Currency: string;\n EventID?: number;\n Items: Array<{\n Key: string;\n Type: string;\n ItemId: number;\n TotalAmount: number;\n OrganisationAmount: number;\n ScopeAmount: number;\n BrokerAmount: number;\n DiscountAmount: number;\n Attendee?: {\n ID: number;\n FirstName: string;\n LastName: string;\n Email: string;\n Phone?: string | null;\n Photo?: string | null;\n };\n }>;\n}\n\n// =============================================================================\n// SDK Configuration\n// =============================================================================\n\n/** @internal */\nexport type Environment = 'sandbox' | 'production' | 'internal';\n\n/** @internal */\n/*\n * WHERE ARTWORK LIVES, and the reason it is here rather than derived from `apiUrl`.\n *\n * `Theme.Backgrounds` and `Theme.Cover` arrive as SITE-ROOT paths — `/assets/images/...`\n * — which resolve correctly on a Scope page and nowhere else. An embedded widget runs on\n * the customer's own domain, so the same path 404s against THEIR origin, silently: an\n * `<img>` that cannot load draws nothing and reports nothing.\n *\n * NOT THE API HOST. Assets are served from the CDN, not from `link`/`testlink`, so this\n * cannot be inferred from the platform the request went to. It is stated per environment\n * so the three can diverge, and they do not currently: one CDN serves all of them.\n *\n * `passkeyRpId` AND `passkeyHostUrl` ARE A PAIR, and the pairing is the whole point: a\n * credential is bound to the RP id, and only a document whose origin ends in that id may\n * ask for one. `passkeys.testlink.scopetickets.com` sits under `testlink.scopetickets.com`\n * for exactly that reason, and a host moved off that suffix stops working with no error\n * worth reading.\n *\n * The RP id is written here rather than read from the platform because\n * `POST /api/Passkeys/Authentications/Challenges` does not return one — its registration\n * twin does. It is a per-environment constant either way, like the two URLs above it.\n */\nexport const ENVIRONMENT_URLS = {\n sandbox: {\n apiUrl: import.meta.env?.VITE_API_URL ?? 'https://testlink.scopetickets.com',\n paymentHostUrl:\n import.meta.env?.VITE_PAYMENT_HOST_URL ?? 'https://sandbox.pay.scopetickets.com',\n artworkUrl: import.meta.env?.VITE_ARTWORK_URL ?? 'https://cdn.scopetickets.com',\n passkeyRpId: 'testlink.scopetickets.com',\n passkeyHostUrl:\n import.meta.env?.VITE_PASSKEY_HOST_URL ?? 'https://passkeys.testlink.scopetickets.com',\n },\n production: {\n apiUrl: import.meta.env?.VITE_API_URL ?? 'https://link.scopetickets.com',\n paymentHostUrl: import.meta.env?.VITE_PAYMENT_HOST_URL ?? 'https://pay.scopetickets.com',\n artworkUrl: import.meta.env?.VITE_ARTWORK_URL ?? 'https://cdn.scopetickets.com',\n passkeyRpId: 'link.scopetickets.com',\n passkeyHostUrl:\n import.meta.env?.VITE_PASSKEY_HOST_URL ?? 'https://passkeys.link.scopetickets.com',\n },\n // Internal environment for local development.\n internal: {\n apiUrl: import.meta.env?.VITE_API_URL ?? 'https://testlink.scopetickets.com',\n paymentHostUrl: import.meta.env?.VITE_PAYMENT_HOST_URL ?? 'http://localhost:3001',\n artworkUrl: import.meta.env?.VITE_ARTWORK_URL ?? 'https://cdn.scopetickets.com',\n /*\n * `localhost` IS ITS OWN RP ID, and the one origin a browser will do WebAuthn on\n * without TLS. A local host cannot borrow the staging id: `localhost` is not a\n * suffix of `testlink.scopetickets.com`, so a credential made here is a local one\n * and does not carry to staging.\n */\n passkeyRpId: 'localhost',\n passkeyHostUrl: import.meta.env?.VITE_PASSKEY_HOST_URL ?? 'http://localhost:3002',\n },\n} as const;\n\n// Internal resolved config (not exported to consumers)\n/** @internal */\nexport interface ScopeConfig {\n apiKey?: string;\n orgKey: string;\n environment: Environment;\n apiUrl: string;\n paymentHostUrl: string;\n /** The RP id credentials are bound to. See `ENVIRONMENT_URLS`. */\n passkeyRpId?: string;\n /** Where the ceremony document is served. Its origin must end in `passkeyRpId`. */\n passkeyHostUrl?: string;\n}\n\n// =============================================================================\n// Passcodes — email verification\n// =============================================================================\n\n/**\n * @Zsolt — AUTH SURFACE. These are the three Passcodes operations as the checkout\n * widget's email-verification step needs them. Nothing in the SDK calls them yet;\n * they are here so the account flow has a typed transport to reach for.\n */\n\n/**\n * `POST /api/Passcodes/Email` — send a code to an address.\n *\n * OPTIONAL `UserKey`, because the flow that spends this has no user to name: the address\n * is verified BEFORE the account exists. It is on the wire for the other caller — an\n * account re-verifying an address it already owns — which this widget is not.\n */\nexport interface SendEmailPasscodeRequest {\n UserKey?: string;\n /** `maxLength: 50` on the wire, which is shorter than most address rules allow. */\n Email: string;\n}\n\n/**\n * What `POST /api/Passcodes/Email` answers with — the key `getPasscodeStatus` reads.\n *\n * `Key`, and it was `PasscodeKey` here until the specification could be read: the field\n * was inferred while the operation sat behind auth, and inferred wrong. Nothing had\n * called it yet, so the mistake cost nothing but is worth a line — the same guess is\n * available to anyone adding the next operation from a swagger page they cannot open.\n */\nexport interface SendEmailPasscodeResponse {\n Key: string;\n}\n\n/**\n * `POST /api/Passcodes/Verification` — submit the code the buyer typed.\n *\n * `{ Code }` ALONE, confirmed against the specification rather than guessed: no passcode\n * key and no address, so the platform is correlating the attempt itself. Which one it\n * correlates BY is the open question — a session would be sound, a global match over\n * every outstanding code would put all of them in one six-digit space at once.\n */\nexport interface VerifyPasscodeRequest {\n Code: string;\n}\n\n/** `GET /api/Passcodes/{passcodeKey}/Status`. */\nexport interface PasscodeStatusResponse {\n Verified: boolean;\n}\n\n// =============================================================================\n// Accounts — the session, the user, and the credentials that open one\n// =============================================================================\n\n/**\n * WHAT EVERY DOOR HANDS BACK. Creating an account, signing in with a password and\n * signing in with a passkey all resolve to this: how somebody proved who they are does\n * not change what the proof is worth.\n *\n * NO USER KEY, AND NO PROFILE EITHER — a header is the whole of it. Confirmed against\n * staging: `/api/Users/{key}/Following` accepts the 32-character key from\n * `PasskeyUser.Key` and nothing else, the numeric `StaffID` and the literal `me` both\n * answer `UserNotFound`, and the JWT carries neither.\n *\n * WHICH IS WHAT `GET /api/Users/Me` IS FOR. It answers with the key and the profile\n * together, so a session no longer has to be traded for a passkey challenge nobody meant\n * to finish before the flow can say who is signed in.\n */\nexport interface LoginResult {\n /**\n * The header value for subsequent calls, sent VERBATIM — and it is a complete one.\n * MEASURED against staging rather than assumed: `POST /api/Auth/Login` answers with a\n * `Bearer ` prefix already on it, wrapping a JWT. Nothing here adds a scheme.\n *\n * The JWT's own claims are `jti` (the `SessionKey` below), `sub` (the `StaffID`), and\n * the usual `iat`/`exp`/`aud`. It carries NO user key, which is why the note on\n * `PasskeyUser.Key` matters.\n */\n Authorization: string | null;\n /** Names the session to `POST /api/Auth/Tokens`. */\n SessionKey: string | null;\n RefreshToken: string | null;\n}\n\n/**\n * `POST /api/Auth/Login`'s answer — a `LoginResult` and an id.\n *\n * NAMED FOR STAFF, AND NOT ONLY FOR THEM. A user is one object whichever roles they\n * occupy, so this is the door a ticket-holder signs in through exactly as much as an\n * administrator. The name is the platform's history rather than a restriction, and it is\n * kept as the platform spells it so the two can be read against each other.\n */\nexport interface StaffLoginResult extends LoginResult {\n StaffID: number;\n}\n\n/** `POST /api/Auth/Login` — an address and a password. Both bounded at 50 on the wire. */\nexport interface LoginRequest {\n UserName: string;\n Password: string;\n}\n\n/** `POST /api/Auth/Tokens` — trading a session and its refresh token for a fresh header. */\nexport interface TokenRequest {\n SessionKey: string;\n RefreshToken: string;\n}\n\n/**\n * What a refresh answers with.\n *\n * NO NEW REFRESH TOKEN, so the one held is spent again next time rather than rotated —\n * worth knowing before writing a refresh loop that expects to replace it.\n */\nexport interface StaffAuthResult {\n StaffID: number;\n Authorization: string | null;\n}\n\n/**\n * `POST /api/Users` — making one.\n *\n * NO PASSCODE KEY, though an address is verified before this is called. The platform\n * joins the two by the address itself, which is why `Email` here must be the exact\n * string the code was sent to — see `confirmAddress` in `@scopetickets/checkout`.\n */\nexport interface ApplicationUserRequest {\n FirstName: string;\n LastName: string;\n Phone?: string;\n /** `maxLength: 50`, which is shorter than most address rules allow. */\n Email: string;\n /** `maxLength: 50` here, and 100 on `PUT /api/Users/Password`. The stricter one wins. */\n Password: string;\n /** Whether the response should carry a session. The account flow wants one. */\n LoginUser?: boolean;\n}\n\n/**\n * `GET /api/Users/Me` — the profile of whoever the session belongs to.\n *\n * THE ONLY PLACE A PROFILE COMES BACK. Every door into an account answers with a\n * `LoginResult`, which is a header and nothing else, so a buyer who has just signed in is\n * somebody the flow cannot name, draw or write to. This is the call that turns a session\n * into a person — see `accountFromUser` in `@scopetickets/checkout`.\n *\n * IT ALSO CARRIES THE USER KEY, which `LoginResult` does not. `Key` here and\n * `PasskeyUser.Key` are the same 32 characters, which is what `/api/Users/{key}/Following`\n * takes — so the follow prompt no longer has to open a passkey challenge to find out whose\n * account it is writing to.\n *\n * `FirstName`, `LastName` and `Email` are required on the wire; the other three are\n * nullable and a real account may have none of them.\n */\nexport interface UserResponse {\n FirstName: string;\n LastName: string;\n Phone: string | null;\n Email: string;\n /** The 32-character user key — a GUID without its dashes. */\n Key: string | null;\n /** The stored avatar value, exactly as the profile carries it. `null` for a face never set. */\n Photo: string | null;\n}\n\n/** `PUT /api/Users` — the signed-in user's own details. */\nexport interface UserUpdateRequest {\n FirstName: string;\n LastName: string;\n Phone?: string;\n}\n\n/** `PUT /api/Users/Password` — for the signed-in user. `maxLength: 100`. */\nexport interface PasswordRequest {\n Password: string;\n}\n\n/** `POST /api/Users/PasswordReset` — for one who cannot sign in. */\nexport interface EmailRequest {\n Email: string;\n}\n\n/**\n * `PUT /api/Users/Photo` — a face, either inline or by reference.\n *\n * IT NEEDS A SESSION, so it cannot run before the account exists. The buyer chooses the\n * photo before that and the call is spent inside the wait that creates the account.\n */\nexport interface ImageRequest {\n EncodedImage?: string;\n ImageURL?: string;\n}\n\n/** `GET /api/Users/{key}/Following` — who a user hears from. */\nexport interface FollowingResponse {\n OrganisationKeys: string[];\n VenueKeys: string[];\n}\n\n/** `POST /api/Users/{key}/Following/Organisation`. */\nexport interface OrganisationKeyRequest {\n OrganisationKey: string;\n}\n\n/** `POST /api/Users/{key}/Following/Venue`. */\nexport interface VenueKeyRequest {\n VenueKey: string;\n}\n\n// =============================================================================\n// Passkeys\n// =============================================================================\n//\n// The ceremony itself does not happen here, or anywhere in a package a customer's page\n// loads: WebAuthn binds a credential to an RP id, and the widget runs on the customer's\n// own origin. These four operations are the platform half; `packages/passkey-host` is\n// the document that calls the browser.\n\n/**\n * `POST /api/Passkeys/Registrations/Challenges`.\n *\n * IT NAMES NOBODY, which is the whole reason the passkey step sits after the account is\n * made: the user comes from the session, so before there is one there is nobody to mint\n * a challenge for.\n */\nexport interface PasskeyRegistrationChallengeRequest {\n /** Ask for a resident key — one the device can offer without being told whose it is. */\n Discoverable: boolean;\n}\n\n/** Who the credential will belong to. `Key` is the only user key the API ever returns. */\nexport interface PasskeyUser {\n Key: string | null;\n Email: string | null;\n FullName: string | null;\n}\n\nexport interface PasskeyRegistrationChallenge {\n ChallengeID: string | null;\n /** Hex on the wire. `@scopetickets/passkey-host` owns the decoding — see its `codec.ts`. */\n Challenge: string | null;\n User: PasskeyUser;\n /**\n * COSE identifiers — `-7` (ES256) and `-257` (RS256), which is the platform's whole\n * `PasskeyAlgorithm` enum. A bare `number[]` here because that is what JSON carries;\n * `passkeyAlgorithms` in `@scopetickets/checkout` is where it becomes a closed set.\n */\n Algorithms: number[];\n UserVerification: string | null;\n /** `testlink.scopetickets.com` on staging — and the reason the ceremony needs its own origin. */\n RPID: string | null;\n}\n\n/** `POST /api/Passkeys/Registrations` — the credential the device made. */\nexport interface PasskeyRegistrationRequest {\n ChallengeID: string;\n CredentialID: string;\n Type: string;\n AuthenticatorAttestation: string;\n ClientData: string;\n}\n\n/**\n * `POST /api/Passkeys/Authentications/Challenges`.\n *\n * `Email` NARROWS IT TO ONE ACCOUNT, and omitting it asks the device for whatever\n * discoverable credential it holds — the usernameless route, which is what the\n * unrecognised card offers.\n */\nexport interface PasskeyValidationChallengeRequest {\n Discoverable: boolean;\n Email?: string;\n}\n\n/**\n * What it answers with.\n *\n * NO `RPID`, unlike its registration twin — and `navigator.credentials.get()` needs one.\n * Until the platform returns it, the caller supplies it from its own environment config,\n * which is a second place the RP id is written down and therefore a second place it can\n * be wrong.\n */\nexport interface PasskeyValidationChallenge {\n ChallengeID: string | null;\n Challenge: string | null;\n /** Empty means the device may offer any discoverable credential it has. */\n CredentialIDs: string[];\n UserVerification: string | null;\n}\n\n/** `POST /api/Passkeys/Authentications` — the assertion the device signed. */\nexport interface PasskeyValidationRequest {\n ChallengeID: string;\n CredentialID: string;\n ClientData: string;\n AuthenticatorData: string;\n /** Absent from a non-discoverable credential, which is a real answer and not an error. */\n UserHandle: string | null;\n Signature: string;\n}\n\n// =============================================================================\n// Payment Frame Types (SDK internal)\n// =============================================================================\n\n/** @internal */\nexport interface PaymentTheme {\n mode?: 'light' | 'dark';\n primaryColor?: string;\n}\n\n/** @internal */\nexport type PaymentStatus = 'idle' | 'ready' | 'processing' | 'success' | 'error' | 'cancelled';\n\n/** @internal */\nexport interface PaymentResult {\n cartKey: string;\n attendeeTicketKey?: string;\n instanceId?: string;\n method?: PaymentHostMethod;\n}\n\nexport interface PaymentError {\n code: string;\n message: string;\n}\n\n// =============================================================================\n// postMessage Protocol\n// =============================================================================\n\n// Buyer data passed from parent to iframe during payment submission\nexport interface BuyerSubmitData {\n firstName: string;\n lastName: string;\n email: string;\n}\n\n/** @internal */\nexport type PaymentHostMethod = 'card' | 'revolut_pay' | 'apple_pay' | 'google_pay';\n\n/** @internal */\nexport interface PaymentFrameMeta {\n instanceId: string;\n method: PaymentHostMethod;\n}\n\n/** @internal */\nexport interface PaymentMethodStatus extends PaymentFrameMeta {\n ready: boolean;\n valid?: boolean;\n processing?: boolean;\n processingLabel?: string;\n error?: { code: string; message: string };\n /**\n * THE WALLET THE HOST ACTUALLY FOUND, in the provider's own naming, sent only by a\n * wallet frame once `canMakePayment()` has answered. The parent's device sniff is a\n * hint for the frame URL and the first paint of a label; this field is the authority,\n * and a parent that reads it can correct a label the sniff got wrong.\n */\n wallet?: 'applePay' | 'googlePay';\n}\n\n/** @internal */\nexport type PaymentPresentationMode = 'inline_provisional' | 'external_handoff';\n\n/** @internal */\nexport interface PaymentPresentation extends PaymentFrameMeta {\n mode: PaymentPresentationMode;\n attemptGeneration: number;\n}\n\n/** @internal */\nexport interface PaymentDiagnostic {\n event: string;\n data?: Record<string, string | number | boolean | null>;\n}\n\n/** @internal */\nexport type FrameMessage =\n // iframe → parent messages\n | { type: 'SCOPE_PAYMENT_READY'; payload?: PaymentFrameMeta }\n /* The host's own ask for its configuration, sent the moment its listener exists —\n * see `Checkout`'s config effect. A parent answers with SCOPE_PAYMENT_CONFIG. */\n | { type: 'SCOPE_PAYMENT_CONFIG_REQUESTED'; payload?: Partial<PaymentFrameMeta> }\n | { type: 'SCOPE_PAYMENT_RESIZE'; payload: { height: number } & Partial<PaymentFrameMeta> }\n | { type: 'SCOPE_PAYMENT_SUCCESS'; payload: PaymentResult }\n | { type: 'SCOPE_PAYMENT_ERROR'; payload: PaymentError & Partial<PaymentFrameMeta> }\n | { type: 'SCOPE_PAYMENT_CANCELLED'; payload?: Partial<PaymentFrameMeta> }\n | { type: 'SCOPE_PAYMENT_SUBMIT_REQUESTED'; payload?: Partial<PaymentFrameMeta> }\n // parent → iframe messages\n | {\n type: 'SCOPE_PAYMENT_CONFIG';\n payload: {\n apiKey?: string;\n selectedMethod?: PaymentHostMethod;\n theme?: Record<string, string>;\n } & Partial<PaymentFrameMeta>;\n }\n | { type: 'SCOPE_PAYMENT_SUBMIT_CONFIRMED'; payload: BuyerSubmitData & Partial<PaymentFrameMeta> }\n | {\n type: 'SCOPE_PAYMENT_SUBMIT_REJECTED';\n payload: { reason: string } & Partial<PaymentFrameMeta>;\n }\n | { type: 'SCOPE_PAYMENT_PRESENTATION'; payload: PaymentPresentation }\n | { type: 'SCOPE_PAYMENT_DIAGNOSTIC'; payload: PaymentDiagnostic & PaymentFrameMeta }\n | { type: 'SCOPE_PAYMENT_METHOD_STATUS'; payload: PaymentMethodStatus }\n | { type: 'SCOPE_PAYMENT_CANCEL_REQUESTED'; payload: PaymentFrameMeta }\n | { type: 'SCOPE_PAYMENT_TRIGGER_SUBMIT'; payload: PaymentFrameMeta };\n","import type {\n ScopeConfig,\n Event,\n Ticket,\n DisplayEvent,\n DisplayEventsResponse,\n EventInfoResponse,\n TicketsResponse,\n TimeslotRequest,\n Cart,\n CartAddItemResponse,\n BulkAddItemRequest,\n BulkAddItemResponse,\n BulkAddItemsRequest,\n BuyerDetails,\n BuyerResponse,\n PaymentIntent,\n PaymentStatusResponse,\n Transaction,\n TransactionByKeyResponse,\n Attendee,\n SetItemAttendeeRequest,\n QuestionnaireQuestion,\n SubmitQuestionnaireResponsesRequest,\n SendEmailPasscodeRequest,\n SendEmailPasscodeResponse,\n VerifyPasscodeRequest,\n PasscodeStatusResponse,\n LoginResult,\n StaffLoginResult,\n LoginRequest,\n TokenRequest,\n StaffAuthResult,\n ApplicationUserRequest,\n UserUpdateRequest,\n UserResponse,\n PasswordRequest,\n EmailRequest,\n ImageRequest,\n FollowingResponse,\n OrganisationKeyRequest,\n VenueKeyRequest,\n PasskeyRegistrationChallengeRequest,\n PasskeyRegistrationChallenge,\n PasskeyRegistrationRequest,\n PasskeyValidationChallengeRequest,\n PasskeyValidationChallenge,\n PasskeyValidationRequest,\n FeedbackRequest,\n PromoCodeCheck,\n} from './types';\n\n// =============================================================================\n// API Error Handling\n// =============================================================================\n\ninterface ApiErrorResponse {\n Reason: string;\n Message: string;\n}\n\n/**\n * Error thrown when the Scope Tickets API returns a non-success response.\n *\n * @see {@link ScopeClient}\n */\nexport class ApiError extends Error {\n constructor(\n public reason: string,\n message: string,\n ) {\n super(message);\n this.name = 'ApiError';\n }\n}\n\n// =============================================================================\n// Scope API Client\n// =============================================================================\n\n/**\n * HTTP client for the Scope Tickets API.\n *\n * Provides typed methods for events, tickets, carts, payments, and transactions.\n * Usually consumed via {@link useScopeContext} rather than instantiated directly.\n *\n * @example\n * ```ts\n * const client = new ScopeClient({ orgKey: 'my-org', environment: 'sandbox' });\n * const events = await client.getDisplayEvents();\n * ```\n */\n/** @internal Low-level HTTP client. Use hooks instead. */\nexport class ScopeClient {\n private config: ScopeConfig;\n private sessionAuthorization: string | null = null;\n private onRefused: (() => void) | null = null;\n\n constructor(config: ScopeConfig) {\n this.config = config;\n }\n\n /**\n * WHO TO TELL WHEN A SESSION IS REFUSED — the one signal a session has that it is over.\n *\n * `LoginResult` carries no expiry, so nothing can know a header has stopped working\n * until the platform says so. This is where that arrives, and it is a callback on the\n * INSTANCE rather than anything global: this library runs inside somebody else's page,\n * and a handler registered anywhere a host could also reach is a handler two things\n * fight over.\n *\n * IT FIRES ONLY WHERE A USER SESSION WAS ACTUALLY SENT. A 401 on the app key alone is\n * the app being wrong about itself, not a buyer being signed out, and waking the session\n * machinery for it would expire somebody who was never signed in.\n */\n setRefusedHandler(handler: (() => void) | null): void {\n this.onRefused = handler;\n }\n\n /**\n * Holds the header a signed-in user's session gave us, or clears it on sign-out.\n *\n * Stored and sent VERBATIM, which is right: staging answers `POST /api/Auth/Login`\n * with the `Bearer ` already on it. Nothing here adds a scheme, and nothing should.\n */\n setAuthorization(authorization: string | null): void {\n this.sessionAuthorization = authorization;\n }\n\n /** Whether a user session is in force, rather than the app key alone. */\n hasAuthorization(): boolean {\n return this.sessionAuthorization !== null;\n }\n\n private getAuthHeaders(): Record<string, string> {\n /*\n * A SESSION REPLACES THE APP KEY RATHER THAN JOINING IT, and this is now measured\n * rather than assumed: an authenticated call carrying ONLY a user session is accepted\n * by staging, and the same call carrying nothing is refused with a 401. The app key\n * does not need to travel alongside.\n */\n if (this.sessionAuthorization !== null) {\n return { Authorization: this.sessionAuthorization };\n }\n if (this.config.apiKey) {\n return { Authorization: `Bearer ${this.config.apiKey}` };\n }\n return {};\n }\n\n /** A 401 on a call that carried a session, and nothing else. See `setRefusedHandler`. */\n private reportIfRefused(status: number): void {\n if (status === 401 && this.sessionAuthorization !== null) this.onRefused?.();\n }\n\n private async fetch<T>(endpoint: string, options?: RequestInit): Promise<T> {\n const response = await fetch(`${this.config.apiUrl}${endpoint}`, {\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...this.getAuthHeaders(),\n ...options?.headers,\n },\n });\n\n if (!response.ok) {\n this.reportIfRefused(response.status);\n let errorResponse: ApiErrorResponse;\n try {\n errorResponse = await response.json();\n } catch (e) {\n console.error('Failed to parse API error response:', e);\n throw new ApiError('UnknownError', `API error: ${response.status} ${response.statusText}`);\n }\n throw new ApiError(errorResponse.Reason, errorResponse.Message);\n }\n\n // Handle empty responses (204 No Content, etc.)\n const text = await response.text();\n if (!text) {\n return undefined as T;\n }\n\n try {\n return JSON.parse(text);\n } catch {\n return text as T;\n }\n }\n\n private async fetchVoid(endpoint: string, options?: RequestInit): Promise<void> {\n const response = await fetch(`${this.config.apiUrl}${endpoint}`, {\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...this.getAuthHeaders(),\n ...options?.headers,\n },\n });\n\n if (!response.ok) {\n this.reportIfRefused(response.status);\n let errorResponse: ApiErrorResponse;\n try {\n errorResponse = await response.json();\n } catch (e) {\n console.error('Failed to parse API error response:', e);\n throw new ApiError('UnknownError', `API error: ${response.status} ${response.statusText}`);\n }\n throw new ApiError(errorResponse.Reason, errorResponse.Message);\n }\n }\n\n // ===========================================================================\n // v2 Events\n // ===========================================================================\n\n async getDisplayEvents(signal?: AbortSignal): Promise<DisplayEvent[]> {\n const response = await this.fetch<DisplayEventsResponse>('/api/v2/EventSummaries', { signal });\n return response.Events;\n }\n\n async getEventInfo(eventKey: string, signal?: AbortSignal): Promise<EventInfoResponse> {\n return this.fetch<EventInfoResponse>(`/api/v2/EventInformation?type=event&key=${eventKey}`, {\n signal,\n });\n }\n\n async getSeriesInfo(seriesKey: string, signal?: AbortSignal): Promise<EventInfoResponse> {\n return this.fetch<EventInfoResponse>(`/api/v2/EventInformation?type=series&key=${seriesKey}`, {\n signal,\n });\n }\n\n async getEventTickets(eventKey: string, signal?: AbortSignal): Promise<Ticket[]> {\n const response = await this.fetch<TicketsResponse>(\n `/api/v2/Events/${eventKey}/Tickets?include_timeslots=true`,\n { signal },\n );\n return response.Tickets;\n }\n\n // ===========================================================================\n // v1 Events (deprecated — kept for cart/timeslot compat)\n // ===========================================================================\n\n /** @deprecated Use getDisplayEvents() or getEventInfo() instead */\n async getEvents(count?: number): Promise<Event[]> {\n const params = count ? `?count=${count}` : '';\n return this.fetch<Event[]>(`/api/Events/ByOrganisationKey/${this.config.orgKey}${params}`);\n }\n\n /** @deprecated Use getEventTickets() instead */\n async getTickets(eventId: number): Promise<Ticket[]> {\n return this.fetch<Ticket[]>(`/api/Ticket/Event/${eventId}`);\n }\n\n // ===========================================================================\n // Cart\n // ===========================================================================\n\n async createCart(eventId: number | string): Promise<Cart> {\n const body = typeof eventId === 'string' ? { EventKey: eventId } : { EventId: eventId };\n return this.fetch<Cart>('/api/Cart', {\n method: 'POST',\n body: JSON.stringify(body),\n });\n }\n\n async getCart(cartKey: string): Promise<Cart> {\n return this.fetch<Cart>(`/api/Cart/${cartKey}`);\n }\n\n async addToCart(\n cartKey: string,\n ticketId: number,\n timeslot?: TimeslotRequest,\n ): Promise<CartAddItemResponse> {\n const body = timeslot\n ? { Type: 'ticket' as const, ItemId: ticketId, Timeslot: timeslot }\n : { Type: 'ticket' as const, ItemId: ticketId };\n return this.fetch<CartAddItemResponse>(`/api/Cart/${cartKey}/Items`, {\n method: 'POST',\n body: JSON.stringify(body),\n });\n }\n\n async removeFromCart(cartKey: string, itemKey: string): Promise<Cart> {\n return this.fetch<Cart>(`/api/Cart/${cartKey}/Items/${itemKey}`, {\n method: 'DELETE',\n });\n }\n\n /**\n * WHETHER A CODE MAY BE USED, AND WHY NOT — the one call that answers the second half.\n *\n * THE `PUT` BELOW ONLY APPLIES. It refuses with an `ApiError` whose message is a\n * transport failure's message, which is not a sentence about a promo code; `Reason` here\n * is the platform's own words for an expired, spent or wrong-event code, and it is what\n * the card shows the buyer.\n *\n * `event_id` IS WHAT THE WIDGET KNOWS. The endpoint also narrows by ticket, series and\n * organisation; the cart carries its event and nothing else, so that is what is asked.\n */\n async checkPromoCode(promoCode: string, eventId: number): Promise<PromoCodeCheck> {\n const params = new URLSearchParams({ code: promoCode, event_id: String(eventId) });\n return this.fetch<PromoCodeCheck>(`/api/PromoCode/Check?${params}`);\n }\n\n /**\n * PUT A PROMO CODE ON THE CART, and take back the cart it made — `TotalAmount` already\n * discounted, `DiscountAmount` saying by how much, `PromoCode` naming what did it.\n *\n * ONE PER CART, which is the wire's rule and not this client's: the field is a single\n * string, so a second code REPLACES the first rather than stacking on it.\n *\n * A REFUSED CODE IS AN `ApiError` like any other refusal — expired, spent, or for a\n * different event. The reason is the platform's own words; see `promoRefusal`, which is\n * the only thing allowed to put them in front of a buyer.\n */\n async setCartPromoCode(cartKey: string, promoCode: string): Promise<Cart> {\n return this.fetch<Cart>(`/api/Cart/${encodeURIComponent(cartKey)}/PromoCode`, {\n method: 'PUT',\n body: JSON.stringify({ PromoCode: promoCode }),\n });\n }\n\n /** Take it off again, and the cart comes back at its full price. */\n async clearCartPromoCode(cartKey: string): Promise<Cart> {\n return this.fetch<Cart>(`/api/Cart/${encodeURIComponent(cartKey)}/PromoCode`, {\n method: 'DELETE',\n });\n }\n\n /**\n * `allowPartial` asks the platform to reserve what it can — see\n * `BulkAddItemsRequest.AllowPartialFulfillment`. OMITTED rather than sent as `false`\n * when it is not asked for: a body without it is what every caller already sends.\n */\n async addItemsBulk(\n cartKey: string,\n items: BulkAddItemRequest[],\n { allowPartial = false }: { allowPartial?: boolean } = {},\n ): Promise<BulkAddItemResponse> {\n const body: BulkAddItemsRequest = {\n Items: items,\n ...(allowPartial ? { AllowPartialFulfillment: true } : {}),\n };\n return this.fetch<BulkAddItemResponse>(`/api/v2/Carts/${cartKey}/Items`, {\n method: 'POST',\n body: JSON.stringify(body),\n });\n }\n\n // ===========================================================================\n // Questionnaire\n // ===========================================================================\n\n async getQuestionnaireQuestions(\n eventId: number | string,\n signal?: AbortSignal,\n ): Promise<QuestionnaireQuestion[]> {\n return this.fetch<QuestionnaireQuestion[]>(`/api/Questionnaires/Events/${eventId}/Questions`, {\n signal,\n });\n }\n\n // ── Passcodes ──────────────────────────────────────────────────────────\n //\n // @Zsolt — AUTH SURFACE. Transport only: these three make the calls and return what\n // comes back. Which of them runs when, and what a failure means, is the account\n // flow's business — see `domain/passcode.ts` in @scopetickets/checkout.\n\n /** Sends a verification code to an address. */\n async sendEmailPasscode(body: SendEmailPasscodeRequest): Promise<SendEmailPasscodeResponse> {\n return this.fetch<SendEmailPasscodeResponse>('/api/Passcodes/Email', {\n method: 'POST',\n body: JSON.stringify(body),\n });\n }\n\n /** Submits the code the buyer typed. */\n async verifyPasscode(body: VerifyPasscodeRequest): Promise<void> {\n await this.fetch<void>('/api/Passcodes/Verification', {\n method: 'POST',\n body: JSON.stringify(body),\n });\n }\n\n /**\n * Reads whether a passcode has been verified.\n *\n * The authoritative answer, and separate from `verifyPasscode` on purpose: a code\n * submitted in another tab, or on the phone the mail arrived on, is verified without\n * this browser ever having posted it.\n */\n async getPasscodeStatus(passcodeKey: string): Promise<PasscodeStatusResponse> {\n return this.fetch<PasscodeStatusResponse>(\n `/api/Passcodes/${encodeURIComponent(passcodeKey)}/Status`,\n );\n }\n\n async submitQuestionnaireResponses(\n cartKey: string,\n body: SubmitQuestionnaireResponsesRequest,\n ): Promise<string> {\n return this.fetch<string>(`/api/Cart/${cartKey}/Questionnaires/Responses`, {\n method: 'POST',\n body: JSON.stringify(body),\n });\n }\n\n async setBuyer(cartKey: string, buyer: BuyerDetails): Promise<{ ID: number }> {\n return this.fetch<{ ID: number }>(`/api/Cart/${cartKey}/Buyer`, {\n method: 'POST',\n body: JSON.stringify(buyer),\n });\n }\n\n async getBuyer(cartKey: string): Promise<BuyerResponse> {\n return this.fetch<BuyerResponse>(`/api/Cart/${cartKey}/Buyer`);\n }\n\n async deleteCart(cartKey: string): Promise<void> {\n return this.fetchVoid(`/api/Cart/${cartKey}`, {\n method: 'DELETE',\n });\n }\n\n // ===========================================================================\n // Payment\n // ===========================================================================\n\n async createPaymentIntent(\n cartKey: string,\n options?: { retry?: boolean },\n ): Promise<PaymentIntent> {\n const retryQuery = options?.retry ? '?retry=true' : '';\n return this.fetch<PaymentIntent>(`/api/Cart/${cartKey}/Payment${retryQuery}`, {\n method: 'POST',\n });\n }\n\n async getPaymentStatus(cartKey: string): Promise<PaymentStatusResponse> {\n return this.fetch<PaymentStatusResponse>(`/api/Cart/${cartKey}/Payment/Status`);\n }\n\n // ===========================================================================\n // Transactions\n // ===========================================================================\n\n async convertCartToTransaction(cartKey: string): Promise<Transaction> {\n return this.fetch<Transaction>('/api/Transactions/FromCart', {\n method: 'POST',\n body: JSON.stringify({ CartKey: cartKey }),\n });\n }\n\n async getTransactionItems(transactionKey: string): Promise<Transaction> {\n return this.fetch<Transaction>(`/api/Transactions/${transactionKey}/Items`);\n }\n\n async getTransactionByCartKey(cartKey: string): Promise<TransactionByKeyResponse> {\n return this.fetch<TransactionByKeyResponse>(`/api/Transactions/ByKey/${cartKey}`);\n }\n\n // ===========================================================================\n // Attendees\n // ===========================================================================\n\n /**\n * AMENDS ATTENDEES A TRANSACTION ALREADY OWNS, and refuses everything else with\n * `AttendeesNotMatchingTransaction`. It cannot create one — the v2 `setItemAttendee`\n * below is what a first naming goes through.\n *\n * THE TRANSACTION-WIDE CALL, and `packages/sdk`'s ticket-confirmation flow still wants\n * it: it amends an attendee that already exists (buyer-as-holder on a portal-style\n * purchase) and declines politely where none does. New code should prefer the\n * key-addressed call, which needs no id read first and cannot erase anybody by omission.\n */\n async saveAttendees(transactionKey: string, attendees: Attendee[]): Promise<Attendee[]> {\n return this.fetch<Attendee[]>(`/api/Transactions/${transactionKey}/Attendees`, {\n method: 'PUT',\n body: JSON.stringify(attendees),\n });\n }\n\n /**\n * WHO A TICKET IS FOR — creating the attendee where there is none and rebinding the\n * ticket where there is, addressed by keys on both counts.\n *\n * The route takes the TRANSACTION's key and the ITEM's — the same value the bulk add\n * returned as `item_key` and the booking reads as `AttendeeTicketKey` — so there is no\n * attendee id to have read first and nothing integer-shaped on the wire. The platform\n * scopes the item to the transaction and refuses a pair that does not match with\n * `ItemNotFound`.\n *\n * Answers `204`-shaped success with no body: the call either went or it did not, and the\n * name it saved is read back on the next booking read rather than off the response.\n */\n async setItemAttendee(\n transactionKey: string,\n itemKey: string,\n body: SetItemAttendeeRequest,\n ): Promise<void> {\n await this.fetchVoid(`/api/v2/Transactions/${transactionKey}/Items/${itemKey}/Attendee`, {\n method: 'PUT',\n body: JSON.stringify(body),\n });\n }\n\n // ===========================================================================\n // Accounts\n // ===========================================================================\n //\n // Transport only: these make the calls and return what comes back. WHICH of them runs\n // when, and what a failure means, is the account flow's business — see `domain/auth.ts`\n // and `domain/account-creation.ts` in @scopetickets/checkout.\n\n /**\n * Makes an account, and signs into it.\n *\n * `LoginUser` defaults to `true` here and is omitted from the type's own default,\n * because every caller in this workspace wants the session: an account created without\n * one leaves the buyer holding credentials they would then have to spend immediately.\n */\n async createAccount(body: ApplicationUserRequest): Promise<LoginResult> {\n return this.fetch<LoginResult>('/api/Users', {\n method: 'POST',\n body: JSON.stringify({ LoginUser: true, ...body }),\n });\n }\n\n /** An address and a password. */\n async signIn(body: LoginRequest): Promise<StaffLoginResult> {\n return this.fetch<StaffLoginResult>('/api/Auth/Login', {\n method: 'POST',\n body: JSON.stringify(body),\n });\n }\n\n /** Ends the session at the platform. The caller still has to forget its own copy. */\n async signOut(): Promise<boolean> {\n return this.fetch<boolean>('/api/Auth/Logout');\n }\n\n /**\n * A fresh `Authorization` for a session that still holds its refresh token.\n *\n * The answer carries no new refresh token, so the one held is spent again rather than\n * rotated.\n */\n async refreshAuthorization(body: TokenRequest): Promise<StaffAuthResult> {\n return this.fetch<StaffAuthResult>('/api/Auth/Tokens', {\n method: 'POST',\n body: JSON.stringify(body),\n });\n }\n\n /**\n * WHO THE SESSION BELONGS TO. The one call that turns a header into a person: every\n * door into an account answers with a `LoginResult` carrying no name, no address and no\n * key, so this is what the flow asks immediately after one opens.\n *\n * IT NEEDS A USER SESSION, not merely the app key. Measured against staging: with no\n * `Authorization` at all it answers `401 NotAuthorized`, and with the app key alone it\n * answers `500` — so `hasAuthorization` gates the call rather than the answer being\n * read for which of the two happened.\n */\n async getCurrentUser(signal?: AbortSignal): Promise<UserResponse> {\n return this.fetch<UserResponse>('/api/Users/Me', { signal });\n }\n\n /** The signed-in user's own details. */\n async updateUser(body: UserUpdateRequest): Promise<void> {\n return this.fetchVoid('/api/Users', { method: 'PUT', body: JSON.stringify(body) });\n }\n\n /** Changes the password of the signed-in user, who therefore knows the old one. */\n async updatePassword(body: PasswordRequest): Promise<void> {\n return this.fetchVoid('/api/Users/Password', { method: 'PUT', body: JSON.stringify(body) });\n }\n\n /** Starts recovery for somebody who cannot sign in. Needs no session, by definition. */\n async requestPasswordReset(body: EmailRequest): Promise<void> {\n return this.fetchVoid('/api/Users/PasswordReset', {\n method: 'POST',\n body: JSON.stringify(body),\n });\n }\n\n /** Sets the signed-in user's photo. Needs the session, so it runs after creation. */\n async updatePhoto(body: ImageRequest): Promise<void> {\n return this.fetchVoid('/api/Users/Photo', { method: 'PUT', body: JSON.stringify(body) });\n }\n\n // ===========================================================================\n // Following\n // ===========================================================================\n\n async getFollowing(userKey: string, signal?: AbortSignal): Promise<FollowingResponse> {\n return this.fetch<FollowingResponse>(`/api/Users/${encodeURIComponent(userKey)}/Following`, {\n signal,\n });\n }\n\n async followOrganisation(userKey: string, body: OrganisationKeyRequest): Promise<void> {\n return this.fetchVoid(`/api/Users/${encodeURIComponent(userKey)}/Following/Organisation`, {\n method: 'POST',\n body: JSON.stringify(body),\n });\n }\n\n async unfollowOrganisation(userKey: string, organisationKey: string): Promise<void> {\n return this.fetchVoid(\n `/api/Users/${encodeURIComponent(userKey)}/Following/Organisation/${encodeURIComponent(organisationKey)}`,\n { method: 'DELETE' },\n );\n }\n\n async followVenue(userKey: string, body: VenueKeyRequest): Promise<void> {\n return this.fetchVoid(`/api/Users/${encodeURIComponent(userKey)}/Following/Venue`, {\n method: 'POST',\n body: JSON.stringify(body),\n });\n }\n\n async unfollowVenue(userKey: string, venueKey: string): Promise<void> {\n return this.fetchVoid(\n `/api/Users/${encodeURIComponent(userKey)}/Following/Venue/${encodeURIComponent(venueKey)}`,\n { method: 'DELETE' },\n );\n }\n\n // ===========================================================================\n // Passkeys\n // ===========================================================================\n //\n // Four calls and no ceremony. The browser half cannot run in a page a customer serves —\n // see `packages/passkey-host` — so these hand challenges out and take credentials back,\n // and something on a Scope origin does the part in between.\n\n /** Opens a registration. Names nobody: the user comes from the session. */\n async createPasskeyRegistrationChallenge(\n body: PasskeyRegistrationChallengeRequest,\n ): Promise<PasskeyRegistrationChallenge> {\n return this.fetch<PasskeyRegistrationChallenge>('/api/Passkeys/Registrations/Challenges', {\n method: 'POST',\n body: JSON.stringify(body),\n });\n }\n\n /** Lodges the credential the device made. */\n async registerPasskey(body: PasskeyRegistrationRequest): Promise<void> {\n return this.fetchVoid('/api/Passkeys/Registrations', {\n method: 'POST',\n body: JSON.stringify(body),\n });\n }\n\n /** Opens a sign-in. Needs no session — proving who you are is the point of it. */\n async createPasskeyAuthenticationChallenge(\n body: PasskeyValidationChallengeRequest,\n ): Promise<PasskeyValidationChallenge> {\n return this.fetch<PasskeyValidationChallenge>('/api/Passkeys/Authentications/Challenges', {\n method: 'POST',\n body: JSON.stringify(body),\n });\n }\n\n /** Spends the assertion, and opens a session with it. */\n async authenticateWithPasskey(body: PasskeyValidationRequest): Promise<LoginResult> {\n return this.fetch<LoginResult>('/api/Passkeys/Authentications', {\n method: 'POST',\n body: JSON.stringify(body),\n });\n }\n\n // ===========================================================================\n // Feedback\n // ===========================================================================\n\n /**\n * How the buyer rated a ticket. Answers 200 and nothing else, so there is no receipt\n * to hold on to — the call either went or it did not.\n */\n async submitFeedback(body: FeedbackRequest): Promise<void> {\n return this.fetchVoid('/api/Feedback', { method: 'POST', body: JSON.stringify(body) });\n }\n\n // ===========================================================================\n // Utilities\n // ===========================================================================\n\n /**\n * SEND ONE TICKET TO AN ADDRESS — the platform's own email, to whoever the buyer names.\n *\n * `template` IS OMITTED ON PURPOSE. The parameter takes a free string, the spec documents\n * no values for it and nothing else in the API names one; left off, the platform sends\n * its default. Conall, 2026-09-13.\n *\n * IT IS A `GET` THAT SENDS MAIL, which is the platform's shape and not a choice made\n * here. A `GET` is the one method browsers, proxies, prefetchers and generic retry layers\n * treat as free to repeat, so at-most-once cannot be delegated to any of them: every\n * caller has to fire this from one deliberate press and never from anything that can\n * re-run. See `sendTicket` in the booking gateway, which is the only caller.\n */\n async sendTicketEmail(attendeeTicketId: number, email: string): Promise<void> {\n const params = new URLSearchParams({\n email,\n attendee_ticket_id: String(attendeeTicketId),\n });\n await this.fetch<string>(`/api/AttendeeTicket/SendSingleEmail?${params}`);\n }\n\n async getQrCode(content: string, foreground = '000000', background = 'FFFFFF'): Promise<string> {\n const params = new URLSearchParams({\n content,\n foreground,\n background,\n drawQuietZone: 'false',\n });\n return this.fetch<string>(`/api/Utils/GetQrCodeAsSVG?${params}`);\n }\n}\n","/**\n * THE PARENT-SIDE PAYMENT PROTOCOL — React-free, browser-shape only.\n *\n * Payment Host owns the wire format; everything here is what a parent page needs to talk\n * to a mounted host iframe: build the URL, decide which origin may message us, filter\n * what arrives, and say things back. No React, no components, no window access at import\n * time — every function takes what it uses, so tests (and a non-browser parent) can call\n * them with values. The SDK's `PaymentFrame` and `@scopetickets/checkout`'s frame adapter\n * both use this module rather than each keeping a copy; `packages/payment-host` keeps its\n * own child-side copy and is deliberately untouched.\n *\n * GUARDS, NOT TRUST. `parseFrameEvent` checks origin, source, instanceId and payload\n * shape; a message that fails any check is dropped, not repaired. The parent still\n * decides what the accepted message means — these are the protocol's ears, not the flow.\n */\n\nimport type { FrameMessage, PaymentPresentation } from '../types';\n\n/** How a parent names one mounted payment frame instance. */\nexport type FrameIdentity = {\n readonly instanceId: string;\n readonly method: 'card' | 'revolut_pay' | 'apple_pay' | 'google_pay';\n};\n\n/**\n * THE FRAME'S URL — the only thing that ever identifies which host document a frame\n * holds. Selection and configuration travel over the validated message boundary, never\n * in the URL, so the URL stays stable across selection changes and the pre-warmed\n * provider document is never reloaded.\n */\n/**\n * THE CHECKOUT PAGE'S OWN PARAMS A RETURN MUST HAND BACK. The payment host copies these\n * from the frame URL (where `buildFrameUrl` carried them off the checkout page) into its\n * provider redirect URLs, so a return can take the buyer back to the checkout they came\n * from — `event` and `eventKey` are the two names a site gives its event param. Bounded\n * on purpose: unknown params are not carried, because a return URL is not a forwarding\n * service.\n */\nexport const CARRIED_CHECKOUT_PARAMS = ['event', 'eventKey'] as const;\n\nexport function buildFrameUrl(\n hostUrl: string,\n cartKey: string,\n identity: FrameIdentity,\n options: {\n readonly parentOrigin: string;\n readonly checkoutSessionId?: string;\n readonly debug?: boolean;\n /** Extra host-page query params to carry through, by name. */\n readonly carriedParams?: readonly string[];\n readonly parentSearchParams?: URLSearchParams | null;\n /**\n * THE FRAME EPOCH'S OWN WORD. The inline journey's provider redirects the frame\n * itself away on failure, destroying the host page; the island remounts the frame\n * by asking for this param, and the fresh host reads it as \"the record it finds is\n * a dead attempt — mint a new order for the same cart\". Changing the URL is also\n * what remounts the `<iframe>` (its React key is the URL).\n */\n readonly retry?: boolean;\n },\n): string {\n const url = new URL(`/checkout/${cartKey}`, hostUrl);\n url.searchParams.set('method', identity.method);\n url.searchParams.set('instanceId', identity.instanceId);\n if (options.checkoutSessionId !== undefined)\n url.searchParams.set('checkoutSessionId', options.checkoutSessionId);\n url.searchParams.set('displayMode', 'prewarm');\n url.searchParams.set('origin', options.parentOrigin);\n if (options.debug === true) url.searchParams.set('scopePaymentDebug', '1');\n if (options.retry === true) url.searchParams.set('paymentRetry', '1');\n\n for (const name of options.carriedParams ?? []) {\n const value = options.parentSearchParams?.get(name);\n if (value) url.searchParams.set(name, value);\n }\n\n return url.toString();\n}\n\n/** The one origin a host frame may speak to this parent — the host URL's own. */\nexport function allowedFrameOrigin(hostUrl: string): string {\n try {\n return new URL(hostUrl).origin;\n } catch {\n return hostUrl;\n }\n}\n\nconst PAYMENT_DIAGNOSTIC_EVENTS = new Set([\n 'revolut.provider_init_started',\n 'revolut.provider_init_finished',\n 'revolut.provider_init_failed',\n 'revolut.button_pressed',\n 'revolut.create_order_callback_started',\n 'revolut.create_order_callback_returned',\n 'revolut.inline_journey_detected',\n 'revolut.external_handoff_detected',\n 'revolut.detector_state',\n]);\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\n/** A diagnostic is only what the known events say, with only the fields the host sends. */\nexport function parsePaymentDiagnostic(\n value: unknown,\n): { event: string; data?: Record<string, string | number | boolean | null> } | null {\n if (!isPlainObject(value)) return null;\n const payload = value;\n if (typeof payload.event !== 'string' || !PAYMENT_DIAGNOSTIC_EVENTS.has(payload.event))\n return null;\n\n const sourceData = isPlainObject(payload.data) ? payload.data : undefined;\n const data: Record<string, string | number | boolean | null> = {};\n if (sourceData?.paymentHostClass === 'local_tunnel' || sourceData?.paymentHostClass === 'other') {\n data.paymentHostClass = sourceData.paymentHostClass;\n }\n if (typeof sourceData?.active === 'boolean') data.active = sourceData.active;\n if (typeof sourceData?.tokenPresent === 'boolean') data.tokenPresent = sourceData.tokenPresent;\n if (\n typeof sourceData?.errorType === 'string' &&\n /^[A-Za-z][A-Za-z0-9]{0,63}$/.test(sourceData.errorType)\n ) {\n data.errorType = sourceData.errorType;\n }\n if (\n sourceData?.evidence === 'provider_frame_loaded' ||\n sourceData?.evidence === 'provider_frame_replaced' ||\n sourceData?.evidence === 'mobile_inline_provisional'\n ) {\n data.evidence = sourceData.evidence;\n }\n if (typeof sourceData?.generation === 'number' && Number.isSafeInteger(sourceData.generation)) {\n data.generation = sourceData.generation;\n }\n if (typeof sourceData?.mobile === 'boolean') data.mobile = sourceData.mobile;\n if (typeof sourceData?.visible === 'boolean') data.visible = sourceData.visible;\n if (\n sourceData?.state === 'initialized' ||\n sourceData?.state === 'attempt_started' ||\n sourceData?.state === 'order_returned' ||\n sourceData?.state === 'inline_provisional' ||\n sourceData?.state === 'external_handoff' ||\n sourceData?.state === 'disconnected'\n ) {\n data.state = sourceData.state;\n }\n if (\n sourceData?.reason === 'not_mobile' ||\n sourceData?.reason === 'no_attempt' ||\n sourceData?.reason === 'terminal' ||\n sourceData?.reason === 'external_handoff' ||\n sourceData?.reason === 'hidden'\n ) {\n data.reason = sourceData.reason;\n }\n\n return { event: payload.event, ...(Object.keys(data).length > 0 ? { data } : {}) };\n}\n\n/*\n * The presentation shape lives in `types.ts` with the rest of the wire; this module\n * only decides whether a claim is believable.\n */\n/**\n * A presentation claim is only believed from the frame it names, for the method that can\n * make one, with a generation the parent has not already passed.\n */\nexport function parsePaymentPresentation(\n value: unknown,\n expectedInstanceId: string,\n latestGeneration: number,\n): PaymentPresentation | null {\n if (!isPlainObject(value)) return null;\n const payload = value;\n if (\n payload.instanceId !== expectedInstanceId ||\n payload.method !== 'revolut_pay' ||\n (payload.mode !== 'inline_provisional' && payload.mode !== 'external_handoff') ||\n typeof payload.attemptGeneration !== 'number' ||\n !Number.isSafeInteger(payload.attemptGeneration) ||\n payload.attemptGeneration <= 0 ||\n payload.attemptGeneration < latestGeneration\n ) {\n return null;\n }\n return {\n instanceId: payload.instanceId,\n method: payload.method,\n mode: payload.mode,\n attemptGeneration: payload.attemptGeneration,\n };\n}\n\n/*\n * WHAT ARRIVES IS WHAT THE SENDER SENT. The parser VALIDATES, it never rebuilds: a\n * message that passes is returned with its own payload untouched, so the callbacks a\n * parent hands it to receive exactly what the frame said — and a test (or a host)\n * that sends a minimal payload gets that minimal payload back. The meta fields are\n * checked WHEN PRESENT (a foreign instanceId is still a drop) and never injected,\n * because a parent that rewrites the frame's words is a parent inventing traffic.\n */\nexport function parseFrameEvent(\n event: { readonly origin: string; readonly source: unknown; readonly data: unknown },\n expected: {\n readonly allowedOrigin: string;\n readonly source: unknown;\n readonly identity: FrameIdentity;\n },\n): FrameMessage | null {\n if (\n expected.source == null ||\n event.origin !== expected.allowedOrigin ||\n event.source !== expected.source ||\n !isPlainObject(event.data)\n )\n return null;\n const { type } = event.data;\n if (typeof type !== 'string' || !type.startsWith('SCOPE_PAYMENT_')) return null;\n /*\n * THE PAYLOAD IS OPTIONAL ON THE WIRE. `READY`, `CANCELLED` and\n * `SUBMIT_REQUESTED` all arrive bare; an absent payload is an empty one, and a\n * present-but-not-an-object payload is a drop.\n */\n const payload: Record<string, unknown> = isPlainObject(event.data.payload)\n ? event.data.payload\n : {};\n /*\n * INSTANCE AND METHOD, checked only when the sender names them. `READY` arrives\n * without either; `RESIZE` may arrive without both. A payload that names a\n * DIFFERENT instance is a stranger's message wearing our prefix, and is dropped.\n */\n if (payload.instanceId !== undefined && payload.instanceId !== expected.identity.instanceId)\n return null;\n if (payload.method !== undefined && payload.method !== expected.identity.method) return null;\n\n /*\n * SAFETY: the checks above ARE the type claim — a payload that carries meta at\n * all carries OUR meta, and each per-type branch below has just verified the one\n * field its `FrameMessage` variant requires, so the passthrough is the wire\n * message the sender actually sent, typed as the protocol type it just earned.\n */\n const frameMessage = { type, payload } as unknown as FrameMessage;\n\n switch (type) {\n case 'SCOPE_PAYMENT_READY':\n case 'SCOPE_PAYMENT_CONFIG_REQUESTED':\n case 'SCOPE_PAYMENT_CANCELLED':\n case 'SCOPE_PAYMENT_SUBMIT_REQUESTED':\n return frameMessage;\n case 'SCOPE_PAYMENT_RESIZE':\n if (typeof payload.height !== 'number' || !Number.isFinite(payload.height)) return null;\n return frameMessage;\n case 'SCOPE_PAYMENT_SUCCESS':\n if (typeof payload.cartKey !== 'string' || !payload.cartKey) return null;\n return frameMessage;\n case 'SCOPE_PAYMENT_ERROR':\n if (typeof payload.code !== 'string' || typeof payload.message !== 'string') return null;\n return frameMessage;\n case 'SCOPE_PAYMENT_METHOD_STATUS':\n if (typeof payload.ready !== 'boolean') return null;\n /* The resolved wallet, WHEN PRESENT, is one of the two the provider names — a\n * frame claiming anything else is not reporting a wallet, and a parent that drew\n * a label from it would be drawing one the provider never offered. */\n if (\n payload.wallet !== undefined &&\n payload.wallet !== 'applePay' &&\n payload.wallet !== 'googlePay'\n )\n return null;\n return frameMessage;\n case 'SCOPE_PAYMENT_DIAGNOSTIC': {\n /*\n * THE ONE EXCEPTION TO PASSTHROUGH. A diagnostic is telemetry, and the\n * frame may be a compromised document: what reaches the parent's callbacks\n * is the allow-listed event and its safe fields, never the raw payload.\n */\n const diagnostic = parsePaymentDiagnostic(payload);\n return diagnostic === null ? null : ({ type, payload: diagnostic } as FrameMessage);\n }\n case 'SCOPE_PAYMENT_PRESENTATION': {\n /*\n * Monotonicity is the CALLER's state (its latest seen generation), not this\n * module's — the frame event parser is stateless, so it validates shape and\n * identity here and leaves the generation window to `PaymentFrame`.\n */\n const presentation = parsePaymentPresentation(payload, expected.identity.instanceId, 0);\n return presentation === null ? null : ({ type, payload: presentation } as FrameMessage);\n }\n default:\n /* Parent-directed messages are not frame events; a frame that sends one is dropped. */\n return null;\n }\n}\n\n/** The one authoritative configuration a parent sends a frame after it loads. */\nexport function buildConfigMessage(\n identity: FrameIdentity,\n config: {\n readonly apiKey?: string;\n readonly selectedMethod?: 'card' | 'revolut_pay' | 'apple_pay' | 'google_pay';\n readonly theme?: Record<string, string>;\n },\n): FrameMessage {\n return {\n type: 'SCOPE_PAYMENT_CONFIG',\n payload: {\n ...(config.apiKey === undefined ? {} : { apiKey: config.apiKey }),\n ...(config.selectedMethod === undefined ? {} : { selectedMethod: config.selectedMethod }),\n ...(config.theme === undefined ? {} : { theme: config.theme }),\n instanceId: identity.instanceId,\n method: identity.method,\n },\n };\n}\n\n/** The parent's answer to `SUBMIT_REQUESTED`: the buyer data the charge is named for. */\nexport function buildSubmitConfirmedMessage(\n identity: FrameIdentity,\n buyer: { readonly firstName: string; readonly lastName: string; readonly email: string },\n): FrameMessage {\n return {\n type: 'SCOPE_PAYMENT_SUBMIT_CONFIRMED',\n payload: { ...buyer, instanceId: identity.instanceId, method: identity.method },\n };\n}\n\n/** The parent's refusal: the host returns the field to ready and the buyer to the form. */\nexport function buildSubmitRejectedMessage(identity: FrameIdentity, reason: string): FrameMessage {\n return {\n type: 'SCOPE_PAYMENT_SUBMIT_REJECTED',\n payload: { reason, instanceId: identity.instanceId, method: identity.method },\n };\n}\n\n/** Ask the active frame to submit what its field holds. */\nexport function buildTriggerSubmitMessage(identity: FrameIdentity): FrameMessage {\n return {\n type: 'SCOPE_PAYMENT_TRIGGER_SUBMIT',\n payload: { instanceId: identity.instanceId, method: identity.method },\n };\n}\n\n/**\n * Cancel an in-flight provider journey. The host honours this for `revolut_pay` only —\n * the card method has no cancel — so it is the caller's decision to send it.\n */\nexport function buildCancelRequestedMessage(identity: FrameIdentity): FrameMessage {\n return {\n type: 'SCOPE_PAYMENT_CANCEL_REQUESTED',\n payload: { instanceId: identity.instanceId, method: identity.method },\n };\n}\n","/**\n * WHAT THE PAYMENT PROVIDER WILL ACCEPT FOR A BUYER — the one place the three fields'\n * rules are written, because three packages send them and all three reach Revolut.\n *\n * Revolut's Merchant API documents the customer object as `full_name`, `email` and\n * `phone`, and names a format for exactly one of them: the phone is E.164. The other two\n * are \"string\" with no stated pattern, so what they refuse only appears as a charge\n * coming back `validation.email.invalid` / `error.invalid-email` — reaching a buyer as\n * \"PaymentError Invalid email format\" — AFTER they have committed.\n *\n * That is the failure these predicates exist to pre-empt. A field the provider would\n * refuse is refused at the step that collects it, where there is someone to fix it.\n *\n * @see https://developer.revolut.com/docs/api/merchant/operations/create-order\n * @see https://developer.revolut.com/docs/api/merchant/operations/create-customer\n */\n\n/**\n * RFC 5321 §4.5.3.1: a forward path is 256 octets, which is the 254 an address may run\n * to plus its angle brackets. The 320 the frame boundary bounded this at is the sum of\n * the two PART maxima and is not a length any whole address may be.\n */\nexport const MAX_EMAIL_LENGTH = 254;\n/** RFC 5321 §4.5.3.1 again — the local part, and one domain label. */\nconst MAX_LOCAL_LENGTH = 64;\nconst MAX_LABEL_LENGTH = 63;\nconst MAX_DOMAIN_LENGTH = 255;\n\n/**\n * THE DOT-ATOM FORM — RFC 5322 §3.4.1 without the quoted and address-literal\n * alternatives, which is the shape every provider actually issues and accepts.\n *\n * This rule was deliberately loose — `/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/` — on the argument\n * that all it has to catch is a typo and the authority on whether an address exists is\n * the mail sent to it. The second half of that is still true. The first half was not:\n * that pattern accepts `bob..smith@example.com`, `.bob@example.com`, `bob@-example.com`\n * and an address of any length, and Revolut refuses every one of them — at the card\n * machine, one step past the last place the buyer could have been asked again.\n *\n * STILL NOT A DELIVERABILITY CHECK. No TLD list, no MX lookup; subdomains and `+` tags\n * are welcome. What it refuses is a shape that cannot be charged.\n *\n * NOT SMTPUTF8. An internationalised local part and an IDN domain are both refused here,\n * which matches what the wire carries: a host holding such an address punycodes the\n * domain before handing it over.\n */\nconst LOCAL_PART = /^[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(\\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*$/;\nconst DOMAIN_LABEL = /^[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?$/;\n/** The last label: letters only and at least two — no all-numeric final label. */\nconst TOP_LEVEL_LABEL = /^[A-Za-z]{2,}$/;\n\n/** Whether an address is well-formed enough to put on a charge. Trims first. */\nexport function isAcceptableEmail(value: string): boolean {\n const email = value.trim();\n if (email.length === 0 || email.length > MAX_EMAIL_LENGTH) return false;\n\n /*\n * THE LAST `@`, not the first. A local part may legally contain one only inside\n * quotes, which this form does not admit — so splitting at the last one and letting\n * `LOCAL_PART` refuse the `@` it kept is what turns `a@b@c.com` down, where splitting\n * at the first would have handed `b@c.com` to the domain check and turned it down for\n * the wrong reason.\n */\n const at = email.lastIndexOf('@');\n if (at <= 0 || at === email.length - 1) return false;\n\n const local = email.slice(0, at);\n if (local.length > MAX_LOCAL_LENGTH || !LOCAL_PART.test(local)) return false;\n\n const domain = email.slice(at + 1);\n if (domain.length > MAX_DOMAIN_LENGTH) return false;\n\n const labels = domain.split('.');\n if (labels.length < 2) return false;\n if (labels.some((label) => label.length > MAX_LABEL_LENGTH || !DOMAIN_LABEL.test(label))) {\n return false;\n }\n return TOP_LEVEL_LABEL.test(labels[labels.length - 1] as string);\n}\n\n/**\n * E.164, and the whole of it: a `+`, a country code whose first digit is never `0`, and\n * fifteen digits at the very most for the country code and the national number together.\n * No spaces, no brackets, no trunk prefix.\n *\n * Turning a TYPED number into this needs a country's numbering plan, which is not\n * transport's to know — so each package converts with its own table and checks the\n * result here. One answer to \"is this sendable\", several to \"what did they mean\".\n */\nconst E164 = /^\\+[1-9]\\d{1,14}$/;\n\nexport function isE164(value: string): boolean {\n return E164.test(value.trim());\n}\n\n/** Not writing — framing. Refused in a name because it is what a name never contains. */\n// eslint-disable-next-line no-control-regex\nconst CONTROL_CHARACTERS = /[\\x00-\\x1F\\x7F]/;\n\n/**\n * The cardholder name Revolut takes as `'FirstName LastName'`, and `full_name` on the\n * customer. OPTIONAL to the provider, which is the point: an empty string is not a name\n * and is worth OMITTING rather than sending, because sent it earns `error.invalid-name`\n * where absent it earns nothing.\n *\n * NOTHING ELSE IS ASKED OF ITS CONTENTS. Every rule anyone reaches for here — letters\n * only, a minimum length, two words — is wrong for somebody's actual name.\n */\nexport function isAcceptableName(value: string): boolean {\n const name = value.trim();\n return name.length > 0 && name.length <= 256 && !CONTROL_CHARACTERS.test(name);\n}\n","/**\n * DID THEY MEAN SOMETHING ELSE — which is a different question from whether the address\n * can be charged, and carries a different consequence.\n *\n * `isAcceptableEmail` refuses what no provider will take, and a field that fails it is in\n * ERROR. Everything here is well-formed and chargeable: `ada@gnail.com` is a perfectly\n * good address and Revolut would take it happily. It is just not the one they meant, and\n * the tickets go to it. So this earns a WARNING — the mark beside the field, nothing\n * blocked, the buyer free to carry on if `gnail.com` really is their mail host.\n *\n * The evidence is the addresses support actually sees: `@gnail.com`, `@hotnail.com`,\n * `.con`, and `.co` where `.com` was meant.\n */\n\n/**\n * REAL HOSTS, NEVER SECOND-GUESSED. A domain on this list is answered \"fine\" before any\n * rule below runs — which is the only thing that keeps `mail.com` off, a genuine provider\n * sitting one inserted `g` away from `gmail.com`.\n */\nconst KNOWN_DOMAINS: readonly string[] = [\n 'gmail.com',\n 'googlemail.com',\n 'icloud.com',\n 'me.com',\n 'mac.com',\n 'mail.com',\n 'hotmail.com',\n 'outlook.com',\n 'live.com',\n 'yahoo.com',\n 'aol.com',\n 'proton.me',\n 'protonmail.com',\n 'eircom.net',\n];\n\n/**\n * WHAT A NEAR-MISS IS MEASURED AGAINST — a strict subset of the above, and short names\n * are missing on purpose.\n *\n * At a distance of one, a six-letter domain is a keystroke from half the alphabet:\n * `me.com` accused `ms.com`, `we.com` and `be.com`, and `aol.com` accused `ao.com`,\n * `al.com` and `sol.com`. All four of those are real. A domain too short to be missed\n * distinctively is one we cannot correct without accusing somebody, so it is only ever\n * recognised, never suggested.\n */\nconst NEAR_MISS_TARGETS: readonly string[] = [\n 'gmail.com',\n 'googlemail.com',\n 'icloud.com',\n 'hotmail.com',\n 'outlook.com',\n 'yahoo.com',\n 'protonmail.com',\n 'eircom.net',\n];\n\n/** The shortest domain body — everything before the last dot — worth measuring. */\nconst MIN_DISTINCTIVE_BODY = 4;\n\n/**\n * TOP-LEVEL LABELS THAT ARE ONLY EVER A SLIP, whatever the domain in front of them — the\n * half of this that a near-miss cannot do. `mycompany.con` is nobody's near-miss for\n * `gmail.com`, and it is still plainly a typo.\n *\n * `co` IS A REAL TLD — Colombia's, and a fashionable one — so it is the single entry here\n * that can be wrong about a real address. It earns its place on volume: a buyer typing\n * `.co` in a checkout has overwhelmingly dropped the `m`, and a warning they can ignore is\n * the right price for catching that. Note `example.co.uk` is untouched: the top-level\n * label there is `uk`.\n */\nconst TOP_LEVEL_SLIPS: Readonly<Record<string, string>> = {\n co: 'com',\n con: 'com',\n cim: 'com',\n cmo: 'com',\n ocm: 'com',\n comm: 'com',\n coom: 'com',\n cpm: 'com',\n vom: 'com',\n xom: 'com',\n nte: 'net',\n ner: 'net',\n ogr: 'org',\n orh: 'org',\n};\n\n/**\n * Optimal string alignment — Levenshtein plus the ONE extra move that matters here.\n *\n * The SDK's copy of this was plain Levenshtein at a distance of two, and the two were\n * load-bearing: a transposition costs a plain edit distance of 2, so `gmial.com` needed\n * the same tolerance as a domain two whole characters out. That tolerance is what made\n * the hand-written alias table necessary AND what flagged `mac.com` as a misspelling of\n * `me.com`. Counting a swap as the one keystroke it is lets the threshold drop to one,\n * which catches more and accuses less.\n */\nfunction editDistance(a: string, b: string): number {\n const columns = b.length + 1;\n /* One flat row-major grid — `(rows + 1) x columns` — so every read is a single index. */\n const d = new Uint16Array((a.length + 1) * columns);\n for (let j = 0; j < columns; j += 1) d[j] = j;\n\n for (let i = 1; i <= a.length; i += 1) {\n const row = i * columns;\n const previous = row - columns;\n d[row] = i;\n for (let j = 1; j <= b.length; j += 1) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n let best = Math.min(\n (d[previous + j] ?? 0) + 1 /* deletion */,\n (d[row + j - 1] ?? 0) + 1 /* insertion */,\n (d[previous + j - 1] ?? 0) + cost /* substitution */,\n );\n /* The swap, counted as the one keystroke it is. */\n if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {\n best = Math.min(best, (d[previous - columns + j - 2] ?? 0) + 1);\n }\n d[row + j] = best;\n }\n }\n\n return d[a.length * columns + b.length] ?? 0;\n}\n\n/** A domain as the part that names the host and the top-level label that follows it. */\nfunction splitDomain(domain: string): { body: string; top: string } | null {\n const lastDot = domain.lastIndexOf('.');\n if (lastDot <= 0 || lastDot === domain.length - 1) return null;\n return { body: domain.slice(0, lastDot), top: domain.slice(lastDot + 1) };\n}\n\n/**\n * The known host a typed domain is a single keystroke away from, if there is one.\n *\n * THE TOP-LEVEL LABEL MUST MATCH EXACTLY, and this is the rule that makes the near-miss\n * safe. One edit inside a country code turns a real host into another real host —\n * `yahoo.de` and `yahoo.it` were both being \"corrected\" to `yahoo.ie`, and `live.se` to\n * `live.ie`, which is a Dane told their address is Irish. A slipped top-level label is\n * `repairTopLevel`'s business and is answered from a closed list of labels that are not\n * TLDs at all; everything here is about the name in front of it.\n */\nfunction nearestKnownDomain(domain: string): string | null {\n const typed = splitDomain(domain);\n if (typed === null || typed.body.length < MIN_DISTINCTIVE_BODY) return null;\n\n for (const candidate of NEAR_MISS_TARGETS) {\n const known = splitDomain(candidate);\n if (known === null || known.top !== typed.top) continue;\n if (known.body.length < MIN_DISTINCTIVE_BODY) continue;\n if (editDistance(typed.body, known.body) === 1) return candidate;\n }\n return null;\n}\n\n/** The domain with a slipped top-level label put right, or `null` where it was fine. */\nfunction repairTopLevel(domain: string): string | null {\n const labels = domain.split('.');\n if (labels.length < 2) return null;\n const top = labels[labels.length - 1] as string;\n const meant = TOP_LEVEL_SLIPS[top];\n if (meant === undefined) return null;\n return [...labels.slice(0, -1), meant].join('.');\n}\n\n/**\n * WHAT WE THINK THEY MEANT, or `null` where nothing looks wrong.\n *\n * One function and not two, because the flag and the suggestion are the same question\n * asked for different reasons — the island's email field wants to know WHETHER, the\n * SDK's buyer form wants the corrected address to offer. Two implementations of \"is this\n * a typo\" would drift the first time either was tuned.\n *\n * THE TWO RULES COMPOSE. `gnail.con` has both a slipped top-level label and a domain a\n * keystroke out; repairing the label first is what lets the near-miss then see\n * `gnail.com` and reach `gmail.com`, rather than each rule answering half.\n */\nexport function suspectedEmailTypo(email: string): string | null {\n const trimmed = email.trim().toLowerCase();\n const at = trimmed.lastIndexOf('@');\n if (at <= 0 || at === trimmed.length - 1) return null;\n\n const local = trimmed.slice(0, at);\n const domain = trimmed.slice(at + 1);\n /* A host they are plainly on is never second-guessed, whatever the tables say. */\n if (KNOWN_DOMAINS.includes(domain)) return null;\n\n const repaired = repairTopLevel(domain);\n const corrected = nearestKnownDomain(repaired ?? domain) ?? repaired;\n if (corrected === null || corrected === domain) return null;\n return `${local}@${corrected}`;\n}\n","/** The buyer's contact details, and whether what they have typed is usable yet. */\n\nimport { isAcceptableEmail, isE164, suspectedEmailTypo } from '@scopetickets/api';\n\n/**\n * How a field reports on its own contents — Figma's `ContentFlag` on `InputTextShort`,\n * ported unchanged.\n */\nexport type ContentFlag = 'none' | 'success' | 'warning' | 'error';\n\n/**\n * THE PROVIDER'S RULE, NOT A SECOND ONE. This held its own loose pattern, and the field\n * it gates is the field a charge is named for — so an address this accepted and Revolut\n * did not reached the buyer as \"PaymentError Invalid email format\", at the card machine,\n * one step past the last place we could have asked them again.\n *\n * `isAcceptableEmail` is what the payment frame's boundary and the SDK's own form now\n * spend too. The authority on whether an address EXISTS is still the mail sent to it.\n */\nexport function isValidEmail(email: string): boolean {\n return isAcceptableEmail(email);\n}\n\n/**\n * What the email field's trailing mark says. Empty is `none`, not `error`.\n *\n * THE FOURTH STATE, WHICH NOTHING USED UNTIL NOW. `warning` is an address that will be\n * accepted everywhere and is probably not theirs — `@gnail.com`, `.con`, a `.co` with the\n * `m` dropped. The distinction the three tones carry is exactly the one that matters: an\n * ERROR cannot be charged and the buyer must fix it, a WARNING can and they need only\n * look. Nothing is gated on this — see `EmailStep`, which reports answered from\n * `isValidEmail` — so a buyer genuinely on `gnail.com` reads the mark and carries on.\n *\n * ERROR OUTRANKS WARNING, because a malformed address is the more useful thing to be\n * told: there is no point suggesting a domain for something that is not yet an address.\n */\nexport function emailFlag(email: string): ContentFlag {\n if (email.length === 0) return 'none';\n if (!isValidEmail(email)) return 'error';\n return suspectedEmailTypo(email) === null ? 'success' : 'warning';\n}\n\n/**\n * WHAT THE MARK MEANS, for anyone who cannot see it — and only where the mark is the only\n * thing saying it. A `warning` names the address we think they meant, because a mark that\n * says \"something is off\" without saying what is a mark nobody can act on. The other three\n * tones are left decorative, which is what `ContentFlag` does with an absent title.\n */\nexport function emailFlagTitle(email: string): string | undefined {\n const meant = emailFlag(email) === 'warning' ? suspectedEmailTypo(email) : null;\n return meant === null ? undefined : `Did you mean ${meant}?`;\n}\n\n/**\n * TWO FIELDS, BECAUSE the design DRAWS TWO. The design is the Country Code row — label\n * \"Country Code\", the dial code as its value, and the country NAME right-aligned beside\n * it. The design is the number itself, with the content flag. The dial code is not part\n * of the second field, and the country name is a readout of the first rather than a\n * control of its own.\n */\n\n/**\n * The digits a country's national significant number may run to — the part after the\n * dial code and after any trunk prefix.\n */\nexport type NationalDigits = { readonly min: number; readonly max: number };\n\n/** How a country's numbers are written out, where the rule is unambiguous. */\nexport type PhoneGrouping = {\n /**\n * First digits of the national significant number this applies to. Absent where the\n * whole plan is one shape — the NANP, which needs no prefix to disambiguate because\n * every number is grouped the same way.\n */\n readonly startsWith?: readonly string[];\n /** Total digits of the national significant number this describes. */\n readonly digits: number;\n /** Group sizes, in order, summing to `digits`. */\n readonly groups: readonly number[];\n};\n\nexport type Country = {\n /** ISO 3166-1 alpha-2, and the key everything else is looked up by. */\n readonly code: string;\n /** What the buyer reads, right-aligned in the Country Code row. */\n readonly name: string;\n /** E.164 country calling code, with its `+`. */\n readonly dialCode: string;\n /**\n * The digit dialled before a national number inside the country, and dropped when it is\n * written internationally — `0` across most of Europe. Absent where the plan has none:\n * North America dials `1`, which is the country code rather than a trunk prefix, and no\n * NANP number begins with `0`.\n */\n readonly trunkPrefix?: string;\n /** Verified plan length, where we have one. See `NationalDigits`. */\n readonly nationalDigits?: NationalDigits;\n /**\n * How the number is written, where the rule is unambiguous — see `PhoneGrouping`.\n * Absent means the number is left exactly as entered.\n */\n readonly grouping?: readonly PhoneGrouping[];\n};\n\n/**\n * E.164 caps a whole number at 15 digits including the country code, and the shortest\n * usable national part is about 4. What a country with no verified plan is checked\n * against — loose enough never to mark a real number wrong.\n */\nconst E164_MAX_DIGITS = 15;\nconst GENERIC_NATIONAL_DIGITS: NationalDigits = { min: 4, max: E164_MAX_DIGITS - 1 };\n\n/**\n * IRELAND FIRST, and it is the default rather than the head of an alphabetical list —\n * the first host to ship this sells an Irish event and most of its buyers will never\n * touch the country row. `DEFAULT_COUNTRY_CODE` names it so no call site depends on the\n * ordering here, and so a host that needs a different default has one name to change\n * rather than an order to reshuffle.\n */\nexport const COUNTRIES: readonly Country[] = [\n // ── Ireland, the default, and the United Kingdom ────────────\n {\n code: 'IE',\n name: 'Ireland',\n dialCode: '+353',\n trunkPrefix: '0',\n nationalDigits: { min: 7, max: 9 },\n // `08X XXX XXXX`, which is what the design draws.\n grouping: [{ startsWith: ['8'], digits: 9, groups: [2, 3, 4] }],\n },\n {\n code: 'GB',\n name: 'United Kingdom',\n dialCode: '+44',\n trunkPrefix: '0',\n nationalDigits: { min: 9, max: 10 },\n // London is also ten digits and is grouped `020 7946 0958`, so nothing beyond the\n // `7` may be assumed.\n grouping: [{ startsWith: ['7'], digits: 10, groups: [4, 6] }],\n },\n\n // ── The rest of the EU, alphabetically ──────────────────────\n {\n code: 'AT',\n name: 'Austria',\n dialCode: '+43',\n trunkPrefix: '0',\n // Austria's plan is the widest in the EU — subscriber numbers run from four digits\n // to thirteen.\n nationalDigits: { min: 4, max: 13 },\n grouping: [{ startsWith: ['6'], digits: 10, groups: [3, 7] }],\n },\n {\n code: 'BE',\n name: 'Belgium',\n dialCode: '+32',\n trunkPrefix: '0',\n nationalDigits: { min: 8, max: 9 },\n grouping: [{ startsWith: ['4'], digits: 9, groups: [3, 2, 2, 2] }],\n },\n {\n code: 'BG',\n name: 'Bulgaria',\n dialCode: '+359',\n trunkPrefix: '0',\n nationalDigits: { min: 8, max: 9 },\n grouping: [{ startsWith: ['87', '88', '89'], digits: 9, groups: [2, 3, 4] }],\n },\n {\n code: 'HR',\n name: 'Croatia',\n dialCode: '+385',\n trunkPrefix: '0',\n nationalDigits: { min: 8, max: 9 },\n grouping: [{ startsWith: ['9'], digits: 9, groups: [2, 3, 4] }],\n },\n {\n code: 'CY',\n name: 'Cyprus',\n dialCode: '+357',\n nationalDigits: { min: 8, max: 8 },\n grouping: [{ startsWith: ['9'], digits: 8, groups: [2, 6] }],\n },\n {\n code: 'CZ',\n name: 'Czechia',\n dialCode: '+420',\n nationalDigits: { min: 9, max: 9 },\n // Threes throughout, and Czechia has no trunk prefix.\n grouping: [{ digits: 9, groups: [3, 3, 3] }],\n },\n {\n code: 'DK',\n name: 'Denmark',\n dialCode: '+45',\n nationalDigits: { min: 8, max: 8 },\n // Every Danish number is eight digits in pairs, mobile or not — so this needs no\n // prefix to disambiguate.\n grouping: [{ digits: 8, groups: [2, 2, 2, 2] }],\n },\n {\n code: 'EE',\n name: 'Estonia',\n dialCode: '+372',\n nationalDigits: { min: 7, max: 8 },\n grouping: [\n { startsWith: ['5'], digits: 8, groups: [4, 4] },\n { startsWith: ['5'], digits: 7, groups: [3, 4] },\n ],\n },\n {\n code: 'FI',\n name: 'Finland',\n dialCode: '+358',\n trunkPrefix: '0',\n nationalDigits: { min: 6, max: 10 },\n grouping: [{ startsWith: ['4', '5'], digits: 9, groups: [2, 3, 4] }],\n },\n {\n code: 'FR',\n name: 'France',\n dialCode: '+33',\n trunkPrefix: '0',\n nationalDigits: { min: 9, max: 9 },\n // Pairs throughout — `06 12 34 56 78`.\n grouping: [{ startsWith: ['6', '7'], digits: 9, groups: [1, 2, 2, 2, 2] }],\n },\n {\n code: 'DE',\n name: 'Germany',\n dialCode: '+49',\n trunkPrefix: '0',\n nationalDigits: { min: 6, max: 11 },\n // NO GROUPING, deliberately, and the one EU country without it.\n },\n {\n code: 'GR',\n name: 'Greece',\n dialCode: '+30',\n nationalDigits: { min: 10, max: 10 },\n // Ten digits, no trunk prefix, and the leading digit is kept when dialling.\n grouping: [{ startsWith: ['69'], digits: 10, groups: [3, 3, 4] }],\n },\n {\n code: 'HU',\n name: 'Hungary',\n dialCode: '+36',\n // `06`, and written apart from the number — see `formatNational`.\n trunkPrefix: '06',\n nationalDigits: { min: 8, max: 9 },\n grouping: [{ startsWith: ['20', '30', '31', '50', '70'], digits: 9, groups: [2, 3, 4] }],\n },\n {\n code: 'IT',\n name: 'Italy',\n dialCode: '+39',\n // NO TRUNK PREFIX, and Italy is the exception worth knowing: the leading `0` of a\n // landline is part of the number and is dialled internationally too.\n nationalDigits: { min: 6, max: 11 },\n grouping: [{ startsWith: ['3'], digits: 10, groups: [3, 3, 4] }],\n },\n {\n code: 'LV',\n name: 'Latvia',\n dialCode: '+371',\n nationalDigits: { min: 8, max: 8 },\n grouping: [{ startsWith: ['2'], digits: 8, groups: [2, 3, 3] }],\n },\n {\n code: 'LT',\n name: 'Lithuania',\n dialCode: '+370',\n // `8`, and written apart from the number — see `formatNational`.\n trunkPrefix: '8',\n nationalDigits: { min: 8, max: 8 },\n grouping: [{ startsWith: ['6'], digits: 8, groups: [3, 5] }],\n },\n {\n code: 'LU',\n name: 'Luxembourg',\n dialCode: '+352',\n nationalDigits: { min: 4, max: 11 },\n grouping: [{ startsWith: ['6'], digits: 9, groups: [3, 3, 3] }],\n },\n {\n code: 'MT',\n name: 'Malta',\n dialCode: '+356',\n nationalDigits: { min: 8, max: 8 },\n grouping: [{ startsWith: ['7', '9'], digits: 8, groups: [4, 4] }],\n },\n {\n code: 'NL',\n name: 'Netherlands',\n dialCode: '+31',\n trunkPrefix: '0',\n nationalDigits: { min: 9, max: 9 },\n // `06 12345678` — the mobile prefix, then the number unbroken.\n grouping: [{ startsWith: ['6'], digits: 9, groups: [1, 8] }],\n },\n {\n code: 'PL',\n name: 'Poland',\n dialCode: '+48',\n // Poland dropped its trunk prefix; the nine digits are dialled as they are.\n nationalDigits: { min: 9, max: 9 },\n grouping: [{ digits: 9, groups: [3, 3, 3] }],\n },\n {\n code: 'PT',\n name: 'Portugal',\n dialCode: '+351',\n nationalDigits: { min: 9, max: 9 },\n grouping: [{ digits: 9, groups: [3, 3, 3] }],\n },\n {\n code: 'RO',\n name: 'Romania',\n dialCode: '+40',\n trunkPrefix: '0',\n nationalDigits: { min: 9, max: 9 },\n grouping: [{ startsWith: ['7'], digits: 9, groups: [3, 3, 3] }],\n },\n {\n code: 'SK',\n name: 'Slovakia',\n dialCode: '+421',\n trunkPrefix: '0',\n nationalDigits: { min: 9, max: 9 },\n grouping: [{ startsWith: ['9'], digits: 9, groups: [3, 3, 3] }],\n },\n {\n code: 'SI',\n name: 'Slovenia',\n dialCode: '+386',\n trunkPrefix: '0',\n nationalDigits: { min: 8, max: 8 },\n grouping: [{ startsWith: ['3', '4', '5', '6', '7'], digits: 8, groups: [2, 3, 3] }],\n },\n {\n code: 'ES',\n name: 'Spain',\n dialCode: '+34',\n // No trunk prefix; the nine digits are the whole number.\n nationalDigits: { min: 9, max: 9 },\n grouping: [{ digits: 9, groups: [3, 3, 3] }],\n },\n {\n code: 'SE',\n name: 'Sweden',\n dialCode: '+46',\n trunkPrefix: '0',\n nationalDigits: { min: 7, max: 9 },\n grouping: [{ startsWith: ['7'], digits: 9, groups: [2, 3, 4] }],\n },\n\n /*\n * Named and length-checked so a number from one of them is not read as nonsense, but\n * NOT formatted: the brief is the EU and the UK, and a grouping rule written for a\n * market nobody asked about is a rule nobody will check. The NANP is the exception — it\n * was already here, and it is one shape throughout.\n */\n {\n code: 'US',\n name: 'United States',\n dialCode: '+1',\n nationalDigits: { min: 10, max: 10 },\n grouping: [{ digits: 10, groups: [3, 3, 4] }],\n },\n { code: 'CH', name: 'Switzerland', dialCode: '+41', trunkPrefix: '0' },\n { code: 'NO', name: 'Norway', dialCode: '+47' },\n { code: 'AU', name: 'Australia', dialCode: '+61', trunkPrefix: '0' },\n { code: 'NZ', name: 'New Zealand', dialCode: '+64', trunkPrefix: '0' },\n { code: 'ZA', name: 'South Africa', dialCode: '+27', trunkPrefix: '0' },\n { code: 'AE', name: 'United Arab Emirates', dialCode: '+971', trunkPrefix: '0' },\n { code: 'IN', name: 'India', dialCode: '+91', trunkPrefix: '0' },\n { code: 'BR', name: 'Brazil', dialCode: '+55', trunkPrefix: '0' },\n];\n\n/**\n * The EU and the UK — the markets this step is expected to handle, and the ones that\n * carry a grouping rule. Named so a test can hold the table to it rather than the list\n * living only in a comment.\n */\nexport const EU_AND_UK: readonly string[] = [\n 'AT',\n 'BE',\n 'BG',\n 'HR',\n 'CY',\n 'CZ',\n 'DK',\n 'EE',\n 'FI',\n 'FR',\n 'DE',\n 'GR',\n 'HU',\n 'IE',\n 'IT',\n 'LV',\n 'LT',\n 'LU',\n 'MT',\n 'NL',\n 'PL',\n 'PT',\n 'RO',\n 'SK',\n 'SI',\n 'ES',\n 'SE',\n 'GB',\n];\n\nexport const DEFAULT_COUNTRY_CODE = 'IE';\n\nexport function countryByCode(code: string): Country {\n const found = COUNTRIES.find((country) => country.code === code);\n // Unreachable while every caller passes a code from `COUNTRIES`, which the tests\n // assert.\n if (!found) throw new Error(`unknown country: ${code}`);\n return found;\n}\n\n/**\n * What the Country Code row starts at, and what an unrecognised code falls back to for\n * the purpose of checking the number's length.\n */\nexport const DEFAULT_DIAL_CODE = countryByCode(DEFAULT_COUNTRY_CODE).dialCode;\n\n/** Just the digits, which is what every rule below actually reads. */\nconst digitsOf = (value: string): string => value.replace(/\\D/g, '');\n\n/** The country a DIAL CODE names, or `null` while it names none. */\nexport function countryByDialCode(dialCode: string): Country | null {\n const raw = digitsOf(dialCode);\n // `0044` and `+44` are one code written two ways — a handset's international prefix\n // against E.164's.\n const digits = raw.startsWith('00') && raw.length > 2 ? raw.slice(2) : raw;\n if (digits.length === 0) return null;\n return COUNTRIES.find((country) => country.dialCode.slice(1) === digits) ?? null;\n}\n\n/** What a single typed or AUTOFILLED string means across the two fields. */\nexport type PhoneParts = {\n /** The code the string named, or `null` when it named none. */\n readonly dialCode: string | null;\n /** What is left for the number field, with the code removed. */\n readonly national: string;\n};\n\nexport function splitPhoneNumber(raw: string): PhoneParts {\n const trimmed = raw.trim();\n const digits = digitsOf(trimmed);\n\n // `+` is unambiguous.\n const international = trimmed.startsWith('+') || (digits.startsWith('00') && digits.length > 2);\n if (!international || digits.length === 0) return { dialCode: null, national: trimmed };\n\n const body = trimmed.startsWith('+') ? digits : digits.slice(2);\n const match = [...COUNTRIES]\n .sort((a, b) => b.dialCode.length - a.dialCode.length)\n .find((country) => body.startsWith(country.dialCode.slice(1)));\n\n if (!match) return { dialCode: null, national: trimmed };\n return { dialCode: match.dialCode, national: body.slice(match.dialCode.length - 1) };\n}\n\n/**\n * The longest dial code we carry, in digits. Derived rather than typed as 3: E.164\n * allows one to three, and a table that grew a longer one would silently stop routing\n * it.\n */\nconst MAX_DIAL_DIGITS = Math.max(...COUNTRIES.map((country) => country.dialCode.length - 1));\n\n/** Which of the two rows a string arrived at. */\nexport type PhoneField = 'dialCode' | 'national';\n\n/** The pair the step holds — one row each. */\nexport type PhoneValue = { readonly dialCode: string; readonly national: string };\n\n/**\n * WHAT A PHONE NUMBER IS MADE OF — digits and a plus, and nothing else. Both rows took\n * letters: this row because a short string naming no country fell through to whatever was\n * typed, the other because `formatNational` handed back anything it could not group.\n *\n * STRIPPED AND NOT REFUSED: `(085) 123-4567` is a real number written the way people\n * write them. The `+` survives because it is what tells the two rows apart.\n */\nconst NOT_PHONE = /[^\\d+]/g;\n\n/** Where a string that arrived at one of the two rows actually belongs. */\nexport function routePhoneInput(typed: string, field: PhoneField, current: PhoneValue): PhoneValue {\n const raw = typed.replace(NOT_PHONE, '');\n const parts = splitPhoneNumber(raw);\n\n if (field === 'national') {\n // A code typed or filled here belongs upstairs, and this row is then empty.\n if (parts.dialCode === null) return { ...current, national: raw };\n return { dialCode: parts.dialCode, national: parts.national };\n }\n\n /*\n * This tested whether the value had arrived all at once — a keystroke changes a field\n * by one character and a fill never does — and that was wrong twice over. It is\n * STATEFUL: once a bad value is sitting in the row, the next fill is no longer a jump,\n * so the row that most needs correcting is the one the rule stops correcting. Reported\n * twice, and the second time from a row that already held the number.\n */\n if (parts.dialCode !== null) {\n return {\n dialCode: parts.dialCode,\n /*\n * A remainder long enough to BE a number takes the row below; one too short to be\n * anything replaces nothing. `+3531` is a slipped keystroke after a complete code, and\n * letting its `1` overwrite an entered number is the same bug in the other direction —\n * so it is dropped, unless the row below is empty and there is nothing to lose.\n */\n national:\n digitsOf(parts.national).length >= GENERIC_NATIONAL_DIGITS.min ||\n current.national.length === 0\n ? parts.national\n : current.national,\n };\n }\n\n /*\n * Not a code at all: no international prefix, and more digits than any dial code has.\n * This is what a browser filling `tel-country-code` hands over — a whole NATIONAL\n * number, with nothing to mark it as one. The code the row was already reading against\n * stands.\n */\n if (digitsOf(raw).length > MAX_DIAL_DIGITS) {\n return { dialCode: current.dialCode, national: raw };\n }\n\n /*\n * A browser filling this pair sets `tel-national` to the number and CLEARS\n * `tel-country-code` when it has no code stored for that contact — so the number lands\n * correctly and the row above it goes blank. A blank code names no country and makes an\n * E.164 value impossible, and the buyer is given no hint that anything is missing.\n */\n if (raw.trim().length === 0) return { ...current, dialCode: DEFAULT_DIAL_CODE };\n\n return { ...current, dialCode: raw };\n}\n\n/** The national SIGNIFICANT number — the digits a plan actually counts. */\nexport function nationalDigits(phone: string, country: Country): string {\n let digits = digitsOf(phone);\n\n const dial = country.dialCode.slice(1);\n if (digits.startsWith(dial) && digits.length > dial.length) digits = digits.slice(dial.length);\n\n const trunk = country.trunkPrefix;\n if (trunk !== undefined && digits.startsWith(trunk)) digits = digits.slice(trunk.length);\n\n return digits;\n}\n\n/** The number, written the way its country writes it — `085 123 4567`. */\nexport function formatNational(value: string, country: Country): string {\n const digits = digitsOf(value);\n /*\n * NOTHING TO GROUP IS NOTHING TO SHOW. This handed the value back untouched, which is\n * how anything that is not a number stayed in the field — the one exception is a lone\n * `+`, which is a number being typed rather than a number that is not one.\n */\n if (digits.length === 0) return value.trim() === '+' ? '+' : '';\n\n const trunk =\n country.trunkPrefix !== undefined && digits.startsWith(country.trunkPrefix)\n ? country.trunkPrefix\n : '';\n const nsn = digits.slice(trunk.length);\n\n const pattern = country.grouping?.find(\n (candidate) =>\n nsn.length <= candidate.digits &&\n (candidate.startsWith === undefined ||\n candidate.startsWith.some((start) => nsn.startsWith(start))),\n );\n if (pattern === undefined) return value;\n\n const parts: string[] = [];\n let at = 0;\n for (const size of pattern.groups) {\n if (at >= nsn.length) break;\n parts.push(nsn.slice(at, at + size));\n at += size;\n }\n\n if (trunk === '') return parts.join(' ');\n return trunk === '0'\n ? [trunk + (parts[0] ?? ''), ...parts.slice(1)].join(' ')\n : [trunk, ...parts].join(' ');\n}\n\n/** The plan's range, or E.164's own bound where there is no verified plan. */\nexport function digitsAllowed(country: Country): NationalDigits {\n return country.nationalDigits ?? GENERIC_NATIONAL_DIGITS;\n}\n\nexport function isValidPhone(phone: string, country: Country): boolean {\n const national = nationalDigits(phone, country);\n const { min, max } = digitsAllowed(country);\n return national.length >= min && national.length <= max;\n}\n\n/** What the number field's trailing mark says. Empty is `none`, not `error`. */\nexport function phoneFlag(phone: string, country: Country): ContentFlag {\n if (phone.trim().length === 0) return 'none';\n return isValidPhone(phone, country) ? 'success' : 'error';\n}\n\n/** The two fields as the one string the platform will want. */\nexport function e164(dialCode: string, phone: string): string | null {\n const country = countryByDialCode(dialCode);\n if (country === null) return null;\n const national = nationalDigits(phone, country);\n if (!isValidPhone(phone, country)) return null;\n const composed = `${country.dialCode}${national}`;\n /*\n * CHECKED AGAINST THE STANDARD, not just against the plan. `GENERIC_NATIONAL_DIGITS`\n * allows fourteen national digits for a country we carry no plan for, and a\n * three-digit dial code in front of those is seventeen — two past what E.164 permits\n * and what Revolut's `customer.phone` will take. A number no plan vouches for is worth\n * dropping rather than sending.\n */\n return isE164(composed) ? composed : null;\n}\n\n/**\n * A WHOLE PHONE STRING FROM OUTSIDE, narrowed to the one format the provider takes.\n *\n * `e164` composes the two fields the buyer typed, whose country the row above them\n * already names. This is for a number that arrives complete and unattributed — a host's\n * `IntentBuyer.phone`, which the type documents as E.164 and nothing enforced — so the\n * country has to be read out of the number itself. Anything that names no country we\n * carry, or that its country's plan does not admit, resolves to `null`: absent is a\n * thing the provider accepts, and a malformed number is not.\n */\nexport function normalizeE164(value: string): string | null {\n const { dialCode, national } = splitPhoneNumber(value);\n if (dialCode === null) return null;\n return e164(dialCode, national);\n}\n\n/**\n * Both parts required and nothing else asked of them — which gates Continue on\n * `firstName.trim && lastName.trim` and validates neither further. It is right not to:\n * every rule anyone reaches for here (letters only, a minimum length, two words) is\n * wrong for somebody's actual name.\n */\nexport function isCompleteName(firstName: string, lastName: string): boolean {\n return firstName.trim().length > 0 && lastName.trim().length > 0;\n}\n\n/** A stored full name, split into the two fields the platform actually takes. */\nexport type NameParts = { readonly firstName: string; readonly lastName: string };\n\nexport function splitFullName(full: string): NameParts | null {\n const parts = full.trim().split(/\\s+/).filter(Boolean);\n if (parts.length < 2) return null;\n const [firstName, ...rest] = parts;\n return { firstName: firstName as string, lastName: rest.join(' ') };\n}\n","/**\n * WHAT A HOST HANDS THE WIDGET, complete or partial.\n *\n * A host calls the widget to do the parts it will not or cannot do itself. So it says\n * what it already knows and leaves the rest absent, and the widget collects whatever is\n * missing. Every field but the subject is optional for exactly that reason: absent means\n * \"you ask\", not \"there is none\".\n *\n * PARTIAL IS THE NORMAL CASE. A host with its own calendar fills the day and leaves the\n * buyer empty; a host with nothing but a series key fills only the subject. Both are\n * valid, and the difference between them is which steps the widget mounts.\n */\n\nimport { isAcceptableName } from '@scopetickets/api';\nimport { isValidEmail, normalizeE164 } from './contact';\nimport type { PurchaseStepId } from './purchase-steps';\n\n/**\n * WHAT IS BEING BOUGHT INTO, as one value rather than two nullable keys.\n *\n * A series is a run of events sold together — the buyer still picks a day. An event is\n * one occasion, so the day is already decided and the widget must not ask for it. Two\n * separate `seriesKey`/`eventKey` fields would allow both at once and neither, and\n * would leave every reader deciding which wins.\n */\nexport type OrderSubject =\n /** A run the buyer chooses a day within. */\n | { readonly kind: 'series'; readonly key: string }\n /** One occasion, its day already settled by the choice of it. */\n | { readonly kind: 'event'; readonly key: string };\n\n/**\n * How many of each user type, BY NAME — see `groupUserTypes`. NOT by assignment key: one\n * assignment is a type on one product, so a name is the only key that survives the walk\n * from `PARTY` to the product `TIME` picks.\n */\nexport type IntentComposition = Readonly<Record<string, number>>;\n\n/** What the platform needs about the person paying. */\nexport type IntentBuyer = {\n readonly firstName?: string;\n readonly lastName?: string;\n readonly email?: string;\n /** E.164, or absent. */\n readonly phone?: string;\n};\n\nexport type OrderIntent = {\n /** The one field a host must supply: there is nothing to sell without it. */\n readonly subject: OrderSubject;\n /** Who is coming. Absent means the widget asks. */\n readonly composition?: IntentComposition;\n /** `YYYY-MM-DD`. Meaningless on an event subject, which carries its own day. */\n readonly day?: string;\n /** The slot's own key, where the event sells timed sessions. */\n readonly timeslot?: string;\n readonly buyer?: IntentBuyer;\n /**\n * WHETHER THE EVENT ASKS ITS OWN QUESTIONS, and the one field where absent does NOT\n * mean \"you ask\".\n *\n * Every other field here is optional because the widget can collect it: there is a\n * party stepper, a calendar, a name field. There is no such control for these. The\n * questions are the EVENT's, they vary in number and height, and they come from an\n * endpoint that takes an id the widget has no cart to read — see `DETAILS`'s blurb.\n * So \"absent\" cannot mean \"ask them\", because there is nothing to ask with; it means\n * the event asks nothing, which is the common case and the safe one.\n *\n * Saying `true` puts the More Information card in the flow as a GATE — it says\n * questions are waiting, and does not draw them.\n */\n readonly asksQuestions?: boolean;\n /** Questionnaire answers already collected, by question id. */\n readonly answers?: Readonly<Record<string, string>>;\n /** A method the host has already had chosen. */\n readonly paymentMethodKey?: string;\n};\n\n/** Whether a composition names anybody at all. */\nexport function intentHasParty(composition: IntentComposition | undefined): boolean {\n if (composition === undefined) return false;\n return Object.values(composition).some((count) => count > 0);\n}\n\n/**\n * THE HOST'S BUYER, WITH EVERY FIELD A PAYMENT PROVIDER WOULD REFUSE DROPPED.\n *\n * An `IntentBuyer` is free text from someone else's page. Nothing checked it: the type\n * says `phone` is E.164 and asked nicely, `email` was taken on presence, and both were\n * folded into the order and sent. Revolut then answered for them — `invalid_phone`, or\n * the \"Invalid email format\" a buyer meets as a declined card — which is the latest and\n * most expensive moment either mistake could have been caught.\n *\n * DROPPED RATHER THAN REFUSED, and that is deliberate. Absent is a thing every one of\n * these fields is allowed to be, and it already means one exact thing to the rest of the\n * flow: the widget asks. So a host that sends a malformed address gets the email step\n * back, with a buyer standing in front of it — not an error it has no way to act on, and\n * not an order that dies at the card machine.\n *\n * THE PHONE IS NORMALISED, not merely judged. `+353 85 123 4567` is the same number as\n * `+353851234567` and only one of them can be sent, so the acceptable spelling is what\n * comes back.\n *\n * THE NAME IS JUDGED BY HALVES, and the all-or-nothing rule stays where it already was —\n * in `excusedByIntent`, which asks for both. A host that knows the first name and not the\n * surname has given the buyer a head start on a step they will still be asked, and\n * dropping the half they typed to make a point about completeness would take that away.\n */\nexport function answeredBuyer(buyer: IntentBuyer | undefined): IntentBuyer {\n if (buyer === undefined) return {};\n\n const { firstName, lastName, email, phone } = buyer;\n const half = (value: string | undefined) =>\n value !== undefined && isAcceptableName(value) ? value.trim() : undefined;\n const sendablePhone = phone === undefined ? null : normalizeE164(phone);\n\n const given = half(firstName);\n const family = half(lastName);\n return {\n ...(given === undefined ? {} : { firstName: given }),\n ...(family === undefined ? {} : { lastName: family }),\n ...(email !== undefined && isValidEmail(email) ? { email: email.trim() } : {}),\n ...(sendablePhone === null ? {} : { phone: sendablePhone }),\n };\n}\n\n/**\n * WHICH STEPS THE HOST HAS ALREADY ANSWERED, which is the whole bridge between an intent\n * and a flow: `FlowSituation.excused` takes exactly this, and the walk does the rest.\n *\n * A step is excused when the intent HOLDS its answer, never when the answer merely could\n * be derived. The difference matters at DATE: an event subject settles the day by being\n * an event, and a series with a day in hand settles it by having been asked already.\n *\n * NOT INCLUDED, DELIBERATELY: `SIGN_IN`, `REVIEW`, `PROCESSING`, `CREATE_ACCOUNT`,\n * `PASSWORD` and `FOLLOW`. A host cannot answer those on the buyer's behalf — they are\n * the buyer's own, or the platform's, and an intent that claimed them would be claiming\n * something it cannot know.\n */\nexport function excusedByIntent(intent: OrderIntent): readonly PurchaseStepId[] {\n const excused: PurchaseStepId[] = [];\n\n if (intentHasParty(intent.composition)) excused.push('PARTY');\n if (intent.subject.kind === 'event' || intent.day !== undefined) excused.push('DATE');\n if (intent.timeslot !== undefined) excused.push('TIME');\n\n /*\n * ANSWERED, WHICH IS NOT THE SAME AS PRESENT. These three read the host's fields\n * through `answeredBuyer`, and every other line here still reads presence — because\n * these three are the only ones that leave for a payment provider. A host's `email: ''`\n * excused the step and then failed `buyerForFrame`, stranding a buyer on a card whose\n * question had been taken away; a host's `email: 'bob@-example.com'` excused the step\n * and reached Revolut, which refused the charge for it.\n *\n * So a field the provider would refuse is not an answer, and the widget asks. That is\n * the whole of the fix: the step that collects it is the only place with someone who\n * can correct it.\n */\n const buyer = answeredBuyer(intent.buyer);\n if (buyer.firstName !== undefined && buyer.lastName !== undefined) excused.push('NAME');\n if (buyer.email !== undefined) excused.push('EMAIL');\n if (buyer.phone !== undefined) excused.push('PHONE');\n\n /*\n * DETAILS IS EXCUSED BY DEFAULT, which is the opposite of every line above it.\n *\n * The others read \"the host answered this, so do not ask\". This one reads \"nothing says\n * there is anything to ask\" — see `asksQuestions` for why absence has to mean that\n * here. An order otherwise ready for payment was being stopped at a card asking for\n * information nobody had said was needed, which is a step the buyer cannot answer and\n * cannot skip.\n */\n if (intent.asksQuestions !== true || intent.answers !== undefined) excused.push('DETAILS');\n if (intent.paymentMethodKey !== undefined) excused.push('PAYMENT');\n\n return excused;\n}\n\n/** Why a host's intent cannot be honoured as written. */\nexport type IntentRefusal = 'PARTY_OVER_CEILING' | 'PARTY_UNDER_FLOOR' | 'TIMESLOT_NOT_ON_SALE';\n\n/**\n * WHAT THE HOST ASSERTED, CHECKED AGAINST WHAT IS ACTUALLY ON SALE.\n *\n * `excusedByIntent` reads a filled field as answered and stops asking; nothing until now\n * read it as CORRECT. A party over the ceiling reached `addItemsBulk` as that many line\n * items, and a timeslot the run does not sell was dropped on the way to the cart — the\n * order was then placed for the right day at no particular time, which is worse than\n * refusing it.\n *\n * The headcount is checked first: it is the answer the buyer can still fix.\n */\nexport function refuseIntent(asserted: {\n readonly headcount: number;\n /** The ticket's `MinPerTransaction`, or 1 where the tickets have not been read. */\n readonly minParty: number;\n readonly maxParty: number;\n /** The start time the intent names, if it names one. */\n readonly timeslot: string | undefined;\n /**\n * Whether the day's sessions are KNOWN. Before they load, a timeslot that does not\n * resolve has not been refused — it has not been checked, and refusing on a pending\n * fetch would turn every slow network into a dead order.\n */\n readonly slotsKnown: boolean;\n readonly timeslotResolved: boolean;\n}): IntentRefusal | null {\n if (asserted.headcount > asserted.maxParty) return 'PARTY_OVER_CEILING';\n /*\n * A FLOOR ONLY ONCE SOMEBODY IS COMING. An empty composition is the stepper at rest and\n * the PARTY step has not been answered yet — refusing there would refuse every order\n * before it began.\n */\n if (asserted.headcount > 0 && asserted.headcount < asserted.minParty) {\n return 'PARTY_UNDER_FLOOR';\n }\n if (\n asserted.timeslot !== undefined &&\n asserted.timeslot !== '' &&\n asserted.slotsKnown &&\n !asserted.timeslotResolved\n ) {\n return 'TIMESLOT_NOT_ON_SALE';\n }\n return null;\n}\n\n/** The sum of a composition, which is what a ceiling is measured against. */\nexport function intentHeadcount(composition: IntentComposition | undefined): number {\n return Object.values(composition ?? {}).reduce((total, n) => total + n, 0);\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport type { ScopeClient } from '@scopetickets/api';\nimport {\n withHolder,\n type BookedTicket,\n type BookingGateway,\n type BookingRecord,\n type BookingState,\n type HolderSave,\n type TicketSend,\n type Ticketholder,\n} from '../domain/booking';\nimport { bookingGateway } from './bookingGateway';\n\nexport type BookingStore = {\n readonly state: BookingState;\n readonly save: HolderSave;\n /** Whether a copy of a ticket has gone, and where to. See `TicketSend`. */\n readonly send: TicketSend;\n /**\n * Send a copy of one ticket to an address. Resolves TRUE where the platform took it.\n *\n * IT REFUSES A SECOND SEND WHILE ONE IS IN FLIGHT, which is not politeness: the call\n * behind it is a `GET`, so a doubled press is a doubled email and nothing downstream\n * would notice.\n */\n readonly sendTicket: (ticket: BookedTicket, email: string) => Promise<boolean>;\n /** Put a standing send outcome away, so a fresh card starts from nothing. */\n readonly clearSend: () => void;\n /**\n * Name a different person on one ticket. Resolves TRUE when the platform took it, which\n * is what lets the card go back to the ticket it came from — anything else leaves the\n * buyer on the form with what they typed still in it.\n */\n readonly saveHolder: (ticket: BookedTicket, holder: Ticketholder) => Promise<boolean>;\n /** Put a standing save outcome away, so a corrected attempt starts from nothing. */\n readonly clearSave: () => void;\n /** Ask again after a failed read. */\n readonly retry: () => void;\n};\n\n/**\n * THE BOOKING BEHIND A CART, AND THE ONE EDIT IT ALLOWS.\n *\n * ── IT DEPENDS ON THE CART KEY AND NOTHING ELSE ──────────────────────────────\n *\n * The occasion and the attribution are the caller's and are folded in at RENDER, not here —\n * see `dressBooking`, where that decision is argued. What is left is one request keyed on\n * one string, which is why this hook has no memoisation hazard to warn about.\n *\n * ── THE RECORD IS HELD HERE BECAUSE A SAVE CHANGES IT ────────────────────────\n *\n * Editing a holder is the one thing on these cards that writes, and what it writes is\n * already in hand: the save's own body is the holder the buyer typed, and the platform's\n * answer carries nothing back to read. So the record is amended locally (`withHolder`)\n * rather than refetched — a second read would put a spinner over a booking the buyer is\n * looking at, to learn what they just typed.\n */\nexport function useBooking(\n gateway: BookingGateway | null,\n cartKey: string | null,\n /**\n * THE RECORD ALREADY IN HAND, where the caller read it before mounting this.\n *\n * IT EXISTS TO REMOVE A WHOLE STATE FROM THE SCREEN. The island fetches its incoming\n * content BEFORE it transitions, then morphs, then fades in — so a booking that arrives\n * unread puts a fifth card (\"Opening Your Booking\") between the last step of the purchase\n * and the tickets, and the buyer watches two transitions where the design draws one. See\n * `PlacedBooking`, which is where the flow does that read.\n */\n seed?: BookingRecord,\n): BookingStore {\n const [state, setState] = useState<BookingState>(\n seed === undefined ? { status: 'LOADING' } : { status: 'LOADED', record: seed },\n );\n const [save, setSave] = useState<HolderSave>({ status: 'IDLE' });\n /* Asking again is a new attempt at the same key, so the effect needs something to move. */\n const [attempt, setAttempt] = useState(0);\n /**\n * WHICH KEY IS ALREADY ANSWERED FOR — the seed's, until a read answers for another.\n *\n * KEYED ON THE VALUE AND NOT A BARE \"SPENT\" FLAG, because a flag is wrong twice: React's\n * strict mode mounts effects twice in development, so the second run would fetch exactly\n * the thing the seed exists to avoid fetching; and a cart key that changes later must\n * still be read. Comparing the key answers both.\n */\n const answered = useRef<string | null>(seed === undefined ? null : cartKey);\n\n useEffect(() => {\n if (gateway === null || cartKey === null || cartKey === '') {\n /*\n * NOTHING ASKED IS NOT AN ERROR EITHER. A widget mounted without a key has no booking\n * to fail to load; it has no booking, which is what `NONE` says.\n *\n * AND IT SAYS SO OUT LOUD, because this was the one branch that could draw \"No Tickets\n * Here Yet\" without a single line anywhere explaining it — no request in the network\n * panel and nothing in the console, which is indistinguishable from a platform that\n * answered with an empty transaction. The two have completely different remedies and\n * cost an evening to tell apart. `appKey` empty is the likeliest: it is what makes the\n * client, and therefore the gateway, null.\n */\n if (typeof console !== 'undefined') {\n console.warn(\n '[ScopeTicketsCheckout] no booking was asked for, so none is drawn. ' +\n `${gateway === null ? 'There is no client — `appKey` is empty. ' : ''}` +\n `${cartKey === null || cartKey === '' ? 'There is no cart key. ' : ''}` +\n 'Nothing was requested from the platform.',\n );\n }\n setState({ status: 'NONE' });\n return undefined;\n }\n\n /* Already in hand — see `answered`. Cleared by `retry`, which is how Try Again works. */\n if (answered.current === cartKey) return undefined;\n\n /* A key that changes mid-flight must not be answered by the old request. */\n let live = true;\n setState({ status: 'LOADING' });\n\n gateway\n .read(cartKey)\n .then((record) => {\n if (!live) return;\n answered.current = cartKey;\n setState(record === null ? { status: 'NONE' } : { status: 'LOADED', record });\n })\n .catch((cause: unknown) => {\n if (!live) return;\n setState({\n status: 'ERROR',\n error: cause instanceof Error ? cause : new Error(String(cause)),\n });\n });\n\n return () => {\n live = false;\n };\n }, [gateway, cartKey, attempt]);\n\n /*\n * THE SAVE OUTLIVES THE CARD. A host can take the widget off its page while a `PUT` is in\n * flight, so what comes back is dropped rather than written into a component that has\n * gone.\n */\n const mounted = useRef(true);\n useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n };\n }, []);\n\n const saveHolder = useCallback(\n async (ticket: BookedTicket, holder: Ticketholder): Promise<boolean> => {\n if (gateway === null || state.status !== 'LOADED') return false;\n const record = state.record;\n setSave({ status: 'SAVING' });\n\n try {\n const took = await gateway.saveHolder(record.transactionKey, ticket.key, holder);\n if (!mounted.current) return took;\n setSave(took ? { status: 'IDLE' } : { status: 'REFUSED' });\n /*\n * WRITTEN ONLY ON SUCCESS, and onto the record the save was BUILT from rather than\n * onto whatever is current: nothing else writes here, so the two cannot have\n * diverged — and reading the state again inside a promise is how they start to.\n *\n * THE HOLDER IS ALL THAT CHANGES: the save is addressed by keys and the platform\n * binds the attendee itself, so the record holds no id to carry across edits. A\n * re-read of the booking would name the same person.\n */\n if (took) {\n setState({ status: 'LOADED', record: withHolder(record, ticket.key, holder) });\n }\n return took;\n } catch (cause: unknown) {\n if (mounted.current) {\n setSave({\n status: 'FAILED',\n error: cause instanceof Error ? cause : new Error(String(cause)),\n });\n }\n return false;\n }\n },\n [gateway, state],\n );\n\n /*\n * ── A COPY OF ONE TICKET, TO AN ADDRESS ──────────────────────────────────\n *\n * THE GUARD IS THE STATE, and it is the only one there is. The platform sends this on a\n * `GET`, so nothing between the press and the inbox treats a repeat as costly — a second\n * press while the first is in flight is a second email. `SENDING` is what the card's\n * button reads, and this refuses to start a second send whatever the card does.\n */\n const [send, setSend] = useState<TicketSend>({ status: 'IDLE' });\n\n const sendTicket = useCallback(\n async (ticket: BookedTicket, email: string): Promise<boolean> => {\n if (gateway === null) return false;\n /* Read off the state rather than a ref: a re-render cannot lose it, and nothing else sets it. */\n let already = false;\n setSend((was) => {\n already = was.status === 'SENDING';\n return already ? was : { status: 'SENDING' };\n });\n if (already) return false;\n\n try {\n const sent = await gateway.sendTicket(ticket.attendeeTicketId, email);\n if (!mounted.current) return sent;\n setSend(\n sent\n ? { status: 'SENT', email }\n : { status: 'FAILED', error: new Error('The ticket could not be sent.') },\n );\n return sent;\n } catch (cause: unknown) {\n if (mounted.current) {\n setSend({\n status: 'FAILED',\n error: cause instanceof Error ? cause : new Error(String(cause)),\n });\n }\n return false;\n }\n },\n [gateway],\n );\n\n /* A fresh card asks again from nothing — see `clearSave`, which is the same service. */\n const clearSend = useCallback(() => setSend({ status: 'IDLE' }), []);\n\n const clearSave = useCallback(() => setSave({ status: 'IDLE' }), []);\n const retry = useCallback(() => {\n /* Forget that this key is answered for, or the effect below would decline to ask again. */\n answered.current = null;\n setAttempt((was) => was + 1);\n }, []);\n\n return { state, save, saveHolder, clearSave, send, sendTicket, clearSend, retry };\n}\n\n/**\n * The booking calls, built on the widget's own client — `useSignInGateway`'s twin, and for\n * the same reason: one gateway for the life of the client rather than a new object each\n * render.\n */\nexport function useBookingGateway(client: ScopeClient | null): BookingGateway | null {\n return useMemo(() => (client === null ? null : bookingGateway(client)), [client]);\n}\n","/**\n * HOW LONG A STRING FROM OUTSIDE MAY BE, AND THE TWO WAYS OF ASKING.\n *\n * Every value the platform or the ceremony frame hands us crosses one of these, because a\n * string nobody bounded is one somebody else decides the size of — and this library runs\n * inside another company's page, where an unbounded value becomes their memory, their DOM\n * and their render loop rather than ours.\n *\n * TOO LONG IS `null`, NOT TRUNCATED. A trimmed name is a wrong name presented as a right\n * one; absent is a case every reader of `Account` already handles. The one place the\n * opposite is right is the reporter, which truncates prose deliberately — see\n * `scopeReporter`, where the payload has to go somewhere rather than be dropped.\n */\n\n/**\n * The limits, named for what they bound rather than for their size, so a caller picks by\n * meaning. Where the platform states its own — `UserResponse` is `maxLength: 50` on every\n * field of a profile — that number is taken from the spec rather than invented.\n */\nexport const WIRE_LIMITS = {\n /** A name, an address, a phone number. The platform's own `maxLength` on all of them. */\n profile: 50,\n /**\n * A KEY THE PLATFORM ISSUED — an attendee ticket's, so far. Fifty is `FeedbackModel`'s\n * own `maxLength` on `AttendeeTicketKey`, and it is separate from `profile` despite\n * being the same number: they are two facts that happen to agree, and a ticket key\n * bounded by \"what a first name may be\" is a coincidence waiting to be edited.\n */\n key: 50,\n /**\n * A CART'S KEY, OR THE TRANSACTION IT BECAME — and NOT `key` above, despite both being\n * tokens the platform issued.\n *\n * MEASURED RATHER THAN TAKEN FROM A SPEC, because the spec states none for these: staging\n * issues them as 64 hex characters, where an attendee ticket's key is 32 and its own\n * model says 50.\n *\n * THE COINCIDENCE ABOVE IS WHY THIS EXISTS. `key` bounds an attendee ticket at 50, which\n * is generous for a 32-character value and far too small for a 64-character one — so a\n * transaction key run through it came back `null`, `readBooking` answered \"no booking\",\n * and a buyer who had just paid for three tickets was shown a card saying they had none.\n * Nothing looked at the items at all. Two facts that happen to be near each other are not\n * one limit.\n *\n * 128 IS HEADROOM, not a measurement: the platform promises nothing about the length, so\n * the bound is what a token of this shape could plausibly grow to.\n */\n order: 128,\n /**\n * An avatar VALUE: a URL, or one of `@scopetickets/avatar`'s prefixed forms. Generous,\n * because a signed CDN URL is long, and bounded because it reaches an `<img src>`.\n */\n avatar: 2048,\n /**\n * A header, a session key or a refresh token. A JWT runs to a few hundred characters —\n * staging's is about 300 — and this one is spent as an `Authorization`, so its ceiling\n * is what a server will accept in a header rather than anything about the value.\n */\n credential: 4096,\n /**\n * A credential or a challenge crossing the passkey frame. An attestation object in\n * base64 runs to hundreds of characters, and these go on to the platform.\n */\n ceremony: 8192,\n /** A failure code from the ceremony document — one word from a closed set. */\n code: 64,\n /**\n * A PROMO CODE, which a buyer types and the platform echoes back on the cart. The spec\n * states no length, and one nobody could type is one nobody applied — this is the bound\n * on the field, not a guess at the platform's.\n */\n promoCode: 64,\n /**\n * WHY THE PLATFORM REFUSED ONE, in its own words — prose we did not author, drawn on the\n * card, so bounded to a sentence. Longer than that is not a reason, it is a payload.\n */\n promoReason: 200,\n /** An RP id is a domain name, and the longest a DNS name can be is 253. */\n rpId: 253,\n} as const;\n\n/**\n * A typed wire string, or `null` where there is nothing usable — absent, empty, or longer\n * than its limit. For values that ALREADY have a string type: an API response the client\n * has parsed.\n */\nexport function bounded(value: string | null | undefined, limit: number): string | null {\n if (typeof value !== 'string' || value.length === 0 || value.length > limit) return null;\n return value;\n}\n\n/**\n * The same question of something that has no type at all — a `postMessage`, where the\n * shape is whatever the sender chose and even `typeof` has to be asked.\n */\nexport function isBounded(value: unknown, limit: number): value is string {\n return typeof value === 'string' && value.length > 0 && value.length <= limit;\n}\n","/**\n * MY BOOKING — what a buyer owns once the money has moved, as the cards draw it.\n *\n * ── THE TWO HALVES, AND WHY THEY COME FROM DIFFERENT PLACES ──────────────────\n *\n * A booking is an OCCASION and a set of TICKETS, and the platform answers for only one of\n * them. `GET /api/Transactions/ByKey/{cartKey}` returns the attendee tickets — a key each,\n * and the person each is for — and says nothing about what was bought into: no event name,\n * no artwork, no day, no session. It carries a numeric `EventID`, which no endpoint here\n * takes.\n *\n * So the occasion is the CALLER'S, exactly as `cartLines` is: the flow has just walked a\n * buyer through choosing it and holds every field, and a host mounting this on its own page\n * holds them too or it would not have had anything to sell. Inventing a lookup that cannot\n * be made is the alternative, and it ends in a card that says \"Ice Skating\" for one mount\n * and nothing for the other.\n *\n * ── WHICH IS WHY THERE ARE TWO TYPES AND NOT ONE ─────────────────────────────\n *\n * `BookingRecord` is what the platform holds. `Booking` is that record with the caller's\n * facts folded in, and `dressBooking` is the fold. Keeping them apart is not tidiness: the\n * occasion and the attribution are written inline by most callers and are therefore new\n * objects on every render, so a read that took them would refetch the whole booking every\n * time anything above it moved. Folded at render, the request depends on the cart key and\n * nothing else.\n *\n * ── WHAT A TICKET IS, AND WHAT IT IS NOT ─────────────────────────────────────\n *\n * `Items[].Key` IS the `AttendeeTicketKey` — what a QR code is drawn FROM, and the only\n * identity a ticket has on screen. `Attendee.ID` is separate and is what `PUT /Attendees`\n * names when a holder is edited; the two are not interchangeable and both are kept.\n *\n * `Items[].Type` IS DELIBERATELY NOT READ. A booking must list tickets and not booking fees,\n * and the tempting way to say so is to narrow that free text to a closed union. The honest\n * rule is the one the cards actually need: an item is a ticket when it has a key a code can\n * be drawn from AND an attendee it belongs to. A fee has neither. Narrowing `Type` would\n * mean a closed union over spellings nobody here has seen, and the first unrecognised one\n * would empty a buyer's booking rather than draw an extra row.\n */\n\nimport type {\n AttendeeTicket,\n SetItemAttendeeRequest,\n TransactionByKeyResponse,\n} from '@scopetickets/api';\nimport { isValidEmail } from './contact';\nimport { WIRE_LIMITS, bounded } from './wire';\n\n/** Who a ticket is for. */\nexport type Ticketholder = {\n readonly firstName: string;\n readonly lastName: string;\n readonly email: string;\n /** The platform takes one and the design never asks for it — carried so a save keeps it. */\n readonly phone: string | null;\n /**\n * A FACE THE PLATFORM ACTUALLY HOLDS, or none — and \"none\" is the ordinary answer.\n *\n * IT IS NOT DERIVED. Initials are a thing this package can always manufacture, which is\n * exactly why they are the wrong answer here: a ticket drawn with a generated mark claims\n * to show somebody, and what it shows is two letters off a name already printed beside it.\n * A ticket with no face draws no face.\n */\n readonly photo: string | null;\n};\n\n/** One ticket, as the platform holds it. */\nexport type BookedTicket = {\n /**\n * The platform's `AttendeeTicketKey`, and the QR code's own content. Stable for the life\n * of the ticket, which is why the carousel and the ticket card are keyed on it — and it\n * is one of the two keys a save is ADDRESSED BY, which is why nothing else about the\n * ticket has to be known before a holder can be named.\n */\n readonly key: string;\n /**\n * THE SAME ROW'S NUMERIC ID — `AttendeeTicket.ID`, which the platform's own\n * send-a-copy call is addressed by. The save is not: it takes the key above.\n *\n * `0` where the attendee-ticket list did not answer, which is the one case a ticket\n * cannot be SENT — see the gateway's `sendTicket`.\n */\n readonly attendeeTicketId: number;\n readonly holder: Ticketholder;\n};\n\n/** What the platform holds: the transaction, and who each of its tickets is for. */\nexport type BookingRecord = {\n /** What a save is addressed to. Read off the response; a cart key will not do. */\n readonly transactionKey: string;\n readonly tickets: readonly BookedTicket[];\n};\n\n/**\n * WHAT WAS BOUGHT INTO. The caller's, for the reason at the top of this file.\n *\n * `day` is `YYYY-MM-DD` and the two times are `HH:MM`, which is the shape the rest of this\n * package already speaks — see `island-timeslots`, whose `parseWallClockTime` is what turns\n * a wire value into one.\n */\nexport type BookingOccasion = {\n /** \"Ice Skating\". */\n readonly name: string;\n /** `YYYY-MM-DD` in the VENUE's local day, never the device's. */\n readonly day: string;\n /** The run's picture, for the hero. */\n readonly artwork: string | null;\n /** `HH:MM`, or absent where the event sells no sessions. */\n readonly startTime: string | null;\n readonly endTime: string | null;\n};\n\n/**\n * WHAT THE CALLER KNOWS THAT THE WIRE DOES NOT — the product and the user type.\n *\n * ── TWO LEVELS, BECAUSE THE TWO FACTS ARE KNOWN AT DIFFERENT GRAINS ──────────\n *\n * `product` is the whole booking's: this widget fills one cart from one event, so \"Peak\" is\n * true of every ticket in it, and the flow holds that name from the moment the cart was\n * opened (`CheckoutOrder.productName`).\n *\n * `tickets` is per ATTENDEE TICKET KEY, and almost nothing can fill it. The user type is a\n * fact about a cart ITEM, the key is a fact about an attendee ticket, and the platform\n * exposes no join between them — so the flow supplies none and a host that has its own\n * records supplies what it has. Keyed rather than positional because the two lists have no\n * order in common.\n *\n * A KEY THAT IS NOT IN HERE resolves to the booking-wide product and no user type, which is\n * a ticket drawn with a shorter qualifier rather than one that is dropped.\n */\nexport type TicketAttribution = {\n /** \"Peak\" — true of every ticket, where the caller knows it. */\n readonly product?: string | null;\n /** Per attendee ticket key, where the caller can tell them apart. */\n readonly tickets?: Readonly<\n Record<string, { readonly product?: string | null; readonly userType?: string | null }>\n >;\n};\n\n/** One ticket as the cards draw it. */\nexport type BookingTicket = BookedTicket & {\n /** \"Peak\" — the product, where the caller knows it. */\n readonly product: string | null;\n /** \"Adult\" — the user type, where the caller knows it. */\n readonly userType: string | null;\n};\n\n/** A booking as the cards draw it — the record, dressed. */\nexport type Booking = {\n readonly transactionKey: string;\n readonly occasion: BookingOccasion;\n readonly tickets: readonly BookingTicket[];\n};\n\n/**\n * THE BOUNDARY — and it takes TWO responses, because neither endpoint is complete.\n *\n * ── WHY BOTH, AND WHY THIS COST A BOOKING ITS TICKETS ────────────────────────\n *\n * `Transactions/ByKey/{cartKey}` is the only call that carries a holder's NAME. It also\n * OMITS the nested `Attendee` entirely for a transaction made from the v2 cart endpoint —\n * which is every transaction this widget makes. `@scopetickets/sdk`'s own\n * `useTicketConfirmation` has said so since before the island existed: \"do not rely on it\n * as the only source of the attendee ID\".\n *\n * This file did rely on it. An item was a ticket when it had a key AND an attendee, so\n * against a real purchase every row was dropped, `readBooking` answered `null`, and a buyer\n * who had just paid was shown \"No Tickets Here Yet\".\n *\n * `Transactions/{transactionKey}/Items` is the other half: a list of ATTENDEE TICKETS by\n * definition, each with its `AttendeeTicketKey` and its numeric `ID` — and no names at\n * all.\n *\n * ── SO A ROW IS A TICKET WHEN EITHER HALF SAYS IT IS ─────────────────────────\n *\n * It is named by the attendee-ticket list, OR it carries an attendee. Two clauses, each\n * with its own reason: the first is the platform's own statement that this is a ticket, and\n * the second is that it belongs to a PERSON. A booking fee has neither, which is the whole\n * of what has to be excluded — and `Items[].Type` still goes unread, for the reason at the\n * top of this file.\n *\n * ── AND THE TRANSACTION KEY FALLS BACK TO THE CART'S ─────────────────────────\n *\n * `TransactionKey || cartKey` is the SDK's own line. On staging the two are the same 64-hex\n * token for a cart that became a transaction; where they are not, the platform accepts the\n * cart's on the routes that matter, so a summary that came back without one is not a reason\n * to refuse a buyer their tickets.\n *\n * BOTH ARE BOUNDED BY `WIRE_LIMITS.order` AND NOT BY `.key`, which is the whole of the bug\n * this function was written with: an attendee ticket's key is 32 characters and a\n * transaction's is 64, and the 50 that is generous for the first rejects the second\n * outright. See the limit's own note.\n */\nexport function readBooking(\n summary: TransactionByKeyResponse,\n attendeeTickets: readonly AttendeeTicket[],\n /** What the summary was asked for, as the last resort for the key a save needs. */\n cartKey: string,\n): BookingRecord | null {\n const transactionKey =\n bounded(summary.TransactionKey, WIRE_LIMITS.order) ?? bounded(cartKey, WIRE_LIMITS.order);\n if (transactionKey === null) return null;\n\n /* What the summary knows about each key: who it is for, and their id where it has one. */\n const named = new Map<string, WireItem>();\n for (const item of summary.Items ?? []) {\n const key = bounded(item.Key, WIRE_LIMITS.key);\n if (key !== null) named.set(key, item);\n }\n\n const tickets: BookedTicket[] = [];\n const taken = new Set<string>();\n\n /*\n * THE ATTENDEE-TICKET LIST LEADS, because it is the one that is always complete and\n * because its order is the order the tickets were issued in.\n */\n for (const ticket of attendeeTickets) {\n const key = bounded(ticket.AttendeeTicketKey, WIRE_LIMITS.key);\n if (key === null || taken.has(key)) continue;\n taken.add(key);\n tickets.push(readTicket(key, named.get(key), ticket.ID));\n }\n\n /*\n * THEN ANYTHING THE SUMMARY NAMES A PERSON ON that the list did not mention — the shape\n * this file used to handle alone, kept so a booking still draws if the second call is the\n * one that comes back empty.\n */\n for (const [key, item] of named) {\n if (taken.has(key)) continue;\n /*\n * IT BELONGS TO A PERSON, OR THE SUMMARY CALLS IT A TICKET. Either is enough; a booking\n * fee is neither.\n *\n * `== null` AND NOT `=== undefined` on the first. The summary sends `\"Attendee\": null`\n * on every row of a v2-cart transaction — an explicit null, not an absent field — so a\n * strict test reads it as present and quietly turns this clause into \"anything listed\".\n */\n if (item.Attendee == null && itemKind(item.Type) === null) continue;\n taken.add(key);\n /*\n * NO ATTENDEE TICKET ID ON THIS SIDE. The summary carries the key and not the row's\n * number, so a ticket known only from here cannot have a copy SENT of it — see the\n * gateway's `sendTicket`, which is the one call that number still addresses. The save\n * is not: it takes the key, which is in hand.\n */\n tickets.push(readTicket(key, item, 0));\n }\n\n return tickets.length === 0 ? null : { transactionKey, tickets };\n}\n\ntype WireItem = TransactionByKeyResponse['Items'][number];\n\n/**\n * WHAT THE SUMMARY CALLS A ROW, narrowed to a closed set.\n *\n * `\"ticket\"` is what staging sends on every row of a real purchase. Anything else — a\n * booking fee, a donation, a spelling nobody here has seen — is `null`, which means NOT\n * PROVEN A TICKET rather than \"not a ticket\".\n *\n * THAT WEAKER READING IS WHAT MAKES THIS SAFE TO CONSULT AT ALL. The attendee-ticket list is\n * the authority on which rows are tickets, and this is asked only for rows that list did not\n * mention — which in practice means only when the second request failed. So an unrecognised\n * spelling costs a row on a degraded read, where narrowing it as the PRIMARY test would have\n * emptied a buyer's booking outright.\n */\nfunction itemKind(type: string | undefined): 'TICKET' | null {\n switch (type?.trim().toLowerCase()) {\n case 'ticket':\n return 'TICKET';\n default:\n return null;\n }\n}\n\n/**\n * One ticket, from whichever halves of it arrived.\n *\n * A TICKET NEEDS NOTHING TO BE EDITABLE: the save is addressed by the key, which is in\n * hand wherever a ticket is known from at all. `attendeeTicketId` is `0` where the list\n * did not answer — the summary-only fallback — and only the SEND declines on that.\n */\nfunction readTicket(\n key: string,\n item: WireItem | undefined,\n attendeeTicketId: number,\n): BookedTicket {\n const attendee = item?.Attendee;\n\n return {\n key,\n attendeeTicketId: usableId(attendeeTicketId) ?? 0,\n holder: {\n firstName: bounded(attendee?.FirstName, WIRE_LIMITS.profile) ?? '',\n lastName: bounded(attendee?.LastName, WIRE_LIMITS.profile) ?? '',\n /* Bounded by the platform's own `maxLength` on a profile, as `sign-in` bounds one. */\n email: bounded(attendee?.Email, WIRE_LIMITS.profile) ?? '',\n phone: bounded(attendee?.Phone, WIRE_LIMITS.profile),\n /* An avatar VALUE, which reaches an `<img src>` — bounded as `sign-in` bounds one. */\n photo: bounded(attendee?.Photo, WIRE_LIMITS.avatar),\n },\n };\n}\n\nconst usableId = (id: number | undefined): number | null =>\n typeof id === 'number' && id > 0 ? id : null;\n\n/** The record with the caller's own facts folded in — see the top of this file. */\nexport function dressBooking(\n record: BookingRecord,\n occasion: BookingOccasion,\n attribution: TicketAttribution = {},\n): Booking {\n return {\n transactionKey: record.transactionKey,\n occasion,\n tickets: record.tickets.map((ticket) => {\n const own = attribution.tickets?.[ticket.key];\n return {\n ...ticket,\n /* The ticket's own name wins over the booking's, and the booking's is the fallback. */\n product: own?.product ?? attribution.product ?? null,\n userType: own?.userType ?? null,\n };\n }),\n };\n}\n\n/** The ticket a key names, or `null`. */\nexport function ticketAt(booking: Booking, key: string): BookingTicket | null {\n return booking.tickets.find((ticket) => ticket.key === key) ?? null;\n}\n\n/**\n * The record with one holder replaced — what a successful save leaves behind, so the list\n * the buyer goes back to names the person they just typed rather than the one they edited.\n *\n * NOTHING IS KEPT BUT THE HOLDER, because there is nothing to keep: the save is addressed\n * by keys and the platform binds the attendee itself, so the record holds no attendee id\n * to carry across edits. A re-read of the booking would name the same person.\n */\nexport function withHolder(\n record: BookingRecord,\n key: string,\n holder: Ticketholder,\n): BookingRecord {\n return {\n ...record,\n tickets: record.tickets.map((ticket) => (ticket.key === key ? { ...ticket, holder } : ticket)),\n };\n}\n\n/**\n * A holder as `PUT /api/v2/Transactions/{transaction_key}/Items/{item_key}/Attendee` takes\n * one — the whole of what a save carries, because the route names the ticket and there is\n * no id to tell the platform which attendee is meant.\n *\n * `Photo` IS SENT BACK AS IT CAME, where the platform holds one: the save writes the whole\n * holder, so an omitted photo is a face LOST rather than a face unchanged. Nothing is ever\n * invented — see `Ticketholder.photo`, which is the same rule on the read.\n */\nexport function itemAttendeeBody(holder: Ticketholder): SetItemAttendeeRequest {\n return {\n FirstName: holder.firstName,\n LastName: holder.lastName,\n Email: holder.email,\n /* The platform's field is optional and its absence means \"unchanged\" nowhere: an\n * omitted phone on a save is a phone erased. Sent back as it came. */\n Phone: holder.phone ?? '',\n ...(holder.photo === null ? {} : { Photo: holder.photo }),\n };\n}\n\n/**\n * THE SEAM. Everything this island asks of the platform, and nothing about WHEN — that is\n * the hook's, exactly as it is for `SignInGateway`.\n *\n * THREE CALLS AND NOT FOUR. Reading a booking is one request: `Transactions/ByKey` carries\n * the transaction's own key alongside the items, so nothing has to be looked up before a\n * save can be addressed.\n */\nexport type BookingGateway = {\n /** The booking behind a cart, or `null` where the cart has not become one. */\n readonly read: (cartKey: string) => Promise<BookingRecord | null>;\n /**\n * Name a person on one ticket — creating the attendee where there is none, which is the\n * ordinary case. `false` is the platform declining; anything worse keeps travelling and\n * becomes a notice.\n *\n * ADDRESSED BY THE TWO KEYS AND NOTHING ELSE: the transaction's and the ticket's, which\n * is why every ticket a read can draw is a ticket this can name — there is no row number\n * to be missing. The platform binds the attendee itself, so there is no id to hand back\n * and none to keep for the next edit: re-addressing the same item is how a holder is\n * changed.\n */\n readonly saveHolder: (\n transactionKey: string,\n ticketKey: string,\n holder: Ticketholder,\n ) => Promise<boolean>;\n /** One ticket's code, as an SVG document, or `null` where nothing usable came back. */\n readonly code: (key: string) => Promise<string | null>;\n /**\n * Send a copy of one ticket to an address. `false` is \"it did not go\" and nothing more:\n * the endpoint says nothing about why, so neither does this.\n *\n * BY THE NUMERIC ID — `BookedTicket.attendeeTicketId`, which is what the platform's own\n * call takes and is `0` where the list did not answer for the ticket.\n */\n readonly sendTicket: (attendeeTicketId: number, email: string) => Promise<boolean>;\n};\n\n/**\n * WHAT IS KNOWN ABOUT THE BOOKING — one value, never a record beside a pair of flags.\n *\n * `NONE` IS NOT `ERROR` AND IT IS NOT `LOADING`. A cart that never became a transaction is\n * a complete, successful answer — there is nothing to show — and it needs a card that says\n * so rather than a spinner that never stops or a failure nobody caused.\n */\nexport type BookingState =\n | { readonly status: 'LOADING' }\n | { readonly status: 'LOADED'; readonly record: BookingRecord }\n | { readonly status: 'NONE' }\n | { readonly status: 'ERROR'; readonly error: Error };\n\n/**\n * WHAT THE EDIT CARD'S SAVE IS DOING. `REFUSED` is the platform declining the details;\n * `FAILED` is never having reached it. Two outcomes because they read differently to a\n * buyer — one is \"that address will not do\" and the other is \"try again in a moment\" — and\n * because only the second is a fault worth reporting. See `raiseForBooking`.\n */\nexport type HolderSave =\n | { readonly status: 'IDLE' }\n | { readonly status: 'SAVING' }\n | { readonly status: 'REFUSED' }\n | { readonly status: 'FAILED'; readonly error: Error };\n\n/**\n * WHETHER A COPY OF THE TICKET HAS GONE — and `SENT` is a state and not an event, because\n * the card has to keep saying so.\n *\n * IT IS SENT ONCE PER PRESS AND NEVER BY ANYTHING ELSE. The platform's endpoint is a `GET`\n * that sends mail, so nothing between here and it treats a repeat as costly: a retry layer,\n * a prefetch or an effect that re-runs would each put another copy in somebody's inbox.\n * `SENDING` is what the card gates its own button on, and it is the only guard there is.\n */\nexport type TicketSend =\n | { readonly status: 'IDLE' }\n | { readonly status: 'SENDING' }\n /** Gone, to the address it went to — which the card says back, because nothing else can. */\n | { readonly status: 'SENT'; readonly email: string }\n | { readonly status: 'FAILED'; readonly error: Error };\n\n/**\n * WHETHER THE EDIT CARD'S SAVE MAY GO.\n *\n * ── WHAT IS REQUIRED, AND WHAT IS DELIBERATELY NOT ──────────────────────────\n *\n * A NAME AND AN ADDRESS. The address because it is where the ticket goes and a malformed\n * one is refused by the platform anyway — asked here so the buyer is told by the field they\n * are standing in rather than by a notice two presses later. A first name because a ticket\n * belonging to nobody is what this card exists to fix, and saving one straight back would\n * make the button look broken.\n *\n * A LAST NAME IS NOT REQUIRED. Plenty of people have one name, and a widget that refuses to\n * save a ticket until a stranger supplies a surname they do not have is a widget that has\n * decided what names are.\n *\n * A PREDICATE BECAUSE IT IS THE KIND OF RULE THAT GETS RE-TYPED. The Save button reads it\n * and so does the press behind it — two copies of `email.includes('@')` is how the two come\n * to disagree.\n */\nexport function holderComplete(holder: Ticketholder): boolean {\n return holder.firstName.trim() !== '' && isValidEmail(holder.email.trim());\n}\n\n/** Whether anything was actually changed — a Save that sends what is already there. */\nexport function holderChanged(was: Ticketholder, now: Ticketholder): boolean {\n return (\n was.firstName !== now.firstName || was.lastName !== now.lastName || was.email !== now.email\n );\n}\n\n// ── Where the buyer is ───────────────────────────────────────\n\n/**\n * WHICH OF THE FOUR CARDS IS SHOWING.\n *\n * ONE VALUE, AND EACH ARM CARRIES WHAT ONLY IT NEEDS. The alternative — a screen name\n * beside an optional ticket key beside a carousel index — can say \"the edit card, for no\n * ticket\", which is a card with three empty fields and a Save that addresses nobody.\n *\n * THE INDEX LIVES ON `CODES` FOR THE SAME REASON. It is where the run is scrolled to, which\n * is a fact about that card and about nothing else: kept beside the screen, a buyer who\n * leaves and comes back opens on the first ticket, which is right — they arrived by pressing\n * Show QRs, not by resuming.\n */\nexport type BookingScreen =\n /** The root: what was bought, and who each ticket is for. Its way out is out of the island. */\n | { readonly kind: 'BOOKING' }\n /** Every code, one at a time. `at` counts from zero. */\n | { readonly kind: 'CODES'; readonly at: number }\n /** One ticket, and the two things that can be done with it. */\n | { readonly kind: 'TICKET'; readonly ticketKey: string }\n /** Who that ticket is for, as a form. */\n | { readonly kind: 'EDIT'; readonly ticketKey: string }\n /**\n * WHERE A COPY OF IT GOES — an address, and nothing else. Not the holder's form: this\n * sends the ticket to WHOEVER the buyer names, which is the whole point of it, and\n * changing who the ticket BELONGS to is the other card.\n */\n | { readonly kind: 'SEND'; readonly ticketKey: string };\n\n/**\n * ── WHAT STANDS IN FRONT OF A TICKET'S OWN CARD ──────────────────────────────\n *\n * A ticket card is \"Alex’s Ticket\", a wallet badge and two quick actions. On a ticket\n * NOBODY IS NAMED ON it is \"Your Ticket\" and a greyed control — a card about a ticket that\n * has nothing to say about itself yet, standing between the buyer and the one thing they\n * came to do. So where details can still be taken, the FORM is what that row opens, and the\n * card waits behind it.\n *\n * `CLOSED` IS NOT A REFUSAL, it is a different door: the form is reached instead, and\n * reaching it is how the card opens.\n */\nexport type TicketGate =\n /** The ticket's own card — the holder is named, or there is no way to name one. */\n | { readonly kind: 'OPEN' }\n /** Nobody is named and the platform will take a name: the form stands in front. */\n | { readonly kind: 'CLOSED' }\n /** No such ticket in this booking. */\n | { readonly kind: 'ABSENT' };\n\n/**\n * THE GATE, ASKED ONCE.\n *\n * Three readers: the row's destination, the screen a key resolves to, and where Back goes\n * from the form. Written at each of them, the row's `Add` pill promised a form while the\n * header's arrow walked back onto the card the pill exists to skip — which is the drift a\n * shared predicate is for.\n *\n * A BOOKING NOT READ YET GATES NOTHING. There is no card being drawn to gate, and answering\n * `CLOSED` from ignorance would send a buyer to a form for a ticket we cannot describe.\n */\nexport function ticketGate(booking: Booking | null, ticketKey: string): TicketGate {\n if (booking === null) return { kind: 'OPEN' };\n const ticket = ticketAt(booking, ticketKey);\n if (ticket === null) return { kind: 'ABSENT' };\n if (holderName(ticket.holder) !== null) return { kind: 'OPEN' };\n /*\n * EVERY TICKET CAN BE NAMED, because the save is addressed by the key in hand — see\n * `BookingGateway.saveHolder`. So an unnamed ticket is always gated CLOSED: the form\n * stands in front of it, and the card behind is reached by naming somebody first.\n */\n return { kind: 'CLOSED' };\n}\n\n/**\n * WHERE BACK GOES — the whole navigation, as one function.\n *\n * IT IS A TREE AND NOT A HISTORY, which is the decision this encodes. Show QRs is reachable\n * from the root AND from a ticket, and a history would send a buyer back to whichever they\n * came from; this sends them to the root either way. That is the right answer because the\n * carousel is the whole booking's codes rather than one ticket's — going \"back\" from all of\n * them to one of them is not a step backwards.\n *\n * `BOOKING` HAS NO BACK, and `null` is how it says so: the root's header draws a Close, and\n * closing the island is not navigation.\n *\n * ── AND THE FORM BACKS OUT PAST A CARD THAT IS STILL GATED ──────────────────\n *\n * The form is reached two ways and they are not the same journey. From a NAMED ticket's\n * quick action it is a detour off that ticket's card, and Back returns to it. From an\n * unnamed row it is what the row opened INSTEAD of that card, and backing onto the card\n * anyway would hand the buyer the \"Your Ticket\" screen the gate exists to keep shut — so\n * Back goes to the list, which is where they pressed.\n *\n * The booking is optional because three of the four answers do not need it, and without one\n * nothing is gated — `ticketGate` says why — so the form backs out to its ticket exactly as\n * it did before there was a gate. `BookingIsland` always has one to pass.\n */\nexport function backFrom(\n screen: BookingScreen,\n booking: Booking | null = null,\n): BookingScreen | null {\n switch (screen.kind) {\n case 'BOOKING':\n return null;\n case 'CODES':\n return { kind: 'BOOKING' };\n case 'TICKET':\n return { kind: 'BOOKING' };\n case 'EDIT':\n return ticketGate(booking, screen.ticketKey).kind === 'OPEN'\n ? { kind: 'TICKET', ticketKey: screen.ticketKey }\n : { kind: 'BOOKING' };\n /*\n * AND SEND ALWAYS BACKS ONTO ITS TICKET, which the form does not. The form is reached\n * two ways — as a detour off a named ticket, and INSTEAD of an unnamed one's card —\n * and only the second has a gated card behind it. This is reached one way, from the\n * ticket's own quick action, so the card it came from is always open.\n */\n case 'SEND':\n return { kind: 'TICKET', ticketKey: screen.ticketKey };\n default: {\n const exhaustive: never = screen;\n return exhaustive;\n }\n }\n}\n\n// ── What a holder is called ──────────────────────────────────\n\n/** \"Alex Whelan\", or `null` where the platform holds neither half. */\nexport function holderName(holder: Ticketholder): string | null {\n const name = `${holder.firstName} ${holder.lastName}`.trim();\n return name === '' ? null : name;\n}\n\n/**\n * \"AW\" — the programmatic avatar's value, for a holder with no photo. Tickets carry no\n * `Photo` on this endpoint, so this is what every row and every code draws.\n *\n * ONE LETTER IS A COMPLETE ANSWER: a holder with only a first name gets \"A\", and padding it\n * to two with something invented would be worse than short.\n */\nexport function holderInitials(holder: Ticketholder): string {\n return [holder.firstName, holder.lastName]\n .map((part) => part.trim().charAt(0).toUpperCase())\n .filter((letter) => letter !== '')\n .join('');\n}\n\n/**\n * \"Alex’s Ticket\" — the ticket card's own title, or `null` where nobody is named.\n *\n * ALWAYS `’s`, INCLUDING AFTER AN `s`. Both \"James’s\" and \"James’\" are correct English and\n * house styles differ; what is not defensible is a rule that inspects the last letter of a\n * stranger's name and guesses. One form, applied to everyone, and the apostrophe is the\n * typographic one because this is prose rather than code.\n */\nexport function ticketTitle(holder: Ticketholder): string | null {\n const first = holder.firstName.trim();\n return first === '' ? null : `${first}’s Ticket`;\n}\n\n/**\n * \"Peak • Adult\" — what the ticket IS, on one line, or `null` where the caller supplied\n * neither half. Either half alone stands on its own; the bullet is a separator and never a\n * decoration, so it is not drawn against an empty side.\n */\nexport function ticketQualifier(ticket: BookingTicket): string | null {\n const parts = [ticket.product, ticket.userType].filter(\n (part): part is string => part !== null && part.trim() !== '',\n );\n return parts.length === 0 ? null : parts.join(' • ');\n}\n\n/**\n * \"12:00 - 12:45\", \"12:00\" for an event with no end, or `null` for one that sells no\n * sessions at all. A hyphen with spaces around it, which is the design's own.\n */\nexport function occasionTime(occasion: BookingOccasion): string | null {\n if (occasion.startTime === null) return null;\n return occasion.endTime === null\n ? occasion.startTime\n : `${occasion.startTime} - ${occasion.endTime}`;\n}\n","/**\n * THE CODE ON A TICKET — what it is drawn from, what colours it is drawn in, and the guard\n * it crosses on the way in.\n */\n\n/**\n * THE PAPER AND THE INK, AND WHY THEY ARE CONSTANTS RATHER THAN TOKENS READ AT RUNTIME.\n *\n * `GetQrCodeAsSVG` takes a foreground and a background and hands back a document already\n * painted, so these two hexes are baked into the file the moment it is fetched. That rules\n * out the obvious arrangement — declare them in the stylesheet, read them off the rendered\n * element — because the fetch happens before there is an element, and a theme toggle would\n * have to refetch every code on the card.\n *\n * IT COSTS NOTHING, BECAUSE THE TICKET DOES NOT INVERT. A ticket is paper: the design draws\n * the same near-white stock with the same near-black ink on the light card and the dark one,\n * which is why `--scopetickets-island-ticket-*` carry identical values in both appearance\n * blocks. These are those values, and `booking-css.test.ts` pins the pair together so the\n * stylesheet cannot drift away from what was fetched.\n *\n * BARE HEX, NO HASH: the endpoint rejects the hash.\n */\nexport const TICKET_PAPER = 'FAFAFA';\nexport const TICKET_INK = '111111';\n\n/**\n * HOW BIG A CODE MAY BE. It is about to be put into a page inside somebody else's site, so\n * \"the request resolved\" is not enough — see the same rule for every other value crossing\n * this boundary in `wire.ts`. A QR for a fifty-character key measures a few kilobytes;\n * sixty-four is room for a far denser code and still a bound.\n */\nconst LARGEST_CODE = 64 * 1024;\n\n/**\n * THE GUARD. A document that is not an SVG, or carries a script, is not a code — it is\n * whatever else was at that URL, and the ticket draws nothing rather than draw it.\n *\n * The script test is belt over braces: the document is spent as an `<img src>` data URI\n * below, where scripts do not run at all. It is here because the two decisions are one\n * line apart today and need not stay that way.\n */\nexport function isTicketCode(body: unknown): body is string {\n return (\n typeof body === 'string' &&\n body.length > 0 &&\n body.length <= LARGEST_CODE &&\n /^\\s*<svg[\\s>]/i.test(body) &&\n !/<script[\\s>]/i.test(body)\n );\n}\n\n/**\n * The code as something an `<img>` can take.\n *\n * AN `<img>` RATHER THAN THE DOCUMENT INLINED. An SVG put into a page with `innerHTML`\n * brings its scripts and its external references with it, and this one arrived over the\n * wire. Inside an `<img>` it is a picture and nothing else.\n *\n * Percent-encoded rather than base64 because `btoa` throws on anything outside Latin-1.\n */\nexport function ticketCodeDataUrl(svg: string): string {\n return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;\n}\n","import type { AttendeeTicket, ScopeClient } from '@scopetickets/api';\nimport {\n itemAttendeeBody,\n readBooking,\n type BookingGateway,\n type BookingRecord,\n type Ticketholder,\n} from '../domain/booking';\nimport { isTicketCode, TICKET_INK, TICKET_PAPER } from '../domain/ticket-code';\n\n/**\n * MY BOOKING, AGAINST THE REAL PLATFORM. `BookingGateway` is the seam and this is the only\n * thing that fills it; it decides nothing about WHEN, which is the hook's.\n *\n * ── IT IS KEYED ON THE CART, AND THAT IS THE PLATFORM'S CHOICE, NOT OURS ─────\n *\n * `Transactions/ByKey/{cartKey}` takes the CART's key, and it is the only call that carries\n * a holder's NAME. Everything else a booking needs — which tickets exist, and the numeric\n * `ID` a ticket's copy is sent by — comes off `Transactions/{transactionKey}/Items`, which\n * takes the transaction's. The transaction key comes back inside the first response, which\n * is why the save is handed the whole record's key rather than a list of tickets.\n *\n * BOTH ARE READ, AND `readBooking` SAYS WHY: the summary omits its attendees entirely for a\n * transaction made from the v2 cart endpoint, which is every transaction this widget makes.\n */\nexport function bookingGateway(client: ScopeClient): BookingGateway {\n return {\n async read(cartKey: string): Promise<BookingRecord | null> {\n /*\n * TWO CALLS, AND THE SECOND ONE IS NOT OPTIONAL. See `readBooking`: the summary is the\n * only source of a holder's NAME and it omits the attendee entirely for a transaction\n * made from the v2 cart endpoint, which is every transaction this widget makes. The\n * attendee-ticket list is the half that is always complete.\n *\n * SEQUENTIAL BECAUSE THE SECOND NEEDS THE FIRST: the transaction's own key only comes\n * back inside the summary. `Promise.all` is not available here at any price.\n */\n const summary = await client.getTransactionByCartKey(cartKey);\n const transactionKey = summary.TransactionKey || cartKey;\n\n /*\n * A FAILED SECOND CALL IS NOT A FAILED BOOKING. Where the summary DID carry attendees\n * — an older transaction — it is a complete answer on its own, so the list is asked\n * for and forgiven. The warning is what stops that being silent: \"no tickets\" and \"we\n * could not ask\" look identical on the card and are not the same thing.\n */\n let attendeeTickets: readonly AttendeeTicket[] = [];\n try {\n attendeeTickets = (await client.getTransactionItems(transactionKey)).Items ?? [];\n } catch (error) {\n warn(`could not read the attendee tickets on transaction '${transactionKey}'.`, error);\n }\n\n const record = readBooking(summary, attendeeTickets, cartKey);\n if (record === null) {\n /*\n * A 200 THAT YIELDED NOTHING. It is a real answer — a cart that never became a\n * transaction — and it is also what a shape change looks like, so it says which\n * cart and what came back rather than leaving the next person to guess.\n */\n warn(\n `no tickets on cart '${cartKey}'. The transaction summary had ` +\n `${(summary.Items ?? []).length} item(s) and the attendee-ticket list had ` +\n `${attendeeTickets.length}.`,\n summary,\n );\n }\n return record;\n },\n\n async saveHolder(\n transactionKey: string,\n ticketKey: string,\n holder: Ticketholder,\n ): Promise<boolean> {\n /*\n * ── ADDRESSED BY THE TWO KEYS, AND NOTHING IS READ FIRST ─────────────────\n *\n * `PUT /api/v2/Transactions/{transaction_key}/Items/{item_key}/Attendee` takes the\n * transaction's key and the ticket's own, creates the attendee where there is none\n * and rebinds where there is, and answers nothing it could be useful to hold. There\n * is no id to have minted and kept, and no list to have sent whole: one ticket is\n * named by one call, and the next edit of the same ticket is the same call again.\n *\n * THE PLATFORM SCOPES THE PAIR, refusing a key from another transaction with\n * `ItemNotFound` — the check that keeps a photographed QR code from renaming a\n * stranger's ticket.\n */\n try {\n await client.setItemAttendee(transactionKey, ticketKey, itemAttendeeBody(holder));\n return true;\n } catch (error) {\n /*\n * A REFUSAL BECOMES `false` AND ANYTHING ELSE KEEPS TRAVELLING — `signInGateway`'s\n * line, and for the same reason: the platform declining an edit is an answer, and a\n * request that never reached it is not.\n */\n if (refused(error)) return false;\n throw error;\n }\n },\n\n /**\n * SEND A COPY OF ONE TICKET TO AN ADDRESS.\n *\n * BY THE NUMERIC ID AND NOT THE KEY — `AttendeeTicket.ID`, which is what the endpoint\n * takes and which `readTicket` carries as `attendeeTicketId`. It is `0` on a ticket the\n * attendee-ticket list did not answer for, and a send addressed to nothing would be a\n * request the platform cannot place. The caller gates on that; this states it again\n * rather than trusting it, because a `0` reaching the wire is an email nobody gets and\n * no error either.\n */\n async sendTicket(attendeeTicketId: number, email: string): Promise<boolean> {\n if (attendeeTicketId <= 0) return false;\n try {\n await client.sendTicketEmail(attendeeTicketId, email);\n return true;\n } catch (cause: unknown) {\n /*\n * A REFUSED ADDRESS AND A BROKEN PLATFORM READ THE SAME HERE, which is the one\n * place this file does not split them: the endpoint answers a bare string and says\n * nothing about WHY, so a card claiming to know would be inventing it. The buyer is\n * told it did not go and may try again.\n */\n warn('the ticket could not be sent', cause);\n return false;\n }\n },\n\n async code(key: string): Promise<string | null> {\n /*\n * THE KEY IS THE CODE'S CONTENT. It goes through `URLSearchParams` inside the client,\n * so a key carrying a `+` or a `/` survives the trip. The two colours are baked into\n * the document the platform paints — see `TICKET_PAPER`, which is where that is\n * argued about.\n */\n const svg = await client.getQrCode(key, TICKET_INK, TICKET_PAPER);\n return isTicketCode(svg) ? svg : null;\n },\n };\n}\n\n/** Named, so a shape change in either response is one line in a console rather than a hunt. */\nfunction warn(message: string, cause: unknown): void {\n if (typeof console === 'undefined') return;\n console.warn(`[ScopeTicketsCheckout] ${message}`, cause);\n}\n\n/** Whether an error from the transport is the platform refusing, or something worse. */\nfunction refused(error: unknown): boolean {\n return (\n typeof error === 'object' && error !== null && (error as { name?: unknown }).name === 'ApiError'\n );\n}\n","/**\n * WHO THE ORDER IS NAMED FOR — one buyer, composed from the three sources that can answer\n * for them, and the only value anything downstream is allowed to build a payload from.\n *\n * ── THE BUG THIS IS ─────────────────────────────────────────────────────────\n *\n * There were already two sources and they were read in two different places. The FLOW\n * asked both: `excusedByIntent` for what the host and the buyer have answered, then\n * `requirementGate` for what the ACCOUNT answers, which is what lets a signed-in buyer\n * walk past Name, Email and Phone. The PAYLOAD asked only the first — `standing.buyer`,\n * four times over, at each of the three `setBuyer` calls and again at the card field.\n *\n * So signing in skipped the three steps and then sent `Email: ''`, and the platform said\n * \"Email is not a valid email address\" the moment the flow reached Review. The buyer was\n * never asked and their account was never spent: the two readings of \"is this answered?\"\n * disagreed, and the one that could see the account was not the one filling the order.\n *\n * ── WHAT THIS PROMISES ──────────────────────────────────────────────────────\n *\n * A field is here EXACTLY when the flow considers it answered, because both readings now\n * come from the same two functions in the same order. `order-buyer.test.ts` binds that to\n * `walkPurchase`: a requirement this holds is a step the walk skips, and a requirement it\n * lacks is a step the buyer is shown — so an order can no longer go out missing a field\n * nobody was asked for, in either direction.\n *\n * ── PRECEDENCE: WHOEVER ANSWERED LAST, THEN THE HOST, THEN THE ACCOUNT ──────\n *\n * The intent first and the account second, which is the order `checkout-preflight`'s\n * `order-requirements` check already walks — and the intent standing here is the FOLDED\n * one, so a value the buyer typed into the widget is already in front of the host's. The\n * account answers only what neither did, which is the one thing it is for.\n */\n\nimport type { BuyerDetails } from '@scopetickets/api';\nimport { requirementGate, type AuthState, type OrderRequirementId } from './auth';\nimport { splitFullName } from './contact';\nimport { answeredBuyer, type IntentBuyer, type OrderIntent } from './order-intent';\n\n/**\n * THE BUYER THE ORDER IS PLACED FOR, from everything known about them.\n *\n * THE INTENT GOES THROUGH `answeredBuyer`, exactly as `excusedByIntent` does — so a field\n * a payment provider would refuse is not treated as an answer here either, and the\n * account gets its turn at it rather than the order carrying it to the card machine.\n */\nexport function orderBuyer(intent: OrderIntent, auth: AuthState): IntentBuyer {\n const answered = answeredBuyer(intent.buyer);\n const email = answered.email ?? accountAnswer(auth, 'EMAIL');\n const phone = answered.phone ?? accountAnswer(auth, 'PHONE');\n return {\n ...buyerName(answered, auth),\n ...(email === undefined ? {} : { email }),\n ...(phone === undefined ? {} : { phone }),\n };\n}\n\n/**\n * THE NAME IS ALL OR NOTHING, and both halves come from ONE source.\n *\n * `excusedByIntent` excuses NAME only when the intent holds both halves, so a host that\n * knows the first name and not the surname has NOT answered it — and the account then\n * does, which is what makes the step drop out of the walk. Taking \"Ada\" from the host and\n * \"Hopper\" from the account would name the order after a person who does not exist; the\n * lone half is the Name step's prefill, which reads the intent itself.\n */\nfunction buyerName(answered: IntentBuyer, auth: AuthState): IntentBuyer {\n const { firstName, lastName } = answered;\n if (firstName !== undefined && lastName !== undefined) return { firstName, lastName };\n const full = accountAnswer(auth, 'NAME');\n /* Non-null by the gate, which refuses a stored name that does not give both halves. */\n return full === undefined ? {} : (splitFullName(full) ?? {});\n}\n\n/** What the account will answer a requirement with, or nothing where it cannot. */\nfunction accountAnswer(auth: AuthState, requirement: OrderRequirementId): string | undefined {\n const gate = requirementGate(auth, requirement);\n return gate.kind === 'ANSWERED' ? gate.value : undefined;\n}\n\n/**\n * THE PLATFORM'S SHAPE, written once.\n *\n * AN ABSENT FIELD STILL GOES, as the empty string it has always gone as. A field missing\n * here is a field the flow believed answered and could not produce, which is a bug in the\n * composition above — and the honest end of it is the platform refusing the order in front\n * of the buyer, not a Pay press that quietly does nothing. `buyerForFrame` is the floor\n * under the charge itself and refuses there; this one reports.\n *\n * THE PHONE IS OMITTED RATHER THAN EMPTIED, because `BuyerDetails` has it optional and the\n * flow does not always ask for one.\n */\nexport function buyerDetails(buyer: IntentBuyer): BuyerDetails {\n return {\n FirstName: buyer.firstName ?? '',\n LastName: buyer.lastName ?? '',\n Email: buyer.email ?? '',\n ...(buyer.phone === undefined ? {} : { Phone: buyer.phone }),\n };\n}\n","/**\n * The steps of a purchase, in the buyer's order, and what the resting pill's action\n * says at each.\n */\n\nimport type { AuthCheckpoint } from './auth';\nimport { AUTH_COPY } from './auth-copy';\n\n/**\n * What the island shows when this step is the next thing and the buyer has not pressed\n * anything yet.\n */\nexport type CollapsedState =\n | { readonly kind: 'PILL'; readonly actionLabel: string }\n | { readonly kind: 'NONE'; readonly reason: string };\n\n/** In the flow's own order, so the union reads as the sequence it names. */\nexport type PurchaseStepId =\n | 'PARTY'\n | 'DATE'\n | 'TIME'\n | 'SIGN_IN'\n | 'NAME'\n | 'EMAIL'\n | 'PHONE'\n | 'DETAILS'\n | 'REVIEW'\n | 'PAYMENT'\n | 'PROMO'\n | 'ABANDON'\n | 'PROCESSING'\n | 'PAYMENT_FAILED'\n | 'PAYMENT_SUCCESS'\n | 'FEEDBACK'\n | 'CREATE_ACCOUNT'\n | 'CONFIRM_EMAIL'\n | 'VERIFY_EMAIL'\n | 'PASSWORD'\n | 'PROFILE_PHOTO'\n | 'ACCOUNT_CREATING'\n | 'ACCOUNT_CREATED'\n | 'PASSKEY'\n | 'FOLLOW';\n\n/** Which half of the purchase a step belongs to. */\nexport type PurchaseChunk = 'COMPOSE' | 'COMMIT' | 'COMPLETE';\n\nexport type PurchaseStep = {\n readonly id: PurchaseStepId;\n readonly chunk: PurchaseChunk;\n /** What the step IS, for a caption. Never shown in the island. */\n readonly name: string;\n /** The auth checkpoint this step IS, where it is one. */\n readonly checkpoint?: AuthCheckpoint;\n /** so the two can be diffed by hand. */\n readonly islandState: string;\n /**\n * The `PreflightStep.id` that sends a buyer here, or `null` where no single check does\n * — `REVIEW` is where everything continuing lands, and `PROCESSING` is reached by\n * paying rather than by a check.\n */\n readonly preflightStepId: string | null;\n /** The step this one is a DETOUR from, where it is not walked to at all. */\n readonly detourFrom?: PurchaseStepId;\n /** Why a buyer is here, for the gallery's notes column. */\n readonly blurb: string;\n /** When this step is passed over, or absent when it always runs. */\n readonly excusedWhen?: string;\n readonly collapsed: CollapsedState;\n};\n\nconst pill = (actionLabel: string): CollapsedState => ({ kind: 'PILL', actionLabel });\n\n/** PLACEHOLDER LABELS, except \"Select Day\", which is the one the design gave. */\nexport const PURCHASE_STEPS: readonly PurchaseStep[] = [\n {\n id: 'PARTY',\n chunk: 'COMPOSE',\n name: 'Party Size',\n islandState: 'party',\n preflightStepId: 'party-size',\n blurb:\n 'Who is coming, and how many — the user-type stepper, one count per type, so the headcount is the sum rather than a second number that can disagree. A user type is NOT necessarily a price: it may grant a discount, gate whether a ticket is visible at all, or simply be recorded as a datum. It opens the funnel because in the first two cases nothing below can be quoted or even listed until it is answered — and it costs no request and no account.',\n excusedWhen:\n 'No type is relevant to the event, leaving everyone on the fallback type — or the composition is already constructed in the OrderIntent, which is what happens when an implementation renders its own party selector in Compose. A host that composes its own party is the second case: its party selector fills the composition before the island is ever asked. EXCUSED, NOT ABSENT — the island still carries this step for implementations that defer Compose to it.',\n collapsed: pill('Select Party'),\n },\n {\n id: 'DATE',\n chunk: 'COMPOSE',\n name: 'Select Day',\n islandState: 'date',\n preflightStepId: 'series-date',\n blurb:\n 'A series is a run of linked events and only ONE is bought, so nothing below has a subject until a day is picked. IT OPENS ON THE CALENDAR: the splash that used to introduce it — \"This Event Runs Over Several Days\" — is gone, because a card whose only content is the name of the next card costs a tap and teaches nothing the pill did not already say.',\n excusedWhen:\n 'The event is a plain one with no run behind it and therefore no day to choose — or a day has already been chosen, which is what lets the same preflight be re-run after the picker and carry on past this step.',\n collapsed: pill('Select Day'),\n },\n {\n id: 'TIME',\n chunk: 'COMPOSE',\n name: 'Select Time',\n islandState: 'time',\n preflightStepId: 'select-time',\n blurb:\n 'A timeslot hangs off a TICKET, and it is part of what is being bought, so it must precede the cart. IT IS NOT TIED TO A CHOSEN DAY: multiple days are a property of a SERIES, and a single-day event sells timed sessions just as readily — for one of those the time is the first thing asked and no day step runs at all. Where a series IS involved this follows the day, because the day is what resolves which event’s ticket the slots hang off. THE LAST STEP BEFORE THE ORDER EXISTS: what its Continue presses is Add to Cart.',\n excusedWhen:\n 'The chosen event sells no timeslots, which is most of them — or a slot has already been chosen. This is the one predicate that must READ rather than answer from memory: which slots exist depends on the event the day resolved to, and a sync answer would report “no timeslots” for a request still in flight and walk the buyer straight past the picker.',\n collapsed: pill('Select Time'),\n },\n {\n id: 'SIGN_IN',\n chunk: 'COMMIT',\n name: 'Sign In',\n checkpoint: 'ORDER_CREATED',\n islandState: 'login',\n preflightStepId: 'signed-in',\n blurb:\n 'Where the order meets an identity, and the first step of Commit. IT COMES AFTER ADD TO CART, which is the shape of the whole flow: compose an OrderIntent, convert it to a pending order, and only then ask whose it is — there is nothing to attach to an account before that, and nothing to check out as a guest either, which is why the same card offers a guest button here and none at `IDLE`. THIS STEP IS THE `ORDER_CREATED` CHECKPOINT — one of three places the flow asks about an account, and the only one that is a purchase step at all. Which card it draws is CONTENT decided by what is already known about the buyer, not a second step: an unrecognised buyer is asked one way and one we hold a profile for another. See `authPrompt` in `@/domain/auth`, which owns all nine cells and is the only one of these checks that is code so far.',\n excusedWhen:\n \"The buyer is already authenticated — the commonest case by far, since the identity is inherent to the account rather than collected per purchase — or they have taken the guest route for this order, or the implementation authenticates its own buyer and hands the identity in. All three are `authPrompt('ORDER_CREATED', session)` returning BYPASS.\",\n /*\n * NOT \"Sign In\", WHICH IS ONE OF TWO ROUTES OFF A CARD THAT OFFERS BOTH. The pill is\n * what a buyer meets the moment their tickets are in hand, and telling them to sign in\n * there both overstates what is required — guest checkout is right behind it — and\n * borrows `AUTH_COPY.SIGN_IN`, which is the label of the BUTTON that signs somebody in.\n * A way into a checkout and the action of authenticating are not the same words.\n *\n * \"Check Out\" and not \"Buy\": these tickets may be free, and a pill promising a purchase\n * would be wrong on every free event. Checking out is completing an order, whatever it\n * costs. It also keeps the register of every other collapsed label here — a verb and\n * its object, \"Select Day\", \"Review Order\" — which a bare \"Continue\" would not.\n */\n collapsed: pill('Check Out'),\n },\n {\n id: 'NAME',\n chunk: 'COMMIT',\n name: 'Name',\n islandState: 'question-name',\n preflightStepId: 'order-requirements',\n blurb:\n 'What to call the buyer. The first of the ORDER REQUIREMENTS — the minimum an order needs before the platform will accept it — and the three of them sit here, below the identity, for two reasons that agree: an account holder has already answered every one, so asking first would ask the commonest buyer for what we hold; and the SDK puts them here anyway, `createCart` → `addItemsBulk` → `setBuyer`, on an order that exists by the time the buyer is named.',\n excusedWhen:\n 'The buyer already has a name — which is nearly always, since a signed-in account carries one. THE OTHER HALF OF THIS PREDICATE IS NOT BUILT: the platform exposes no way to ask which requirements an order actually has, so this step can only be excused by what the OrderIntent already holds, never by the event not wanting it.',\n collapsed: pill('Add Name'),\n },\n {\n id: 'EMAIL',\n chunk: 'COMMIT',\n name: 'Email Address',\n islandState: 'question-email',\n preflightStepId: 'order-requirements',\n blurb:\n 'Where the tickets go. The one requirement no order can do without, and the only field in the flow that checks its own contents as they are typed — see `emailFlag`.',\n excusedWhen: 'The buyer already has an email. Same missing half as `NAME`.',\n collapsed: pill('Add Email'),\n },\n {\n id: 'PHONE',\n chunk: 'COMMIT',\n name: 'Phone Number',\n islandState: 'question-phone',\n preflightStepId: 'order-requirements',\n blurb:\n 'For booking confirmations and account recovery. It carries a COUNTRY, which is what its check is against — the same digits are a valid number in one plan and not in another.',\n excusedWhen:\n 'The buyer already has a phone number, OR the order does not require one — which is the likeliest of the three to be genuinely optional, and the one where not being able to ask the platform hurts most.',\n collapsed: pill('Add Phone'),\n },\n {\n id: 'DETAILS',\n chunk: 'COMMIT',\n name: 'More Information',\n islandState: 'details',\n preflightStepId: 'questionnaire',\n blurb:\n 'The event’s own questions — the last thing the order can still be missing. Needs the cart, which is the only source of the integer EventId the questions endpoint takes, and by here the cart is four steps old.',\n excusedWhen:\n 'The event asks nothing. A failed LOOKUP is NOT this — it resolves to a notice, because proceeding would let the buyer reach payment and be rejected server-side with nothing on screen to fix.',\n collapsed: pill('Add Details'),\n },\n {\n id: 'REVIEW',\n chunk: 'COMMIT',\n name: 'Order Review',\n islandState: 'expanded',\n preflightStepId: null,\n blurb:\n 'Where everything continuing lands. Nothing is in the way, the cart is held, and the only thing left is to pay. THE DEFAULT DESTINATION OF A READY ORDER — and the only card that offers the payment list, which hangs off it as a detour rather than standing in front of it.',\n collapsed: pill('Review Order'),\n },\n {\n id: 'PAYMENT',\n chunk: 'COMMIT',\n name: 'Payment Method',\n islandState: 'payment',\n /*\n * NOT A DESTINATION ANY MORE — see `detourFrom`. It was `payment-method`, check 8 of\n * the ported preflight.\n */\n preflightStepId: null,\n detourFrom: 'REVIEW',\n blurb:\n 'The list of ways to pay, opened from Order Review’s own “Select Payment Method” and from nowhere else. IT IS NOT IN THE SEQUENCE: an order that is ready for payment opens on Order Review with a method already chosen, and a buyer who is happy with it never sees this card. Conall, 2026-09-08. It was the last of the preflight’s checks — a buyer with no method on file was SENT here — which put a list of cards between them and a Pay button they had not asked to leave.',\n collapsed: pill('Select Payment'),\n },\n {\n id: 'PROMO',\n chunk: 'COMMIT',\n name: 'Promo Code',\n islandState: 'promo',\n preflightStepId: null,\n detourFrom: 'REVIEW',\n blurb:\n 'A code off the order’s total, opened from the header’s own pill and from nowhere else. IT IS NOT IN THE SEQUENCE: nothing sends a buyer here and nothing waits for them to come back — an order with no code is an order at its full price, which is what every order is until somebody says otherwise. ONE PER ORDER, which is the wire’s rule and not a choice: the cart carries a single `PromoCode`, so a second replaces the first.',\n collapsed: pill('Promo Code'),\n },\n {\n id: 'ABANDON',\n chunk: 'COMMIT',\n name: 'Leaving the Order',\n islandState: 'abandon',\n preflightStepId: null,\n detourFrom: 'REVIEW',\n blurb:\n 'What the way out asks once there is something to lose. From Compose the cross costs nothing — no cart is open and nothing is held — but an accepted OrderIntent is stock taken off sale on this buyer’s behalf, and closing the card gives it back. So past that point the cross opens this instead of closing, and the buyer says which they meant. IT IS NOT IN THE SEQUENCE: nothing walks here and nothing waits for it, and returning is the whole of one of its two answers.',\n collapsed: {\n kind: 'NONE',\n reason:\n 'The design draws the header at zero opacity: there is no way out but the two answers, and a cross here would be a third — one that closes without saying which the buyer meant, on the very card asking them to say.',\n },\n },\n {\n id: 'PROCESSING',\n chunk: 'COMMIT',\n name: 'Processing',\n islandState: 'processing',\n preflightStepId: null,\n blurb:\n 'The payment is in flight. Reached by paying rather than by a check, and the buyer cannot leave.',\n collapsed: {\n kind: 'NONE',\n reason:\n 'Input is blocked entirely — there is no way out and nothing to collapse to. A pill here would offer an action that must not be available.',\n },\n },\n {\n id: 'PAYMENT_FAILED',\n chunk: 'COMMIT',\n name: 'Payment Failed',\n islandState: 'payment-failed',\n preflightStepId: null,\n /*\n * NOT WALKED TO, like the payment list — but reached by an EVENT rather than by a\n * control, which is the one way it differs from every other detour here. Nothing in\n * the flow decides a payment fails.\n */\n detourFrom: 'PROCESSING',\n blurb:\n 'The design. What the buyer meets when a payment is declined: the reason the provider gave, the same method offered again, and the way to a different one. THE ORDER IS STILL PENDING — nothing was taken, the hold is still running, and the header comes back with it, which is why this is COMMIT and not COMPLETE. It is the one card here that the widget cannot reach on its own: there is no payment integration to fail, so a host says it did.',\n collapsed: pill('Try Again'),\n },\n {\n id: 'PAYMENT_SUCCESS',\n chunk: 'COMPLETE',\n name: 'Payment Successful',\n islandState: 'payment-successful',\n preflightStepId: null,\n blurb:\n 'The design, and the first step of Complete. The money has moved and the tickets are the buyer’s; everything after this is an OFFER rather than a requirement. It thanks the buyer BY NAME where there is one to use — see `paymentSuccessSubtitle` — and drops the cart summary, because a placed order has no hold left to count.',\n collapsed: pill('View Order'),\n },\n {\n id: 'FEEDBACK',\n chunk: 'COMPLETE',\n name: 'Rate Your Purchase',\n islandState: 'feedback',\n preflightStepId: null,\n blurb:\n 'Five stars over the question \"How Was Your Purchase?\". IT IS ASKED HERE AND NOT AT THE END, one card after the money moved, because the purchase is the thing that just happened — everything below this is an OFFER the buyer may or may not take, and a rating collected after the account sub-flow would be a rating of the sub-flow for the buyers who took it and of the checkout for the buyers who did not. Asked in one place, the answers compare. NOTHING IS REQUIRED: Skip goes the same place Continue does, and Continue is shut until a star is chosen — a rating of none is not a rating, and a button that sends nothing is worse than one that waits.',\n /*\n * NO `excusedWhen`, AND THAT IS A DECISION RATHER THAN AN OMISSION. A buyer standing\n * here has bought a ticket, which is a thing that can be rated — so there is no state\n * of the flow that makes this card pointless to draw.\n *\n * WHICH TICKET IS A SEPARATE QUESTION, and it is not one the walk can answer: the walk\n * is planned before the payment exists, and the attendee ticket is named by the payment\n * that creates it. See `PaymentOutcome`, which carries it, and the widget's own warning\n * for the case where nothing named one.\n */\n collapsed: pill('Rate Purchase'),\n },\n {\n id: 'CREATE_ACCOUNT',\n chunk: 'COMPLETE',\n name: 'Create Account',\n checkpoint: 'ORDER_SUCCESS',\n islandState: 'create-account',\n preflightStepId: null,\n blurb:\n 'Offered once the order is placed, on a card that reads \"Add to Account\". THIS STEP IS THE `ORDER_SUCCESS` CHECKPOINT, the third and last place the flow asks about an account, and the only one that costs the buyer nothing to decline: the order is placed and the tickets are theirs either way. A guest has just typed everything an account needs, so what is actually asked for is the one thing it does not yet have — a password, which is the step below. Reached by paying rather than by a check, like everything else in this chunk.',\n collapsed: pill(AUTH_COPY.CREATE_ACCOUNT),\n },\n {\n id: 'CONFIRM_EMAIL',\n chunk: 'COMPLETE',\n name: 'Confirm Email',\n islandState: 'confirm-email',\n preflightStepId: null,\n blurb:\n 'Reached by pressing Create Account on the offer. THE ADDRESS IS ALREADY KNOWN — the order carries it, and it is shown pre-filled rather than asked for — so what this step is really for is CONSENT: the buyer is being told which address is about to become their account, and given the chance to make it a different one before a code goes to the wrong inbox. Editable for exactly that reason.',\n excusedWhen: 'The buyer declined the account, or already had one.',\n collapsed: pill('Confirm Email'),\n },\n {\n id: 'VERIFY_EMAIL',\n chunk: 'COMPLETE',\n name: 'Verify Email',\n islandState: 'verify-email',\n preflightStepId: null,\n blurb:\n 'Six boxes and a code. THE ONLY STEP IN THE FLOW THAT CAN BE COMPLETED SOMEWHERE ELSE: the mail may arrive on a phone and the code be entered there, which is why the platform is polled for the answer rather than only being told what this browser typed. Re-send is shut for thirty seconds after a code goes out — see `RESEND_COOLDOWN_MS`, which also records that the design draws 72.',\n excusedWhen: 'The buyer declined the account, or already had one.',\n collapsed: pill('Verify Email'),\n },\n {\n id: 'PASSWORD',\n chunk: 'COMPLETE',\n name: 'Add Password',\n islandState: 'question-password',\n preflightStepId: null,\n blurb:\n 'The one field an account needs that an order does not — which is why it is here and not among the requirements above. Two fields, and the second counts itself against the first rather than against the rule; see `confirmPasswordCounter`.',\n excusedWhen:\n 'The buyer declined the account, or already had one. Written even though this chunk does not require it: the step really is skippable, and saying so is cheaper than the reader working out whether the omission was meaningful.',\n collapsed: pill('Add Password'),\n },\n {\n id: 'PROFILE_PHOTO',\n chunk: 'COMPLETE',\n name: 'Profile Photo',\n islandState: 'profile-photo',\n preflightStepId: null,\n blurb:\n 'A face for the account, chosen from the stock set or uploaded. THE LAST THING ASKED BEFORE THE ACCOUNT IS MADE, so what the buyer picks is part of the account rather than an edit to one that already exists — and the hero above the grid wears the choice as it is made, which is the only preview of an avatar worth having. The photos are the PLATFORM’s, like the calendar’s days: the widget owns the grid and none of its faces. It stays ahead of the account even though `PUT /api/Users/Photo` needs a session to accept it: the choice is made here and SPENT inside the wait on `ACCOUNT_CREATING`, one call after the account is minted, so the buyer picks a face for an account they are making rather than editing one they already have.',\n excusedWhen:\n 'The buyer declined the account, or already had one — or nobody supplied a stock set, which leaves the card with nothing to offer and no reason to be drawn.',\n collapsed: pill('Add Photo'),\n },\n {\n id: 'ACCOUNT_CREATING',\n chunk: 'COMPLETE',\n name: 'Creating Account',\n islandState: 'account-creating',\n preflightStepId: null,\n blurb:\n 'The card that is up while the account is being made. NOT A STEP THE BUYER DOES ANYTHING ON — it draws no buttons and takes no input, like `PROCESSING` before it. It is held for a moment even when the call is quick: see `ACCOUNT_CREATING_FLOOR_MS`, and `PROCESSING_FLOOR_MS`, which is the same rule for the same reason.',\n excusedWhen: 'The buyer declined the account, or already had one.',\n collapsed: { kind: 'NONE', reason: 'Input is blocked while the account is being created.' },\n },\n {\n id: 'ACCOUNT_CREATED',\n chunk: 'COMPLETE',\n name: 'Account Created',\n islandState: 'account-created',\n preflightStepId: null,\n blurb:\n 'The account exists, said once and by name — \"Welcome, Alex!\" over the face they just chose. It is the counterpart of `PAYMENT_SUCCESS` and it is there for the same reason: the card before it was a wait with no buttons, and a wait that ends by silently becoming the next question leaves nobody sure anything happened. Its Continue rejoins the flow where the account route left it.',\n excusedWhen: 'The buyer declined the account, or already had one.',\n /*\n * A VERB AND ITS OBJECT, like every other pill here — see `SIGN_IN`'s note on why a\n * bare \"Continue\" is not one, even though that is what the card's own button says.\n * `PAYMENT_SUCCESS` made the same choice for the same kind of card: the pill names\n * what pressing it opens, and what this one opens is the new account's welcome.\n */\n collapsed: pill('View Account'),\n },\n {\n id: 'PASSKEY',\n chunk: 'COMPLETE',\n name: 'Create a Passkey',\n islandState: 'passkey',\n preflightStepId: null,\n blurb:\n 'Offered once the account exists, and skippable. THE CHEAPEST ROUTE BACK IN there is — a face or a fingerprint against a password typed on a phone. It is here rather than before the account because the platform mints its challenge from the SESSION: `POST /api/Passkeys/Registrations/Challenges` is told only whether the credential should be discoverable and names the user itself, so until the account exists there is nobody for it to name. Standing as its own card also earns the ceremony the fresh user gesture WebAuthn requires — an intent collected earlier and registered later would have spent it two screens back. A device with no authenticator, or a buyer who does not want one, presses Not Now.',\n excusedWhen:\n 'The buyer declined the account, or already had one — or the device offers no authenticator, which is a question only the browser can answer.',\n collapsed: pill('Create Passkey'),\n },\n {\n id: 'FOLLOW',\n chunk: 'COMPLETE',\n name: 'Follow Prompt',\n islandState: 'follow',\n preflightStepId: null,\n blurb:\n 'Everyone behind the event — organiser, ticketing partner, venue, artists — offered for subscription before the buyer goes on to their ticket. Nothing is required and nothing is refused: the primary button follows the selection and goes the same place either way.',\n excusedWhen: 'The event has nobody to follow.',\n collapsed: pill('Stay Updated'),\n },\n];\n\n/**\n * WHICH STEPS ARE ANSWERED BY BEING READ, though they draw a control.\n *\n * A card with a control is normally answered when the control says so, and that is what\n * every field, picker and list here reports. The FOLLOW prompt is the exception, and its\n * own blurb has said so since it was written — \"nothing is required and nothing is\n * refused: the primary follows the selection and goes the same place either way\". A list\n * of checkboxes never reports itself answered, so the rule and the gate disagreed and a\n * buyer who wanted to follow nobody had no way forward at all.\n *\n * A PREDICATE BECAUSE IT WAS GOT WRONG, and because the next step like it belongs here\n * rather than in a third condition inside a component.\n */\nexport function answeredByReading(id: PurchaseStepId): boolean {\n return id === 'FOLLOW';\n}\n\nexport function purchaseStep(id: PurchaseStepId): PurchaseStep {\n const step = PURCHASE_STEPS.find((candidate) => candidate.id === id);\n // Unreachable while `PurchaseStepId` and the array agree, which the tests assert.\n if (!step) throw new Error(`unknown purchase step: ${id}`);\n return step;\n}\n","/** Whether there is an order yet, and whether it has been paid for. */\n\nimport type { AuthCheckpoint } from './auth';\nimport { PURCHASE_STEPS, purchaseStep, type PurchaseStepId } from './purchase-steps';\n\n/** The order, as three states rather than two booleans. */\nexport type OrderStatus =\n /**\n * Nothing has been proposed. The island is composing a selection, and there is neither\n * a cart to summarise nor a hold to count.\n */\n | 'NONE'\n /**\n * PLACED: an OrderIntent has been accepted and converted to an order. The buyer has\n * committed to a product at a price and nothing has been paid yet — it is held, unpaid,\n * and on a clock, which is the one state the header summarises.\n *\n * NAMED FOR THE HOLD AND NOT FOR THE COMMITMENT, though placing the order is what\n * causes it. `PaymentOutcome.kind` already has a `PLACED`, meaning the payment went\n * through, and that one is on a PUBLIC prop a host implements — so it is the name that\n * cannot move. Two `PLACED`s three lines apart in `ScopeTicketsCheckout`, one either\n * side of the money, is worse than a synonym.\n */\n | 'HELD'\n /**\n * Paid. The tickets are the buyer's, nothing can change, and there is no hold left to\n * run. Fulfilment is the platform's from here, and the order is not COMPLETE until it\n * has happened — a distinction this type does not carry because the widget is gone by\n * then.\n */\n | 'PAID';\n\n/**\n * The step at which an order first exists — the one carrying the `ORDER_CREATED`\n * checkpoint.\n */\nconst ORDER_CREATED_INDEX = PURCHASE_STEPS.findIndex((step) => step.checkpoint === 'ORDER_CREATED');\n\nexport function orderStatusAt(id: PurchaseStepId): OrderStatus {\n const index = PURCHASE_STEPS.findIndex((step) => step.id === id);\n // Unreachable while `PurchaseStepId` and the array agree, which\n // `purchase-steps.test.ts` asserts.\n if (index === -1) throw new Error(`unknown purchase step: ${id}`);\n\n // PAID FIRST, because it is the outer boundary: every COMPLETE step is also past\n // ORDER_CREATED, so asking in the other order would report all three of them as\n // HELD.\n if (PURCHASE_STEPS[index]?.chunk === 'COMPLETE') return 'PAID';\n return index < ORDER_CREATED_INDEX ? 'NONE' : 'HELD';\n}\n\n/** The same reading, for the two checkpoints that are not steps. */\nexport function orderStatusAtCheckpoint(checkpoint: AuthCheckpoint): OrderStatus {\n if (checkpoint === 'IDLE') return 'NONE';\n\n const step = PURCHASE_STEPS.find((candidate) => candidate.checkpoint === checkpoint);\n if (!step) throw new Error(`no purchase step carries the ${checkpoint} checkpoint`);\n return orderStatusAt(step.id);\n}\n\n/** Whether the header carries the cart summary. */\nexport function cartIsHeld(status: OrderStatus): boolean {\n return status === 'HELD';\n}\n\n/**\n * WHETHER A HOLD THAT HAS RUN OUT IS THE BUYER'S PROBLEM AT THIS STEP — which is not the\n * same question as whether it ran out. Two steps must not be interrupted by it, for\n * opposite reasons.\n *\n * PAST THE PAYMENT nothing is held any more: a buyer reading \"Thank you\" is not dragged\n * back to a lapsed clock because fifteen minutes went by. DURING it the answer is not in\n * yet — a hold that lapses while the bank is deciding is a race the provider's news wins,\n * not our clock — and a step with no pill to collapse to IS that step, which is why the\n * hold covering Processing is not enough on its own.\n */\nexport function timeoutTakesOver(id: PurchaseStepId): boolean {\n if (!cartIsHeld(orderStatusAt(id))) return false;\n return purchaseStep(id).collapsed.kind === 'PILL';\n}\n\n/**\n * WHETHER PRESSING THIS STEP'S BUTTON IS WHAT CREATES THE ORDER — asked of the walk,\n * because there is no one step it is always true of.\n *\n * The press is Add to Cart, and which card carries it depends on the event: Select Time\n * on a run that sells sessions, Select Day on one that does not, Party Size on a plain\n * event with neither, and NO card at all where the host composed the order itself and\n * the island opens past the cart. Naming Select Time here — the longest walk's answer —\n * would label the button on one event in three and leave the rest saying Continue into a\n * cart.\n *\n * So the question is asked of the pair: the last stop with no order behind it, whose\n * next stop has one.\n */\nexport function pressCreatesOrder(here: PurchaseStepId, next: PurchaseStepId | undefined): boolean {\n if (next === undefined) return false;\n return orderStatusAt(here) === 'NONE' && orderStatusAt(next) !== 'NONE';\n}\n","/**\n * THE EMAIL CODE — what is typed, whether it can be sent again, and what the flow may do\n * next.\n *\n * @Zsolt — AUTH SURFACE, but pure. It says WHEN a call should happen and what its answer\n * means; the calls are `sendEmailPasscode`, `verifyPasscode` and `getPasscodeStatus`.\n */\n\n/** The design draws six boxes, and the box count IS the code length. */\nexport const PASSCODE_LENGTH = 6;\n\n/**\n * THIRTY SECONDS, WHICH IS NOT WHAT THE DESIGN DRAWS — the node shows \"Re-send (72s)\".\n * Thirty is the instruction; recorded here so the discrepancy is not rediscovered.\n */\nexport const RESEND_COOLDOWN_MS = 30_000;\n\n/** Only digits, and never more than the boxes can hold. */\nexport function normalisePasscode(raw: string): string {\n return raw.replace(/\\D/g, '').slice(0, PASSCODE_LENGTH);\n}\n\n/** Whether what the buyer has typed is long enough to be worth submitting. */\nexport function passcodeComplete(code: string): boolean {\n return normalisePasscode(code).length === PASSCODE_LENGTH;\n}\n\n/**\n * The first empty box, or the last once full. Derived rather than stored: a cursor held\n * beside the value is a second thing that can disagree with it.\n */\nexport function passcodeCaretIndex(code: string): number {\n const filled = normalisePasscode(code).length;\n return Math.min(filled, PASSCODE_LENGTH - 1);\n}\n\n/**\n * WHERE THE CODE IS UP TO. One union rather than parallel flags, which could say two\n * things at once and could not tell \"failed\" from \"still going\".\n */\nexport type PasscodeState =\n /** Nothing sent. The Confirm Email step, before its button is pressed. */\n | { readonly status: 'IDLE' }\n /** A send is in flight. */\n | { readonly status: 'SENDING' }\n /**\n * A code is out and the buyer is typing. `sentAt` is what the cooldown counts from,\n * and `key` is what `getPasscodeStatus` reads.\n */\n | { readonly status: 'SENT'; readonly key: string; readonly sentAt: number }\n /** A code has been submitted and the platform has not answered yet. */\n | { readonly status: 'VERIFYING'; readonly key: string; readonly sentAt: number }\n /** Carries its send, so Re-send counts from the code going out, not from the guess. */\n | { readonly status: 'REJECTED'; readonly key: string; readonly sentAt: number }\n /** Verified. The only state the flow may move on from. */\n | { readonly status: 'VERIFIED'; readonly key: string }\n /** No code was issued. Distinct from REJECTED, which is a code that exists and was wrong. */\n | { readonly status: 'SEND_FAILED'; readonly reason: string };\n\nexport const PASSCODE_IDLE: PasscodeState = { status: 'IDLE' };\n\n/** The send this state belongs to, or `null` where no code is outstanding. */\nfunction outstandingSend(state: PasscodeState): { key: string; sentAt: number } | null {\n switch (state.status) {\n case 'SENT':\n case 'VERIFYING':\n case 'REJECTED':\n return { key: state.key, sentAt: state.sentAt };\n case 'IDLE':\n case 'SENDING':\n case 'VERIFIED':\n case 'SEND_FAILED':\n return null;\n }\n}\n\n/**\n * A REMAINDER RATHER THAN A TICKING NUMBER: the state records when the code went out and\n * this subtracts, so a backgrounded tab, a throttled clock and a re-mount all agree\n * where a decremented counter would drift.\n */\nexport function resendRemainingMs(state: PasscodeState, now: number): number {\n const send = outstandingSend(state);\n if (send === null) return 0;\n return Math.max(0, send.sentAt + RESEND_COOLDOWN_MS - now);\n}\n\n/** The countdown as the design writes it — whole seconds, rounded UP. */\nexport function resendRemainingSeconds(state: PasscodeState, now: number): number {\n return Math.ceil(resendRemainingMs(state, now) / 1000);\n}\n\n/**\n * OPEN IMMEDIATELY AFTER A FAILED SEND: nothing went out, and making a buyer serve a\n * cooldown for our outage punishes them for it.\n */\nexport function canResend(state: PasscodeState, now: number): boolean {\n if (state.status === 'SENDING' || state.status === 'VERIFYING') return false;\n if (state.status === 'VERIFIED') return false;\n if (state.status === 'SEND_FAILED' || state.status === 'IDLE') return true;\n return resendRemainingMs(state, now) === 0;\n}\n\n/** Whether Verify can be pressed — a full code, and nothing already in flight. */\nexport function canVerify(state: PasscodeState, code: string): boolean {\n if (!passcodeComplete(code)) return false;\n return state.status === 'SENT' || state.status === 'REJECTED';\n}\n\n/** Whether the flow may leave this step. */\nexport function passcodeSettled(state: PasscodeState): boolean {\n return state.status === 'VERIFIED';\n}\n\n// ── TRANSITIONS ──────────────────────────────────────────────\n// @Zsolt — each is the answer to one call. They take `now` rather than reading a clock,\n// so the cooldown is testable without waiting thirty seconds.\n\nexport function passcodeSending(): PasscodeState {\n return { status: 'SENDING' };\n}\n\nexport function passcodeSent(key: string, now: number): PasscodeState {\n return { status: 'SENT', key, sentAt: now };\n}\n\nexport function passcodeSendFailed(reason: string): PasscodeState {\n return { status: 'SEND_FAILED', reason };\n}\n\n/** Submitting the typed code. A no-op from anywhere a code is not outstanding. */\nexport function passcodeVerifying(state: PasscodeState): PasscodeState {\n const send = outstandingSend(state);\n if (send === null) return state;\n return { status: 'VERIFYING', key: send.key, sentAt: send.sentAt };\n}\n\n/** `true` from either route — this browser's post, or a status read from elsewhere. */\nexport function passcodeChecked(state: PasscodeState, verified: boolean): PasscodeState {\n const send = outstandingSend(state);\n if (send === null) return state;\n if (verified) return { status: 'VERIFIED', key: send.key };\n /* Carrying the original `sentAt`: a wrong guess neither adds nor clears a cooldown. */\n return { status: 'REJECTED', key: send.key, sentAt: send.sentAt };\n}\n","/**\n * MAKING AN ACCOUNT OUT OF AN ORDER — which step comes next, and what each needs.\n *\n * @Zsolt — AUTH SURFACE, and the file to start from. Pure: no client, no fetch, no React.\n * `AccountCreationGateway` below is the shape of the four calls, three of which exist on\n * `ScopeClient` already.\n *\n * A buyer who has just paid has given an account everything but two things: a verified\n * address and a credential. That is the whole sub-flow.\n */\n\nimport type { Account } from './auth';\nimport { PASSCODE_IDLE, passcodeSettled, type PasscodeState } from './passcode';\nimport type { PasskeyRegistrationChallenge, PasskeyRegistrationRequest } from '@scopetickets/api';\nimport type { Session } from './session';\nimport type { PurchaseStepId } from './purchase-steps';\n\n/**\n * The steps this sub-flow walks, in order. A subset of `PurchaseStepId`.\n *\n * NO PASSKEY HERE, though there is a `PASSKEY` step: it is offered AFTER the account\n * exists, because the challenge that opens the ceremony is minted from the session. See\n * `registerPasskey` below, and the step's own blurb in `purchase-steps.ts`.\n */\nexport type AccountCreationStepId =\n | 'CONFIRM_EMAIL'\n | 'VERIFY_EMAIL'\n | 'PASSWORD'\n | 'PROFILE_PHOTO'\n | 'ACCOUNT_CREATING';\n\n/**\n * AN ADDRESS AND ITS PROOF, AS ONE VALUE — because the platform joins the verified code\n * to the new account by the address STRING and nothing else. `POST /api/Users` carries\n * no passcode key, so the only thing standing between a buyer and an account on an\n * address nobody can read is that these two agree.\n *\n * They were two fields, and two fields can disagree. `VERIFY_EMAIL` is reversible — its\n * back arrow goes to the address behind it — so a buyer could return, type a DIFFERENT\n * address, and walk forward past a verification the old one had earned. Holding the code\n * inside the address makes that unrepresentable rather than something the reducer has to\n * remember.\n */\nexport type ConfirmedEmail =\n /** No address yet, and therefore no code. The `CONFIRM_EMAIL` step. */\n | { readonly status: 'UNCONFIRMED' }\n /** An address the buyer gave, and how far its code has got. */\n | {\n readonly status: 'CONFIRMED';\n /**\n * EXACTLY AS TYPED. Not lowercased and not trimmed: this is the string sent to\n * `POST /api/Passcodes/Email` and, later, to `POST /api/Users`, and the guarantee\n * is that they are the same string — which normalising in one place and not the\n * other is how it would be lost.\n */\n readonly address: string;\n readonly passcode: PasscodeState;\n };\n\n/**\n * WHAT HAS BEEN SETTLED. One record rather than a step pointer — the step derives from\n * it, and a pointer beside it is a second thing that can disagree.\n */\nexport type AccountCreationProgress = {\n /** The address, and the code that proves it. */\n readonly email: ConfirmedEmail;\n /** Whether a password has been set. */\n readonly passwordSet: boolean;\n /**\n * The avatar value the buyer chose — a `default:<id>` from the stock set, or the photo\n * they uploaded — and `null` before they have chosen. The account is made WITH it,\n * which is why it is settled here rather than edited afterwards.\n */\n readonly photo: string | null;\n};\n\nexport const ACCOUNT_CREATION_START: AccountCreationProgress = {\n email: { status: 'UNCONFIRMED' },\n passwordSet: false,\n photo: null,\n};\n\n/**\n * WHICH STEP THE BUYER BELONGS ON — the sequence as one function, so the order is read\n * in one place rather than inferred from five components.\n */\nexport function nextAccountStep(progress: AccountCreationProgress): AccountCreationStepId | null {\n /*\n * THE ADDRESS FIRST, confirmed rather than assumed: the order's address is where a\n * ticket goes and the account's is how somebody signs in.\n */\n if (progress.email.status === 'UNCONFIRMED') return 'CONFIRM_EMAIL';\n /*\n * Nothing is built on an address nobody has proved they can read — WHILE THERE IS A WAY\n * TO PROVE IT. With the passcode endpoints down the step is not in the walk, so asking\n * for a code here would stop the sub-flow at a card the buyer can never leave. See\n * `UNBUILT_ACCOUNT_STEPS`.\n */\n if (accountStepBuilt('VERIFY_EMAIL') && !passcodeSettled(progress.email.passcode)) {\n return 'VERIFY_EMAIL';\n }\n /*\n * A PASSWORD, AND NOT INSTEAD OF IT. The passkey is offered too, after the account\n * exists — but it is bound to one device, so an account holding no other credential is\n * one its owner can be locked out of by losing a phone. This step is the reason\n * declining the passkey costs a buyer nothing.\n */\n if (!progress.passwordSet) return 'PASSWORD';\n /*\n * THE FACE LAST, and last for a reason: it is the only thing asked here that the\n * account could live without, so it is the one question a buyer meets when everything\n * that would stop the account existing has already been answered.\n */\n if (progress.photo === null) return 'PROFILE_PHOTO';\n return 'ACCOUNT_CREATING';\n}\n\n/** Whether every question has been answered and only the call is left. */\nexport function accountCreationReady(progress: AccountCreationProgress): boolean {\n return nextAccountStep(progress) === 'ACCOUNT_CREATING';\n}\n\n/**\n * Only the code step goes back, to the address it was sent to — which is what Verify\n * Email's back arrow is for. Everything after it has been DONE rather than chosen.\n */\nexport function accountStepReversible(step: AccountCreationStepId): boolean {\n return step === 'VERIFY_EMAIL';\n}\n\n/**\n * ── STEPS THE DESIGN HAS AND THE PLATFORM CANNOT ANSWER YET ──────────────────\n *\n * Modelled the way `UNBUILT_AUTH_ROUTES` is, and for the same reason: \"the design has no\n * dead end\" and \"every route works today\" are two claims, and only one of them is\n * currently true. A step named here is drawn nowhere and walked by nobody — the card, the\n * reducer and the gateway call behind it all stay, tested, waiting for the endpoint.\n *\n * VERIFY EMAIL is the six boxes and the code. `POST /api/Passcodes/Email` and its\n * verification pair are not live, so a buyer would be asked for a code that was never sent\n * and could not be checked — a step with no way past it.\n *\n * PASSKEY is the registration ceremony. `POST /api/Passkeys/Registrations/Challenges`\n * answers nothing to mint a ceremony from, so the card would offer a credential the\n * platform cannot store. Signing in WITH a passkey is a different endpoint and is not\n * affected.\n *\n * ── WHAT REMOVING VERIFICATION COSTS, SAID OUT LOUD ─────────────────────────\n *\n * An account is now made on an address NOBODY HAS PROVED THEY CAN READ. That is the exact\n * failure `ConfirmedEmail` was shaped to prevent, and it is a deliberate trade while the\n * endpoints are missing rather than an oversight: the alternative is no account creation\n * at all. `addressForAccount` is where the suspended guarantee is written down, and the\n * day `VERIFY_EMAIL` leaves this record the old rule comes back with it, untouched.\n */\nexport const UNBUILT_ACCOUNT_STEPS: Partial<Record<PurchaseStepId, string>> = {\n VERIFY_EMAIL: 'The passcode endpoints are not live — no code can be sent or checked.',\n PASSKEY: 'Passkey registration is not live — there is no challenge to open a ceremony with.',\n};\n\n/** Whether a step of this sub-flow can be walked today. */\nexport function accountStepBuilt(step: PurchaseStepId): boolean {\n return UNBUILT_ACCOUNT_STEPS[step] === undefined;\n}\n\n/**\n * These ids are `PurchaseStepId`s too — asserted rather than assumed.\n *\n * FILTERED THROUGH THE ONE SWITCH, so the order a buyer walks and the list of what cannot\n * be walked are the same fact asked once. Writing the short order out by hand would be the\n * second copy that drifts the day an endpoint lands.\n */\nexport const ACCOUNT_CREATION_ORDER: readonly (AccountCreationStepId & PurchaseStepId)[] = (\n ['CONFIRM_EMAIL', 'VERIFY_EMAIL', 'PASSWORD', 'PROFILE_PHOTO', 'ACCOUNT_CREATING'] as const\n).filter(accountStepBuilt);\n\n// ── TRANSITIONS ──────────────────────────────────────────────\n\n/**\n * Confirming an address — the answer to `CONFIRM_EMAIL`, and the only way into\n * `CONFIRMED`.\n *\n * THE SAME ADDRESS KEEPS ITS CODE, so a buyer who goes back to check what they typed and\n * confirms it unchanged neither loses a verification nor serves the re-send cooldown a\n * second time. A DIFFERENT ADDRESS DISCARDS IT, which is the whole reason the code lives\n * inside the address.\n *\n * Compared byte for byte, and deliberately not case-insensitively: treating `A@x.test`\n * and `a@x.test` as one address costs a needless code if the platform agrees they are\n * the same, and creates an account on an unproved address if it does not. Only one of\n * those two mistakes can be taken back.\n */\nexport function confirmAddress(\n progress: AccountCreationProgress,\n address: string,\n): AccountCreationProgress {\n const { email } = progress;\n if (email.status === 'CONFIRMED' && email.address === address) return progress;\n return { ...progress, email: { status: 'CONFIRMED', address, passcode: PASSCODE_IDLE } };\n}\n\n/**\n * Where the code has got to, put back on the address it is about. A no-op before there\n * is an address: the alternative is every caller reaching into the union and building\n * the half of it that has no address to carry.\n */\nexport function withPasscode(\n progress: AccountCreationProgress,\n passcode: PasscodeState,\n): AccountCreationProgress {\n const { email } = progress;\n if (email.status === 'UNCONFIRMED') return progress;\n return { ...progress, email: { ...email, passcode } };\n}\n\n/**\n * The address the account will be made on, or `null` while there is still something to\n * settle about it. THE ONLY READER `createAccount` MAY USE — reaching for `address` itself\n * would hand it one the buyer has not even confirmed.\n *\n * IT WAS `verifiedAddress`, AND THE RENAME IS THE POINT. While the passcode endpoints are\n * down there is no verification to wait for, so this answers a CONFIRMED address rather\n * than a proved one — and a function still called `verifiedAddress` handing back an\n * unverified address is the drift a name is supposed to prevent. The guarantee comes back\n * with the step: see `UNBUILT_ACCOUNT_STEPS`, where the trade is written down.\n */\nexport function addressForAccount(\n progress: AccountCreationProgress,\n /**\n * Whether an address can be PROVED today — injected, defaulted to the switch, so the\n * rule that returns with the endpoint stays under test beside the one in force. Same\n * reasoning as injecting a clock rather than mocking the module that reads one.\n */\n verificationBuilt: boolean = accountStepBuilt('VERIFY_EMAIL'),\n): string | null {\n const { email } = progress;\n if (email.status === 'UNCONFIRMED') return null;\n if (!verificationBuilt) return email.address;\n return passcodeSettled(email.passcode) ? email.address : null;\n}\n\n// ── THE CALLS ────────────────────────────────────────────────\n\n/**\n * WHAT MAKING AN ACCOUNT ACTUALLY COSTS, now that the operations exist. Injected so the\n * flow can be walked without a server, and so the account work lands here rather than in\n * a component.\n *\n * It was written before the endpoints were known and guessed two of them wrong. The\n * shape below is what `packages/api` actually offers.\n */\nexport type AccountCreationGateway = {\n /** `POST /api/Passcodes/Email`. Resolves with the key `checkPasscode` reads. */\n readonly sendCode: (email: string) => Promise<string>;\n /** `POST /api/Passcodes/Verification`. `false` for a code the platform refused. */\n readonly submitCode: (code: string) => Promise<boolean>;\n /**\n * `GET /api/Passcodes/{passcodeKey}/Status`. Separate from `submitCode` on purpose: the\n * mail may arrive on a phone and be entered there, so the authoritative answer is not\n * always the one this browser posted.\n */\n readonly checkPasscode: (passcodeKey: string) => Promise<boolean>;\n /**\n * `POST /api/Users`, which mints the session as it creates the account — hence a\n * `Session` back rather than nothing. Everything after this call needs it.\n */\n readonly createAccount: (details: AccountCreationDetails) => Promise<Session>;\n /**\n * `PUT /api/Users/Photo`, AFTER the account exists, because it needs that session. The\n * buyer chooses the face two steps earlier and the choice is spent here — which is why\n * the photo is not part of `AccountCreationDetails`.\n */\n readonly setPhoto: (photo: AccountPhoto) => Promise<void>;\n /**\n * Whether there is an account to act for.\n *\n * A QUESTION RATHER THAN A CLIENT. Everything below this line needs a session, and\n * `POST /api/Passkeys/Registrations/Challenges` answers 401 without one — so asking\n * first is the difference between not offering a passkey and offering one that cannot\n * work. The gateway answers it because the gateway holds the client; nothing above\n * reaches past it to ask.\n */\n readonly signedIn: () => boolean;\n /**\n * `POST /api/Passkeys/Registrations/Challenges`, which opens a ceremony THIS PACKAGE\n * CANNOT RUN. WebAuthn binds a credential to an RP id and the widget is on the\n * customer's origin, so the browser half happens in `packages/passkey-host` and the\n * gateway's job is the two calls either side of it.\n *\n * It also carries `User.Key`, which is the only place the platform hands one back — so\n * a buyer who declines a passkey has still told us who they are, and the follow prompt\n * has an address to write to.\n */\n readonly openPasskeyRegistration: () => Promise<PasskeyRegistrationChallenge>;\n /** `POST /api/Passkeys/Registrations`, with whatever the ceremony document handed back. */\n readonly lodgePasskey: (credential: PasskeyRegistrationRequest) => Promise<void>;\n};\n\n/**\n * What making the account needs, over and above the order.\n *\n * TWO HALVES OF A NAME AND NOT ONE, because `POST /api/Users` requires both and the\n * order's own NAME step collects them separately — splitting a single string here would\n * put a guess between two places that already agree.\n *\n * NO PASSCODE KEY. It never goes on the wire: the platform joins the verified code to the\n * new account by the ADDRESS, which is why `email` here must be the exact string the code\n * was sent to. `verifiedAddress` is the only reader allowed to supply it.\n */\nexport type AccountCreationDetails = {\n readonly firstName: string;\n readonly lastName: string;\n readonly email: string;\n readonly password: string;\n readonly phone: string | null;\n};\n\n/**\n * A face, in the two forms `ImageRequest` accepts — and the two the step can produce.\n *\n * A stock face is the PLATFORM's and already has a URL, so it is sent by reference; an\n * upload exists only in this browser and has to be carried whole.\n */\nexport type AccountPhoto =\n | { readonly kind: 'STOCK'; readonly url: string }\n | { readonly kind: 'UPLOAD'; readonly encoded: string };\n\n/**\n * WHETHER THE ACCOUNT EXISTS YET.\n *\n * Separate from `AccountCreationProgress`, which is about what the buyer has ANSWERED.\n * This is about what the platform has done with those answers, and the two are different\n * questions — every question can be answered and the call still fail.\n */\nexport type AccountOutcome =\n /** Nothing has been attempted. */\n | { readonly status: 'NOT_STARTED' }\n /** The call is in flight. `ACCOUNT_CREATING` is the card that is up. */\n | { readonly status: 'CREATING' }\n /** Made, and signed into. The session is already on the client — see `accountGateway`. */\n | { readonly status: 'CREATED'; readonly session: Session }\n /**\n * Refused, or unreachable. Carries the platform's own words, which are NOT shown to the\n * buyer — a notice's subtitle is ours to write. See `noticeTelemetry`.\n */\n | { readonly status: 'FAILED'; readonly reason: string };\n\n/** Who the account is for, over and above what the sub-flow collected. */\nexport type AccountIdentity = {\n readonly firstName: string;\n readonly lastName: string;\n readonly phone: string | null;\n};\n\n/**\n * THE CHOSEN FACE, IN THE FORM THE PLATFORM TAKES — or `null` where none was chosen.\n *\n * WHAT THE STEP COLLECTS IS AN AVATAR VALUE, not a picture: `default:<id>` for one of the\n * platform's own, and for an upload a `blob:` url this page made to draw the cell with.\n * Neither can be sent. A stock face is sent by REFERENCE — the url the grid drew it from,\n * which is the platform's own file — and an upload has to be carried WHOLE, because a\n * `blob:` url means nothing to anybody but this document.\n *\n * THE UPLOAD'S BYTES ARE THE CALLER'S TO SUPPLY, read from the `File` when it was chosen.\n * Empty where the read has not landed yet, which answers `null`: an account made in the\n * half-second before a `FileReader` finishes is an account with no face, and that is a\n * better answer than a card that waited for one.\n */\nexport function chosenPhoto(\n value: string,\n options: readonly { readonly value: string; readonly url: string }[],\n encodedUpload: string,\n): AccountPhoto | null {\n if (value === '') return null;\n const stock = options.find((option) => option.value === value && option.value !== option.url);\n if (stock !== undefined) return { kind: 'STOCK', url: stock.url };\n return encodedUpload === '' ? null : { kind: 'UPLOAD', encoded: encodedUpload };\n}\n\nexport const ACCOUNT_NOT_STARTED: AccountOutcome = { status: 'NOT_STARTED' };\n\n/**\n * THE ACCOUNT THAT WAS JUST MADE, as the flow will spend it from here on.\n *\n * Built from what the sub-flow collected rather than read back from the platform: `POST\n * /api/Users` answers with a `LoginResult` and no profile, so asking for one would be a\n * second round trip for facts this browser typed a moment ago.\n *\n * THE EMPTY STRING IS NOT A VALUE. Every field a buyer skipped has to arrive here as\n * `null`, because `Account`'s readers test for exactly that — a name of `''` renders an\n * empty welcome and a phone of `''` reads as an answered order requirement.\n *\n * AND THE AVATAR IS NEVER THE GUEST SENTINEL. `null` here is a real account that has not\n * set a face, which is a different thing from the placeholder a guest is drawn with;\n * `buyerAvatarValue` is the only thing allowed to spend that, and it does so by asking\n * the auth state rather than by reading a value anybody stored.\n */\nexport function accountFromCreation(\n identity: AccountIdentity,\n /** The address the code was verified at, which is the one the account was made on. */\n email: string,\n /** The face the buyer chose two steps earlier, or `null` where they chose none. */\n avatar: string | null,\n): Account {\n const name = `${identity.firstName} ${identity.lastName}`.trim();\n return {\n avatar: avatar === null || avatar === '' ? null : avatar,\n name: name === '' ? null : name,\n email: email === '' ? null : email,\n phone: identity.phone === null || identity.phone === '' ? null : identity.phone,\n /*\n * NOT KNOWN, AND NOT GUESSED. A user type is a thing the platform associates with an\n * account; the composition the buyer picked for THIS order is a different question\n * with a different key — see `user-types`.\n */\n userTypeKey: null,\n };\n}\n","/**\n * COMPOSE, AS A ROW OF STEPS THE BUYER CAN WALK BACK INTO.\n *\n * The first half of a purchase asks three questions — who is coming, which day, which\n * session — and until the cart is opened none of them is committed to anything. So they\n * are not a one-way walk: the header draws them together and a buyer can go back to any\n * of them, which is what `HeaderButtons-TicketSelectionFunnel` is.\n *\n * ── WHY THE RULE IS HERE AND NOT IN THE HEADER ──────────────────────────────\n *\n * Two things have to agree about a compose step and they are drawn in different places:\n * the CARD's Continue, which is gated on the step being answered, and the FUNNEL's own\n * mark, which is dimmed when it is not. Asked twice, they drift — and the drift is\n * invisible, because each one looks right on its own screen.\n *\n * Pure: no React, no client, and it reads a SLICE of what the flow has collected rather\n * than the whole record, so the island's own type does not leak down here.\n */\n\nimport { intentHasParty } from './order-intent';\nimport { PURCHASE_STEPS, type PurchaseStepId } from './purchase-steps';\n\n/**\n * The compose steps, in the buyer's order.\n *\n * FILTERED FROM `PURCHASE_STEPS` RATHER THAN LISTED, because the chunk is already the\n * fact: a step added to Compose belongs in the funnel by being what it is, and a list\n * here would be the copy that forgets.\n */\nexport const COMPOSE_STEPS: readonly PurchaseStepId[] = PURCHASE_STEPS.filter(\n (step) => step.chunk === 'COMPOSE',\n).map((step) => step.id);\n\n/** Whether a step belongs to the funnel at all. */\nexport function isComposeStep(id: PurchaseStepId): boolean {\n return COMPOSE_STEPS.includes(id);\n}\n\n/**\n * WHAT COMPOSE HAS COLLECTED — the three answers and nothing else.\n *\n * `partyRefused` is part of the party's answer rather than a fourth field: a count over\n * the ticket's ceiling leaves the stepper showing a number the event cannot sell, and a\n * step is not answered while that stands.\n */\nexport type ComposeAnswers = {\n readonly composition: Readonly<Record<string, number>>;\n /** `YYYY-MM-DD`, or empty for a day not yet chosen. */\n readonly day: string;\n /** The slot's `startTime`, or empty for a time not yet chosen. */\n readonly timeslot: string;\n /** A number over the ceiling that was asked for, or `null` once one within it is. */\n readonly partyRefused: number | null;\n};\n\n/**\n * WHETHER A COMPOSE STEP HAS ITS ANSWER — the one reading, for the card's gate and the\n * funnel's ink both.\n *\n * A step outside Compose is not this function's business and answers `false`; callers ask\n * `isComposeStep` first, and the funnel only ever holds compose steps.\n */\nexport function composeAnswered(id: PurchaseStepId, answers: ComposeAnswers): boolean {\n switch (id) {\n case 'PARTY':\n return intentHasParty(answers.composition) && answers.partyRefused === null;\n case 'DATE':\n return answers.day !== '';\n case 'TIME':\n return answers.timeslot !== '';\n default:\n return false;\n }\n}\n\n/**\n * ── CHANGING ONE ANSWER EMPTIES THE ONES BEHIND IT ──────────────────────────\n *\n * The three questions are not independent. Which sessions exist depends on the day, which\n * days are sellable depends on how many tickets are wanted, and neither dependency is one\n * the buyer can see — so an answer carried forward past a change to the thing it hung off\n * is an answer nobody has checked.\n *\n * The timeslot was already cleared by the day picker, at the picker. Said there it was one\n * half of a rule whose other half did not exist, and it had to be repeated at the second\n * place a day can be chosen (the time card's own strip) to hold at all.\n *\n * RETURNS THE FIELDS TO EMPTY, not a whole record: the caller folds it into whatever else\n * its own change is writing, so a picker still says in one expression what it collected\n * and what that cost.\n */\nexport function clearedAfter(\n id: PurchaseStepId,\n): Partial<Pick<ComposeAnswers, 'day' | 'timeslot'>> {\n const after = COMPOSE_STEPS.slice(COMPOSE_STEPS.indexOf(id) + 1);\n return {\n ...(after.includes('DATE') ? { day: '' } : {}),\n ...(after.includes('TIME') ? { timeslot: '' } : {}),\n };\n}\n\n/** One mark in the funnel. */\nexport type ComposeStop = {\n readonly id: PurchaseStepId;\n /** What it IS, for anyone who cannot see the glyph — `PurchaseStep.name`. */\n readonly name: string;\n /** Whether it has its answer. The mark is dimmed where it does not. */\n readonly answered: boolean;\n /** Whether it is the card the buyer is looking at. */\n readonly current: boolean;\n};\n\n/**\n * THE FUNNEL, BUILT FROM THE WALK — so a step this order does not stop at is not drawn.\n *\n * `stops` is the walk's own list and is already in the buyer's order with every excusal\n * applied: a plain event asks for no day, a run with no sessions asks for no time, and a\n * host that composed the party itself asks for neither. Reading the walk rather than\n * `COMPOSE_STEPS` is what keeps the funnel from offering a card nobody can reach.\n *\n * NOTHING TO OFFER IS AN EMPTY FUNNEL, and there are two ways to have nothing.\n *\n * ONE MARK IS NOT A FUNNEL — there is nowhere to navigate to — so a compose half with a\n * single step draws no header buttons at all.\n *\n * AND IT IS GONE THE MOMENT COMPOSE IS. These questions stop being a set a buyer may\n * revisit at Add to Cart: past it there is an order held against real inventory, and a\n * mark offering to change the day it was held for would be offering something this widget\n * cannot do. The header's trailing slot is the cart summary's from there on, which is the\n * same fact said in the other direction.\n */\nexport function composeFunnel(\n stops: readonly PurchaseStepId[],\n answers: ComposeAnswers,\n at: PurchaseStepId | null,\n): readonly ComposeStop[] {\n if (at === null || !isComposeStep(at)) return [];\n\n const drawn = stops.filter(isComposeStep);\n if (drawn.length < 2) return [];\n\n return drawn.map((id) => ({\n id,\n name: PURCHASE_STEPS.find((step) => step.id === id)?.name ?? id,\n answered: composeAnswered(id, answers),\n current: id === at,\n }));\n}\n","import { CalendarIcon, ClockWithSegmentSolidIcon, PeopleTwoIcon } from '@scopetickets/icons';\nimport type { PurchaseStepId } from '../domain/purchase-steps';\nimport type { ComposeStop } from '../domain/compose-funnel';\nimport { useIslandPress } from './island-press';\n\n/**\n * THE COMPOSE STEPS, IN THE HEADER — the design's `HeaderButtons-TicketSelectionFunnel`.\n *\n * ONE PILL HOLDING THREE MARKS, hairline-separated, at the trailing end of the header row\n * where the cart summary goes once there is a cart. There is no cart during Compose, so\n * the two never share the slot.\n *\n * ── IT IS A WAY BACK, NOT A PROGRESS BAR ────────────────────────────────────\n *\n * Nothing in Compose is committed to anything — the cart is opened by the last of these\n * steps — so the three questions are a set a buyer may revisit rather than a walk they are\n * pushed down. Pressing a mark goes to that card.\n *\n * FORWARD ONLY AS FAR AS THE ANSWERS REACH, which is the one limit. A step is reachable\n * when everything before it is answered: Select Time draws the sessions the chosen DAY\n * resolves to, so opening it without one is a list of times for a day nobody picked. The\n * mark is drawn and declines rather than vanishing — the same reading the codes pager's\n * ends get, and the same reason: a row of marks that changes length as answers arrive is a\n * different control each time you look at it.\n *\n * DIM IS \"NO VALUE YET\" AND NOT \"CANNOT BE PRESSED\". The first unanswered step is both dim\n * and reachable, which is right: it is the one the buyer is being sent to.\n */\nexport type ComposeFunnelProps = {\n readonly stops: readonly ComposeStop[];\n /** Where a press goes. The caller owns the walk; this only names a step. */\n readonly onGo: (id: PurchaseStepId) => void;\n /** Names the group for assistive technology. This package holds no copy. */\n readonly label: string;\n};\n\n/**\n * THE MARK PER STEP. A table rather than a prop, for the reason `STEP_BADGES` is one: a\n * step's glyph is a fact about the step, and the caller that would have to supply it is\n * the same file either way.\n */\nconst FUNNEL_GLYPHS: Partial<Record<PurchaseStepId, typeof CalendarIcon>> = {\n PARTY: PeopleTwoIcon,\n DATE: CalendarIcon,\n TIME: ClockWithSegmentSolidIcon,\n};\n\nexport function ComposeFunnel({ stops, onGo, label }: ComposeFunnelProps) {\n if (stops.length === 0) return null;\n\n /*\n * REACHABLE IS A RUNNING READ, not a property of a step on its own: it is \"everything\n * before this one is answered\", so it can only be known walking the row in order.\n */\n let open = true;\n\n return (\n <div\n className=\"scopetickets-island-chrome-pill scopetickets-island-funnel\"\n role=\"group\"\n aria-label={label}\n >\n {stops.map((stop, index) => {\n const reachable = open;\n open = open && stop.answered;\n return (\n <FunnelStep\n key={stop.id}\n stop={stop}\n reachable={reachable}\n /* The hairline goes BEFORE every mark but the first, so the row cannot end on one. */\n ruled={index > 0}\n onGo={() => onGo(stop.id)}\n />\n );\n })}\n </div>\n );\n}\n\nfunction FunnelStep({\n stop,\n reachable,\n ruled,\n onGo,\n}: {\n stop: ComposeStop;\n reachable: boolean;\n ruled: boolean;\n onGo: () => void;\n}) {\n /* `element` — going back to a question does not change what the island IS. */\n const press = useIslandPress('element');\n const Glyph = FUNNEL_GLYPHS[stop.id];\n\n return (\n <>\n {ruled ? <span className=\"scopetickets-island-funnel__rule\" aria-hidden=\"true\" /> : null}\n <button\n type=\"button\"\n className=\"scopetickets-island-funnel__step\"\n aria-label={stop.name}\n /*\n * WHICH ONE IS SHOWING, said to assistive technology as well as drawn. `current`\n * rather than `pressed`: the mark does not toggle, it names where you are.\n */\n aria-current={stop.current ? 'step' : undefined}\n /* Not the attribute — a disabled button leaves the tab order, and a step a buyer is\n about to be able to reach is somewhere they navigate past. See `PagerArrow`. */\n aria-disabled={reachable ? undefined : true}\n data-answered={stop.answered ? '' : undefined}\n data-disabled={reachable ? undefined : ''}\n onClick={reachable ? onGo : undefined}\n {...press}\n >\n {/* `fill` and `currentColor`, both, like every other glyph in this row: the mark\n takes its size from the slot and its colour from the button. */}\n <span className=\"scopetickets-island-glyph-slot\" aria-hidden=\"true\">\n {Glyph === undefined ? null : <Glyph fill color=\"currentColor\" />}\n </span>\n </button>\n </>\n );\n}\n","import { ShoppingCartIcon } from '@scopetickets/icons';\nimport { useIslandPress } from './island-press';\n\n/**\n * THE HEADER'S TRAILING PILL ONCE THERE IS AN ORDER — the design's\n * `HeaderButton-CartSummary` on the Pay cards: what is being bought, and the one thing\n * that can still change what it costs.\n *\n * ── TWO TARGETS AGAIN, AND THE RULE IS BACK BETWEEN THEM ─────────────────────\n *\n * This pill held an order glyph and a hold ring once, lost the ring when the two screens\n * behind them became one, and is two controls again for a different reason: the second one\n * is no longer another way to the same screen, it is the promo code.\n *\n * THE CLOCK IS NOT HERE AND DOES NOT NEED TO BE. The Pay cards count the hold down in\n * their own subtitle and wear the same ring on their hero — see the `REVIEW`/`PAYMENT`\n * branch of `subtitle`, which is where that moved. A third reading of one countdown in the\n * header would be the pill saying what the card already says twice.\n *\n * NEITHER IS THE TOTAL, for the same reason: the card's title IS the money on every step\n * that draws this — `Pay €12.34`, off the quote.\n */\nexport type IslandCommitPillProps = {\n /** Opens the cart screen. */\n readonly onOpenCart: () => void;\n /** Names the cart target for assistive technology. This package holds no copy. */\n readonly cartLabel: string;\n /** Opens the promo code step. */\n readonly onOpenPromo: () => void;\n /** The promo target's own words — it is the one half of this pill that is drawn as text. */\n readonly promoLabel: string;\n};\n\nexport function IslandCommitPill({\n onOpenCart,\n cartLabel,\n onOpenPromo,\n promoLabel,\n}: IslandCommitPillProps) {\n /* `element` for both — neither changes what the island IS, they open a screen on it. */\n const cartPress = useIslandPress('element');\n const promoPress = useIslandPress('element');\n\n return (\n <div className=\"scopetickets-island-chrome-pill scopetickets-island-commit\">\n <button\n type=\"button\"\n className=\"scopetickets-island-commit__target\"\n aria-label={cartLabel}\n onClick={onOpenCart}\n {...cartPress}\n >\n <span className=\"scopetickets-island-glyph-slot\" aria-hidden=\"true\">\n <ShoppingCartIcon fill color=\"currentColor\" />\n </span>\n </button>\n {/* `ConstructionLine`, the same hairline the compose funnel sets between its marks. */}\n <span className=\"scopetickets-island-commit__rule\" aria-hidden=\"true\" />\n <button\n type=\"button\"\n className=\"scopetickets-island-commit__target scopetickets-island-commit__promo\"\n onClick={onOpenPromo}\n {...promoPress}\n >\n {promoLabel}\n </button>\n </div>\n );\n}\n","/**\n * THE RATING, SENT — one call, and the only thing in this package that writes to\n * `POST /api/Feedback`.\n *\n * A HOOK AND NOT A CALL FROM THE CARD, for the reason every other call here is: a\n * component that reached the platform itself would be a component holding a client, and\n * the rating card's whole job is to draw five stars and report which one was pressed.\n */\n\nimport { useCallback, useRef, useState } from 'react';\nimport type { ScopeClient } from '@scopetickets/api';\nimport type { FeedbackRating, FeedbackSubmission } from '../domain/feedback';\n\nexport type CheckoutFeedback = {\n readonly submission: FeedbackSubmission;\n /**\n * Send the rating for the ticket this was built against. A no-op where there is no\n * ticket to rate or no platform to reach — see `useFeedback`, which says why that is\n * silence rather than a failure.\n */\n readonly send: (rating: FeedbackRating) => void;\n /**\n * Send the LAST rating again — the notice's Try Again. It needs no argument because a\n * failed submission still carries the number; a retry with nothing to retry is a no-op.\n */\n readonly retry: () => void;\n};\n\nexport function useFeedback(\n client: ScopeClient | null,\n /**\n * THE TICKET BEING RATED, or absent where the payment named none. The platform hangs\n * feedback off an attendee ticket, so without one there is nothing this hook can say.\n */\n attendeeTicketKey: string | undefined,\n): CheckoutFeedback {\n const [submission, setSubmission] = useState<FeedbackSubmission>({ status: 'UNSENT' });\n /*\n * WHAT IS IN FLIGHT, so a second press cannot start a second send. Pressing Continue\n * advances the card, so the ordinary buyer cannot press it twice — but the notice's\n * Try Again can be pressed as often as it is on screen, and each press against a slow\n * network would be another rating for the same ticket.\n *\n * A REF AND NOT THE STATE, because the guard has to hold WITHIN a render: two presses\n * in one tick both read the same `submission`.\n */\n const inFlight = useRef(false);\n\n const post = useCallback(\n (rating: FeedbackRating) => {\n /*\n * NOTHING TO SEND TO IS NOT A FAILURE. A host that asserted a placed payment without\n * naming a ticket, and a widget with no client at all, have both said as much as they\n * are going to — raising a notice at the buyer about it would be reporting our own\n * integration back to them. The widget says it in the console instead, where the\n * integrator is; see `PaymentOutcome.attendeeTicketKey`.\n */\n if (client === null || attendeeTicketKey === undefined) return;\n if (inFlight.current) return;\n inFlight.current = true;\n setSubmission({ status: 'SENDING', rating });\n client\n .submitFeedback({ AttendeeTicketKey: attendeeTicketKey, Rating: rating })\n .then(() => setSubmission({ status: 'SENT', rating }))\n .catch(() => setSubmission({ status: 'FAILED', rating }))\n .finally(() => {\n inFlight.current = false;\n });\n },\n [client, attendeeTicketKey],\n );\n\n const retry = useCallback(() => {\n if (submission.status !== 'FAILED') return;\n post(submission.rating);\n }, [post, submission]);\n\n return { submission, send: post, retry };\n}\n","import { StarFilledIcon } from '@scopetickets/icons';\nimport { FEEDBACK_RATINGS, ratingLabel, type FeedbackRating } from '../domain/feedback';\nimport { useIslandPress } from './island-press';\n\nexport type StarRatingProps = {\n /** The rating so far, or `null` while the buyer has chosen none. */\n readonly value: FeedbackRating | null;\n /**\n * THE NEW RATING, OR `null` FOR ONE TAKEN BACK — see the star's own note. The card is\n * gated on `value`, so handing `null` back shuts Continue again, which is the whole\n * point: a buyer who has unrated has not rated.\n */\n readonly onChange: (rating: FeedbackRating | null) => void;\n /** Names the group — see `ratingLabel` for what the options are called. */\n readonly label: string;\n};\n\n/**\n * THE RATING CARD'S FIVE STARS — the design's `StarRating`, in its well.\n *\n * ON ARRIVAL EVERY STAR IS FILLED, under the dim `island.css` holds the row at. It shows\n * what the control is FOR: five stars, waiting. It is emphatically NOT a rating of five,\n * and nothing downstream reads it as one — `value` is still `null`, the radios are all\n * unchecked, and Continue is shut until the buyer presses something.\n */\nexport function StarRating({ value, onChange, label }: StarRatingProps) {\n return (\n <div className=\"scopetickets-island-rating\">\n <div\n className=\"scopetickets-island-rating__row\"\n role=\"radiogroup\"\n aria-label={label}\n /* The dim is the ROW's and not each star's, so the five fade as one thing. */\n data-unrated={value === null ? '' : undefined}\n >\n {FEEDBACK_RATINGS.map((rating) => (\n <RatingStar\n key={rating}\n rating={rating}\n /*\n * FILLED IS \"AT OR BELOW\", AND ALL FIVE BEFORE THERE IS A BELOW. Three stars\n * means the first three are gold; nothing chosen means every one of them is,\n * under the row's 40%.\n */\n filled={value === null || rating <= value}\n /* CHECKED IS EXACTLY ONE, because the group's value is one number. */\n checked={value === rating}\n /*\n * ── PRESSING THE RATING YOU ALREADY GAVE TAKES IT BACK ──────────────\n *\n * A rating is volunteered, and until Continue is pressed nothing has been\n * sent — so the row has to be able to return to the state it opened in.\n * Without this the only way out of a rating is to give a DIFFERENT one,\n * which turns an accidental tap on the fifth star into a choice between\n * lying and leaving the card.\n *\n * IT IS STILL A RADIO GROUP. One of five, or none of five, is what this\n * control has always meant — `value` was nullable before this line existed.\n * This is the way back to the second of those, not a second kind of control,\n * and the way PAST without rating is still the card's own Skip.\n */\n onChoose={() => onChange(value === rating ? null : rating)}\n />\n ))}\n </div>\n </div>\n );\n}\n\nfunction RatingStar({\n rating,\n filled,\n checked,\n onChoose,\n}: {\n rating: FeedbackRating;\n filled: boolean;\n checked: boolean;\n onChoose: () => void;\n}) {\n /*\n * `element` — rating a purchase does not change what the island IS, so the star\n * compresses and the surface behind it does not.\n */\n const press = useIslandPress('element');\n\n return (\n <button\n type=\"button\"\n role=\"radio\"\n aria-checked={checked}\n aria-label={ratingLabel(rating)}\n className=\"scopetickets-island-rating__star\"\n data-filled={filled ? '' : undefined}\n onClick={onChoose}\n {...press}\n >\n {/*\n * ONE GLYPH, DRAWN TWICE, IN ONE OF TWO PALETTES — the same construction the icon\n * set's own METAL treatment uses, and the same one the node draws: a flat base with a\n * sheen over it fading out along the 0,0 → 32,32 diagonal. A single fill cannot carry\n * a gradient, and without the sheen an unearned star is a 20%-black shape on a card\n * that is already dark — very nearly nothing.\n *\n * THE SAME SHAPE EITHER WAY. An unearned star is not an outline or a smaller mark;\n * it is this star in the well's own colours, which is what makes the row read as five\n * places rather than as two kinds of thing.\n */}\n <StarFilledIcon\n fill\n color={\n filled\n ? 'var(--scopetickets-island-rating-star)'\n : 'var(--scopetickets-island-rating-star-empty)'\n }\n />\n <span className=\"scopetickets-island-rating__sheen\" aria-hidden=\"true\">\n <StarFilledIcon\n fill\n color={\n filled\n ? 'var(--scopetickets-island-rating-star-sheen)'\n : 'var(--scopetickets-island-rating-star-empty-sheen)'\n }\n />\n </span>\n </button>\n );\n}\n","/**\n * WHAT THE BUYER THOUGHT OF THE PURCHASE — five stars, and the one number they come to.\n *\n * IT IS AN OFFER AND NOT A REQUIREMENT, which is the whole shape of it: the tickets are\n * already the buyer's by the time this is asked, the card carries a Skip, and nothing\n * downstream reads the answer. A rating that never arrives costs the buyer nothing.\n *\n * Pure: no React, no network, no DOM.\n */\n\n/**\n * FIVE STARS, AND THE RANGE IS THE DESIGN'S RATHER THAN THE PLATFORM'S.\n *\n * `POST /api/Feedback` types `Rating` as a bare `int32` and states no range at all, so\n * the wire would take 7 or -1 as readily as 4. The only authority on what a rating MEANS\n * is the card, which draws five stars — so the range is stated here, once, and\n * `isFeedbackRating` is what stops anything else reaching the wire.\n */\nexport const FEEDBACK_STARS = 5;\n\n/** One through five, as the card's stars are counted. */\nexport type FeedbackRating = 1 | 2 | 3 | 4 | 5;\n\n/**\n * The ratings in the order the stars are drawn, so the card maps rather than counts —\n * a `FEEDBACK_STARS`-long loop producing numbers it then has to assert are ratings is\n * the same list written twice, and the second copy is the one that drifts.\n */\nexport const FEEDBACK_RATINGS: readonly FeedbackRating[] = [1, 2, 3, 4, 5];\n\n/**\n * WHETHER A NUMBER IS ONE OF THE FIVE. The guard the wire is behind: `FeedbackRating`\n * narrows what this package passes around, and this is the only thing that can make one\n * out of a number that was not already.\n */\nexport function isFeedbackRating(value: number): value is FeedbackRating {\n return Number.isInteger(value) && value >= 1 && value <= FEEDBACK_STARS;\n}\n\n/**\n * WHAT A STAR IS CALLED OUT LOUD. The stars are a radio group and each option needs a\n * name; \"3\" alone is a number with no unit, and the control is not announced anywhere\n * else — the card's title asks a question and says nothing about stars.\n */\nexport function ratingLabel(rating: FeedbackRating): string {\n return rating === 1 ? '1 star' : `${rating} stars`;\n}\n\n/**\n * WHERE THE RATING GOT TO — one state rather than a flag beside an error, so \"sent\" and\n * \"still going\" and \"would not go\" cannot be true at once.\n *\n * `FAILED` KEEPS THE RATING, and keeping it is what makes the notice's Try Again a real\n * button: the buyer has left the card by the time a failure is known, so there is no\n * control left holding the number. `ACCOUNT_NOT_CREATED` keeps the password for exactly\n * the same reason.\n */\nexport type FeedbackSubmission =\n /** Nothing has been sent — the buyer has not pressed, or had nothing to send. */\n | { readonly status: 'UNSENT' }\n | { readonly status: 'SENDING'; readonly rating: FeedbackRating }\n | { readonly status: 'SENT'; readonly rating: FeedbackRating }\n | { readonly status: 'FAILED'; readonly rating: FeedbackRating };\n","/** Money, and how it is written. */\n\n/**\n * Chosen once, here, so two screens cannot disagree about where the symbol goes.\n * `en-IE` matches the SDK's own convention and the deployment; it is not read from the\n * viewer, because the price is the organiser's, not the reader's.\n */\nconst MONEY_LOCALE = 'en-IE';\n\nfunction formatterFor(currency: string): Intl.NumberFormat {\n return new Intl.NumberFormat(MONEY_LOCALE, { style: 'currency', currency });\n}\n\n/** How many digits this currency's minor unit has. */\nfunction minorUnitDigits(formatter: Intl.NumberFormat): number {\n // `maximumFractionDigits` is typed optional because it is, for the other number\n // styles.\n return formatter.resolvedOptions().maximumFractionDigits ?? 2;\n}\n\n/** `1234, 'EUR'` → `\"€12.34\"`. `1200, 'JPY'` → `\"¥1,200\"`. */\nexport function formatMoney(minorUnits: number, currency: string): string {\n const formatter = formatterFor(currency);\n return formatter.format(minorUnits / 10 ** minorUnitDigits(formatter));\n}\n\n/**\n * A MONEY VALUE IN ITS TWO HALVES — the symbol and the digits, apart.\n *\n * The cart draws them in two faces, the symbol in the text face and the amount in the\n * mono one, and it needs them separable for a second reason: the amounts share a column\n * as wide as the widest of them, so the symbols stack. See `widestAmount`.\n *\n * `formatToParts` rather than a split, so a currency that TRAILS its symbol is still\n * taken apart correctly — the design's own `€ 10.00` is one locale's answer, not the rule.\n */\nexport type MoneyParts = { readonly symbol: string; readonly amount: string };\n\nexport function moneyParts(minorUnits: number, currency: string): MoneyParts {\n const formatter = formatterFor(currency);\n const parts = formatter.formatToParts(minorUnits / 10 ** minorUnitDigits(formatter));\n const of = (kind: 'symbol' | 'amount') =>\n parts\n .filter((part) => (kind === 'symbol' ? part.type === 'currency' : part.type !== 'currency'))\n /* Literals are the spaces a locale puts between the two; neither half wants them. */\n .filter((part) => part.type !== 'literal')\n .map((part) => part.value)\n .join('');\n\n return { symbol: of('symbol'), amount: of('amount') };\n}\n\n/**\n * HOW WIDE A COLUMN OF AMOUNTS IS, in characters of the mono face — the longest of them.\n *\n * IT IS A COUNT AND NOT A MEASUREMENT because the amounts are set in the mono face, where\n * every character is one advance wide: `1ch` per character is exact, and no element has to\n * be measured to learn it. The symbols then stack, because every amount beside them\n * occupies the same width whatever it says.\n */\nexport function widestAmount(amounts: readonly string[]): number {\n return amounts.reduce((widest, amount) => Math.max(widest, amount.length), 0);\n}\n\n/** What the buyer is being asked to pay, as one value. */\nexport type Quote =\n /** Nothing priceable at all — no floor, no total. See `quoteLines`. */\n | { readonly kind: 'NONE' }\n /**\n * THE DEFAULT: the cheapest ticket, and the buyer may pay more. Qualified \"From\" on the\n * line above.\n */\n | { readonly kind: 'FROM'; readonly minorUnits: number; readonly currency: string }\n /**\n * A price with a discount already applied. The saving REPLACES the \"From\" rather than\n * joining it — one qualifier, or the line says two things at once and the buyer has to\n * work out which governs.\n */\n | {\n readonly kind: 'SAVING';\n readonly minorUnits: number;\n readonly currency: string;\n readonly savedMinorUnits: number;\n }\n /** Settled: what will actually be charged, with nothing to qualify. */\n | { readonly kind: 'TOTAL'; readonly minorUnits: number; readonly currency: string };\n\n/** The two lines the pill shows, or `null` when there is nothing to say. */\nexport type QuoteLines = {\n readonly qualifier: string | null;\n readonly headline: string;\n};\n\nexport function quoteLines(quote: Quote): QuoteLines | null {\n if (quote.kind === 'NONE') return null;\n const headline = formatMoney(quote.minorUnits, quote.currency);\n if (quote.kind === 'FROM') return { qualifier: 'From', headline };\n if (quote.kind === 'SAVING') {\n return { qualifier: `Save ${formatMoney(quote.savedMinorUnits, quote.currency)}`, headline };\n }\n return { qualifier: null, headline };\n}\n","import {\n chooseGuest,\n signIn,\n signOut,\n type Account,\n type AuthCardId,\n type AuthSession,\n} from './auth';\nimport type { AuthCopyKey } from './auth-copy';\n\n/**\n * WHAT EACH BUTTON ON AN AUTH CARD DOES — the half a reachability proof needs.\n * `authPrompt` says which card a checkpoint draws; this says what happens when the\n * buyer presses something on it, so `flow-walk.ts` can answer \"can a buyer always get\n * out of here?\" by search rather than by reading five button stacks.\n */\n\n/** What pressing an auth-card button does to the flow. */\nexport type AuthOutcome =\n /**\n * The buyer ends up authenticated — passkey, password, federated, or a new account.\n * FIVE LABELS COLLAPSE TO THIS ONE OUTCOME, and that is a statement about the flow\n * rather than a shortcut: how a buyer proves who they are does not change anything\n * downstream. Which is also why the platform team can implement them one at a time\n * without anything here moving.\n */\n | { readonly kind: 'AUTHENTICATE'; readonly ceremony: AuthCeremony }\n /**\n * To `UNRECOGNISED`, keeping the guest choice. At OrderCreated this is also the route\n * to the guest card — see `signOut` in `./auth`.\n */\n | { readonly kind: 'SIGN_OUT' }\n /** Declining to sign in for this order. */\n | { readonly kind: 'GUEST' }\n /**\n * Past the checkpoint with the session untouched — the OrderSuccess offer's \"Skip\", and\n * the only outcome that proceeds without changing anything.\n */\n | { readonly kind: 'PROCEED' }\n /** Leaving for password recovery — `FORGOT_PASSWORD`, and nothing else. */\n | { readonly kind: 'RECOVER' };\n\n/** HOW a buyer gets from pressing a button to being authenticated. */\nexport type AuthCeremony =\n /**\n * The device is asked for a passkey and nothing is drawn. One confirmation — a\n * fingerprint, a face, a screen lock — and no typing at all. The cheapest route into an\n * account there is, which is why `USE_PASSKEY` is the primary on the card that offers\n * it.\n */\n | 'PASSKEY'\n /**\n * The sign-in funnel — the design. The card opens straight away and asks for an email\n * and a password. It asks the device nothing: the passkey is a separate,\n * explicitly-pressed ceremony. See `@/domain/auth-funnel`.\n */\n | 'FUNNEL'\n /**\n * Creating one. The account does not exist, so no passkey can shortcut it, and the\n * `PASSWORD` step is where the credential is set — which is why this ceremony costs\n * nothing extra here and the step carries it instead.\n */\n | 'NEW_ACCOUNT';\n\n/** Every word in the vocabulary, and what it does. */\nexport const AUTH_ACTION_OUTCOME: Record<AuthCopyKey, AuthOutcome> = {\n /*\n * `ADD_TO_ACCOUNT`'s middle button — a buyer with an existing account, after paying. It\n * opens the funnel like the others: there is no shortcut into an account whose\n * credentials we do not have.\n */\n SIGN_IN: { kind: 'AUTHENTICATE', ceremony: 'FUNNEL' },\n /*\n * THE FUNNEL'S ENTRY POINT. Pressing it draws the design immediately; the device's\n * passkey, if it has one, is offered inside the email field rather than in front of it.\n * — an unbidden modal on a press is worse than a card.\n */\n SIGN_IN_WITH: { kind: 'AUTHENTICATE', ceremony: 'FUNNEL' },\n /*\n * Already on the recognised card, where we know there is an account. Straight to the\n * authenticator — the funnel's probe would be the same call with a card behind it that\n * this buyer has explicitly declined.\n */\n USE_PASSKEY: { kind: 'AUTHENTICATE', ceremony: 'PASSKEY' },\n /*\n * The buyer has ASKED for the password card, and the funnel opens on it — which is now\n * the same thing every entry point does.\n */\n ENTER_PASSWORD: { kind: 'AUTHENTICATE', ceremony: 'FUNNEL' },\n /*\n * AUTHENTICATES TOO. Creating an account signs you into it — the difference from the\n * four above is where the credential comes from, and the flow does not care. What it\n * DOES change is that the `PASSWORD` step then runs, which is the walk's business\n * rather than this table's.\n */\n CREATE_ACCOUNT: { kind: 'AUTHENTICATE', ceremony: 'NEW_ACCOUNT' },\n CONTINUE_AS_GUEST: { kind: 'GUEST' },\n SIGN_OUT: { kind: 'SIGN_OUT' },\n SKIP: { kind: 'PROCEED' },\n FORGOT_PASSWORD: { kind: 'RECOVER' },\n};\n\n/**\n * WHICH BUTTONS EACH CARD OFFERS, in the design's own order — and domain rather than\n * fixture, because the button stack is what decides whether a buyer can get OUT.\n * `flow-walk.ts` walks these lists; `AUTH_CARDS` in `src/dev/island-samples.tsx` draws\n * them, keeps its own transcription of the nodes, and `auth-cards.test.ts` binds the\n * two on both the words and the ORDER.\n */\nexport const AUTH_CARD_ACTIONS: Record<AuthCardId, readonly AuthCopyKey[]> = {\n /*\n * SIGN IN ALONE. Creating an account moved to after the order — `ADD_TO_ACCOUNT` and\n * the sub-flow behind it — so offering it here would be a second route to a place this\n * one cannot reach, or a demand for details the buyer is about to give anyway.\n */\n SIGN_IN_UNRECOGNISED: ['SIGN_IN_WITH'],\n /* The card above plus the guest route, which is the whole difference between them. */\n SIGN_IN_UNRECOGNISED_GUEST: ['SIGN_IN_WITH', 'CONTINUE_AS_GUEST'],\n /*\n * PASSKEY FIRST, and that is a product decision rather than a layout one. `SIGN_OUT`\n * last is what makes the guest route reachable from here at all.\n */\n SIGN_IN_RECOGNISED: ['USE_PASSKEY', 'ENTER_PASSWORD', 'SIGN_OUT'],\n ACCOUNT_READY: ['SIGN_OUT'],\n ADD_TO_ACCOUNT: ['CREATE_ACCOUNT', 'SIGN_IN', 'SKIP'],\n};\n\n/** Whether an outcome gets the buyer past the checkpoint on its own. */\nexport function outcomeProceeds(outcome: AuthOutcome): boolean {\n return outcome.kind !== 'SIGN_OUT' && outcome.kind !== 'RECOVER';\n}\n\n/** The session after pressing a button. */\nexport function applyAuthOutcome(\n session: AuthSession,\n outcome: AuthOutcome,\n account: Account,\n): AuthSession {\n switch (outcome.kind) {\n case 'AUTHENTICATE':\n return signIn(account);\n case 'SIGN_OUT':\n return signOut(session);\n case 'GUEST':\n return chooseGuest(session);\n case 'PROCEED':\n case 'RECOVER':\n /*\n * Recovery leaves the flow rather than moving within it, so there is nothing here to\n * change. The buyer comes back to a fresh page.\n */\n return session;\n }\n}\n\n/**\n * Which routes exist but cannot be walked yet, and what blocks each. Modelled so the\n * tests can tell \"no dead end in the DESIGN\" from \"no route works TODAY\" — two\n * different claims, both worth making.\n */\nexport const UNBUILT_AUTH_ROUTES: Partial<Record<AuthCopyKey, string>> = {\n /*\n * FOUR OF THE FIVE HAVE GONE, and what they were waiting for was never the same thing\n * P11(a) said it was. `USE_PASSKEY` went when `GET /api/Users/Me` arrived to say whose\n * account an assertion had opened; `SIGN_IN`, `SIGN_IN_WITH` and `ENTER_PASSWORD` went\n * when the funnel behind them was built — `POST /api/Auth/Login` had been answering all\n * along, and what was missing was a card to type into. See `auth-funnel.ts`.\n */\n FORGOT_PASSWORD: 'P11(a) — no card to land on. `POST /api/Users/PasswordReset` exists.',\n};\n","import {\n authPrompt,\n checkpointGates,\n requirementGate,\n type Account,\n type AuthCheckpoint,\n type AuthSession,\n} from './auth';\nimport { AUTH_COPY, type AuthCopyKey } from './auth-copy';\nimport {\n AUTH_ACTION_OUTCOME,\n AUTH_CARD_ACTIONS,\n UNBUILT_AUTH_ROUTES,\n applyAuthOutcome,\n outcomeProceeds,\n type AuthCeremony,\n type AuthOutcome,\n} from './auth-actions';\nimport { PURCHASE_STEPS, type PurchaseStepId } from './purchase-steps';\nimport { UNBUILT_ACCOUNT_STEPS } from './account-creation';\n\n/**\n * WALKING A PURCHASE END TO END — what a buyer meets, what it costs, and whether they\n * can get out of every room they can get into.\n */\n\n// ── WHAT A STEP COSTS ────────────────────────────────────────\n\n/**\n * TAPS AND FIELDS, COUNTED APART, because they are not the same kind of work and\n * collapsing them flatters the wrong flow. A step with three text fields and one button\n * is not \"four clicks\" — it is one click and three things to type, and a buyer with\n * autofill pays almost nothing for the second half while a buyer on a phone pays a\n * great deal.\n */\nexport type StepCost = { readonly taps: number; readonly fields: number };\n\nconst cost = (taps: number, fields = 0): StepCost => ({ taps, fields });\n\n/**\n * The steps that exist only because a buyer chose to make an account.\n *\n * A SET AND NOT A CHAIN OF `||`, because the shape of the sub-flow is still moving — a\n * passkey step that turns out to need splitting, or a recovery question added later, is\n * one line here rather than a condition growing another clause. The profile photo was\n * exactly that: one line.\n */\nconst ACCOUNT_CREATION_STEPS: ReadonlySet<PurchaseStepId> = new Set<PurchaseStepId>([\n 'CONFIRM_EMAIL',\n 'VERIFY_EMAIL',\n 'PASSKEY',\n 'PASSWORD',\n 'PROFILE_PHOTO',\n 'ACCOUNT_CREATING',\n 'ACCOUNT_CREATED',\n]);\n\n/** The minimum interaction each step's card demands, read off the controls it draws. */\nexport const STEP_COST: Record<PurchaseStepId, StepCost> = {\n /*\n * The stepper opens at one guest, so the minimum is Continue alone. A larger party\n * costs a tap per head, which is the stepper's own design.\n */\n PARTY: cost(1),\n /* A day, then Continue — the design draws both. */\n DATE: cost(2),\n /*\n * A slot, then Continue — the design. Its Continue is Add to Cart, which is why the\n * order exists from the next step on.\n */\n TIME: cost(2),\n /*\n * The press. What the button OPENS is the ceremony's, and is added separately — see\n * `ceremonyCost`.\n */\n SIGN_IN: cost(1),\n /*\n * TWO FIELDS, NOT ONE. `BuyerDetails` takes `FirstName` and `LastName` apart, so a\n * single \"Name\" field would have to be split on whitespace before it could be sent. The\n * first cost model said one; counting the card's own controls caught it.\n */\n NAME: cost(1, 2),\n EMAIL: cost(1, 1),\n PHONE: cost(1, 1),\n /*\n * A GATE, not the questionnaire. Continue leaves for the questions, which are the\n * organiser's and are not counted: no floor we stated would be honest.\n */\n DETAILS: cost(1),\n /* One press, and it is the one that charges. */\n REVIEW: cost(1),\n /* A row from the list, then Confirm. */\n PAYMENT: cost(2),\n /*\n * A DETOUR NOBODY IS SENT TO, so its cost never enters a walk — the same reading\n * `PAYMENT` has. Stated because the record is exhaustive and a step with no entry\n * would not compile, which is the point of that.\n */\n PROMO: cost(2),\n /* A detour nobody is sent to, like the two above it. */\n ABANDON: cost(2),\n /* Input is blocked entirely, which is why the step has no collapsed state. */\n PROCESSING: cost(0),\n /*\n * A DETOUR, so it is never walked to and never counted — nothing in the flow decides a\n * payment fails. Its cost is the retry a buyer who meets it pays, which is the one tap\n * they would not otherwise have spent.\n */\n PAYMENT_FAILED: cost(1),\n /* The acknowledgement, and its Continue. */\n PAYMENT_SUCCESS: cost(1),\n /*\n * ONE TAP, AND IT IS SKIP — the MINIMUM, which is what this record measures. A star and\n * then Continue is two, and the photo grid is counted at two for exactly that shape; the\n * difference is that the grid offers no way past without choosing and this card does.\n * Nothing downstream reads the rating, so a buyer who presses Skip has completed the\n * step as fully as one who rates.\n *\n * IT STILL COSTS EVERY WALK A TAP, and it should: this card is in front of every buyer\n * who pays, so every benchmark here got one longer the day it was added. A step that\n * measured zero because it can be waved past would hide exactly that.\n */\n FEEDBACK: cost(1),\n /* The OrderSuccess checkpoint's card. As with SIGN_IN, the press only. */\n /*\n * ONE FIELD, PRE-FILLED. The address is already known — the order carries it — so the\n * work is reading it and pressing Confirm, not typing it again. Counted as a field all\n * the same: it is editable, and a buyer who wants a different account email pays for\n * the correction here rather than after the code has gone to the wrong inbox.\n */\n CONFIRM_EMAIL: cost(1, 1),\n /*\n * SIX BOXES, ONE FIELD. The code is one value however many notches it is drawn in, and\n * a buyer pasting it from a mail pays once. Counting six would say this step costs more\n * than the name and the email together, which is the opposite of true.\n */\n VERIFY_EMAIL: cost(1, 1),\n /*\n * @Zsolt — AUTH SURFACE. One press, and what it opens is the device's, which is the\n * same reason `SIGN_IN` counts only its own button: a fingerprint is not a tap we can\n * count and not one the buyer experiences as typing.\n */\n PASSKEY: cost(1),\n /*\n * A FACE, THEN CONTINUE. The grid opens on nothing chosen — a photo is the buyer's to\n * pick and not ours to pre-select — so the cheapest way past is one tap on a stock\n * avatar and one on the button. Upload costs whatever the device's own picker costs,\n * which is not a tap we can count, exactly as the passkey ceremony is not.\n */\n PROFILE_PHOTO: cost(2),\n /* Nothing to press. The account is being made; the card only says so. */\n ACCOUNT_CREATING: cost(0),\n /* The acknowledgement, and its Continue — `PAYMENT_SUCCESS`'s counterpart exactly. */\n ACCOUNT_CREATED: cost(1),\n CREATE_ACCOUNT: cost(1),\n /* The password and its confirmation, and a Continue. */\n PASSWORD: cost(1, 2),\n /* One Continue past the follow prompt. */\n FOLLOW: cost(1),\n};\n\n/** WHAT THE CEREMONY BEHIND A BUTTON COSTS, on top of pressing it. */\nexport function ceremonyCost(ceremony: AuthCeremony, devicePasskey: boolean): StepCost {\n switch (ceremony) {\n case 'PASSKEY':\n return cost(1);\n case 'FUNNEL':\n return devicePasskey ? cost(1) : cost(1, 2);\n case 'NEW_ACCOUNT':\n return cost(0);\n }\n}\n\n/** Whether a ceremony can be completed on this device at all. */\nexport function ceremonyAvailable(ceremony: AuthCeremony, devicePasskey: boolean): boolean {\n return ceremony === 'PASSKEY' ? devicePasskey : true;\n}\n\nfunction addCost(a: StepCost, b: StepCost): StepCost {\n return { taps: a.taps + b.taps, fields: a.fields + b.fields };\n}\n\n// ── THE SITUATIONS ───────────────────────────────────────────\n\nexport type FlowSituation = {\n readonly name: string;\n /** What this situation is, and on what authority. */\n readonly basis: string;\n /** Steps the host already composed, or the event does not need. */\n readonly excused: readonly PurchaseStepId[];\n /** Whether a card is on file. */\n readonly savedPaymentMethod: boolean;\n /** Whether THIS DEVICE holds a passkey for the buyer. */\n readonly devicePasskey: boolean;\n};\n\n/*\n * These numbers compare AUTH STATES WITHIN ONE ISLAND. They do not benchmark a\n * checkout, and reading them as one is unfair to this island: it is built to host every\n * possible step crossed with three sign-in states, and an implementation chooses how\n * much of that it defers.\n */\n\n/**\n * The island composing everything — a host that defers Compose to it, on an event that\n * uses every step. The longest legitimate walk, and the one the island has to be right\n * about. Nothing here is a typical purchase.\n */\nexport const ISLAND_COMPOSES: FlowSituation = {\n name: 'The island composes everything',\n basis:\n 'A host that defers Compose to the island, on a series sold in timed sessions that asks its own questions and has people to follow. The longest legitimate walk, and the one the island has to be right about.',\n excused: [],\n savedPaymentMethod: false,\n devicePasskey: false,\n};\n\n/**\n * The host composing the whole COMPOSE chunk — its own party selector, calendar and\n * timeslot picker — so the island is handed an order to commit.\n */\nexport const HOST_COMPOSES: FlowSituation = {\n name: 'The host composes',\n basis:\n \"The host's own calendar, party selector and timeslot picker fill the OrderIntent before the island is asked. DETAILS is excused — an order ready for payment does not need a questionnaire, and nothing says such a series asks one. FOLLOW is still assumed to run; it costs nothing to decline.\",\n excused: ['PARTY', 'DATE', 'TIME', 'DETAILS'],\n savedPaymentMethod: false,\n /*\n * A first-time buyer on somebody's marketing page has no passkey for that domain, so\n * the credential card is the realistic case rather than the worst one.\n */\n devicePasskey: false,\n};\n\n/**\n * The order preloaded, opening on Order Review — how a native host ships it. A single\n * ticket chosen by the host, an authenticated buyer, a card on file, no questionnaire\n * and nobody to follow.\n */\nexport const PRELOADED: FlowSituation = {\n name: 'Preloaded — straight to Order Review',\n basis:\n 'The preloaded shape: the host preloads the order with a single ticket and an authenticated buyer, so every Compose step is answered before the island opens. No questionnaire, nobody to follow, a card on file.',\n excused: ['PARTY', 'DATE', 'TIME', 'DETAILS', 'FOLLOW'],\n savedPaymentMethod: true,\n devicePasskey: true,\n};\n\n// ── THE WALK ─────────────────────────────────────────────────\n\n/**\n * How the buyer resolves an auth checkpoint when they have a choice. The walk is TOLD,\n * because both routes are legitimate and cost different amounts — which is the\n * comparison worth having. It is not a preference the flow holds.\n */\nexport type AuthRoute =\n /** Get into an account: passkey, password, or a new one. */\n | 'ACCOUNT'\n /** Stay out of one: Continue as Guest, and Skip at the end. */\n | 'GUEST';\n\n/** One route for the whole purchase, or a different one per checkpoint. */\nexport type RoutePlan = AuthRoute | Partial<Record<AuthCheckpoint, AuthRoute>>;\n\nfunction routeFor(plan: RoutePlan, checkpoint: AuthCheckpoint): AuthRoute {\n return typeof plan === 'string' ? plan : (plan[checkpoint] ?? 'ACCOUNT');\n}\n\nexport type FlowStop = {\n readonly step: PurchaseStepId;\n readonly cost: StepCost;\n /** Which button was pressed, on the steps that are checkpoints. */\n readonly via?: AuthCopyKey;\n /** Why the only way past this stop cannot be walked today. */\n readonly blockedBy?: string;\n};\n\n/**\n * WHERE A BUYER STANDING ON `step` SITS IN THIS WALK — the rule that lets a position be\n * a STEP rather than an offset.\n *\n * A walk is re-planned from the session on every render, and the session moves during a\n * purchase: making an account bypasses the OrderSuccess offer and answers the name, the\n * email and the phone, so up to four stops can disappear from BEHIND the buyer. An offset\n * into a list that shrinks is a position that silently means a different card — which is\n * how `ACCOUNT_CREATING` carried a buyer to the welcome the instant the account came\n * back, with the three-second floor under it never served.\n *\n * A STEP THE WALK NO LONGER STOPS AT IS NOT AN ERROR. It is a card this buyer no longer\n * needs, so the answer is the next one they do — `PURCHASE_STEPS` is a fixed total order,\n * which is what makes \"next\" mean something when the step itself is gone. Past every\n * remaining stop, the last one is the honest answer: there is nowhere further to be.\n */\nexport function stopIndex(stops: readonly FlowStop[], step: PurchaseStepId): number {\n const exact = stops.findIndex((stop) => stop.step === step);\n if (exact !== -1) return exact;\n\n const order = (id: PurchaseStepId) =>\n PURCHASE_STEPS.findIndex((candidate) => candidate.id === id);\n const here = order(step);\n const after = stops.findIndex((stop) => order(stop.step) >= here);\n return after === -1 ? Math.max(0, stops.length - 1) : after;\n}\n\nexport type FlowSkip = { readonly step: PurchaseStepId; readonly why: string };\n\nexport type FlowWalk = {\n readonly stops: readonly FlowStop[];\n readonly skipped: readonly FlowSkip[];\n readonly taps: number;\n readonly fields: number;\n /** Every stop whose only route is unbuilt, in the order they are met. */\n readonly blocked: readonly { readonly step: PurchaseStepId; readonly reason: string }[];\n /** The session the buyer ends the purchase in. */\n readonly ended: AuthSession;\n};\n\n/**\n * A guard, not a policy. A checkpoint that asked more than this many times would be\n * looping, and looping is the failure this module exists to catch — so it throws rather\n * than returning a large number a caller might average into a report. Three is\n * generous: the longest legitimate run is Sign Out (one card) then the guest card (a\n * second).\n */\nconst MAX_CHECKPOINT_ROUNDS = 3;\n\n/** The button this route would press on the card in front of it. */\nconst ROUTE_PREFERENCE: Record<AuthRoute, readonly AuthOutcome['kind'][]> = {\n /*\n * Straight into an account. `RECOVER` is last on both routes and is never reached on\n * today's cards — it appears only on the funnel — but a route that could be talked into\n * pressing Forgot Password would leave the purchase.\n */\n ACCOUNT: ['AUTHENTICATE', 'PROCEED', 'SIGN_OUT', 'GUEST', 'RECOVER'],\n /*\n * Stay out of one: the guest button if there is one, then anything that simply proceeds\n * (Skip), then Sign Out — not an exit, but the way to a card that has a guest button.\n */\n GUEST: ['GUEST', 'PROCEED', 'SIGN_OUT', 'AUTHENTICATE', 'RECOVER'],\n};\n\nfunction chooseAction(\n actions: readonly AuthCopyKey[],\n route: AuthRoute,\n devicePasskey: boolean,\n): AuthCopyKey {\n for (const kind of ROUTE_PREFERENCE[route]) {\n const matching = actions.filter((key) => {\n const outcome = AUTH_ACTION_OUTCOME[key];\n if (outcome.kind !== kind) return false;\n return outcome.kind !== 'AUTHENTICATE' || ceremonyAvailable(outcome.ceremony, devicePasskey);\n });\n if (matching.length === 0) continue;\n\n /*\n * THE DESIGN'S OWN ORDER DECIDES, and the availability filter above is the only thing\n * allowed to overrule it. Ranking the matches by what their ceremony costs was tried\n * and was wrong: it had the account route pressing \"Create Account\" instead of \"Sign in\n * with ▮\", because creating one costs nothing here. Those are two journeys, not two\n * prices for one.\n */\n return matching[0] as AuthCopyKey;\n }\n /*\n * Every outcome kind is ranked, so this is reachable only from a card with no buttons\n * at all — a dead end by definition, and it says so.\n */\n throw new Error('an auth card with no actions is a dead end');\n}\n\n/** Walk one purchase and report what it cost. */\nexport function walkPurchase(\n start: AuthSession,\n situation: FlowSituation,\n route: RoutePlan,\n account: Account,\n /**\n * WHETHER THE OFFER HAS ALREADY BEEN TAKEN, which a walk cannot always see for itself.\n *\n * `makingAccount` is otherwise read off the press at `ORDER_SUCCESS` — and that press\n * stops happening the moment the account exists, because an AUTHENTICATED buyer bypasses\n * the offer with \"the order is already on the buyer's account\". So the sub-flow deletes\n * its own reason for running: `ACCOUNT_CREATED` and `PASSKEY` come AFTER the session is\n * minted, and a walk recomputed from the new session skips them both — the buyer goes\n * from Creating Account to the follow prompt without ever being welcomed or offered a\n * passkey.\n *\n * It is a parameter rather than something inferred here because a walk holds no history:\n * \"signed in on arrival\" and \"signed in a card ago by the sub-flow\" are the same session\n * and mean opposite things. Only the caller knows which, and the caller already does —\n * see `accountChosen`. Benchmarks pass nothing and keep the press-derived reading.\n */\n accountTaken = false,\n): FlowWalk {\n let session = start;\n const stops: FlowStop[] = [];\n const skipped: FlowSkip[] = [];\n const blocked: { step: PurchaseStepId; reason: string }[] = [];\n /*\n * Whether the buyer took the account offer AFTER paying, which is the only thing that\n * makes the password step run.\n */\n let makingAccount = accountTaken;\n\n const skip = (step: PurchaseStepId, why: string) => skipped.push({ step, why });\n\n for (const step of PURCHASE_STEPS) {\n /*\n * A DETOUR IS NOT WALKED TO, so it is not a stop and it is not a skip either — nothing\n * was carried past it, because it was never coming. The buyer reaches it by pressing a\n * control on the card it hangs off; see `PurchaseStep.detourFrom`.\n */\n if (step.detourFrom !== undefined) continue;\n\n if (situation.excused.includes(step.id)) {\n skip(step.id, `${situation.name}: the host or the event makes it unnecessary.`);\n continue;\n }\n\n if (step.checkpoint) {\n const walked = walkCheckpoint(\n step.checkpoint,\n session,\n routeFor(route, step.checkpoint),\n account,\n situation.devicePasskey,\n );\n session = walked.session;\n if (walked.presses.length === 0) {\n skip(step.id, walked.bypassReason ?? 'bypassed');\n continue;\n }\n makingAccount ||=\n step.checkpoint === 'ORDER_SUCCESS' && walked.presses.includes('CREATE_ACCOUNT');\n for (const via of walked.presses) {\n const blockedBy = UNBUILT_AUTH_ROUTES[via];\n const outcome = AUTH_ACTION_OUTCOME[via];\n /* The press, PLUS whatever the button opens. Only `AUTHENTICATE` carries a ceremony. */\n const total =\n outcome.kind === 'AUTHENTICATE'\n ? addCost(STEP_COST[step.id], ceremonyCost(outcome.ceremony, situation.devicePasskey))\n : STEP_COST[step.id];\n stops.push({ step: step.id, cost: total, via, ...(blockedBy && { blockedBy }) });\n if (blockedBy) blocked.push({ step: step.id, reason: blockedBy });\n }\n continue;\n }\n\n /*\n * THE ORDER REQUIREMENTS — the only other excusal that is code. An account answers\n * them; a lapsed session and a guest do not. This is where authenticating early pays\n * for itself.\n */\n if (step.id === 'NAME' || step.id === 'EMAIL' || step.id === 'PHONE') {\n const gate = requirementGate(session.auth, step.id);\n if (gate.kind === 'ANSWERED') {\n skip(step.id, `The account already holds it: “${gate.value}”.`);\n continue;\n }\n stops.push({ step: step.id, cost: STEP_COST[step.id] });\n continue;\n }\n\n /*\n * EVERY STEP OF MAKING AN ACCOUNT, and none of them for anyone else. Confirming the\n * address, verifying it, the passkey offer, the password and the wait all exist only\n * because a buyer pressed Create Account — a guest and an existing account-holder walk\n * past the lot.\n *\n * @Zsolt — AUTH SURFACE. This list is what decides whether the account sub-flow runs\n * at all; adding a step to it without adding it here would charge every buyer for it.\n */\n if (ACCOUNT_CREATION_STEPS.has(step.id) && !makingAccount) {\n skip(step.id, 'The buyer declined the account, or already had one.');\n continue;\n }\n\n /*\n * AND THE ONES THE PLATFORM CANNOT ANSWER YET are walked by nobody, account or not.\n *\n * This is BELOW the check above rather than beside it because the two say different\n * things: that one is about this buyer (they declined, or already had an account) and\n * this one is about the platform (the endpoint is not live). A buyer who DID press\n * Create Account still walks past these, and the reason they are skipped is worth\n * being able to read — see `UNBUILT_ACCOUNT_STEPS`, which carries it.\n */\n const unbuilt = UNBUILT_ACCOUNT_STEPS[step.id];\n if (unbuilt !== undefined) {\n skip(step.id, unbuilt);\n continue;\n }\n\n stops.push({ step: step.id, cost: STEP_COST[step.id] });\n }\n\n return {\n stops,\n skipped,\n taps: stops.reduce((n, stop) => n + stop.cost.taps, 0),\n fields: stops.reduce((n, stop) => n + stop.cost.fields, 0),\n blocked,\n ended: session,\n };\n}\n\n/** One checkpoint, pressed until the buyer is past it. */\nfunction walkCheckpoint(\n checkpoint: AuthCheckpoint,\n start: AuthSession,\n route: AuthRoute,\n account: Account,\n devicePasskey: boolean,\n): { session: AuthSession; presses: AuthCopyKey[]; bypassReason?: string } {\n let session = start;\n const presses: AuthCopyKey[] = [];\n\n for (let round = 0; round <= MAX_CHECKPOINT_ROUNDS; round += 1) {\n const prompt = authPrompt(checkpoint, session);\n if (prompt.kind === 'BYPASS') {\n return { session, presses, bypassReason: prompt.reason };\n }\n\n const key = chooseAction(AUTH_CARD_ACTIONS[prompt.card], route, devicePasskey);\n const outcome = AUTH_ACTION_OUTCOME[key];\n presses.push(key);\n session = applyAuthOutcome(session, outcome, account);\n if (outcomeProceeds(outcome)) return { session, presses };\n }\n\n throw new Error(\n `${checkpoint} kept asking after ${MAX_CHECKPOINT_ROUNDS} presses on the ${route} route`,\n );\n}\n\n// ── CAN A BUYER GET OUT? ─────────────────────────────────────\n\n/** The header cross, as a press. */\nexport const DISMISS = 'DISMISS';\n\nexport type ExitPress = AuthCopyKey | typeof DISMISS;\n\nexport type CheckpointExit = {\n /** How many presses it took. Zero means the checkpoint never asked. */\n readonly taps: number;\n readonly via: readonly ExitPress[];\n /** The session the buyer is in once they are past. */\n readonly session: AuthSession;\n};\n\n/**\n * THE SHORTEST WAY PAST A CHECKPOINT, by breadth-first search — or `null` if there is\n * none.\n */\nexport function shortestExit(\n checkpoint: AuthCheckpoint,\n start: AuthSession,\n account: Account,\n { builtOnly = false }: { readonly builtOnly?: boolean } = {},\n): CheckpointExit | null {\n type Node = { session: AuthSession; via: ExitPress[] };\n const queue: Node[] = [{ session: start, via: [] }];\n const seen = new Set<string>();\n\n while (queue.length > 0) {\n const node = queue.shift() as Node;\n const key = `${node.session.auth.status}|${node.session.guest}`;\n if (seen.has(key)) continue;\n seen.add(key);\n\n const prompt = authPrompt(checkpoint, node.session);\n if (prompt.kind === 'BYPASS') {\n return { taps: node.via.length, via: node.via, session: node.session };\n }\n\n /*\n * The cross, where it is an exit at all. Offered before the buttons so a one-press\n * escape is found even when a button would also do.\n */\n if (!checkpointGates(checkpoint)) {\n return { taps: node.via.length + 1, via: [...node.via, DISMISS], session: node.session };\n }\n\n for (const action of AUTH_CARD_ACTIONS[prompt.card]) {\n if (builtOnly && UNBUILT_AUTH_ROUTES[action]) continue;\n const outcome = AUTH_ACTION_OUTCOME[action];\n const next = applyAuthOutcome(node.session, outcome, account);\n const via = [...node.via, action];\n if (outcomeProceeds(outcome)) return { taps: via.length, via, session: next };\n queue.push({ session: next, via });\n }\n }\n\n return null;\n}\n\n/**\n * A route as a sentence, for a failure message that names the doors rather than\n * counting them.\n */\nexport function describeRoute(via: readonly ExitPress[]): string {\n if (via.length === 0) return '(bypassed)';\n return via.map((press) => (press === DISMISS ? '(close)' : `“${AUTH_COPY[press]}”`)).join(' → ');\n}\n","/**\n * THE WIDGET'S OWN DATA LAYER — what `appKey` is for.\n *\n * `CheckoutProps.appKey` has said since the first commit that \"the data layer\n * authenticates with it\", and the body read `void appKey`. Everything the widget needed\n * arrived as a prop instead, which is fine for a host already holding it and wrong for\n * the case this widget exists to serve: an implementation that cannot or will not engage\n * with the SDK, drops the island onto a page and expects it to work.\n *\n * ── WHAT IT REPLACES ─────────────────────────────────────────────────────────\n *\n * `schedule` and `userTypes` were props a host had to fetch and shape. They still are:\n * a host that already holds them passes them and this never runs. Absent, the widget\n * fetches them itself.\n *\n * ONE CALL ANSWERS BOTH. `getSeriesInfo` returns the run's events AND its user types, so\n * the calendar and the party stepper come from the same request — which is also why they\n * are fetched together here rather than by two hooks that would each have to know the key.\n *\n * ── WHY A HOOK AND NOT A PROVIDER ────────────────────────────────────────────\n *\n * The SDK reaches its client through `ScopeProvider`, and a widget that required one\n * would be asking for exactly the engagement it is meant to avoid. So the client is built\n * from the props the widget already takes, and a host that HAS a provider is unaffected —\n * it passes the data and this stays asleep.\n */\n\nimport { useEffect, useMemo, useState } from 'react';\nimport {\n ENVIRONMENT_URLS,\n ScopeClient,\n type Environment,\n type EventTimeslot,\n type QuestionnaireQuestion,\n type Ticket,\n} from '@scopetickets/api';\nimport type { CheckoutSchedule } from '../island/ScopeTicketsCheckout';\nimport type { PartyUserTypeOption } from '../island/PartyStepper';\nimport { soonestRelevantDay, type CalendarSeriesEvent } from '../island/island-calendar';\nimport {\n parseWallClockTime,\n slotFullness,\n timeOfDayInZone,\n type Timeslot,\n} from '../island/island-timeslots';\nimport type { FollowEntity } from '../island/FollowList';\nimport { runArtwork } from '../domain/artwork';\nimport { groupUserTypes, userTypeNames } from '../domain/user-types';\n\n/**\n * WHERE TO REACH THE PLATFORM. Every field optional, because `appKey` is the only thing\n * actually required — it is the Bearer token, and it is what `CheckoutProps.appKey` has\n * always said it was.\n *\n * IT USED TO DEMAND AN `orgKey` AND THAT WAS THE BUG. Nothing the widget calls uses one:\n * it appears in exactly one endpoint on the whole client, the deprecated v1\n * `getEvents`. Requiring it meant a host passing only its app key got no client, so\n * nothing was fetched — no user types, no sessions, and no error either, because a\n * request that is never made cannot fail.\n */\nexport type CheckoutSource = {\n /** Which platform to talk to. Defaults to `production`. */\n readonly environment?: Environment;\n /** Only the deprecated v1 event list needs one; nothing this widget calls does. */\n readonly orgKey?: string;\n};\n\nexport type CheckoutData = {\n readonly schedule: CheckoutSchedule | undefined;\n /**\n * THE RUN'S ARTWORK, for the cart's per-line thumbnails — the design's\n * `AvatarImage-Event`. `Theme.Backgrounds[0]`, made absolute; see `runArtwork`, which\n * owns both of those decisions and the reasons they are not obvious.\n */\n readonly artwork: string | undefined;\n readonly userTypes: readonly PartyUserTypeOption[] | undefined;\n /** Every assignment key to its word, for labelling cart lines — not the stepper's rows. */\n readonly userTypeNames: Readonly<Record<string, string>>;\n /**\n * WHAT THE MONEY IS IN. Set at three levels and read most-specific-first: the product,\n * then its event, then the run. A ticket priced in sterling inside a euro-denominated\n * series is the case the order matters for, and the wrong symbol on a price is worse\n * than no price at all.\n */\n readonly currency: string | undefined;\n /** The event's own questions, where it asks any — see `OrderIntent.asksQuestions`. */\n readonly questions: readonly QuestionnaireQuestion[];\n /** Who a buyer can follow at the end: the people whose event this is. */\n readonly follow: readonly FollowEntity[];\n /** The event key the chosen day belongs to, which is what a cart is opened on. */\n readonly eventKeyByDay: Readonly<Record<string, string>>;\n /**\n * WHETHER THE RUN SELLS SESSIONS AT ALL, or `undefined` before anything has been asked.\n *\n * A run that does not is not a run with an empty list — it is a run where the question\n * does not arise, and Select Time should never be reached. `false` is what excuses it.\n */\n readonly hasTimeslots: boolean | undefined;\n /**\n * WHAT THE DAY WILL SELL IN ONE TRANSACTION, at its most permissive. `maxParty` is a\n * host's own assertion and was the only ceiling the stepper had — TwinkleTown says 20\n * where every ticket says 5, so a buyer could build a party nothing on sale could\n * satisfy and only find out at `addItemsBulk`.\n */\n readonly limits: { readonly min: number; readonly max: number } | undefined;\n readonly loading: boolean;\n readonly error: Error | null;\n};\n\nconst NOTHING: CheckoutData = {\n schedule: undefined,\n artwork: undefined,\n userTypes: undefined,\n userTypeNames: {},\n currency: undefined,\n questions: [],\n follow: [],\n eventKeyByDay: {},\n hasTimeslots: undefined,\n limits: undefined,\n loading: false,\n error: null,\n};\n\n/**\n * A slot as the island draws it.\n *\n * FULLNESS IS CONVERTED NOW, AND IT USED TO BE DROPPED. The note here said the wire's\n * `Remaining` was a raw number whose scale the platform decides, so passing it through\n * would draw an indicator off something nobody had pinned down — and it wrote\n * `remaining: null` instead. That was right about the ambiguity and wrong about the\n * remedy: every slot in a live picker then drew NO ring, because the arc, the colour ramp\n * and the sold-out words are all readings of a number that never arrived.\n *\n * `slotFullness` pins it, from the value's own range and the `Total` beside it. See its\n * note, which is where the two scales and the evidence for each are written down.\n */\nfunction toTimeslot(slot: EventTimeslot): Timeslot {\n /*\n * BOTH SHAPES, because the platform sends both: a SESSION's times are full local\n * timestamps (`2027-06-15T10:00:00`) and a ticket's own are bare clock times (`19:00`).\n * `parseWallClockTime` reads the second and returns null for the first, so the date is\n * taken off before it is asked — and a time that is neither is dropped rather than\n * guessed at, because a slot with an unreadable start is not a slot anybody can pick.\n */\n const clock = (value: string | null) =>\n parseWallClockTime(value === null ? null : value.includes('T') ? value.slice(11) : value);\n\n return {\n startTime: clock(slot.LocalStartTime) ?? '',\n endTime: clock(slot.LocalEndTime),\n remaining: slotFullness(slot.Remaining, slot.Total),\n };\n}\n\n/** `2027-11-01T19:00:00` -> `2027-11-01`. The GROUPING day, which is what the run is keyed on. */\nconst dayOf = (iso: string): string => iso.slice(0, 10);\n\n/**\n * TODAY ON THE VENUE'S CALENDAR, not the device's.\n *\n * `Venue.TimeZone` is an IANA zone and every event carries its venue, so this is a real\n * answer rather than a guess — which matters most at the edges of a day: a buyer in Sydney\n * looking at a Dublin run at 09:00 their time is looking at yesterday's calendar, and a\n * picker that greyed out tonight's show for them would be wrong about the only thing it is\n * for.\n */\nfunction dayInZone(now: Date, timeZone: string | null): string {\n try {\n return new Intl.DateTimeFormat('en-CA', {\n timeZone: timeZone ?? 'UTC',\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n }).format(now);\n } catch {\n /* An unrecognised zone throws rather than falling back, and a calendar that cannot\n * render is worse than one anchored a few hours out. */\n return now.toISOString().slice(0, 10);\n }\n}\n\n/**\n * ONE CLIENT FOR THE WIDGET, built from the props it already takes.\n *\n * Its own hook because two layers need the same one — what the run is, and what the order\n * is — and a second client would be a second connection pool and a second set of headers\n * for no reason. Null without a `source`, which is how a host that supplies everything\n * makes the whole data layer inert.\n */\n/**\n * THE MOST PERMISSIVE TICKET ON THE DAY, not the one the cart happens to open on.\n *\n * The ceiling exists to stop a buyer entering a party nothing on sale could ever satisfy\n * — not to narrow the question to one product. A run selling a family ticket of 10 beside\n * a single of 1 can seat 10, so 10 is the ceiling; reading the first ticket instead would\n * cap the whole run at 1. The floor is the lowest for the same reason.\n */\nfunction ticketLimits(tickets: readonly Ticket[]): { min: number; max: number } | undefined {\n const maxima = tickets\n .map((ticket) => ticket.MaxPerTransaction)\n .filter((value): value is number => typeof value === 'number' && value > 0);\n if (maxima.length === 0) return undefined;\n\n const minima = tickets\n .map((ticket) => ticket.MinPerTransaction)\n .filter((value): value is number => typeof value === 'number' && value > 0);\n\n return { min: minima.length === 0 ? 1 : Math.min(...minima), max: Math.max(...maxima) };\n}\n\nexport function useCheckoutClient(\n appKey: string,\n source: CheckoutSource | undefined,\n): ScopeClient | null {\n /*\n * MEMOISED ON THE VALUES, not on the object. `source` is written inline by most hosts\n * and is therefore a new object every render; keying on it would rebuild the client, and\n * every effect downstream, on each one.\n */\n const orgKey = source?.orgKey ?? '';\n const environment = source?.environment ?? 'production';\n\n return useMemo(() => {\n /* An app key is the whole requirement — see `CheckoutSource`. */\n if (appKey === '') return null;\n const urls = ENVIRONMENT_URLS[environment];\n return new ScopeClient({\n apiKey: appKey,\n orgKey,\n environment,\n apiUrl: urls.apiUrl,\n paymentHostUrl: urls.paymentHostUrl,\n });\n }, [appKey, orgKey, environment]);\n}\n\nexport function useCheckoutData(\n subjectKey: string,\n isSeries: boolean,\n client: ScopeClient | null,\n /** Skipped entirely when the host already holds everything. */\n enabled: boolean,\n /** The day whose sessions are wanted. Absent asks for the soonest the run has. */\n day?: string,\n /**\n * ONLY EVER FOR THE WARNING BELOW. The client already holds it and keeps it private,\n * and the one thing a failed request cannot tell you is which platform it was aimed at\n * — which is the answer whenever a real key 404s on a real subject.\n */\n environment: Environment = 'production',\n): CheckoutData {\n const [data, setData] = useState<CheckoutData>(NOTHING);\n\n useEffect(() => {\n if (!enabled || client === null) return;\n\n const abort = new AbortController();\n setData((was) => ({ ...was, loading: true, error: null }));\n\n const load = async () => {\n const info = isSeries\n ? await client.getSeriesInfo(subjectKey, abort.signal)\n : await client.getEventInfo(subjectKey, abort.signal);\n\n /*\n * THE EVENT A DAY BELONGS TO. A cart is opened on an EVENT and the buyer picks a DAY;\n * this is the join, and without it the order has nothing to be about.\n */\n const eventKeyByDay: Record<string, string> = {};\n for (const event of info.Events) eventKeyByDay[dayOf(event.Date)] = event.Key;\n\n const events: CalendarSeriesEvent[] = info.Events.map((event) => ({\n eventKey: event.Key,\n name: event.Name,\n day: dayOf(event.Date),\n }));\n\n /*\n * THE VENUE'S CLOCK, from the venue. `Venue.TimeZone` is an IANA zone and every event\n * carries its venue — `nowTime` was `00:00` for a turn, which is not a clock at all:\n * it says every slot today is still to come, which is exactly the question the time\n * picker asks it.\n *\n * READ BEFORE THE DAY IS CHOSEN, because the choice below is now made against it.\n */\n const timeZone = info.Events[0]?.Venue?.TimeZone ?? null;\n const now = new Date();\n const today = dayInZone(now, timeZone);\n\n /*\n * ONE REQUEST, FOR THE DAY BEING LOOKED AT — not one per night.\n *\n * It was `Promise.all` over every event in the run: a month's run is thirty parallel\n * requests on mount, and a season is hundreds. They are also all thrown away but one,\n * because a buyer is choosing a session on ONE day. The SDK asks for a single event's\n * tickets and so does this.\n *\n * WHICH DAY: the one chosen, or the soonest the run has — the calendar opens on it,\n * so it is the one about to be asked for.\n *\n * AND \"THE SOONEST\" IS `soonestRelevantDay`, NOT THE FIRST EVENT THE WIRE LISTED.\n * These were two different answers to one question. This side stored the slots under\n * `Events[0]`, whatever order the platform happened to return; the picker looked them\n * up under the soonest day that has not already gone by. On a run with past nights in\n * it — any run midway through — the two disagree, `slotsByDay` misses, and Select Time\n * draws EMPTY with the sessions sitting in the response under a key nobody asks for.\n *\n * It is the picker's own function so that there is one answer and it cannot drift\n * again; `soonestRelevantDay` needs a `today`, which is why the clock is read above.\n */\n const wanted =\n day !== undefined && day in eventKeyByDay ? day : soonestRelevantDay({ events }, today);\n const forDay = wanted === null ? undefined : eventKeyByDay[wanted];\n\n const slotsByDay: Record<string, readonly Timeslot[]> = {};\n const questions: QuestionnaireQuestion[] = [];\n /*\n * IT DOES NOT SWALLOW THE REASON ANY MORE, and swallowing it cost three wrong\n * diagnoses. A failed tickets request produced an empty list, an empty list produced\n * a picker with nothing in it, and a picker with nothing in it looks exactly like a\n * run that sells no sessions. The calendar still survives a failure here — but the\n * failure is now something you can read rather than something you have to infer.\n */\n let list: Ticket[] = [];\n let ticketsError: Error | null = null;\n if (forDay !== undefined) {\n try {\n list = await client.getEventTickets(forDay, abort.signal);\n } catch (cause: unknown) {\n ticketsError = cause instanceof Error ? cause : new Error(String(cause));\n }\n }\n const tickets = wanted === null ? [] : ([[wanted, list]] as const);\n /*\n * `HasTimeslot` DECIDES, NOT THE PRESENCE OF A LIST. A ticket that does not sell\n * sessions can still carry `Timeslots`, and reading them anyway is how a run with no\n * sessions ends up with an empty Select Time in front of it — which is what happened.\n * The SDK's own reader gates on the same flag and its selector skips the step when\n * nothing has one.\n */\n let hasTimeslots = false;\n let productCurrency: string | undefined;\n for (const [on, forThatDay] of tickets) {\n const slots = forThatDay.flatMap((ticket) =>\n ticket.HasTimeslot ? (ticket.Timeslots ?? []) : [],\n );\n if (forThatDay.some((ticket) => ticket.HasTimeslot)) hasTimeslots = true;\n if (slots.length > 0) slotsByDay[on] = slots.map(toTimeslot);\n for (const ticket of forThatDay) {\n questions.push(...(ticket.Questions ?? []));\n productCurrency ??= ticket.Currency ?? undefined;\n }\n }\n\n /*\n * ALL THREE PLACES AN ASSIGNMENT CAN ARRIVE, poured into one list rather than read\n * in precedence: the response's own, each event's, and each product's. The\n * response-level list is the FLAT UNION of the others rather than a summary, so\n * preferring it and stopping was right while it was empty and wrong the moment it\n * filled. Duplicates here are expected and harmless — see `groupUserTypes`, which\n * owns why the rows are grouped by name and what happens if they are not.\n */\n const assignments = [\n ...(info.UserTypes ?? []),\n ...info.Events.flatMap((event) => event.UserTypes ?? []),\n ...list.flatMap((ticket) => ticket.UserTypes ?? []),\n ];\n\n const organisation = info.Events[0]?.Organisation;\n\n /*\n * ARTWORK IS THE ONE THING HERE THAT FAILS IN SILENCE: a missing picture draws the\n * avatar's own fill, which is what a ticket looks like at a glance, and an `<img>` that\n * 404s reports nothing. So a theme that yields none says so, and carries the shape it\n * had — a warning without it only starts an argument about which field was meant.\n */\n const theme = info.Series?.Theme ?? info.Events[0]?.Theme;\n const artwork = runArtwork(\n info.Series,\n info.Events,\n ENVIRONMENT_URLS[environment].artworkUrl,\n );\n if (artwork === undefined && theme !== undefined && typeof console !== 'undefined') {\n console.warn(\n '[ScopeTicketsCheckout] no cart artwork resolved from this run\\u2019s Theme. ' +\n 'Expected a url in `Theme.Backgrounds[0]`. The Theme as it arrived:',\n theme,\n );\n }\n\n return {\n schedule: {\n series: { events },\n today,\n nowTime: timeOfDayInZone(now, timeZone),\n slotsByDay,\n } satisfies CheckoutSchedule,\n userTypes: groupUserTypes(assignments),\n userTypeNames: userTypeNames(assignments),\n /*\n * THE QUESTIONS RIDE ON THE TICKETS, so they arrive with the slots and cost no\n * request of their own. `getQuestionnaireQuestions` wants a cart's event id, which\n * does not exist yet at the step that has to know whether to ask.\n */\n questions: [...new Map(questions.map((q) => [q.QuestionId, q])).values()],\n /*\n * WHOSE EVENT IT IS. There is no follow endpoint and there does not need to be:\n * the organisation is on every event, and it is who a buyer would want to hear\n * from again.\n *\n * NOT THE VENUE, though the event names one. A venue hosts whatever is booked\n * into it — following one subscribes a buyer to every unrelated thing that happens\n * in a building, which is not what \"stay up to date\" offered them. The organiser\n * is the party whose next event resembles this one.\n */\n follow: [\n organisation === undefined\n ? null\n : { key: organisation.Key, name: organisation.Name, kind: 'Organiser' },\n ].filter((entity): entity is FollowEntity => entity !== null),\n /*\n * `Backgrounds[0]`, made absolute against the CDN, the run's before a night's — see\n * `runArtwork`. The platform answers with site-root paths, so the origin is the\n * whole of the work: without it every thumbnail points at the customer's own domain.\n */\n artwork,\n eventKeyByDay,\n hasTimeslots,\n limits: ticketLimits(list),\n ticketsError,\n /* Most specific first — a product's own, then its event's, then the run's. */\n currency: productCurrency ?? info.Events[0]?.Currency ?? info.Series?.Currency ?? undefined,\n };\n };\n\n load()\n .then(({ ticketsError, ...loaded }) => {\n if (abort.signal.aborted) return;\n /*\n * A DAY'S TICKETS FAILING IS NOT THE CALENDAR FAILING, so the run is kept — but the\n * reason travels with it, because \"no sessions\" and \"we could not ask\" look the same\n * on screen and are not the same thing.\n */\n if (ticketsError !== null && typeof console !== 'undefined') {\n console.warn(\n '[ScopeTicketsCheckout] could not load tickets for this day; ' +\n 'sessions, questions and user types will be missing.',\n ticketsError,\n );\n }\n setData({ ...loaded, loading: false, error: ticketsError });\n })\n .catch((cause: unknown) => {\n if (abort.signal.aborted) return;\n /*\n * THE RUN ITSELF FAILING, which is everything failing — no calendar, no sessions,\n * no user types. It used to set `error` and say nothing, and `error` is read by\n * nobody, so the loudest failure the data layer has was also its quietest.\n *\n * IT NAMES THE ENVIRONMENT because that is the failure this shape usually is. An\n * app key belongs to ONE platform, `environment` defaults to production, and a\n * staging key asked of production gets a 404 that looks exactly like a subject\n * that does not exist.\n */\n if (typeof console !== 'undefined') {\n console.warn(\n `[ScopeTicketsCheckout] could not load ${isSeries ? 'series' : 'event'} ` +\n `'${subjectKey}' from ${environment} (${ENVIRONMENT_URLS[environment].apiUrl}). ` +\n 'If the key is right, check `source.environment` \\u2014 it defaults to production.',\n cause,\n );\n }\n setData({\n ...NOTHING,\n error: cause instanceof Error ? cause : new Error(String(cause)),\n });\n });\n\n return () => abort.abort();\n }, [client, subjectKey, isSeries, enabled, day, environment]);\n\n return enabled ? data : NOTHING;\n}\n","/**\n * THE RUN'S OWN PICTURE, resolved to something an `<img>` on somebody else's page can load.\n *\n * TWO FACTS ABOUT THE WIRE, AND EACH ONE LOOKS LIKE SUCCESS WHEN IT IS WRONG.\n * `@scopetickets/avatar` draws `<img src>` unconditionally, so a bad url and a missing one\n * both render as its own fill — which is roughly what a ticket looks like anyway.\n *\n * THE PICTURE IS `Backgrounds`, NOT `Cover`. `Cover` is the link preview: a different asset,\n * and on its own host.\n *\n * THE HOST IS NOT THE PLATFORM'S TO CHOOSE. Artwork urls are stored absolute, keeping the\n * host of whichever environment UPLOADED the file — so a run authored against dev answers\n * `cdn-dev` from production forever. The path is the platform's; the host is this\n * integration's, and `ENVIRONMENT_URLS[env].artworkUrl` states it.\n */\n\nimport { ENVIRONMENT_URLS, type Environment } from '@scopetickets/api';\n\n/** The artwork half of the wire's `Theme`, and nothing else it carries. */\nexport type ArtworkTheme = {\n readonly Backgrounds?: readonly string[] | null;\n readonly Cover?: string | null;\n};\n\n/**\n * Which hosts are Scope's to redirect. Narrow on purpose: artwork an organiser serves from\n * their own domain is theirs, and passes through untouched.\n */\nconst SCOPE_ARTWORK_HOST = /(^|\\.)scopetickets\\.com$/i;\n\n/** One url, made absolute and put on the configured CDN. */\nexport function absoluteArtworkUrl(\n url: string | null | undefined,\n origin?: string,\n): string | undefined {\n if (!url) return undefined;\n /* Protocol-relative. The page's own scheme is not a safe guess inside an embed. */\n const stated = url.startsWith('//') ? `https:${url}` : url;\n if (origin === undefined) return stated;\n\n try {\n /* One call serves both shapes: a site-root path takes the base, an absolute url ignores it. */\n const parsed = new URL(stated, origin);\n if (!SCOPE_ARTWORK_HOST.test(parsed.hostname)) return parsed.href;\n\n /* Everything after the origin is the platform's, and is kept verbatim. */\n const cdn = new URL(origin);\n parsed.protocol = cdn.protocol;\n parsed.host = cdn.host;\n return parsed.href;\n } catch {\n return stated;\n }\n}\n\n/**\n * THE PICTURE EVERY LINE OF THE CART WEARS — `Backgrounds[0]`.\n *\n * THE RUN'S FIRST, THEN A NIGHT'S OWN: a series is one artwork over many nights, and the\n * same order `EventProvider` reads them in. A series that names none does NOT borrow a\n * night's — that would put a different picture on the cart depending on which day happened\n * to come first in the response.\n *\n * `undefined` where there is none, which the avatar answers with its own fill; an empty\n * string would be a src the browser resolves against the host's page.\n */\nexport function runArtwork(\n series: { readonly Theme?: ArtworkTheme } | null | undefined,\n events: readonly { readonly Theme?: ArtworkTheme }[],\n /** The CDN every Scope-hosted url is put on. Stated by the caller, never inferred here. */\n origin?: string,\n): string | undefined {\n const theme = series?.Theme ?? events[0]?.Theme;\n if (theme === undefined) return undefined;\n\n for (const background of theme.Backgrounds ?? []) {\n const resolved = absoluteArtworkUrl(background, origin);\n if (resolved !== undefined) return resolved;\n }\n return undefined;\n}\n\n/**\n * THE CDN A HOST SHOULD RESOLVE AGAINST — the same one this widget uses.\n *\n * PUBLISHED BECAUSE A HOST THAT SUPPLIES `cartLines` OWNS THE PICTURE, and cannot\n * resolve it correctly without this: the url on the wire keeps the host of whichever\n * environment uploaded the file, so the stored one answers 403 from anywhere else.\n * Measured on TwinkleTown's staging series, 2026-09-10 — the same path is 403 on\n * `cdn-dev.scopetickets.com` and 200 on `cdn.scopetickets.com`.\n *\n * A HOST CANNOT READ `ENVIRONMENT_URLS` ITSELF. `@scopetickets/api` is this package's\n * dependency and not the host's, so without this the only way to a working `<img>` is a\n * hostname typed into somebody's integration — which is the fact this module exists to\n * keep in one place.\n */\nexport function artworkOrigin(environment: Environment = 'production'): string {\n return ENVIRONMENT_URLS[environment].artworkUrl;\n}\n","import { useMemo } from 'react';\nimport type { ScopeClient } from '@scopetickets/api';\nimport { accountGateway } from './accountGateway';\nimport { simulatedAccountGateway } from '../testing/simulate';\nimport type { AccountCreationGateway } from '../domain/account-creation';\n\n/**\n * The account operations, built on the widget's own client.\n *\n * A HOOK RATHER THAN A CALL IN THE COMPONENT, so the gateway is one object for the life\n * of the client rather than a new one each render — the passkey step opens a challenge\n * in an effect keyed on it, and a gateway rebuilt every render would open a new challenge\n * every render.\n *\n * `null` where there is no client, which is the same condition the data layer already\n * treats as \"no platform to reach\": see `useCheckoutClient`.\n *\n * THE SEAM IS HERE AND NOT IN THE COMPONENT, because this hook is what decides which\n * thing fills `AccountCreationGateway` — and a caller choosing between two gateways would\n * be a second place that decision is written down. A simulated one needs no client: it\n * answers all eight calls itself. See `testing/simulate`.\n */\nexport function useAccountGateway(\n client: ScopeClient | null,\n simulate: boolean,\n): AccountCreationGateway | null {\n return useMemo(() => {\n if (simulate) return simulatedAccountGateway();\n return client === null ? null : accountGateway(client);\n }, [client, simulate]);\n}\n","import type { LoginResult, StaffAuthResult } from '@scopetickets/api';\nimport { bounded, WIRE_LIMITS } from './wire';\n\n/**\n * WHAT A SIGNED-IN BROWSER IS HOLDING, and what to do when the platform stops accepting\n * it.\n *\n * Distinct from `AuthState` in `./auth`, which is about WHO is buying. This is the\n * credential behind that: `AUTHENTICATED` is a claim about the buyer, and `ACTIVE` is a\n * claim about a string in a header. They can disagree — a session expires mid-purchase\n * while the buyer is still, as far as anyone is concerned, signed in — and keeping them\n * apart is what lets the flow notice.\n */\n\n/**\n * NOTHING IS PERSISTED, AND THAT IS THE DESIGN. A refresh token in `localStorage` sits on\n * the CUSTOMER's origin, readable by their page and by anything their page loads —\n * analytics, tag managers, a chat widget. This library runs inside someone else's page,\n * so the session lives for as long as the widget is mounted and no longer.\n *\n * THE PLATFORM'S TOKEN LASTS A YEAR. Measured on staging: the JWT's `exp` is `iat` plus\n * 31,536,000 seconds. So what would be written to a customer's origin is not a session in\n * any ordinary sense — it is a credential good for twelve months, sitting somewhere its\n * owner cannot see it and we cannot revoke it. That turns this from a preference into the\n * only defensible answer.\n *\n * The cost is real: a buyer who reloads signs in again. The alternative is handing a\n * long-lived credential to every site that embeds the widget, which is not ours to give\n * away. If a session has to survive a reload, it belongs in the passkey host's own\n * origin — where the customer's page cannot reach it — and not here.\n */\nexport type Session =\n /** Nobody is signed in. The state before a login and after a sign-out. */\n | { readonly status: 'NONE' }\n /** A header the platform is accepting. */\n | {\n readonly status: 'ACTIVE';\n /** Sent verbatim as `Authorization` — see `ScopeClient.setAuthorization`. */\n readonly authorization: string;\n /** Both, or neither: a refresh needs the pair. `null` where the login gave one. */\n readonly refresh: RefreshCredentials | null;\n }\n /** The header was refused and the pair is being spent on a new one. */\n | { readonly status: 'REFRESHING'; readonly refresh: RefreshCredentials }\n /**\n * Refused, with nothing left to try. The buyer signs in again — and this is a state of\n * its own rather than a return to `NONE`, because the two mean different things to the\n * card: nobody has signed in yet, versus somebody did and it ran out.\n */\n | { readonly status: 'EXPIRED' };\n\n/** The pair `POST /api/Auth/Tokens` takes. Modelled together because it needs both. */\nexport type RefreshCredentials = {\n readonly sessionKey: string;\n readonly refreshToken: string;\n};\n\nexport const NO_SESSION: Session = { status: 'NONE' };\n\n/**\n * A session from what a login answered — the boundary where three nullable wire fields\n * become one value that either is a session or is not.\n *\n * A LOGIN WITH NO USABLE `Authorization` IS NOT A SESSION — absent, empty, or longer than\n * anything a header may be. It is the shape of a success with nothing in it, and reading\n * it as one would put the flow into `AUTHENTICATED` holding a header it cannot send.\n *\n * The refresh pair is taken only when BOTH halves arrived. One without the other cannot\n * be spent, and carrying it would make `canRefresh` true for a session that will fail\n * the moment it tries.\n */\nexport function sessionFromLogin(result: LoginResult): Session {\n const authorization = bounded(result.Authorization, WIRE_LIMITS.credential);\n if (authorization === null) return NO_SESSION;\n const sessionKey = bounded(result.SessionKey, WIRE_LIMITS.credential);\n const refreshToken = bounded(result.RefreshToken, WIRE_LIMITS.credential);\n const refresh =\n sessionKey !== null && refreshToken !== null ? { sessionKey, refreshToken } : null;\n return { status: 'ACTIVE', authorization, refresh };\n}\n\n/** The header to send, or `null` where there is nothing to send. */\nexport function sessionAuthorization(session: Session): string | null {\n return session.status === 'ACTIVE' ? session.authorization : null;\n}\n\n/** Whether the flow may treat the buyer as signed in. */\nexport function sessionUsable(session: Session): boolean {\n return session.status === 'ACTIVE';\n}\n\n/**\n * What a refused call does to the session.\n *\n * THE ONLY SIGNAL WORTH ACTING ON. `LoginResult` carries no expiry of its own — no\n * `expires_in`, no timestamp — though the JWT inside `Authorization` does, and it is a\n * year out. Reading it to refresh ahead of time would be work done for a deadline that\n * arrives after any plausible checkout, so a refused call stays the first and last word,\n * and this is a transition rather than a clock.\n *\n * A session with no refresh pair goes straight to `EXPIRED`; there is nothing to spend.\n */\nexport function sessionRefused(session: Session): Session {\n switch (session.status) {\n case 'ACTIVE':\n return session.refresh === null\n ? { status: 'EXPIRED' }\n : { status: 'REFRESHING', refresh: session.refresh };\n case 'REFRESHING':\n /* The refresh itself was refused. The pair is spent. */\n return { status: 'EXPIRED' };\n case 'NONE':\n case 'EXPIRED':\n /* Nothing was being offered, so nothing was refused. */\n return session;\n default: {\n const exhaustive: never = session;\n return exhaustive;\n }\n }\n}\n\n/**\n * A refresh that worked.\n *\n * IT KEEPS THE PAIR IT CAME IN WITH. `StaffAuthResult` carries an `Authorization` and\n * nothing else — no new refresh token — so the same one is spent again next time rather\n * than rotated. Discarding it here would make every session single-refresh.\n */\nexport function sessionRefreshed(session: Session, result: StaffAuthResult): Session {\n if (session.status !== 'REFRESHING') return session;\n const authorization = bounded(result.Authorization, WIRE_LIMITS.credential);\n if (authorization === null) return { status: 'EXPIRED' };\n return { status: 'ACTIVE', authorization, refresh: session.refresh };\n}\n\n/** Whether there is a pair worth spending on `POST /api/Auth/Tokens`. */\nexport function refreshCredentials(session: Session): RefreshCredentials | null {\n switch (session.status) {\n case 'REFRESHING':\n return session.refresh;\n case 'ACTIVE':\n return session.refresh;\n case 'NONE':\n case 'EXPIRED':\n return null;\n default: {\n const exhaustive: never = session;\n return exhaustive;\n }\n }\n}\n\n/**\n * Signing out. TO `NONE` AND NOT TO `EXPIRED`: a buyer who chose to leave has not had\n * anything run out on them, and the card that says \"your session ended\" would be a lie\n * told to somebody who pressed Sign Out.\n */\nexport function endSession(): Session {\n return NO_SESSION;\n}\n","import type {\n PasskeyRegistrationChallenge,\n PasskeyRegistrationRequest,\n ScopeClient,\n} from '@scopetickets/api';\nimport type {\n AccountCreationDetails,\n AccountCreationGateway,\n AccountPhoto,\n} from '../domain/account-creation';\nimport { sessionFromLogin, type Session } from '../domain/session';\n\n/**\n * THE ACCOUNT SUB-FLOW, AGAINST THE REAL PLATFORM.\n *\n * `AccountCreationGateway` is the seam and this is the only thing that fills it, so every\n * call the sub-flow makes is in this file and nothing above it holds a client. The steps\n * decide WHEN; this decides nothing at all.\n */\n\n/** Whether an error from the transport is the platform refusing, or something worse. */\nfunction refused(error: unknown): boolean {\n return (\n typeof error === 'object' && error !== null && (error as { name?: unknown }).name === 'ApiError'\n );\n}\n\n/** `ImageRequest`, from whichever kind of face the buyer chose. */\nfunction imageRequest(photo: AccountPhoto): { EncodedImage?: string; ImageURL?: string } {\n switch (photo.kind) {\n case 'STOCK':\n /* The platform's own picture. Sending it by reference beats sending it back. */\n return { ImageURL: photo.url };\n case 'UPLOAD':\n return { EncodedImage: photo.encoded };\n default: {\n const exhaustive: never = photo;\n return exhaustive;\n }\n }\n}\n\nexport function accountGateway(client: ScopeClient): AccountCreationGateway {\n return {\n async sendCode(email: string): Promise<string> {\n /*\n * NO `UserKey`. This flow verifies an address BEFORE the account exists, so there is\n * nobody to name — see `SendEmailPasscodeRequest`, where the field is optional for\n * exactly this caller.\n */\n const { Key } = await client.sendEmailPasscode({ Email: email });\n return Key;\n },\n\n async submitCode(code: string): Promise<boolean> {\n /*\n * A WRONG CODE IS NOT AN EXCEPTION. It is the commonest thing that happens on this\n * step, and the card answers it by staying put — so a refusal becomes `false` here\n * and anything else keeps travelling.\n */\n try {\n await client.verifyPasscode({ Code: code });\n return true;\n } catch (error) {\n if (refused(error)) return false;\n throw error;\n }\n },\n\n async checkPasscode(passcodeKey: string): Promise<boolean> {\n const { Verified } = await client.getPasscodeStatus(passcodeKey);\n return Verified;\n },\n\n async createAccount(details: AccountCreationDetails): Promise<Session> {\n const result = await client.createAccount({\n FirstName: details.firstName,\n LastName: details.lastName,\n Email: details.email,\n Password: details.password,\n ...(details.phone === null ? {} : { Phone: details.phone }),\n });\n\n const session = sessionFromLogin(result);\n /*\n * THE CLIENT IS TOLD IMMEDIATELY, and this is the reason the gateway returns a\n * session rather than a caller lifting one out. Everything after this call — the\n * photo, the passkey challenge, the follow list — is authenticated, and a component\n * remembering to hand the header over is a component that can forget.\n */\n if (session.status === 'ACTIVE') client.setAuthorization(session.authorization);\n return session;\n },\n\n async setPhoto(photo: AccountPhoto): Promise<void> {\n await client.updatePhoto(imageRequest(photo));\n },\n\n signedIn(): boolean {\n return client.hasAuthorization();\n },\n\n async openPasskeyRegistration(): Promise<PasskeyRegistrationChallenge> {\n /*\n * DISCOVERABLE, ALWAYS. A resident key is what lets the device offer itself without\n * being told whose account it is — which is the whole point of the passkey route on\n * the unrecognised card, where there is no address to narrow it with.\n */\n return client.createPasskeyRegistrationChallenge({ Discoverable: true });\n },\n\n async lodgePasskey(credential: PasskeyRegistrationRequest): Promise<void> {\n await client.registerPasskey(credential);\n },\n };\n}\n","/**\n * TEST FIXTURES, AND NOTHING THE WIDGET CAN REACH AT RUNTIME.\n *\n * Things a test needs that a real host would hand in from its own backend: a `session`\n * for the auth walk, and a `schedule` for the calendar. Both are plain data the widget\n * already takes as props — these are ready-made copies of that shape, not machinery. The\n * payment simulation that used to live beside them is gone: payments are real, and a test\n * that needs to say what a payment did passes the `payment` prop or drives the frame.\n *\n * THE ACCOUNT GATEWAY BELOW IS THE EXCEPTION, and it is machinery. The account sub-flow\n * makes eight calls against a platform that does not answer them yet, so unlike the two\n * above there is no real thing for a caller to hand in — see `simulatedAccountGateway`.\n */\n\nimport type { PasskeyRegistrationChallenge, PasskeyValidationChallenge } from '@scopetickets/api';\nimport type { AccountCreationGateway } from '../domain/account-creation';\nimport type { SignedIn, SignInGateway } from '../domain/sign-in';\nimport type { Timeslot } from '../island/island-timeslots';\nimport type { AuthSession } from '../domain/auth';\nimport type { CheckoutSchedule } from '../island/ScopeTicketsCheckout';\nimport type { Session } from '../domain/session';\n\n/**\n * THE FOUR SESSIONS, READY MADE — and there is no machinery behind these on purpose.\n *\n * Auth needs nothing invented: `session` is already a plain data prop the host hands in,\n * so every state the flow reasons about is expressible today. Pass one and the widget\n * behaves as it will when accounts are real.\n */\nexport const SIMULATED_SESSIONS = {\n /** Nobody. The first visit, and the card that offers guest checkout. */\n unrecognised: { auth: { status: 'UNRECOGNISED' }, guest: 'NOT_TAKEN' },\n /** Chose to check out without an account — sign-in is bypassed from here on. */\n guest: { auth: { status: 'UNRECOGNISED' }, guest: 'TAKEN' },\n /** A profile we hold, no live session: the keyhole card, and a face on the island. */\n recognised: {\n auth: { status: 'RECOGNISED', avatar: 'initials:AL' },\n guest: 'NOT_TAKEN',\n },\n /** Signed in. Name, email and phone are answered by the account, not by the buyer. */\n authenticated: {\n auth: {\n status: 'AUTHENTICATED',\n account: {\n avatar: 'initials:AL',\n name: 'Ada Lovelace',\n email: 'ada@example.test',\n phone: '+353871234567',\n userTypeKey: null,\n },\n },\n guest: 'NOT_TAKEN',\n },\n} as const satisfies Record<string, AuthSession>;\n\n/**\n * A RUN TO PICK FROM — what a host deferring the calendar has to supply.\n *\n * The widget owns the pickers' layout and none of their content: which days a run\n * touches and which slots a day holds are the platform's. Without them the two steps\n * GATE, which is correct and is also a dead end, so a test of the calendar needs a run.\n *\n * TAKES ITS OWN \"TODAY\" rather than reading a clock, for the reason the real prop does:\n * the day is the VENUE's, not the device's. A fixture run belongs to no venue, so there\n * is no clock to be wrong about.\n */\nexport function simulatedToday(): string {\n return new Date().toISOString().slice(0, 10);\n}\n\nexport function simulatedSchedule(today: string = simulatedToday(), nights = 21): CheckoutSchedule {\n const from = new Date(`${today}T00:00:00Z`);\n const day = (offset: number) =>\n new Date(from.getTime() + offset * 86_400_000).toISOString().slice(0, 10);\n\n /* Not every night: a run with gaps is what the calendar is FOR. */\n const offsets = Array.from({ length: nights }, (_, n) => n).filter((n) => n % 7 !== 2);\n const slotsByDay: Record<string, readonly Timeslot[]> = {};\n const remaining: Record<string, number> = {};\n for (const offset of offsets) {\n const on = day(offset);\n /* Three houses, and a matinee at the weekend — enough for the strip to have shape. */\n const times =\n offset % 7 === 5 || offset % 7 === 6 ? ['14:00', '18:00', '20:30'] : ['19:00', '21:00'];\n slotsByDay[on] = times.map((startTime, index) => ({\n startTime,\n endTime: null,\n /* A spread of fullness, so the indicator draws all three of its levels. */\n remaining: [0.9, 0.5, 0.15][index % 3] ?? 0.5,\n }));\n remaining[on] = [0.9, 0.45, 0.2, 0.75][offset % 4] ?? 0.6;\n }\n\n return {\n series: {\n events: offsets.map((offset) => ({\n eventKey: `sim-${day(offset)}`,\n name: 'A Run of Nights',\n day: day(offset),\n })),\n },\n today,\n nowTime: '11:00',\n slotsByDay,\n remaining,\n };\n}\n\n/**\n * THE ACCOUNT SUB-FLOW, WITH SOMETHING TO CALL — the eight operations of\n * `AccountCreationGateway`, answered here instead of by the platform.\n *\n * It exists for the same reason the payment rows do, and it closes the same hole: until\n * this, `simulate` returned BEFORE `create()`, so every walk reached `Creating Account`,\n * sat out the floor, and proceeded on a card whose call had never happened. Nothing the\n * sub-flow does was being exercised at all — which is how a render loop lived in\n * `ACCOUNT_CREATING` unseen until it was read for.\n *\n * A FACTORY AND NOT A SINGLETON, because `signedIn()` is a question about THIS browser:\n * one gateway per mount, so a second widget — or a second test — starts signed out\n * rather than inheriting an account somebody else made.\n *\n * ── THE CODE IS THE CONTROL PANEL ────────────────────────────────────────────\n *\n * As with the payment rows: the scenario is chosen through the flow's own controls rather\n * than around them. `SIMULATED_REFUSED_CODE` is refused and every other six-digit code is\n * accepted, so the refusal path is reached by typing it — there is no flag for it.\n */\n\n/** The one code the simulated platform will not take. Anything else verifies. */\nexport const SIMULATED_REFUSED_CODE = '000000';\n\n/**\n * And the one password it will not take, for the same reason and in the same way: the\n * refusal path is reached by TYPING it rather than by setting a flag somewhere.\n */\nexport const SIMULATED_REFUSED_PASSWORD = 'wrong';\n\n/**\n * WHAT EACH CALL COSTS IN TIME. Instant answers would hide every in-flight state the\n * cards draw — the shut Re-send, the spinner under Creating Account — so each one takes\n * long enough to be seen and less than the card's own floor.\n */\nconst SIMULATED_LATENCY_MS = {\n sendCode: 300,\n submitCode: 300,\n checkPasscode: 200,\n createAccount: 800,\n setPhoto: 300,\n passkey: 300,\n signIn: 400,\n} as const;\n\nconst after = <T,>(ms: number, value: T): Promise<T> =>\n new Promise((resolve) => setTimeout(() => resolve(value), ms));\n\nexport function simulatedAccountGateway(): AccountCreationGateway {\n /*\n * THE ONE PIECE OF STATE, and the reason this is a factory. `signedIn` gates the passkey\n * challenge, which answers 401 without a session — so answering `true` before the\n * account exists would offer a ceremony that cannot be run.\n */\n let created = false;\n\n return {\n sendCode: (email) => after(SIMULATED_LATENCY_MS.sendCode, `sim-passcode-${email}`),\n\n /* A refusal is `false`, not a throw — the card answers it by staying put. */\n submitCode: (code) => after(SIMULATED_LATENCY_MS.submitCode, code !== SIMULATED_REFUSED_CODE),\n\n /*\n * ALWAYS \"NOT YET\". The poll is for a code read on a PHONE and entered there, which a\n * simulation has no second device to do — and answering `true` would verify an address\n * the buyer never typed a code for.\n */\n checkPasscode: () => after(SIMULATED_LATENCY_MS.checkPasscode, false),\n\n createAccount: async () => {\n const session = await after<Session>(SIMULATED_LATENCY_MS.createAccount, {\n status: 'ACTIVE',\n authorization: 'Bearer simulated',\n /* Both halves or neither — see `sessionFromLogin`, which is the rule this mirrors. */\n refresh: { sessionKey: 'sim-session', refreshToken: 'sim-refresh' },\n });\n created = true;\n return session;\n },\n\n setPhoto: () => after(SIMULATED_LATENCY_MS.setPhoto, undefined),\n\n signedIn: () => created,\n\n openPasskeyRegistration: () =>\n after<PasskeyRegistrationChallenge>(SIMULATED_LATENCY_MS.passkey, {\n ChallengeID: 'sim-challenge',\n /* Hex, as the wire sends it — see `packages/passkey-host`'s `codec.ts`. */\n Challenge: '00112233445566778899aabbccddeeff',\n User: { Key: 'sim-user', Email: 'ada@example.test', FullName: 'Ada Lovelace' },\n /* ES256 and RS256, which is the platform's whole enum. */\n Algorithms: [-7, -257],\n UserVerification: 'preferred',\n RPID: 'localhost',\n }),\n\n lodgePasskey: () => after(SIMULATED_LATENCY_MS.passkey, undefined),\n };\n}\n\n/**\n * SIGNING IN, SIMULATED — the account gateway's twin, and machinery for the same reason:\n * the route is four calls against a platform a playground has no session on.\n *\n * IT ALWAYS SUCCEEDS, and the ceremony in front of it is what does not. The device says no\n * far more often than the platform does — a buyer with no passkey, a prompt waved away —\n * and that path is already reachable without a flag here, by dismissing the real browser\n * dialog the frame opens. What this stands in for is the pair of calls behind it.\n */\nexport function simulatedSignInGateway(): SignInGateway {\n return {\n /*\n * EVERY PASSWORD BUT ONE WORKS. `SIMULATED_REFUSED_PASSWORD` is refused as the\n * platform refuses one — `null`, not a throw — so the card's own \"that was not it\"\n * path is reachable from the keyboard.\n */\n signInWithPassword: ({ password }) =>\n after<SignedIn | null>(\n SIMULATED_LATENCY_MS.signIn,\n password === SIMULATED_REFUSED_PASSWORD ? null : SIMULATED_BUYER,\n ),\n\n openPasskeyChallenge: () =>\n after<PasskeyValidationChallenge>(SIMULATED_LATENCY_MS.signIn, {\n ChallengeID: 'sim-authentication',\n /* Hex, as the wire sends it — see `packages/passkey-host`'s `codec.ts`. */\n Challenge: 'ffeeddccbbaa99887766554433221100',\n /* Empty, which is the usernameless ceremony rather than a list nobody filled. */\n CredentialIDs: [],\n UserVerification: 'preferred',\n }),\n\n signInWithPasskey: () => after<SignedIn>(SIMULATED_LATENCY_MS.signIn, SIMULATED_BUYER),\n\n signOut: () => after(SIMULATED_LATENCY_MS.signIn, undefined),\n };\n}\n\n/**\n * WHO BOTH DOORS LEAD TO — the same buyer `SIMULATED_SESSIONS.authenticated` describes,\n * arrived at two ways. One value, because the whole claim the flow makes about these two\n * routes is that they are indistinguishable once walked.\n */\nconst SIMULATED_BUYER: SignedIn = {\n account: SIMULATED_SESSIONS.authenticated.auth.account,\n session: {\n status: 'ACTIVE',\n authorization: 'Bearer simulated',\n /* Both halves or neither — see `sessionFromLogin`, which is the rule this mirrors. */\n refresh: { sessionKey: 'sim-session', refreshToken: 'sim-refresh' },\n },\n};\n","import { useMemo } from 'react';\nimport type { ScopeClient } from '@scopetickets/api';\nimport { signInGateway } from './signInGateway';\nimport { simulatedSignInGateway } from '../testing/simulate';\nimport type { SignInGateway } from '../domain/sign-in';\n\n/**\n * The sign-in calls, built on the widget's own client — `useAccountGateway`'s twin, and\n * the same reasons hold: a hook so the gateway is one object for the life of the client\n * rather than a new one each render, and the seam is here so no component chooses between\n * two gateways.\n */\nexport function useSignInGateway(\n client: ScopeClient | null,\n simulate: boolean,\n): SignInGateway | null {\n return useMemo(() => {\n if (simulate) return simulatedSignInGateway();\n return client === null ? null : signInGateway(client);\n }, [client, simulate]);\n}\n","import type {\n PasskeyValidationChallenge,\n PasskeyValidationRequest,\n UserResponse,\n} from '@scopetickets/api';\nimport type { Account } from './auth';\nimport type { AuthenticationArm, PasskeyCeremony } from './passkey';\nimport type { Session } from './session';\nimport { bounded, WIRE_LIMITS } from './wire';\n\n/**\n * SIGNING IN TO AN ACCOUNT THAT ALREADY EXISTS — the other half of `account-creation.ts`,\n * and the same shape: a gateway of named calls, a state the cards read, and no React.\n *\n * ONE ROUTE SO FAR. The device is asked for a passkey and nothing is drawn — the cheapest\n * way into an account there is, which is why `USE_PASSKEY` is the primary on the card\n * that offers it. The password funnel is the other route and is not built; when it is, it\n * ends in the same `SignedIn` and nothing downstream moves. See `AuthOutcome`, which\n * already says why.\n */\n\n/**\n * WHAT PROVING WHO YOU ARE IS WORTH — the account to spend and the credential behind it,\n * as ONE value, for the reason `useAuthSession` holds its own two halves in one state:\n * handing them back apart invites a caller to deposit one without the other.\n */\nexport type SignedIn = {\n readonly account: Account;\n readonly session: Session;\n};\n\n/** An address and a password, as the funnel collects them. */\nexport type Credentials = {\n readonly email: string;\n readonly password: string;\n};\n\n/**\n * THE CALLS, AND NOTHING ELSE. `signInGateway` is the only thing that fills this, so the\n * hook above it holds no client and the domain below it makes no request.\n */\nexport type SignInGateway = {\n /**\n * `POST /api/Auth/Login`, and then `GET /api/Users/Me`.\n *\n * `null` IS A REFUSAL AND NOT A FAILURE — the card answers it and stays put. Anything\n * else throws and becomes a notice. `submitCode` draws the same line, and says why.\n */\n readonly signInWithPassword: (credentials: Credentials) => Promise<SignedIn | null>;\n /**\n * `POST /api/Passkeys/Authentications/Challenges`, for whatever discoverable credential\n * the device holds. NO ADDRESS: the recognised card knows there is an account and not\n * whose it is — an avatar is the whole of what is remembered — so there is nothing to\n * narrow it with, and nothing to ask the buyer for either.\n */\n readonly openPasskeyChallenge: () => Promise<PasskeyValidationChallenge>;\n /**\n * `POST /api/Passkeys/Authentications` and then `GET /api/Users/Me` — two calls behind\n * one name, because a session without a profile is half an answer: it says somebody is\n * signed in and not who, which is a card that cannot be drawn.\n */\n readonly signInWithPasskey: (credential: PasskeyValidationRequest) => Promise<SignedIn>;\n /**\n * `POST /api/Auth/Logout`, and the client's own copy of the header with it. It resolves\n * whatever happens: a platform that cannot be told is no reason to keep drawing somebody\n * who has left as signed in.\n */\n readonly signOut: () => Promise<void>;\n};\n\n/**\n * WHERE THE PASSKEY ROUTE HAS GOT TO — one value and not four flags. A challenge in\n * flight, a ceremony on offer, an assertion being spent and a refusal cannot be true at\n * once; `usePasskeyRegistration` next door keeps three booleans that can be.\n */\nexport type PasskeySignIn =\n /** Nothing has been asked for. The state before the card is up, and after a buyer waves the device away. */\n | { readonly status: 'IDLE' }\n /** A challenge is in flight. */\n | { readonly status: 'OPENING' }\n /** There is a ceremony to arm the frame with — the only state where a button is drawn. */\n | { readonly status: 'OFFERED'; readonly ceremony: AuthenticationArm }\n /** The device signed something and the platform is being asked what it is worth. */\n | { readonly status: 'SPENDING' }\n /** Done. The account and the credential that proved it, ready to deposit. */\n | { readonly status: 'SIGNED_IN'; readonly account: Account; readonly session: Session }\n /**\n * Refused, or unreachable. Carries the platform's own words, which are NOT shown to the\n * buyer — a notice's subtitle is ours to write. See `noticeTelemetry`.\n */\n | { readonly status: 'FAILED'; readonly reason: string };\n\nexport const PASSKEY_SIGN_IN_IDLE: PasskeySignIn = { status: 'IDLE' };\nexport const PASSKEY_SIGN_IN_OPENING: PasskeySignIn = { status: 'OPENING' };\nexport const PASSKEY_SIGN_IN_SPENDING: PasskeySignIn = { status: 'SPENDING' };\n\n/**\n * WHAT THE FRAME IS ARMED WITH, or `null` for every state where it must not be — a\n * predicate rather than a check at each card, because two islands draw this button and the\n * second transcription is the one that keeps a frame armed while an assertion is in flight.\n */\nexport function passkeySignInCeremony(state: PasskeySignIn): PasskeyCeremony | null {\n return state.status === 'OFFERED' ? { kind: 'AUTHENTICATION', ceremony: state.ceremony } : null;\n}\n\n/**\n * WHO THE SESSION BELONGS TO — read back from the platform rather than built from what a\n * buyer typed, which is `accountFromCreation`'s opposite and carries both of its rules:\n * the empty string is not a value, and the avatar is never the guest sentinel.\n *\n * EVERY FIELD IS BOUNDED. The platform states `maxLength: 50` on all of them and this\n * holds it to that — an unbounded name from the wire becomes a customer's DOM, not ours.\n *\n * `Key` IS DELIBERATELY DROPPED. `Account` carries no user key, and adding a field the\n * other constructor can only fill with `null` would be a second, emptier answer to a\n * question the follow prompt already gets from the registration challenge.\n */\nexport function accountFromUser(user: UserResponse): Account {\n const first = bounded(user.FirstName, WIRE_LIMITS.profile) ?? '';\n const last = bounded(user.LastName, WIRE_LIMITS.profile) ?? '';\n const name = `${first} ${last}`.trim();\n return {\n avatar: bounded(user.Photo, WIRE_LIMITS.avatar),\n name: name === '' ? null : name,\n email: bounded(user.Email, WIRE_LIMITS.profile),\n phone: bounded(user.Phone, WIRE_LIMITS.profile),\n /* Not known and not guessed: `UserResponse` carries no user type. */\n userTypeKey: null,\n };\n}\n","import type { LoginResult, PasskeyValidationRequest, ScopeClient } from '@scopetickets/api';\nimport {\n accountFromUser,\n type Credentials,\n type SignedIn,\n type SignInGateway,\n} from '../domain/sign-in';\nimport { sessionFromLogin } from '../domain/session';\n\n/**\n * SIGNING IN, AGAINST THE REAL PLATFORM. `SignInGateway` is the seam and this is the only\n * thing that fills it; it decides nothing about WHEN, which is the hook's.\n *\n * TWO DOORS, ONE HALLWAY. A password and a passkey differ only in the call that opens the\n * session; what turns that session into a BUYER is `establish`, written once.\n */\n\n/** Whether an error from the transport is the platform refusing, or something worse. */\nfunction refused(error: unknown): boolean {\n return (\n typeof error === 'object' && error !== null && (error as { name?: unknown }).name === 'ApiError'\n );\n}\n\n/**\n * A SESSION AND A PROFILE, OR NEITHER — what both doors do once one of them opens.\n *\n * THE CLIENT IS TOLD BETWEEN THE TWO CALLS, because `Users/Me` has to travel on the\n * session `Auth/Login` just opened.\n *\n * AND THE HEADER IS WITHDRAWN IF IT FAILS. Leaving it on would authenticate every later\n * request as somebody the cards are still drawing as a stranger — the gap `useAuthSession`\n * exists to close, opened here behind its back.\n */\nasync function establish(client: ScopeClient, login: LoginResult): Promise<SignedIn> {\n const session = sessionFromLogin(login);\n if (session.status !== 'ACTIVE') {\n /*\n * A SUCCESS WITH NOTHING IN IT. `sessionFromLogin` answers `NONE` for a 200 carrying\n * no `Authorization`, which is not a session and must not be treated as one — see its\n * own note. Nothing was set on the client, so there is nothing to withdraw.\n */\n throw new Error('the platform opened no session');\n }\n\n client.setAuthorization(session.authorization);\n try {\n return { account: accountFromUser(await client.getCurrentUser()), session };\n } catch (error) {\n client.setAuthorization(null);\n throw error;\n }\n}\n\nexport function signInGateway(client: ScopeClient): SignInGateway {\n return {\n async signInWithPassword({ email, password }: Credentials): Promise<SignedIn | null> {\n /*\n * A REFUSAL BECOMES `null` AND ANYTHING ELSE KEEPS TRAVELLING — `submitCode`'s line,\n * and its note says why.\n *\n * THE ADDRESS IS SENT AS TYPED. The platform matches on the string, and normalising\n * it here and nowhere else is how a buyer is refused for a capital letter.\n */\n let login: LoginResult;\n try {\n login = await client.signIn({ UserName: email, Password: password });\n } catch (error) {\n if (refused(error)) return null;\n throw error;\n }\n return establish(client, login);\n },\n\n /*\n * DISCOVERABLE, AND NO ADDRESS. The recognised card remembers a face and nothing else\n * — see `AuthState`, where `RECOGNISED` carries an avatar and no account — so the\n * device is asked for whatever resident key it holds rather than for one belonging to\n * somebody we would first have to ask the buyer to name.\n */\n openPasskeyChallenge: () => client.createPasskeyAuthenticationChallenge({ Discoverable: true }),\n\n /*\n * NO REFUSAL CASE, and the asymmetry with the password above is the point: a device\n * that signs the wrong thing is not a buyer mistyping, and resolves to a notice.\n */\n async signInWithPasskey(credential: PasskeyValidationRequest): Promise<SignedIn> {\n return establish(client, await client.authenticateWithPasskey(credential));\n },\n\n async signOut(): Promise<void> {\n try {\n await client.signOut();\n } catch {\n /* The one swallowed failure in this file: see `signOut` on the contract. */\n } finally {\n client.setAuthorization(null);\n }\n },\n };\n}\n","import { useCallback, useEffect, useRef, useState } from 'react';\nimport { authenticationArm, type PasskeyResult } from '../domain/passkey';\nimport {\n PASSKEY_SIGN_IN_IDLE,\n PASSKEY_SIGN_IN_OPENING,\n PASSKEY_SIGN_IN_SPENDING,\n type PasskeySignIn,\n type SignInGateway,\n} from '../domain/sign-in';\nimport type { AuthSessionStore } from './useAuthSession';\n\n/**\n * THE PASSKEY ROUTE INTO AN ACCOUNT, DRIVEN.\n *\n * `sign-in.ts` says what each state means; `signInGateway` makes the calls. This is the\n * thing in between, and it is one hook rather than a block in each island because BOTH\n * faces of the widget draw the card that offers this — the resting island's `IDLE` and\n * the flow's `ORDER_CREATED` are the same node — and two transcriptions of a four-call\n * lifecycle is two things to keep in step.\n *\n * IT DEPOSITS THE RESULT ITSELF. The account and the credential go into the store here\n * rather than being handed back for a caller to remember to deposit: they arrive from the\n * same answer, and the one thing that must not happen is a buyer authenticated against a\n * session somebody forgot to set.\n */\nexport type PasskeySignInStore = {\n /** Where the route has got to. The ceremony to draw comes from `passkeySignInCeremony`. */\n readonly state: PasskeySignIn;\n /** Hand the ceremony document's answer back. */\n readonly onResult: (result: PasskeyResult) => void;\n /** Ask for another challenge after a failure — the notice's Try Again. */\n readonly retry: () => void;\n};\n\nconst failed = (error: unknown): PasskeySignIn => ({\n status: 'FAILED',\n reason: error instanceof Error ? error.message : 'the passkey could not be checked',\n});\n\nexport function usePasskeySignIn(\n gateway: SignInGateway | null,\n /** `ENVIRONMENT_URLS.passkeyRpId` — the authentication challenge does not carry one. */\n rpId: string,\n /** Whether the card that offers this is up. Nothing is asked for a card nobody is on. */\n active: boolean,\n auth: AuthSessionStore,\n): PasskeySignInStore {\n const [state, setState] = useState<PasskeySignIn>(PASSKEY_SIGN_IN_IDLE);\n\n /**\n * WHICH VISIT TO THE CARD AN ANSWER BELONGS TO.\n *\n * A challenge takes a round trip and a ceremony takes as long as the buyer does, so a\n * card left and come back to has TWO answers in flight against it — and the older one\n * would arm a frame the newer one had already moved past. The counter is bumped by the\n * cleanup below, so leaving the card, changing gateway and unmounting all end the run\n * the same way, and a late answer to an ended run is dropped rather than drawn.\n */\n const run = useRef(0);\n\n /*\n * WHETHER THIS RUN'S ANSWER HAS BEEN BANKED. Lifted when the run ends, so a session that\n * lapses mid-purchase and is signed into again deposits the second answer as well as the\n * first — see the effect at the foot of this file for what it guards.\n */\n const deposited = useRef(false);\n\n useEffect(() => {\n setState(PASSKEY_SIGN_IN_IDLE);\n return () => {\n run.current += 1;\n /* The next run deposits its own answer — see `deposited`, whose latch this lifts. */\n deposited.current = false;\n };\n }, [active, gateway, rpId]);\n\n /*\n * A CHALLENGE IS OPENED BY THE CARD BEING UP, and by `IDLE` — which is also where a\n * buyer who waved the device away lands, so declining once and pressing again gets a\n * fresh ceremony rather than a dead button.\n *\n * KEYED ON THE STATUS, and safe to be: the effect's first act is to leave `IDLE`, and\n * the re-run that provokes returns at the guard. Nothing is cancelled by it, which is\n * why the run counter and not the cleanup is what decides whether an answer still\n * counts.\n */\n useEffect(() => {\n if (!active || gateway === null || state.status !== 'IDLE') return;\n const mine = run.current;\n setState(PASSKEY_SIGN_IN_OPENING);\n void gateway\n .openPasskeyChallenge()\n .then((challenge) => {\n if (run.current !== mine) return;\n /*\n * `authenticationArm` answers `null` where the platform left out anything the\n * ceremony needs — a challenge that cannot be run, which is a failure and not an\n * absent offer: the buyer pressed a button and something has to answer them.\n */\n const ceremony = authenticationArm(challenge, rpId);\n setState(\n ceremony === null\n ? { status: 'FAILED', reason: 'the challenge was missing what a ceremony needs' }\n : { status: 'OFFERED', ceremony },\n );\n })\n .catch((error: unknown) => {\n if (run.current === mine) setState(failed(error));\n });\n }, [active, gateway, rpId, state.status]);\n\n const onResult = useCallback(\n (result: PasskeyResult) => {\n if (gateway === null) return;\n const mine = run.current;\n\n if (!result.ok || result.kind !== 'AUTHENTICATION') {\n /*\n * A DISMISSAL IS NOT A FAULT, and neither is a device that could not — the same\n * line `isPasskeyFault` draws in the host, and the same one the registration step\n * draws. Back to `IDLE`, which opens another challenge: the button the buyer\n * pressed is still the one they meant to press.\n */\n setState(PASSKEY_SIGN_IN_IDLE);\n return;\n }\n\n setState(PASSKEY_SIGN_IN_SPENDING);\n void gateway\n .signInWithPasskey(result.credential)\n .then((signedIn) => {\n if (run.current !== mine) return;\n setState({ status: 'SIGNED_IN', ...signedIn });\n })\n .catch((error: unknown) => {\n if (run.current === mine) setState(failed(error));\n });\n },\n [gateway],\n );\n\n const retry = useCallback(() => setState(PASSKEY_SIGN_IN_IDLE), []);\n\n /*\n * AND THE BUYER BECOMES THE BUYER. Once, because the store's own transition is what\n * takes the card away — the session turns `AUTHENTICATED`, the recognised card is no\n * longer the one being drawn, and this hook's run ends. The latch is for the render in\n * between, where the state still says `SIGNED_IN` and depositing twice would be a second\n * session over an identical first for no reason anybody asked for.\n */\n useEffect(() => {\n if (state.status !== 'SIGNED_IN' || deposited.current) return;\n deposited.current = true;\n auth.signedIn(state.account, state.session);\n }, [state, auth]);\n\n return { state, onResult, retry };\n}\n","import type {\n PasskeyRegistrationChallenge,\n PasskeyRegistrationRequest,\n PasskeyValidationChallenge,\n PasskeyValidationRequest,\n} from '@scopetickets/api';\nimport { bounded, isBounded, WIRE_LIMITS } from './wire';\n\n/**\n * THE PARENT'S HALF OF THE PASSKEY FRAME.\n *\n * The ceremony runs in a document Scope serves — `packages/passkey-host` — because\n * WebAuthn binds a credential to an RP id and this widget runs on the customer's own\n * origin. This module is everything the island needs to talk to that document, and none\n * of the talking: pure shapes, guards and transitions.\n *\n * ITS COUNTERPART IS `packages/passkey-host/src/protocol.ts`, and the two are separate on\n * purpose — the host has no workspace dependencies so it can be deployed from anywhere.\n * They therefore describe one wire format twice. What must stay in step is the message\n * names below and the field names inside them; `PASSKEY_MESSAGES` exists so that is one\n * list to check rather than a search.\n */\n\n/** Every message name on the wire, in both directions. */\nexport const PASSKEY_MESSAGES = {\n /** parent → host: here is a challenge; draw the button. */\n ARM: 'SCOPE_PASSKEY_ARM',\n /** parent → host: take it away again. */\n DISARM: 'SCOPE_PASSKEY_DISARM',\n /** host → parent: I have loaded, and here is whether I can do anything. */\n READY: 'SCOPE_PASSKEY_READY',\n /** host → parent: my button is this big. */\n RESIZE: 'SCOPE_PASSKEY_RESIZE',\n /** host → parent: the ceremony ended, one way or the other. */\n RESULT: 'SCOPE_PASSKEY_RESULT',\n} as const;\n\n/** WebAuthn's three, narrowed from the free text the platform sends. */\nexport type UserVerification = 'required' | 'preferred' | 'discouraged';\n\n/**\n * THE COSE ALGORITHMS THE PLATFORM WILL VERIFY, as a closed set — its own\n * `PasskeyAlgorithm` enum, which is `-7` (ES256) and `-257` (RS256).\n *\n * The wire types this off as a bare `number[]`, because that is what JSON carries. It\n * arrives here as free data and leaves as a value we own.\n */\nexport type PasskeyAlgorithm = -7 | -257;\n\n/** One identifier, narrowed. `null` for anything this build has never heard of. */\nexport function passkeyAlgorithm(raw: number): PasskeyAlgorithm | null {\n switch (raw) {\n case -7:\n case -257:\n return raw;\n default:\n return null;\n }\n}\n\n/**\n * The ones we can actually offer the authenticator.\n *\n * AN UNKNOWN IDENTIFIER IS DROPPED RATHER THAN PASSED THROUGH, which is the one place a\n * narrowing here differs from the rest: `pubKeyCredParams` is a PREFERENCE LIST and the\n * device picks from it, so an entry neither we nor the browser understands is not a\n * decision to make — it is a line the device would ignore, and passing it on would put\n * an unchecked number from the wire into a platform API.\n *\n * A list that narrows to EMPTY is a different thing entirely, and `registrationArm`\n * treats it as one: a challenge offering nothing this build can run is a challenge that\n * cannot be run, not one to try with WebAuthn's defaults.\n */\nexport function passkeyAlgorithms(raw: readonly number[]): readonly PasskeyAlgorithm[] {\n const narrowed: PasskeyAlgorithm[] = [];\n for (const entry of raw) {\n const algorithm = passkeyAlgorithm(entry);\n if (algorithm !== null) narrowed.push(algorithm);\n }\n return narrowed;\n}\n\n/**\n * The platform's `UserVerification` as a value we own, or `null`.\n *\n * `null` IS A CASE AND NOT A DEFAULT. An unrecognised setting means the platform is\n * asking for something this build has never heard of, and quietly substituting\n * `preferred` would weaken a ceremony the platform meant to strengthen.\n */\nexport function userVerification(raw: string | null): UserVerification | null {\n switch (raw) {\n case 'required':\n case 'preferred':\n case 'discouraged':\n return raw;\n default:\n return null;\n }\n}\n\n/** How a ceremony ended, as the host reports it. */\nexport type PasskeyResult =\n | {\n readonly ok: true;\n readonly kind: 'REGISTRATION';\n readonly credential: PasskeyRegistrationRequest;\n }\n | {\n readonly ok: true;\n readonly kind: 'AUTHENTICATION';\n readonly credential: PasskeyValidationRequest;\n }\n | { readonly ok: false; readonly code: string };\n\n/**\n * WHERE THE FRAME IS UP TO.\n *\n * The button's measured size is deliberately NOT in here. It is a measurement applied\n * straight to a style, not a decision anybody makes, and it can change at any point in\n * any of these states — folding it in would make every transition carry a number that\n * has nothing to do with the transition.\n */\nexport type PasskeyFrameState =\n /** Mounted, and it has not spoken yet. */\n | { readonly status: 'LOADING' }\n /**\n * It spoke, and no ceremony is possible here — no WebAuthn, or a frame that was never\n * permitted to ask. THE CARD SHOULD NOT OFFER A PASSKEY, which is why this is asked\n * before the step is drawn rather than discovered when a button fails.\n */\n | { readonly status: 'UNAVAILABLE' }\n /** It can. `platformAuthenticator` is whether the device has one built in. */\n | { readonly status: 'READY'; readonly platformAuthenticator: boolean }\n /** It finished. */\n | { readonly status: 'SETTLED'; readonly result: PasskeyResult };\n\nexport const PASSKEY_FRAME_LOADING: PasskeyFrameState = { status: 'LOADING' };\n\n/** Whether the passkey step is worth drawing at all. */\nexport function passkeyOffered(state: PasskeyFrameState): boolean {\n return state.status === 'READY';\n}\n\n// ── ARMING ───────────────────────────────────────────────────\n\n/** What the host is told to make a credential with. */\nexport type RegistrationArm = {\n readonly challengeId: string;\n readonly challenge: string;\n readonly rpId: string;\n readonly userKey: string;\n readonly userName: string;\n readonly userDisplayName: string;\n readonly algorithms: readonly PasskeyAlgorithm[];\n readonly userVerification: UserVerification;\n readonly discoverable: boolean;\n};\n\n/** And to use one. */\nexport type AuthenticationArm = {\n readonly challengeId: string;\n readonly challenge: string;\n readonly rpId: string;\n readonly credentialIds: readonly string[];\n readonly userVerification: UserVerification;\n};\n\n/**\n * WHAT THE FRAME IS BEING ASKED TO DO — an arm, and which of the two ceremonies it is.\n *\n * HERE AND NOT BESIDE THE COMPONENT that spends it, because it is the ARM plus one word:\n * pure data, the exact payload `PASSKEY_MESSAGES.ARM` carries, and a shape two hooks and\n * two islands hand around without any of them drawing anything. It lived on\n * `PasskeyFrame` and made the data layer import a component to name its own state.\n */\nexport type PasskeyCeremony =\n | { readonly kind: 'REGISTRATION'; readonly ceremony: RegistrationArm }\n | { readonly kind: 'AUTHENTICATION'; readonly ceremony: AuthenticationArm };\n\n/**\n * A registration challenge turned into something the host can be armed with, or `null`\n * where the platform did not send enough to run a ceremony.\n *\n * EVERY FIELD ON THE CHALLENGE IS NULLABLE and none of them is optional to the ceremony,\n * so this is the boundary where a response either becomes a request or becomes nothing.\n * A half-built `create()` fails inside the browser with an error nobody can act on.\n */\nexport function registrationArm(\n challenge: PasskeyRegistrationChallenge,\n { discoverable }: { discoverable: boolean },\n): RegistrationArm | null {\n const verification = userVerification(challenge.UserVerification);\n /* Narrowed BEFORE the emptiness check, so a list of nothing we know reads as no list. */\n const algorithms = passkeyAlgorithms(challenge.Algorithms);\n const challengeId = bounded(challenge.ChallengeID, WIRE_LIMITS.ceremony);\n const value = bounded(challenge.Challenge, WIRE_LIMITS.ceremony);\n const rpId = bounded(challenge.RPID, WIRE_LIMITS.rpId);\n const userKey = bounded(challenge.User.Key, WIRE_LIMITS.ceremony);\n const userName = bounded(challenge.User.Email, WIRE_LIMITS.profile);\n if (\n verification === null ||\n challengeId === null ||\n value === null ||\n rpId === null ||\n userKey === null ||\n userName === null ||\n algorithms.length === 0\n ) {\n return null;\n }\n return {\n challengeId,\n challenge: value,\n rpId,\n userKey,\n userName,\n /* An account with no name shows its address, which is better than showing nothing. */\n userDisplayName: bounded(challenge.User.FullName, WIRE_LIMITS.profile) ?? userName,\n algorithms,\n userVerification: verification,\n discoverable,\n };\n}\n\n/**\n * The same for signing in.\n *\n * `rpId` COMES FROM CONFIG, because `POST /api/Passkeys/Authentications/Challenges`\n * does not return one where its registration twin does. It is a per-environment constant\n * either way — see `ENVIRONMENT_URLS.passkeyRpId` — but it does mean the id is written\n * down in two places, and this is the second.\n */\nexport function authenticationArm(\n challenge: PasskeyValidationChallenge,\n rpId: string,\n): AuthenticationArm | null {\n const verification = userVerification(challenge.UserVerification);\n const challengeId = bounded(challenge.ChallengeID, WIRE_LIMITS.ceremony);\n const value = bounded(challenge.Challenge, WIRE_LIMITS.ceremony);\n if (verification === null || challengeId === null || value === null) return null;\n /*\n * ONE UNREADABLE ID MAKES THE WHOLE LIST UNTRUSTWORTHY, which is the rule the host\n * already applies to a list it cannot decode: dropping one silently would ask the device\n * for a narrower set than the platform named, and answer \"no credential\" for the wrong\n * reason.\n */\n const credentialIds = challenge.CredentialIDs.map((id) => bounded(id, WIRE_LIMITS.ceremony));\n if (credentialIds.some((id) => id === null)) return null;\n return {\n challengeId,\n challenge: value,\n rpId,\n /* Empty is meaningful: it asks the device for any discoverable credential it holds. */\n credentialIds: credentialIds as readonly string[],\n userVerification: verification,\n };\n}\n\n// ── LISTENING ────────────────────────────────────────────────\n\n/** Everything the host says back. */\nexport type HostMessage =\n | {\n readonly type: typeof PASSKEY_MESSAGES.READY;\n readonly available: boolean;\n readonly platformAuthenticator: boolean;\n }\n | {\n readonly type: typeof PASSKEY_MESSAGES.RESIZE;\n readonly width: number;\n readonly height: number;\n }\n | { readonly type: typeof PASSKEY_MESSAGES.RESULT; readonly result: PasskeyResult };\n\n/** A string crossing the frame — see `WIRE_LIMITS.ceremony` for what the limit is about. */\nconst ceremonyString = (value: unknown): value is string => isBounded(value, WIRE_LIMITS.ceremony);\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction size(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 10_000;\n}\n\nfunction registrationCredential(value: Record<string, unknown>): PasskeyRegistrationRequest | null {\n const { ChallengeID, CredentialID, Type, AuthenticatorAttestation, ClientData } = value;\n if (\n !ceremonyString(ChallengeID) ||\n !ceremonyString(CredentialID) ||\n !ceremonyString(Type) ||\n !ceremonyString(AuthenticatorAttestation) ||\n !ceremonyString(ClientData)\n ) {\n return null;\n }\n return { ChallengeID, CredentialID, Type, AuthenticatorAttestation, ClientData };\n}\n\nfunction authenticationCredential(value: Record<string, unknown>): PasskeyValidationRequest | null {\n const { ChallengeID, CredentialID, ClientData, AuthenticatorData, UserHandle, Signature } = value;\n if (\n !ceremonyString(ChallengeID) ||\n !ceremonyString(CredentialID) ||\n !ceremonyString(ClientData) ||\n !ceremonyString(AuthenticatorData) ||\n !ceremonyString(Signature)\n ) {\n return null;\n }\n /* `null` is a real answer — a non-discoverable credential returns no handle. */\n if (UserHandle !== null && !ceremonyString(UserHandle)) return null;\n return {\n ChallengeID,\n CredentialID,\n ClientData,\n AuthenticatorData,\n UserHandle: UserHandle as string | null,\n Signature,\n };\n}\n\nfunction result(value: unknown): PasskeyResult | null {\n if (!isPlainObject(value)) return null;\n if (value.ok === false) {\n /*\n * The code is the host's closed set, but it crosses a frame boundary as free text —\n * so it is bounded here and left as a string rather than re-narrowed. Only\n * `isPasskeyFault` in the host decides what a code MEANS, and this side reports it.\n */\n return isBounded(value.code, WIRE_LIMITS.code) ? { ok: false, code: value.code } : null;\n }\n if (value.ok !== true || !isPlainObject(value.credential)) return null;\n if (value.kind === 'REGISTRATION') {\n const credential = registrationCredential(value.credential);\n return credential === null ? null : { ok: true, kind: 'REGISTRATION', credential };\n }\n if (value.kind === 'AUTHENTICATION') {\n const credential = authenticationCredential(value.credential);\n return credential === null ? null : { ok: true, kind: 'AUTHENTICATION', credential };\n }\n return null;\n}\n\n/**\n * A message from the host, or `null`.\n *\n * Nothing partially valid gets through. A `RESULT` missing one field of a credential is\n * not a result with a gap — it is one the platform would reject, and finding that out\n * here rather than at `POST /api/Passkeys/Registrations` is the difference between a\n * card that can say something and a 400.\n */\nexport function parseHostMessage(data: unknown): HostMessage | null {\n if (!isPlainObject(data)) return null;\n\n if (data.type === PASSKEY_MESSAGES.READY) {\n return typeof data.available === 'boolean' && typeof data.platformAuthenticator === 'boolean'\n ? {\n type: PASSKEY_MESSAGES.READY,\n available: data.available,\n platformAuthenticator: data.platformAuthenticator,\n }\n : null;\n }\n\n if (data.type === PASSKEY_MESSAGES.RESIZE) {\n return size(data.width) && size(data.height)\n ? { type: PASSKEY_MESSAGES.RESIZE, width: data.width, height: data.height }\n : null;\n }\n\n if (data.type === PASSKEY_MESSAGES.RESULT) {\n const parsed = result(data.result);\n return parsed === null ? null : { type: PASSKEY_MESSAGES.RESULT, result: parsed };\n }\n\n return null;\n}\n\n/** Where the frame gets to when it says something. */\nexport function passkeyFrameSaid(\n state: PasskeyFrameState,\n message: HostMessage,\n): PasskeyFrameState {\n switch (message.type) {\n case PASSKEY_MESSAGES.READY:\n return message.available\n ? { status: 'READY', platformAuthenticator: message.platformAuthenticator }\n : { status: 'UNAVAILABLE' };\n case PASSKEY_MESSAGES.RESULT:\n return { status: 'SETTLED', result: message.result };\n case PASSKEY_MESSAGES.RESIZE:\n /* A measurement, not a transition — see `PasskeyFrameState`. */\n return state;\n default: {\n const exhaustive: never = message;\n return exhaustive;\n }\n }\n}\n","import { useCallback, useEffect, useRef, useState } from 'react';\nimport {\n FUNNEL_CLOSED,\n funnelCredentials,\n funnelFailed,\n funnelRefused,\n funnelSignedIn,\n funnelSubmittable,\n openFunnel,\n submitFunnel,\n withCredentials,\n type AuthFunnel,\n} from '../domain/auth-funnel';\nimport type { Credentials, SignInGateway } from '../domain/sign-in';\nimport type { AuthSessionStore } from './useAuthSession';\n\n/**\n * THE SIGN-IN FUNNEL, DRIVEN. `auth-funnel.ts` says what each state means and\n * `signInGateway` makes the call; this is the thing in between, and one hook because both\n * faces of the widget draw this card.\n *\n * IT DEPOSITS THE RESULT ITSELF, and then closes — which is what hands the buyer back to\n * the card they came from, now drawn for somebody who is signed in.\n */\nexport type AuthFunnelStore = {\n readonly state: AuthFunnel;\n /** Open it, on an address the flow already holds where there is one. */\n readonly open: (email?: string) => void;\n /** Leave it. The buyer is back where they were, signed in or not. */\n readonly close: () => void;\n /** Typing into either field. */\n readonly change: (change: Partial<Credentials>) => void;\n /** Send them. Does nothing where the fields are not worth sending. */\n readonly submit: () => void;\n};\n\nexport function useAuthFunnel(\n gateway: SignInGateway | null,\n auth: AuthSessionStore,\n): AuthFunnelStore {\n const [state, setState] = useState<AuthFunnel>(FUNNEL_CLOSED);\n\n /**\n * WHICH SUBMISSION AN ANSWER BELONGS TO — `usePasskeySignIn`'s counter, for its reason:\n * a card closed and opened again has two answers coming back to it, and the older one\n * would refuse a password the buyer has since corrected.\n */\n const run = useRef(0);\n\n /** Whether this visit's answer has been banked — lifted when the card is opened again. */\n const deposited = useRef(false);\n\n useEffect(\n () => () => {\n run.current += 1;\n },\n [gateway],\n );\n\n const open = useCallback((email = '') => {\n run.current += 1;\n deposited.current = false;\n setState(openFunnel(email));\n }, []);\n\n const close = useCallback(() => {\n /* A call still in flight belongs to a card that is gone; its answer is dropped. */\n run.current += 1;\n setState(FUNNEL_CLOSED);\n }, []);\n\n const change = useCallback(\n (next: Partial<Credentials>) => setState((was) => withCredentials(was, next)),\n [],\n );\n\n const submit = useCallback(() => {\n if (gateway === null) {\n /*\n * NO CARD WAITS FOREVER — `useAccountCreation`'s rule. A press with no platform\n * behind it resolves to a failure rather than to nothing.\n */\n setState((was) => (funnelCredentials(was) === null ? was : funnelFailed('no platform')));\n return;\n }\n /* The guard is the domain's — `submitFunnel` refuses to move where the fields are not ready. */\n if (!funnelSubmittable(state)) return;\n const credentials = funnelCredentials(state);\n if (credentials === null) return;\n\n run.current += 1;\n const mine = run.current;\n setState((was) => submitFunnel(was));\n\n void gateway\n .signInWithPassword(credentials)\n .then((signedIn) => {\n if (run.current !== mine) return;\n /* `null` is the platform refusing them, which is the card's to answer. */\n setState((was) => (signedIn === null ? funnelRefused(was) : funnelSignedIn(signedIn)));\n })\n .catch((error: unknown) => {\n if (run.current !== mine) return;\n setState(funnelFailed(error instanceof Error ? error.message : 'sign in failed'));\n });\n }, [gateway, state]);\n\n /* AND THE BUYER BECOMES THE BUYER. Once, then the card goes. */\n useEffect(() => {\n if (state.status !== 'SIGNED_IN' || deposited.current) return;\n deposited.current = true;\n auth.signedIn(state.account, state.session);\n setState(FUNNEL_CLOSED);\n }, [state, auth]);\n\n return { state, open, close, change, submit };\n}\n","import { isValidEmail } from './contact';\nimport { AUTH_COPY, type AuthCopyKey } from './auth-copy';\nimport { AUTH_ACTION_OUTCOME } from './auth-actions';\nimport type { Account } from './auth';\nimport type { Session } from './session';\nimport type { Credentials, SignedIn } from './sign-in';\n\n/**\n * THE SIGN-IN FUNNEL — the card that asks for an address and a password, and the states it\n * moves through.\n *\n * ONE NODE, TWO DOORS. `SIGN_IN_WITH` on the unrecognised card and `ENTER_PASSWORD` on the\n * recognised one open the same thing: see `AUTH_ACTION_OUTCOME`, where both resolve to the\n * `FUNNEL` ceremony. Drawing it twice is how two copies of one card fall out of step.\n *\n * IT IS NOT A PURCHASE STEP. The walk has no stop for it — it is a card that stands in\n * front of whichever checkpoint summoned it, like the notice does, and closing it puts the\n * buyer back exactly where they were.\n *\n * Pure: no React, no network.\n */\n\n/** WHERE THE FUNNEL IS. Closed is a state rather than a `null` beside the value. */\nexport type AuthFunnel =\n /** Not open. The state before a button is pressed and after the card is left. */\n | { readonly status: 'CLOSED' }\n /** Open, and being typed into. */\n | { readonly status: 'COLLECTING'; readonly credentials: Credentials }\n /**\n * The platform would not take them. A state and not a flag on `COLLECTING`: the card says\n * something here, and the first keystroke after it is a transition rather than a boolean\n * somebody has to remember to clear.\n */\n | { readonly status: 'REFUSED'; readonly credentials: Credentials }\n /** Sent, and waiting. Nothing may be typed and nothing may be sent again. */\n | { readonly status: 'SUBMITTING'; readonly credentials: Credentials }\n /** Done. The account and the credential that proved it, ready to deposit. */\n | { readonly status: 'SIGNED_IN'; readonly account: Account; readonly session: Session }\n /**\n * The call could not be made or answered — NOT a refusal, which is `REFUSED` above.\n * Carries the platform's own words, which are never shown to the buyer.\n */\n | { readonly status: 'FAILED'; readonly reason: string };\n\nexport const FUNNEL_CLOSED: AuthFunnel = { status: 'CLOSED' };\n\nconst NOTHING_TYPED: Credentials = { email: '', password: '' };\n\n/**\n * Opening it, on an address the flow already holds where there is one — a head start and\n * not an assertion: a buyer checking out as alex@work may have their account under\n * alex@home, so it goes into a field they can change.\n */\nexport function openFunnel(email = ''): AuthFunnel {\n return { status: 'COLLECTING', credentials: { ...NOTHING_TYPED, email } };\n}\n\n/**\n * What is in the two fields, or `null` where there are none to draw.\n *\n * A PREDICATE AND NOT A CHECK AT EACH CARD, because two islands draw this card.\n */\nexport function funnelCredentials(funnel: AuthFunnel): Credentials | null {\n switch (funnel.status) {\n case 'COLLECTING':\n case 'REFUSED':\n case 'SUBMITTING':\n return funnel.credentials;\n case 'CLOSED':\n case 'SIGNED_IN':\n case 'FAILED':\n return null;\n default: {\n const exhaustive: never = funnel;\n return exhaustive;\n }\n }\n}\n\n/** Whether the card is the one showing. */\nexport function funnelOpen(funnel: AuthFunnel): boolean {\n return funnel.status !== 'CLOSED';\n}\n\n/**\n * Whether the password field is on screen: always, while the funnel is open. A function\n * rather than a constant because it did not used to be — the card once opened on the\n * address alone, and both entry points now open on the whole thing.\n */\nexport function funnelPasswordVisible(funnel: AuthFunnel): boolean {\n return funnelCredentials(funnel) !== null;\n}\n\n/**\n * Typing. A keystroke after a refusal clears it — the passcode boxes' rule: a message about\n * the last attempt sitting over the one being typed is a card arguing with its reader.\n */\nexport function withCredentials(funnel: AuthFunnel, change: Partial<Credentials>): AuthFunnel {\n const credentials = funnelCredentials(funnel);\n /* Nothing is typed into a card that is not collecting — a send in flight is not editable. */\n if (credentials === null || funnel.status === 'SUBMITTING') return funnel;\n return { status: 'COLLECTING', credentials: { ...credentials, ...change } };\n}\n\n/**\n * Whether the button may be pressed. The address is checked; the password is only required\n * to EXIST — `MIN_PASSWORD_LENGTH` is the rule for choosing one, and holding an existing\n * password to it would lock its owner out with a message about our own policy.\n */\nexport function funnelSubmittable(funnel: AuthFunnel): boolean {\n const credentials = funnelCredentials(funnel);\n if (credentials === null || funnel.status === 'SUBMITTING') return false;\n return isValidEmail(credentials.email) && credentials.password.length > 0;\n}\n\n/** Sending. Refuses to move where the fields are not worth sending. */\nexport function submitFunnel(funnel: AuthFunnel): AuthFunnel {\n const credentials = funnelCredentials(funnel);\n if (credentials === null || !funnelSubmittable(funnel)) return funnel;\n return { status: 'SUBMITTING', credentials };\n}\n\n/**\n * The platform said no, and what was typed stays: a buyer who mistyped one character of a\n * long password should fix that character, not the whole field.\n */\nexport function funnelRefused(funnel: AuthFunnel): AuthFunnel {\n const credentials = funnelCredentials(funnel);\n return credentials === null ? funnel : { status: 'REFUSED', credentials };\n}\n\n/**\n * It said yes — and THE CREDENTIALS GO WITH THE TRANSITION, which is the whole of the\n * policy: this state carries no password, so the typed one stops existing the moment it is\n * spent and nothing has to remember to clear it.\n */\nexport function funnelSignedIn(signedIn: SignedIn): AuthFunnel {\n return { status: 'SIGNED_IN', account: signedIn.account, session: signedIn.session };\n}\n\n/** Something broke. Not a refusal — see `REFUSED`, which is the buyer's typing. */\nexport function funnelFailed(reason: string): AuthFunnel {\n return { status: 'FAILED', reason };\n}\n\n/**\n * WHICH BUTTON OPENS THIS CARD, ASKED OF THE TABLE THAT ALREADY KNOWS — `AUTH_ACTION_OUTCOME`\n * rather than a list here, which is the transcription that would be forgotten the day a\n * fourth button opens the same card.\n *\n * It takes `unknown` because a button carries a LABEL and a label is a `ReactNode`: the pay\n * button composes a mark into its words. Only a plain string can be one of these.\n */\nexport function funnelOpenedBy(label: unknown): boolean {\n if (typeof label !== 'string') return false;\n const key = (Object.keys(AUTH_COPY) as AuthCopyKey[]).find((copy) => AUTH_COPY[copy] === label);\n if (key === undefined) return false;\n const outcome = AUTH_ACTION_OUTCOME[key];\n return outcome.kind === 'AUTHENTICATE' && outcome.ceremony === 'FUNNEL';\n}\n","import { useEffect, useRef } from 'react';\nimport type { ScopeClient } from '@scopetickets/api';\nimport { refreshCredentials, sessionAuthorization } from '../domain/session';\nimport type { AuthSessionStore } from './useAuthSession';\n\n/**\n * THE SESSION'S OWN LIFE, WATCHED — the half of `useAuthSession` that nothing drove.\n *\n * `ACTIVE → REFRESHING → EXPIRED` has been modelled since the day sessions existed and\n * every transition was unreachable, because nothing told the store when a call came back\n * refused. A session that lapsed mid-purchase lapsed silently: the cards kept drawing a\n * buyer who was signed in, every request kept going out on a dead header, and the refresh\n * token was never spent.\n *\n * IT ALSO MAKES `RECOGNISED` REACHABLE. `expireSession` is the only thing that produces\n * that state and it runs from `refused` alone, so the card that welcomes a returning buyer\n * by their own face could until now only be reached by a host seeding it.\n */\nexport function useSessionGuard(client: ScopeClient | null, auth: AuthSessionStore): void {\n const { credential, session, refused, refreshed } = auth;\n\n /* Read through refs by the handler below, which is installed once per client. */\n const remembered = useRef(false);\n remembered.current = session.auth.status === 'AUTHENTICATED';\n const live = useRef(credential);\n live.current = credential;\n const report = useRef(refused);\n report.current = refused;\n\n /**\n * WHETHER THIS CREDENTIAL HAS ALREADY BEEN REPORTED REFUSED — a ref, because the state\n * is a render behind and a dead header fails every call in flight within milliseconds of\n * the first. Read off the status alone, the second and third refusals still see `ACTIVE`\n * and report too: REFRESHING → EXPIRED → EXPIRED, and the session is destroyed by the\n * mechanism meant to renew it. Lifted when a credential is ACTIVE again.\n */\n const reported = useRef(false);\n if (credential.status === 'ACTIVE') reported.current = false;\n\n /*\n * THE HEADER FOLLOWS THE CREDENTIAL, so the client and the store cannot drift.\n *\n * `NONE` IS LEFT ALONE, and that is not tidiness: it is the state the store is in DURING\n * a sign-in, while `establish` carries the header itself between the two calls. A render\n * in that window would clear it out from under the one in flight.\n */\n useEffect(() => {\n if (client === null || credential.status === 'NONE') return;\n client.setAuthorization(sessionAuthorization(credential));\n }, [client, credential]);\n\n useEffect(() => {\n if (client === null) return;\n client.setRefusedHandler(() => {\n /*\n * ONLY AN ACTIVE CREDENTIAL IS REFUSABLE. A call failing while one is REFRESHING\n * would expire a session the refresh is about to renew; the refresh's own failure,\n * caught below, is the signal that the pair is spent.\n */\n if (live.current.status !== 'ACTIVE' || reported.current) return;\n reported.current = true;\n report.current(remembered.current);\n });\n return () => client.setRefusedHandler(null);\n }, [client]);\n\n const spending = useRef<string | null>(null);\n useEffect(() => {\n if (client === null || credential.status !== 'REFRESHING') {\n spending.current = null;\n return;\n }\n const pair = refreshCredentials(credential);\n if (pair === null) return;\n /*\n * ONE ATTEMPT PER PAIR. This effect re-runs whenever anything in the store moves, and a\n * refresh is not idempotent — firing twice races two headers into one credential.\n */\n if (spending.current === pair.sessionKey) return;\n spending.current = pair.sessionKey;\n\n void client\n .refreshAuthorization({ SessionKey: pair.sessionKey, RefreshToken: pair.refreshToken })\n .then((result) => refreshed(result))\n .catch(() => {\n /* The pair is spent and there is nothing left to try: this is what EXPIRED means. */\n report.current(remembered.current);\n });\n }, [client, credential, refreshed]);\n}\n","import { useCallback, useEffect, useState } from 'react';\nimport type { AccountCreationGateway } from '../domain/account-creation';\nimport { registrationArm, type PasskeyCeremony, type PasskeyResult } from '../domain/passkey';\n\n/**\n * THE TWO CALLS EITHER SIDE OF A CEREMONY THIS PACKAGE CANNOT RUN.\n *\n * The browser half happens in `packages/passkey-host`, on an origin the RP id covers.\n * What is left here is opening a challenge when the card arrives, and lodging whatever\n * the ceremony document hands back.\n */\n\nexport type PasskeyRegistration = {\n /** What to arm the frame with, or `null` while there is nothing to offer. */\n readonly ceremony: PasskeyCeremony | null;\n /**\n * Who the platform says is signed in.\n *\n * A BY-PRODUCT WORTH HAVING. `User.Key` on the challenge is the only place the platform\n * returns a user key at all — `LoginResult` carries none — so opening this is currently\n * the only way the follow prompt learns whose account to write to. It survives a buyer\n * declining the passkey, which is why it is held separately from the outcome.\n */\n readonly userKey: string | null;\n /** Whether a credential was made and accepted. */\n readonly registered: boolean;\n /**\n * Whether the challenge could not be opened, or the credential could not be lodged.\n * THE STEP IS STILL SKIPPABLE — the card keeps its Skip and the account keeps its\n * password, so this is a button that cannot be offered rather than a buyer who is stuck.\n */\n readonly failed: boolean;\n /** Hand the ceremony document's answer back. */\n readonly onResult: (result: PasskeyResult) => void;\n};\n\nexport function usePasskeyRegistration(\n gateway: AccountCreationGateway | null,\n /** Whether the card is up. Nothing is opened for a step the buyer has not reached. */\n active: boolean,\n): PasskeyRegistration {\n const [ceremony, setCeremony] = useState<PasskeyCeremony | null>(null);\n const [userKey, setUserKey] = useState<string | null>(null);\n const [registered, setRegistered] = useState(false);\n const [failed, setFailed] = useState(false);\n\n useEffect(() => {\n if (!active || gateway === null || ceremony !== null || registered) return;\n /*\n * NOTHING IS ASKED FOR WITHOUT AN ACCOUNT TO ASK FOR. The challenge needs a session\n * and answers 401 without one, so a card reached by a buyer who is not signed in\n * would spend a request to be told what it already knew.\n */\n if (!gateway.signedIn()) return;\n\n /* A challenge opened for a card the buyer has left is a challenge spent for nothing. */\n let live = true;\n void gateway\n .openPasskeyRegistration()\n .then((challenge) => {\n if (!live) return;\n setUserKey(challenge.User.Key);\n /*\n * `registrationArm` answers `null` where the platform left out anything the\n * ceremony needs — which is a challenge that cannot be run, not one to try.\n */\n const arm = registrationArm(challenge, { discoverable: true });\n if (arm === null) {\n setFailed(true);\n return;\n }\n setCeremony({ kind: 'REGISTRATION', ceremony: arm });\n })\n .catch(() => {\n if (live) setFailed(true);\n });\n\n return () => {\n live = false;\n };\n }, [active, gateway, ceremony, registered]);\n\n const onResult = useCallback(\n (result: PasskeyResult) => {\n /*\n * A CHALLENGE IS SPENT EITHER WAY. Whatever happened, this one cannot be offered\n * again — so the frame is disarmed on any answer, and a buyer who wants to try\n * again gets a fresh challenge from the effect above.\n */\n setCeremony(null);\n\n if (!result.ok || result.kind !== 'REGISTRATION') {\n /*\n * A DISMISSAL IS NOT A FAULT and does not set `failed`: the passkey step is\n * skippable by design, and a buyer waving the prompt away has done a normal\n * thing. See `isPasskeyFault` in the host, which draws the same line.\n */\n return;\n }\n\n if (gateway === null) return;\n void gateway\n .lodgePasskey(result.credential)\n .then(() => setRegistered(true))\n .catch(() => setFailed(true));\n },\n [gateway],\n );\n\n return { ceremony, userKey, registered, failed, onResult };\n}\n","import { useCallback, useEffect, useRef, useState } from 'react';\nimport {\n ACCOUNT_CREATION_START,\n ACCOUNT_NOT_STARTED,\n confirmAddress,\n nextAccountStep,\n addressForAccount,\n withPasscode,\n type AccountCreationGateway,\n type AccountCreationProgress,\n type AccountCreationStepId,\n type AccountIdentity,\n type AccountPhoto,\n type AccountOutcome,\n} from '../domain/account-creation';\nimport {\n canResend,\n passcodeChecked,\n passcodeSendFailed,\n passcodeSending,\n passcodeSent,\n passcodeVerifying,\n resendRemainingSeconds,\n} from '../domain/passcode';\n\n/**\n * THE ACCOUNT SUB-FLOW, DRIVEN.\n *\n * `account-creation.ts` says which step comes next and what each has settled;\n * `accountGateway` makes the calls. This is the thing in between — it holds the progress\n * and turns a buyer's presses into calls, so no component holds a gateway and no gateway\n * knows what a card is.\n */\n\n/**\n * FOUR SECONDS. The code may be read on a phone and typed there, so the platform is asked\n * as well as told — see `VERIFY_EMAIL`'s blurb, which is where that rule is written down.\n * Slow enough to be cheap over the half-minute a code takes to arrive, fast enough that\n * finishing on another device does not feel like it failed.\n */\nexport const PASSCODE_POLL_MS = 4_000;\n\n/**\n * How often the Re-send cooldown is re-read. Twice a second, so the number the buyer is\n * watching is never visibly behind the clock it is subtracted from.\n */\nconst RESEND_TICK_MS = 500;\n\nexport type AccountCreation = {\n readonly progress: AccountCreationProgress;\n /** Where the sub-flow is, or `null` once nothing is left to ask. */\n readonly step: AccountCreationStepId | null;\n /** Confirming the address on `CONFIRM_EMAIL`, which is what sends the first code. */\n readonly confirmEmail: (address: string) => void;\n /**\n * A code to the address just confirmed. Arriving at Verify Email is what asks for one —\n * see `confirmEmail`, where the two were one call until that step could be absent.\n *\n * IT TAKES THE ADDRESS rather than reading back the confirmed one, so the caller cannot\n * be made to wait a commit for its own answer: the two land in the same effect pass when\n * the step is there, and a state read between them would still be the old value.\n */\n readonly requestCode: (address: string) => void;\n /** Submitting what was typed into the boxes. */\n readonly verify: (code: string) => void;\n /** Another code to the same address. Does nothing while the cooldown holds. */\n readonly resend: () => void;\n /** The cooldown as the design writes it — what \"Re-send (29s)\" counts down. */\n readonly resendSeconds: number;\n /**\n * Whether Re-send may be pressed. NOT `resendSeconds === 0`: a code still in flight has\n * no send to count from, so the countdown reads zero there while the press is refused —\n * which is exactly the moment the buyer is most likely to press it twice.\n */\n readonly canResend: boolean;\n /** Whether the last code was refused — the boxes' own `invalid`. */\n readonly refused: boolean;\n /** Whether a code could not be SENT, which is a different thing and a notice. */\n readonly sendFailed: boolean;\n /**\n * Where the password goes. `PasswordStep` held it and reported only that it was\n * ANSWERED, which is all a card needs and not enough to make an account with.\n */\n readonly setPassword: (password: string) => void;\n /** Makes the account. A no-op on an address whose code was never verified. */\n /**\n * Make the account. The photo is a SECOND argument and not part of the identity: `POST\n * /api/Users` takes no image, so it is a separate authenticated call that cannot go\n * until this one has minted a session — see the `.then` below.\n */\n readonly create: (identity: AccountIdentity, photo: AccountPhoto | null) => void;\n readonly outcome: AccountOutcome;\n};\n\nexport function useAccountCreation(\n gateway: AccountCreationGateway | null,\n /** Injected so the cooldown can be tested without waiting thirty seconds. */\n now: () => number = Date.now,\n): AccountCreation {\n const [progress, setProgress] = useState<AccountCreationProgress>(ACCOUNT_CREATION_START);\n\n /*\n * THE ADDRESS THE LAST CODE WENT TO, so a re-render cannot send a second one and a\n * changed address always does. Held in a ref rather than derived: `progress.email`\n * carries the address, but not whether a send is already in flight for it.\n */\n const sentFor = useRef<string | null>(null);\n const [outcome, setOutcome] = useState<AccountOutcome>(ACCOUNT_NOT_STARTED);\n /*\n * THE PASSWORD LIVES IN A REF AND NOT IN STATE, and is cleared the moment it has been\n * spent. It is typed two cards before it is used, so it has to be held somewhere — but\n * nothing renders from it, and this library runs inside somebody else's page, so the\n * shortest life and the fewest copies is the whole of the policy.\n */\n const password = useRef('');\n\n const send = useCallback(\n (address: string) => {\n if (gateway === null) return;\n sentFor.current = address;\n setProgress((was) => withPasscode(was, passcodeSending()));\n void gateway\n .sendCode(address)\n .then((key) => setProgress((was) => withPasscode(was, passcodeSent(key, now()))))\n .catch((error: unknown) => {\n /*\n * THE ADDRESS IS FORGOTTEN ON FAILURE, so pressing again really sends again.\n * `canResend` opens immediately after a failed send for the same reason: nothing\n * went out, and making a buyer serve a cooldown for our outage punishes them.\n */\n sentFor.current = null;\n setProgress((was) =>\n withPasscode(\n was,\n passcodeSendFailed(error instanceof Error ? error.message : 'send failed'),\n ),\n );\n });\n },\n [gateway, now],\n );\n\n /*\n * RECORDING THE ADDRESS AND ASKING FOR A CODE ARE TWO THINGS, and they used to be one\n * call because they used to happen at one moment: arriving at Verify Email did both.\n *\n * They come apart the moment that step does. With the passcode endpoints down the step\n * is out of the walk — see `UNBUILT_ACCOUNT_STEPS` — and the address still has to be\n * confirmed, because it is what the account is made on; what must NOT happen is a send\n * to an endpoint that is not there, which would raise a failure notice for a card the\n * buyer is never shown. So the caller asks for each by name, and the day the step\n * returns it asks for both on the same arrival, which is where it started.\n */\n const confirmEmail = useCallback((address: string) => {\n setProgress((was) => confirmAddress(was, address));\n }, []);\n\n const requestCode = useCallback(\n (address: string) => {\n /* A different address needs its own code; the same one keeps the code it has. */\n if (sentFor.current !== address) send(address);\n },\n [send],\n );\n\n const verify = useCallback(\n (code: string) => {\n if (gateway === null) return;\n setProgress((was) => withPasscode(was, passcodeVerifying(passcodeOf(was))));\n void gateway\n .submitCode(code)\n .then((accepted) =>\n setProgress((was) => withPasscode(was, passcodeChecked(passcodeOf(was), accepted))),\n )\n /* A refusal already resolved to `false`; anything reaching here is the transport. */\n .catch(() =>\n setProgress((was) => withPasscode(was, passcodeChecked(passcodeOf(was), false))),\n );\n },\n [gateway],\n );\n\n const resend = useCallback(() => {\n const { email } = progress;\n if (email.status !== 'CONFIRMED') return;\n if (!canResend(email.passcode, now())) return;\n send(email.address);\n }, [progress, send, now]);\n\n /*\n * AND THE PLATFORM IS ASKED, not only told. The code may arrive on a phone and be\n * entered there, in which case this browser posts nothing and would otherwise sit on\n * six empty boxes while the address was already verified.\n */\n useEffect(() => {\n if (gateway === null) return;\n const { email } = progress;\n if (email.status !== 'CONFIRMED') return;\n const { passcode } = email;\n if (passcode.status !== 'SENT' && passcode.status !== 'REJECTED') return;\n\n const key = passcode.key;\n const timer = setInterval(() => {\n void gateway\n .checkPasscode(key)\n .then((verified) => {\n /* Only ever ADVANCES: a `false` here is \"not yet\", not a refusal of a guess. */\n if (verified)\n setProgress((was) => withPasscode(was, passcodeChecked(passcodeOf(was), true)));\n })\n .catch(() => {\n /* A poll that fails is a poll; the buyer can still type the code. */\n });\n }, PASSCODE_POLL_MS);\n\n return () => clearInterval(timer);\n }, [gateway, progress]);\n\n const passcode = progress.email.status === 'CONFIRMED' ? progress.email.passcode : null;\n\n /*\n * A REMAINDER READ OFF THE CLOCK rather than a number counted down: the state records\n * when the code went out and this subtracts it from `now`, so a throttled tab catches up\n * where a decremented counter would drift. The interval decides only how often it is\n * re-read, and it stops itself once there is nothing left to count.\n */\n const [resendSeconds, setResendSeconds] = useState(0);\n useEffect(() => {\n const read = () => (passcode === null ? 0 : resendRemainingSeconds(passcode, now()));\n const left = read();\n setResendSeconds(left);\n if (left === 0) return;\n const tick = window.setInterval(() => {\n const remaining = read();\n setResendSeconds(remaining);\n if (remaining === 0) window.clearInterval(tick);\n }, RESEND_TICK_MS);\n return () => window.clearInterval(tick);\n }, [passcode, now]);\n\n const setPassword = useCallback((next: string) => {\n password.current = next;\n setProgress((was) => ({ ...was, passwordSet: next !== '' }));\n }, []);\n\n const create = useCallback(\n (identity: AccountIdentity, photo: AccountPhoto | null) => {\n /*\n * NO CARD WAITS FOREVER. Every reason this call cannot be made resolves to a\n * FAILURE rather than to nothing, because `ACCOUNT_CREATING` draws no buttons: a\n * silent return leaves the buyer watching a spinner with no way off it, and the\n * notice a failure raises is the way off. The reasons are for telemetry and are\n * never shown — see `AccountOutcome`.\n */\n if (gateway === null) {\n setOutcome({ status: 'FAILED', reason: 'no platform to create an account on' });\n return;\n }\n /*\n * ONCE, AND ONCE MORE AFTER A FAILURE. The card that calls this is up for as long\n * as the call takes, so without this a re-render would open a second account — and\n * a retry after a refusal must still be able to try.\n */\n if (outcome.status === 'CREATING' || outcome.status === 'CREATED') return;\n /*\n * THE ONE READER ALLOWED TO SUPPLY THE ADDRESS. `addressForAccount` answers `null`\n * where the code is still outstanding, and the platform joins the code to the\n * account by this string alone — so a `null` here is a request that would create an\n * account nobody has proved they can read mail for.\n */\n const email = addressForAccount(progress);\n if (email === null) {\n /* The walk reached this card without the address being proved, which is a fault. */\n setOutcome({ status: 'FAILED', reason: 'address not verified' });\n return;\n }\n if (password.current === '') {\n setOutcome({ status: 'FAILED', reason: 'no password collected' });\n return;\n }\n\n setOutcome({ status: 'CREATING' });\n void gateway\n .createAccount({\n firstName: identity.firstName,\n lastName: identity.lastName,\n email,\n password: password.current,\n phone: identity.phone,\n })\n .then((session) => {\n /* Spent. Nothing needs it again, and holding it costs only exposure. */\n password.current = '';\n setOutcome({ status: 'CREATED', session });\n /*\n * AND THE FACE, WHICH IS A SECOND CALL. `POST /api/Users` takes no image, so the\n * photo goes to `PUT /api/Users/Photo` — which is authenticated, and is only\n * authenticated now: the gateway put the new session on the client the moment\n * this resolved.\n *\n * IT DOES NOT GATE THE ACCOUNT. The account exists; a face that failed to upload\n * is a profile picture to set again, not a purchase to stop. So this is not\n * awaited and its failure is warned rather than thrown — the outcome above has\n * already told the flow the buyer is signed in.\n */\n if (photo !== null) {\n /*\n * STARTED OFF A RESOLVED PROMISE so that a gateway throwing SYNCHRONOUSLY\n * cannot reach the outer `catch` below and report the account as not made. It\n * was, and the buyer is signed into it; the only thing that failed is a\n * picture.\n */\n void Promise.resolve()\n .then(() => gateway.setPhoto(photo))\n .catch((cause: unknown) => {\n if (typeof console !== 'undefined') {\n console.warn('[ScopeTicketsCheckout] the profile photo was not saved', cause);\n }\n });\n }\n })\n .catch((error: unknown) => {\n /*\n * KEPT ON FAILURE, because the buyer may retry and being asked to type a\n * password again because our call timed out is a poor apology.\n */\n setOutcome({\n status: 'FAILED',\n reason: error instanceof Error ? error.message : 'account not created',\n });\n });\n },\n [gateway, progress, outcome.status],\n );\n\n return {\n progress,\n step: nextAccountStep(progress),\n confirmEmail,\n requestCode,\n verify,\n resend,\n resendSeconds,\n canResend: passcode !== null && canResend(passcode, now()),\n refused: passcode?.status === 'REJECTED',\n sendFailed: passcode?.status === 'SEND_FAILED',\n setPassword,\n create,\n outcome,\n };\n}\n\n/** The passcode a progress is carrying, or an idle one where it has no address yet. */\nfunction passcodeOf(progress: AccountCreationProgress) {\n return progress.email.status === 'CONFIRMED'\n ? progress.email.passcode\n : /* Unreachable while a code is outstanding, and a no-op if it ever is not. */\n passcodeSending();\n}\n","import { useCallback, useState } from 'react';\nimport {\n ANONYMOUS_SESSION,\n chooseGuest,\n expireSession,\n signIn,\n signOut,\n type Account,\n type AuthSession,\n} from '../domain/auth';\nimport { NO_SESSION, sessionRefreshed, sessionRefused, type Session } from '../domain/session';\nimport type { StaffAuthResult } from '@scopetickets/api';\n\n/**\n * WHO IS BUYING, AND THE CREDENTIAL BEHIND IT — held together, because every transition\n * moves both and moving one without the other is how they come to disagree.\n *\n * They are two values and not one, and `domain/session.ts` says why: `AUTHENTICATED` is a\n * claim about the buyer and `ACTIVE` is a claim about a string in a header. A session can\n * run out mid-purchase while the buyer is still, as far as anyone is concerned, signed in.\n * This hook is where that gap is opened and closed on purpose rather than by accident.\n *\n * THE WIDGET OWNS IT. `CheckoutProps.session` seeds the first value and nothing after\n * that: a host cannot drive identity from outside, because the widget is the only thing\n * that knows whether a passkey ceremony finished or a session was refused. See\n * `seed`, which is read once.\n */\nexport type AuthSessionStore = {\n /** Who is buying, as every checkpoint card reads it. */\n readonly session: AuthSession;\n /** The credential, as the client sends it. */\n readonly credential: Session;\n /**\n * Authenticated, however it happened — a passkey, a password, or an account just made.\n * The credential comes from the same answer that proved it, so the two cannot be set\n * from different places and drift.\n */\n readonly signedIn: (account: Account, credential: Session) => void;\n /** The buyer chose to leave. Both halves go, and neither is EXPIRED — they did this. */\n readonly signedOut: () => void;\n /** Declining to sign in for this order. Touches the credential not at all. */\n readonly continuedAsGuest: () => void;\n /**\n * A call came back refused. The credential decides what happens next — a refresh pair\n * is spent, and a session with none is done — and the BUYER only changes once there is\n * nothing left to try.\n *\n * `remembered` is what separates a buyer who comes back to their own face from one who\n * comes back to a stranger's card; see `expireSession`, which is the only thing in the\n * domain that produces `RECOGNISED`.\n */\n readonly refused: (remembered: boolean) => void;\n /** A refresh that worked. The buyer never knew. */\n readonly refreshed: (result: StaffAuthResult) => void;\n};\n\nexport function useAuthSession(seed: AuthSession = ANONYMOUS_SESSION): AuthSessionStore {\n /*\n * ONE STATE AND NOT TWO, so a transition moves both halves in a single update. Held\n * apart they can be set from different places in the same render and land in an order\n * nobody chose — a buyer authenticated against a credential that is already gone.\n *\n * AND THE SEED IS READ ONCE, as a lazy initial value. A host that re-renders with a\n * different `session` does not reach in and change who is signed in halfway through a\n * purchase: the widget owns identity from mount, and a prop that could overwrite it\n * would be a second authority over the one thing that must have exactly one.\n */\n const [held, setHeld] = useState<Held>(() => ({ session: seed, credential: NO_SESSION }));\n\n const signedIn = useCallback(\n (account: Account, credential: Session) => setHeld({ session: signIn(account), credential }),\n [],\n );\n\n const signedOut = useCallback(\n () => setHeld((was) => ({ session: signOut(was.session), credential: NO_SESSION })),\n [],\n );\n\n const continuedAsGuest = useCallback(\n () => setHeld((was) => ({ ...was, session: chooseGuest(was.session) })),\n [],\n );\n\n const refused = useCallback(\n (remembered: boolean) =>\n setHeld((was) => {\n const credential = sessionRefused(was.credential);\n /*\n * ONLY A CREDENTIAL WITH NOTHING LEFT TO TRY TOUCHES THE BUYER. A refresh in\n * flight is not a sign-out: the card must not change under someone whose session\n * is about to be renewed without them ever knowing it lapsed.\n */\n return credential.status === 'EXPIRED'\n ? { session: expireSession(was.session, remembered), credential }\n : { ...was, credential };\n }),\n [],\n );\n\n const refreshed = useCallback(\n (result: StaffAuthResult) =>\n setHeld((was) => ({ ...was, credential: sessionRefreshed(was.credential, result) })),\n [],\n );\n\n return {\n session: held.session,\n credential: held.credential,\n signedIn,\n signedOut,\n continuedAsGuest,\n refused,\n refreshed,\n };\n}\n\ntype Held = { readonly session: AuthSession; readonly credential: Session };\n","import { useLayoutEffect, useRef, useState } from 'react';\nimport { passkeyButtonTheme } from './island-passkey-theme';\nimport { PasskeyFrame } from './PasskeyFrame';\nimport type { PasskeyCeremony, PasskeyFrameState, PasskeyResult } from '../domain/passkey';\n\n/**\n * THE CARD'S PRIMARY BUTTON, WHEN THE CARD IS THE PASSKEY STEP.\n *\n * It stands exactly where `IslandCard` would have drawn one, and looks like one, but it\n * is an iframe: the press has to land in a document under the RP id or WebAuthn will not\n * run — see `PasskeyFrame` for why activation cannot be handed across.\n *\n * What this adds over the frame is the appearance. The button is painted by the other\n * document, which can inherit nothing from this one, so the card's own tokens are read\n * off this element's computed style and sent over as values.\n */\n\nexport interface PasskeyButtonProps {\n /** Where the ceremony document is served — `ENVIRONMENT_URLS.passkeyHostUrl`. */\n hostUrl: string;\n /**\n * The ceremony to offer, or `null` while there is none — a challenge still being\n * fetched, or a step the buyer has already answered.\n */\n ceremony: PasskeyCeremony | null;\n /** The card's own word for it. `AUTH_COPY` owns the words. */\n label: string;\n onState?: (state: PasskeyFrameState) => void;\n onResult?: (result: PasskeyResult) => void;\n}\n\nexport function PasskeyButton({ hostUrl, ceremony, label, onState, onResult }: PasskeyButtonProps) {\n const slotRef = useRef<HTMLDivElement>(null);\n const [theme, setTheme] = useState<Readonly<Record<string, string>> | null>(null);\n\n /*\n * READ FROM WHERE THE BUTTON WOULD HAVE BEEN, and after layout rather than during\n * render: the tokens resolve through the island's cascade, so an element outside it —\n * or read before it is in the document — resolves nothing at all.\n *\n * ONCE. These are the card's palette and metrics, not per-frame measurements; the one\n * thing that would change them is a light/dark switch, which remounts the surface.\n */\n useLayoutEffect(() => {\n const slot = slotRef.current;\n if (slot === null) return;\n const computed = getComputedStyle(slot);\n setTheme(passkeyButtonTheme((property) => computed.getPropertyValue(property)));\n }, []);\n\n return (\n <div ref={slotRef} className=\"scopetickets-island-passkey-slot\">\n {/*\n * NOT MOUNTED UNTIL THE THEME IS READ. The frame reports its size the moment it\n * loads, and a frame that loaded before it had been told what to look like would\n * report the size of the ceremony document's own default button — then correct\n * itself a frame later, in front of the buyer.\n */}\n {theme === null ? null : (\n <PasskeyFrame\n hostUrl={hostUrl}\n ceremony={ceremony}\n label={label}\n theme={theme}\n onState={onState}\n onResult={onResult}\n />\n )}\n </div>\n );\n}\n","/**\n * THE BUTTON'S LOOK, CARRIED ACROSS A DOCUMENT BOUNDARY.\n *\n * The passkey button is drawn by `packages/passkey-host`, on a Scope origin, because\n * only a document under the RP id may ask for a credential. Two documents cannot share a\n * stylesheet, so the card's appearance has to cross as VALUES — and the values are read\n * off the card's own tokens rather than written down again here, which is the only way\n * the button in the frame and the buttons beside it can be guaranteed to match.\n *\n * The names on the left are the ceremony document's; see its `index.css`, where each is\n * a custom property with a fallback. A property omitted here leaves that fallback in\n * place, which is why every read is allowed to come back empty.\n */\n\n/** `getComputedStyle(element).getPropertyValue`, or a fake in a test. */\nexport type StyleReader = (property: string) => string;\n\n/**\n * The values that cross unchanged, host property first. `min-height` rather than\n * `height`: the frame is sized to what the button measures, and a button given a hard\n * height could not tell the frame it needed more.\n */\nconst DIRECT: readonly (readonly [host: string, island: string])[] = [\n ['--scope-passkey-min-height', '--scopetickets-island-button-height'],\n ['--scope-passkey-radius', '--scopetickets-island-radius-round'],\n ['--scope-passkey-background', '--scopetickets-island-primary-bg'],\n ['--scope-passkey-color', '--scopetickets-island-primary-text'],\n ['--scope-passkey-font-size', '--scopetickets-island-size-body'],\n ['--scope-passkey-line-height', '--scopetickets-island-leading-body'],\n];\n\n/**\n * The two the card composes out of more than one token, and which therefore cannot be\n * mapped one to one — `.scopetickets-island-button` writes them as shorthands.\n */\nconst PADDING_INSET = '--scopetickets-island-button-inset';\nconst BORDER_WIDTH = '--scopetickets-island-space-0-25';\nconst BORDER_COLOUR = '--scopetickets-island-button-stroke';\n\n/**\n * The two that are not tokens at all. The card's button takes `font: inherit`, so the\n * family and weight come down the tree rather than out of a custom property — and a\n * separate document inherits nothing, so they are read as resolved longhands and sent.\n */\nconst INHERITED: readonly (readonly [host: string, property: string])[] = [\n ['--scope-passkey-font-family', 'font-family'],\n ['--scope-passkey-font-weight', 'font-weight'],\n];\n\n/** Every host property this module can send, for the test that binds it to that stylesheet. */\nexport const PASSKEY_THEME_PROPERTIES: readonly string[] = [\n ...DIRECT.map(([host]) => host),\n '--scope-passkey-padding',\n '--scope-passkey-border',\n ...INHERITED.map(([host]) => host),\n];\n\n/**\n * The card's appearance, as the ceremony document's own property names.\n *\n * An empty read is left out rather than sent as `''`: the host's stylesheet carries a\n * fallback for every one of these, and an empty custom property would beat it.\n */\nexport function passkeyButtonTheme(read: StyleReader): Record<string, string> {\n const theme: Record<string, string> = {};\n\n const take = (host: string, value: string) => {\n const trimmed = value.trim();\n if (trimmed !== '') theme[host] = trimmed;\n };\n\n for (const [host, island] of DIRECT) take(host, read(island));\n for (const [host, property] of INHERITED) take(host, read(property));\n\n const inset = read(PADDING_INSET).trim();\n if (inset !== '') theme['--scope-passkey-padding'] = `0 ${inset}`;\n\n const width = read(BORDER_WIDTH).trim();\n const colour = read(BORDER_COLOUR).trim();\n /*\n * BOTH HALVES OR NEITHER. `1px solid` with no colour is a border in `currentColor`,\n * which on a primary button is the label's colour — a bright ring nobody designed.\n */\n if (width !== '' && colour !== '') theme['--scope-passkey-border'] = `${width} solid ${colour}`;\n\n return theme;\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport {\n PASSKEY_FRAME_LOADING,\n PASSKEY_MESSAGES,\n parseHostMessage,\n passkeyFrameSaid,\n type PasskeyCeremony,\n type PasskeyFrameState,\n type PasskeyResult,\n} from '../domain/passkey';\n\n/**\n * THE BUTTON THAT IS NOT OURS.\n *\n * A passkey cannot be made from this page. WebAuthn binds a credential to an RP id, and\n * only a document whose origin ends in that id may ask for one — so the ceremony runs in\n * `packages/passkey-host`, served from `passkeys.testlink.scopetickets.com`, and this\n * frame is how the card reaches it.\n *\n * IT IS VISIBLE, AND THAT IS THE WHOLE DESIGN. A cross-origin `create()` needs transient\n * user activation in the frame that CALLS it, and activation does not cross a frame\n * boundary: a press on a button this package drew would give this document activation\n * and the ceremony document none. So the button the buyer presses is drawn over there,\n * and this element is sized and placed to be exactly where the card's own button would\n * have gone.\n *\n * Which means the frame reports its size rather than being given one, and takes the\n * card's colours as custom properties rather than its stylesheet — the two documents\n * cannot share a stylesheet, so the theme travels as values.\n */\n\nexport interface PasskeyFrameProps {\n /** Where the ceremony document is served — `ENVIRONMENT_URLS.passkeyHostUrl`. */\n hostUrl: string;\n /** The ceremony to arm it with, or `null` to leave the button away. */\n ceremony: PasskeyCeremony | null;\n /** The card's own word for the button. `AUTH_COPY` owns the words; this passes them. */\n label: string;\n /** `--scopetickets-passkey-*` values, so the button matches the card it sits in. */\n theme?: Readonly<Record<string, string>>;\n /** Where the frame has got to — the card decides from this whether to offer the step. */\n onState?: (state: PasskeyFrameState) => void;\n /** How the ceremony ended. */\n onResult?: (result: PasskeyResult) => void;\n}\n\nexport function PasskeyFrame({\n hostUrl,\n ceremony,\n label,\n theme,\n onState,\n onResult,\n}: PasskeyFrameProps) {\n const frameRef = useRef<HTMLIFrameElement>(null);\n const [state, setState] = useState<PasskeyFrameState>(PASSKEY_FRAME_LOADING);\n\n /*\n * THE ONE ORIGIN THIS FRAME WILL SPEAK TO OR HEAR FROM. Derived from the URL it was\n * given rather than configured separately, so the two cannot disagree — a frame\n * listening to an origin it is not showing is a frame listening to somebody else.\n */\n const hostOrigin = useMemo(() => {\n try {\n return new URL(hostUrl).origin;\n } catch {\n return null;\n }\n }, [hostUrl]);\n\n const post = useCallback(\n (message: unknown) => {\n const target = frameRef.current?.contentWindow;\n if (target == null || hostOrigin === null) return;\n target.postMessage(message, hostOrigin);\n },\n [hostOrigin],\n );\n\n useEffect(() => {\n if (hostOrigin === null) return;\n\n const onMessage = (event: MessageEvent<unknown>) => {\n /* Both checks, and neither is enough alone: an origin can be shared by other frames. */\n if (event.origin !== hostOrigin) return;\n if (event.source !== frameRef.current?.contentWindow) return;\n\n const message = parseHostMessage(event.data);\n if (message === null) return;\n\n if (message.type === PASSKEY_MESSAGES.RESIZE) {\n /*\n * A MEASUREMENT, WRITTEN STRAIGHT ONTO THE ELEMENT. It is not part of the frame's\n * state — see `PasskeyFrameState` — and routing a number that changes with a font\n * load through a re-render buys nothing.\n */\n const element = frameRef.current;\n if (element !== null) {\n element.style.setProperty('--scopetickets-island-passkey-width', `${message.width}px`);\n element.style.setProperty('--scopetickets-island-passkey-height', `${message.height}px`);\n }\n return;\n }\n\n setState((current) => passkeyFrameSaid(current, message));\n if (message.type === PASSKEY_MESSAGES.RESULT) onResult?.(message.result);\n };\n\n window.addEventListener('message', onMessage);\n return () => window.removeEventListener('message', onMessage);\n }, [hostOrigin, onResult]);\n\n useEffect(() => {\n onState?.(state);\n }, [state, onState]);\n\n useEffect(() => {\n /* Nothing is armed until the host has said it can do a ceremony at all. */\n if (state.status !== 'READY') return;\n if (ceremony === null) {\n post({ type: PASSKEY_MESSAGES.DISARM });\n return;\n }\n post({\n type: PASSKEY_MESSAGES.ARM,\n kind: ceremony.kind,\n ceremony: ceremony.ceremony,\n appearance: { label, theme: theme ?? {} },\n });\n }, [state.status, ceremony, label, theme, post]);\n\n return (\n <iframe\n ref={frameRef}\n src={hostUrl}\n className=\"scopetickets-island-passkey\"\n title={label}\n /*\n * WITHOUT THIS THE CEREMONY CANNOT HAPPEN. Permissions Policy blocks WebAuthn in a\n * cross-origin frame unless the embedder delegates it, and the failure is a\n * `NotAllowedError` — the same error a buyer pressing Cancel produces, which is why\n * the host probes for availability instead of inferring it from a failure.\n */\n allow=\"publickey-credentials-create; publickey-credentials-get\"\n />\n );\n}\n","/**\n * THE ORDER, AS THE PLATFORM HOLDS IT — a cart, a buyer on it, and a payment against it.\n *\n * Everything here was a prop: `quote` was what the host said was owed, `hold` was the\n * timer the host said was running, and `payment` was the host's news about a charge the\n * widget had no part in. All three are answers the platform gives, and the widget can ask.\n *\n * ── WHERE THIS STOPS, AND WHY ────────────────────────────────────────────────\n *\n * It creates the cart, fills it, puts the buyer on it and watches the status. It does NOT\n * take card details, and it cannot: those are collected in the payment host's own iframe\n * (`packages/payment-host`) so that no card number is ever inside somebody else's page or\n * this bundle. The frame runs the charge and reports back through `settledFromFrame` and\n * `failedFromFrame`; the status watch `chargeAttempted` starts is the backup for an answer\n * that never arrives.\n */\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport {\n ApiError,\n type BulkAddItemRequest,\n type Cart,\n type ScopeClient,\n type BuyerDetails,\n type Ticket,\n type TimeslotRequest,\n} from '@scopetickets/api';\nimport { isPurchaseCompleted, markPurchaseCompleted } from './purchase-completion';\nimport { SOLO_KEY } from '../island/PartyStepper';\nimport type { EscrowHold } from '../island/island-escrow';\nimport { attributeCartItems, withoutUnfilled, type AttributedCartItem } from '../domain/cart';\nimport { fillFromRefusal, type OrderFill } from '../domain/order-fill';\nimport { intentHeadcount } from '../domain/order-intent';\nimport { productForSession, sessionFor, sessionOn } from '../domain/product';\nimport { assignmentFor } from '../domain/user-types';\nimport type { Quote } from '../domain/money';\nimport { PROMO_REFUSED, promoRefusal, type PromoWrite } from '../domain/promo';\nimport type { PaymentOutcome } from '../island/ScopeTicketsCheckout';\n\n/** What the widget knows that the platform needs, to open an order. */\n/** The platform's user-type names, by assignment key — what a cart line is labelled from. */\nexport type UserTypeNames = Readonly<Record<string, string>>;\n\nexport type OrderRequest = {\n /** The event the chosen day belongs to — a cart is opened on one. */\n readonly eventKey: string | undefined;\n /**\n * How many of each user type, BY NAME — `assignmentFor` turns a name into the chosen\n * product's own assignment key. A host's own key still passes through as itself.\n */\n readonly composition: Readonly<Record<string, number>>;\n /**\n * The session, as the cart wants it — A TIME OF DAY at both ends, and not the timestamp\n * this used to send: the field is a `System.TimeSpan` on the platform's side and the\n * day is already said by the event the cart was opened on. See `timeslotRequest`.\n */\n readonly timeslot: TimeslotRequest | undefined;\n};\n\nexport type CheckoutOrder = {\n readonly cart: Cart | null;\n /**\n * WHAT THE ORDER CAME TO — held, short, sold out or broken, as one state. See\n * `OrderFill`, which is also where the reason a refusal is inventory rather than a fault\n * is drawn.\n */\n readonly fill: OrderFill;\n /**\n * The cart's items with the user type each was bought FOR, where that is knowable —\n * see `attributeCartItems`. A cart this widget did not open has no request to read it\n * back off, and the items come through as the platform sent them.\n */\n readonly items: readonly AttributedCartItem[];\n /**\n * WHAT THE CART WAS FILLED WITH, as the product names itself — \"Peak\", off\n * `Ticket.Name`. `undefined` for a cart this widget did not open, which has no product it\n * chose and only the items the platform sent. See `CartLineContext.productName`.\n */\n readonly productName: string | undefined;\n readonly quote: Quote | undefined;\n readonly hold: EscrowHold | undefined;\n readonly payment: PaymentOutcome | undefined;\n /**\n * THE MARKER'S ANSWER, read when the cart arrives: this browser already finalized a\n * purchase against it, so nothing downstream may offer a charge or publish a\n * completion again.\n */\n readonly completedPreviously: boolean;\n /**\n * Put the buyer on the cart. Resolves false when the save failed — the caller then\n * does not authorize a charge, because a payment cannot be named after nobody.\n */\n readonly saveBuyer: (buyer: BuyerDetails) => Promise<boolean>;\n /** What the promo card is doing. The code itself is `cart.PromoCode` — see `PromoWrite`. */\n readonly promo: PromoWrite;\n /** Put a code on the order. Resolves false where the platform refused it. */\n readonly applyPromo: (code: string) => Promise<boolean>;\n /** Take the code off again, and the order goes back to its full price. */\n readonly removePromo: () => Promise<boolean>;\n /**\n * Report the frame's SUCCESS: money taken and finalized by the payment host. Writes\n * the once-marker BEFORE publishing, which is the ordering the exactly-once rule\n * hangs on.\n *\n * IT CARRIES THE TICKET THE PAYMENT MADE, where the frame named one — the only moment\n * that key is knowable, and the reason it rides the outcome rather than being fetched\n * back off the cart later. See `PaymentOutcome`.\n */\n readonly settledFromFrame: (attendeeTicketKey?: string) => void;\n /**\n * Report the frame's ERROR: a decline, with the provider's own words. The buyer\n * stays on the order and may correct and retry; the hold keeps running.\n */\n readonly failedFromFrame: (reason: string) => void;\n /**\n * The frame's TransactionError: money taken, tickets not finalized. The recovery\n * card's own road to the poll's PAID answer — no retry is offered, because the\n * charge has already happened.\n */\n readonly paidWithoutFinalizing: () => void;\n /**\n * Drop a standing failure so a corrected attempt can run. The charge is not retried\n * here — only the outcome is cleared; a new attempt needs a new submit.\n */\n readonly retryPayment: () => void;\n /**\n * A charge has been submitted. Starts the status watch, which is the backup when the\n * frame's own answer does not arrive — a cross-origin message can be lost, and a\n * purchase that is waiting forever on nobody is the worst place to be stuck.\n */\n readonly chargeAttempted: () => void;\n /**\n * START A NEW CART FOR THE SAME ORDER — what a buyer whose hold ran out is doing when\n * they put the news away and press the pill again.\n *\n * NOT A RETRY OF ANYTHING. The old cart is gone: its stock went back to the pool when\n * the clock stopped, and nothing about it can be reused. This forgets it — the state AND\n * the once-per-event guard that exists so a re-render cannot open a second cart — so the\n * next time the walk stands somewhere an order is needed, one is opened from scratch.\n *\n * WHAT THE BUYER TYPED IS NOT TOUCHED, because it was never in here: the party, the day\n * and the buyer live in the island's own `collected`, which is why starting again is not\n * starting over. Same intent, new reservation.\n */\n readonly restart: () => void;\n};\n\n/**\n * `quote`, `hold` and `completedPreviously` are DERIVED on the way out rather than kept:\n * all three are readings of the cart, which is the one thing that changes. `currency` and\n * `productName` are kept, because both are readings of the PRODUCT rather than of\n * anything in here — see `money`.\n */\ntype OrderState = Omit<\n CheckoutOrder,\n | 'quote'\n | 'hold'\n | 'completedPreviously'\n | 'saveBuyer'\n | 'promo'\n | 'applyPromo'\n | 'removePromo'\n | 'settledFromFrame'\n | 'failedFromFrame'\n | 'paidWithoutFinalizing'\n | 'retryPayment'\n | 'chargeAttempted'\n | 'restart'\n> & {\n readonly currency: string | undefined;\n readonly productName: string | undefined;\n};\n\nconst IDLE: OrderState = {\n cart: null,\n fill: { status: 'PENDING' },\n items: [],\n currency: undefined,\n productName: undefined,\n payment: undefined,\n};\n\n/** How often the status is asked while a payment is in flight. */\nconst POLL_MS = 2000;\n\n/**\n * The cart's total as the island says it. `TotalAmount` is MINOR UNITS on the wire and\n * `Quote` takes minor units, so nothing is scaled.\n *\n * NO CURRENCY, NO QUOTE. A total with the wrong symbol in front of it is worse than no\n * total at all — it is a number a buyer would act on. The pill simply says nothing until\n * the platform has said what the money is in.\n */\nfunction toQuote(cart: Cart, currency: string | undefined): Quote | undefined {\n if (currency === undefined) return undefined;\n return { kind: 'TOTAL', minorUnits: cart.TotalAmount, currency };\n}\n\n/**\n * THE ESCROW WINDOW, STAMPED HERE BECAUSE NOTHING ELSE STAMPS IT.\n *\n * `Cart.ExpirationTime` is an anticipated field: the platform does not send one, which\n * its own type says. So a cart this widget opened had NO expiry, `toHold` answered\n * `undefined`, and the header drew no summary at all — no timer, and since both screens\n * beside the flow hang off that pill, no way to the cart screen either. Reported as the\n * two header icons being missing throughout the flow.\n *\n * FIVE MINUTES, WHICH IS `@scopetickets/sdk`'s OWN `CHECKOUT_ESCROW_DURATION_MS`. The two\n * packages do not depend on each other, so this is the same number written twice rather\n * than one shared — and two clocks disagreeing about how long a buyer has is worse than\n * the duplication. When the platform sends the field, the real one wins: `??`.\n */\nexport const ESCROW_WINDOW_SECONDS = 5 * 60;\n\n/** The cart with an expiry on it whatever the platform said — the SDK's own remedy. */\nfunction withExpiry(cart: Cart, heldFrom: number): Cart {\n return {\n ...cart,\n ExpirationTime:\n cart.ExpirationTime ?? new Date(heldFrom + ESCROW_WINDOW_SECONDS * 1000).toISOString(),\n };\n}\n\n/**\n * The escrow, as seconds remaining rather than a deadline — which is what the ring draws.\n * A cart with no expiry is not held, and says so by being absent rather than by counting\n * down from nothing.\n *\n * THE WINDOW IS MEASURED, not assumed: `heldFrom` is when this widget learned the cart\n * existed, so the ring's denominator is the window the buyer actually got. It was a flat\n * fifteen minutes, which against a five-minute expiry would open the ring a third full and\n * drain it to nothing in a third of a turn. A cart the widget ADOPTED has no start it can\n * know, and falls back to the stated window.\n */\nfunction toHold(cart: Cart, now: number, heldFrom: number | null): EscrowHold | undefined {\n if (cart.ExpirationTime === undefined || cart.ExpirationTime === null) return undefined;\n const deadline = Date.parse(cart.ExpirationTime);\n if (Number.isNaN(deadline)) return undefined;\n\n const measured = heldFrom === null ? 0 : Math.round((deadline - heldFrom) / 1000);\n return {\n secondsLeft: Math.round((deadline - now) / 1000),\n durationSeconds: measured > 0 ? measured : ESCROW_WINDOW_SECONDS,\n };\n}\n\n/**\n * WHAT A 200 CAME TO. Nothing refused is a whole order; something refused with nothing\n * held is the session gone.\n *\n * THE SECOND CASE CANNOT HAPPEN TODAY and is written anyway: a request the platform can\n * fill NONE of is refused outright, flag or no flag, so it arrives in the catch as\n * `NoTicketsAvailable`. If that ever softens into an empty 200 — which is the shape the\n * flag's own contract implies — this reads it correctly instead of raising \"Only 0\n * Tickets Left\" over a cart with nothing in it.\n */\nfunction fillOf(held: number, asked: number, refused: number): OrderFill {\n if (refused === 0) return { status: 'FILLED' };\n if (held === 0) return { status: 'SOLD_OUT', asked };\n return { status: 'SHORT', held, asked };\n}\n\n/**\n * One line per head — the cart takes items, not counts.\n *\n * `SOLO_KEY` IS NOT A USER TYPE AND MUST NOT BE SENT AS ONE. It is the key the party\n * stepper counts under when the event NAMES no types — a word this package chose,\n * `default`, which the platform has never heard of. It was going out as\n * `UserTypeAssignmentKey` on every head, and a bulk add that refuses an unknown key\n * leaves no cart: no cart is no quote and no hold, which is no summary in the header, and\n * both screens that hang off it gone with it. Nothing said so, because nothing reads\n * `order.error`.\n *\n * OMITTED RATHER THAN NULLED, which is the distinction the platform draws: an ABSENT key\n * means \"no user type\", and an explicit `null` is a different claim.\n *\n * THE COMPOSITION IS KEYED BY NAME AND THE WIRE TAKES AN ASSIGNMENT, so the product is\n * what converts one to the other — see `assignmentFor` and the note above it. The product\n * is passed WHOLE rather than as its key for exactly that: an assignment belongs to a\n * product, and until this line there was no product to belong to. A type this product\n * does not offer resolves to `undefined` and the head goes without a key, which is the\n * same \"no user type\" the paragraph above describes — not a refusal, and not somebody\n * else's key sent on the off-chance.\n */\nfunction itemsFor(\n request: OrderRequest,\n product: Pick<Ticket, 'Key'> & Partial<Pick<Ticket, 'UserTypes'>>,\n) {\n const items: BulkAddItemRequest[] = [];\n for (const [userTypeKey, count] of Object.entries(request.composition)) {\n const named = userTypeKey !== SOLO_KEY && userTypeKey !== '';\n const assignment = named ? assignmentFor(product, userTypeKey) : undefined;\n for (let head = 0; head < count; head += 1) {\n items.push({\n ProductKey: product.Key,\n ...(assignment === undefined ? {} : { UserTypeAssignmentKey: assignment }),\n ...(request.timeslot === undefined ? {} : { Timeslot: request.timeslot }),\n });\n }\n }\n return items;\n}\n\n/**\n * THE SERIALISATION ROUND-TRIP, guarded. The `JSON.stringify` values this hook\n * serialises with come back through `JSON.parse`, and a parse failure here would take\n * the whole cart load down with it — an effect that throws is an effect that never sets\n * state. A malformed value is treated as EMPTY, which is what it always was before\n * this hook learned to serialise.\n */\nfunction safeParse<T>(value: string, fallback: T): T {\n try {\n return JSON.parse(value) as T;\n } catch {\n return fallback;\n }\n}\n\nexport function useCheckoutOrder(\n client: ScopeClient | null,\n request: OrderRequest,\n currency: string | undefined,\n /** Whether there should be an order at all — the flow is past Add to Cart. */\n open: boolean,\n /**\n * A CART THE HOST ALREADY OPENED, adopted rather than duplicated.\n *\n * A host that composes the order itself has a cart before this widget mounts — it made\n * one to price the order and to hold the stock. Opening a second for the same purchase\n * put the items in twice, paid against the widget's, and left the host's holding stock\n * nobody would ever buy. Given a key, the cart is READ and never created or filled: the\n * host has already said what is in it.\n */\n adopt: string | undefined,\n /**\n * The user types by assignment key, for the split a cart line draws — \"(Child)\". The\n * NAMES are the platform's and arrive through `useCheckoutData`; this hook holds only\n * the keys it sent.\n */\n userTypeNames: UserTypeNames = {},\n): CheckoutOrder {\n const [state, setState] = useState(IDLE);\n /* The cart is opened ONCE for a given event; a second render must not open a second. */\n const opened = useRef<string | null>(null);\n /*\n * WHICH RESERVATION THIS IS — bumped by `restart`, and in the opening effect's deps for\n * exactly one reason: clearing the guard above is not a signal. The effect re-runs when\n * its inputs change, and after a hold lapses every one of them is the same as it was —\n * the same event, the same party, the same timeslot — so a buyer starting again asks for\n * a cart identical to the one they lost, and nothing would have re-run to open it.\n */\n const [reservation, setReservation] = useState(0);\n /*\n * WHEN THE WINDOW STARTED, for the ring's denominator — null for a cart this widget did\n * not open, whose window began before it was asked. See `toHold`.\n */\n const held = useRef<number | null>(null);\n\n const { eventKey } = request;\n /* Serialised so the effect compares by VALUE — all three are rebuilt on every render. */\n const composition = JSON.stringify(request.composition);\n const timeslot = JSON.stringify(request.timeslot ?? null);\n const names = JSON.stringify(userTypeNames);\n\n useEffect(() => {\n if (!open || client === null) return;\n /* Adopting needs no event: the cart it names already belongs to one. */\n const mark = adopt ?? eventKey;\n if (mark === undefined) return;\n if (opened.current === mark) return;\n opened.current = mark;\n\n let live = true;\n /*\n * WHICH CALL IS IN FLIGHT, so a refusal can say what refused. Opening a cart is three\n * requests answering ONE notice — \"Something went wrong before we could hold your\n * tickets\" is all a buyer can be told, and reads the same whether the event key was\n * wrong or the platform would not reserve the heads. Three things to whoever has to\n * fix it, and the console said none of them.\n */\n let asking = `opening a cart on '${mark}'`;\n /*\n * THE CART, AND WHO EACH ITEM IS FOR. The second half is only knowable where the\n * widget opened the cart itself: it sent a user type per head and can read that back\n * off its own request — see `attributeCartItems`.\n */\n const load = async (): Promise<{\n cart: Cart;\n items: readonly AttributedCartItem[];\n fill: OrderFill;\n currency: string | undefined;\n /* The product the cart was filled with, where this widget chose one. */\n productName: string | undefined;\n }> => {\n if (adopt !== undefined) {\n /*\n * A HOST'S CART IS TAKEN AS IT IS. Its window began before this widget existed, so\n * there is no instant to measure from and no expiry of ours to stamp on somebody\n * else's reservation — see `heldFrom`, which stays null for it.\n */\n asking = `reading the host's cart '${adopt}'`;\n const adopted = await client.getCart(adopt);\n /*\n * `?? []` BECAUSE THE FIELD IS THE PLATFORM'S. `Cart.Items` is typed as an array\n * and a GET of somebody else's cart is an external input like any other — one that\n * answers with a total and no items leaves the screen listing nothing, which is a\n * thin card rather than a crash.\n */\n /*\n * Nothing was asked for here, so nothing can be short of what was asked — and no\n * product was read, so what the money is in stays the caller's to say.\n */\n return {\n cart: adopted,\n items: adopted.Items ?? [],\n fill: { status: 'FILLED' },\n currency: undefined,\n productName: undefined,\n };\n }\n /* `mark` is the event key in this branch — `adopt` is what the other one takes. */\n /*\n * READ THE INSTANT THE CART EXISTS, which is the only chance to learn where its\n * window started — nothing on the cart reports it.\n */\n const opening = Date.now();\n const cart = withExpiry(await client.createCart(mark), opening);\n held.current = opening;\n asking = `reading the tickets on '${mark}'`;\n const tickets = await client.getEventTickets(mark);\n /*\n * THE PRODUCT THAT SELLS WHAT THE BUYER PICKED — see `productForSession`. Read\n * before the items are built, because it is the session that decides the product\n * and not the other way round.\n */\n const asked = safeParse<TimeslotRequest | null>(timeslot, null) ?? undefined;\n const session = sessionFor(tickets, asked);\n const product = productForSession(tickets, session);\n if (product === undefined) {\n /*\n * NOTHING ON THIS EVENT SELLS THAT SESSION, which is the widget having offered a\n * time it cannot fill — a fault, and one worth saying out loud rather than\n * sending to the platform to be refused in words about inventory. An event with\n * no products at all is the other case, and is simply an empty cart.\n */\n if (session !== undefined && tickets.length > 0)\n throw new Error(\n `no product on '${mark}' sells the ${session.LocalStartTime}–${session.LocalEndTime} ` +\n 'session the buyer was offered',\n );\n return {\n cart,\n items: cart.Items ?? [],\n fill: { status: 'FILLED' },\n currency: undefined,\n productName: undefined,\n };\n }\n /*\n * WHAT THE CART'S MONEY IS IN, from the very product it is being filled with —\n * `Ticket.Currency` is the most specific of the three places one is stated.\n *\n * It was the caller's to supply and the caller does not always know, so a filled cart\n * could have a total with nothing to put in front of it: `toQuote` answers undefined\n * without a currency, and the header's summary is drawn only where there is money to\n * state. Reported as the cart screen appearing under one demo and not the other.\n */\n const money = product.Currency ?? undefined;\n\n const requested = itemsFor(\n {\n eventKey: mark,\n composition: safeParse(composition, {}),\n timeslot: session,\n },\n product,\n );\n if (requested.length === 0)\n return {\n cart,\n items: cart.Items ?? [],\n fill: { status: 'FILLED' },\n currency: money,\n productName: product.Name,\n };\n\n /*\n * NAMED DOWN TO THE SESSION, because this is the call that answers on INVENTORY and\n * \"All of the currently selected tickets have been purchased\" is unactionable\n * without knowing which product and which session it is about. `Total` and\n * `Remaining` are printed as they arrive: their scale is the platform's to say, and\n * reading a fraction as a count is how this failure was first misdiagnosed.\n */\n const sold = sessionOn(product, session);\n asking =\n `filling cart '${cart.Key}' on '${mark}' with ${requested.length} × '${product.Key}' ` +\n `(Available: ${product.Available})` +\n (session === undefined ? '' : ` at ${session.LocalStartTime}–${session.LocalEndTime}`) +\n (sold === undefined ? '' : ` (session Total: ${sold.Total}, Remaining: ${sold.Remaining})`);\n\n /*\n * FILL WHAT YOU CAN. Six heads against four remaining was a refusal with an empty\n * cart behind it; it is four tickets the buyer owns now, on the ordinary escrow. See\n * `AllowPartialFulfillment`.\n */\n const filled = await client.addItemsBulk(cart.Key, requested, { allowPartial: true });\n const reserved = filled.Items ?? [];\n /*\n * WHAT THE PLATFORM SAYS IT COULD NOT FILL, rather than what subtracting two lengths\n * implies. A returned item carries a key and amounts and no product or session, so\n * this is the only account of WHICH heads went unfilled — and a `?? []` because it is\n * an external input like any other.\n */\n const unfilled = filled.UnavailableItems ?? [];\n /*\n * The refused heads taken back out, so the rest still pair with what came back and a\n * short cart keeps its \"(Child)\" labels. A refusal describing nothing that was asked\n * for answers null, and handing the whole request over is how `attributeCartItems`\n * is told to attribute none of it.\n */\n const kept = withoutUnfilled(requested, unfilled) ?? requested;\n return {\n /* The filled cart is a fresh object from the wire, so it needs the stamp too. */\n cart: withExpiry(filled.Cart, held.current ?? Date.now()),\n items: attributeCartItems(kept, reserved, safeParse<UserTypeNames>(names, {})),\n fill: fillOf(reserved.length, requested.length, unfilled.length),\n currency: money,\n /* The product the cart was filled WITH — the cart's own items do not reliably name it. */\n productName: product.Name,\n };\n };\n\n load()\n .then(({ cart, items, fill, currency: filled, productName }) => {\n if (!live) return;\n setState((was) => ({ ...was, cart, items, fill, currency: filled, productName }));\n })\n .catch((cause: unknown) => {\n if (!live) return;\n opened.current = null;\n /*\n * HOW MANY WERE ASKED FOR, counted the one way the island counts heads — a refusal\n * on inventory is worded by the size of the party it turned away.\n */\n const fill = fillFromRefusal(cause, intentHeadcount(safeParse(composition, {})));\n /*\n * SAID OUT LOUD, ONCE, because nothing else can say it. The notice is drawn from\n * the buyer's side of this and carries no cause; an integrator whose widget will\n * not open an order had the card and nothing behind it. `ApiError` carries the\n * platform's own reason, and this prints it with the call that got it.\n *\n * AT THE LEVEL THE REFUSAL DESERVES: a sold-out session is the platform working,\n * and an integrator who greps their console for errors should not find one every\n * time a busy on-sale turns somebody away.\n */\n if (typeof console !== 'undefined') {\n const say = fill.status === 'SOLD_OUT' ? console.warn : console.error;\n say(`[ScopeTicketsCheckout] ${asking} failed.`, cause);\n }\n setState((was) => ({ ...was, fill }));\n });\n\n return () => {\n live = false;\n };\n }, [client, open, adopt, eventKey, composition, timeslot, names, reservation]);\n\n /*\n * THE STATUS IS ASKED FOR, not pushed. A payment resolves in a webhook the browser never\n * sees, so the only honest way to know is to keep asking until it answers — and to stop\n * the moment it does, which is what the outcome being set does.\n *\n * IT RUNS ONCE ON MOUNT TOO, not only while a charge is in flight: a purchase that\n * was paid in a previous mount (tab closed mid-finalization, page reloaded) has no\n * frame to say SUCCESS, and this is the only place left that can say anything at\n * all about it.\n *\n * ONCE PER CART, NOT ONCE PER EFFECT RUN. The effect's deps (watching, payment)\n * flip during recoveries too: `retryPayment` disarms the watch exactly as a\n * cancellation has terminalised the attempt on the platform, and a stray ask\n * landing in that window reads `requires_new_payment` and paints a failure over\n * the recovery — the cancelled buyer's \"Payment Failed\", the decline's instantly\n * re-failed retry. So the once-ask fires for a cart's first run only (a fresh\n * mount's ref is empty, and reload recovery keeps working), and every later ask\n * belongs to the interval, which only runs while a charge is genuinely in flight.\n */\n const [watching, setWatching] = useState(false);\n const askedOnceForRef = useRef<string | null>(null);\n useEffect(() => {\n const cartKey = state.cart?.Key;\n if (client === null || cartKey === undefined) return;\n if (!watching && state.payment !== undefined) return;\n\n let live = true;\n const ask = async () => {\n const status = await client.getPaymentStatus(cartKey);\n if (!live) return;\n /*\n * `completed` — the platform's own literal — MEANS THE PROVIDER TOOK THE MONEY,\n * never that the tickets exist. The frame's SUCCESS is the finalized word; this\n * is the paid one, and the two must not collapse into one state, because a\n * resubmit against a completed order is the double-charge path.\n */\n if (status.PaymentStatus === 'completed') {\n setWatching(false);\n setState((was) => ({ ...was, payment: { kind: 'PAID' } }));\n return;\n }\n if (status.PaymentStatus === 'requires_new_payment') {\n setWatching(false);\n setState((was) => ({\n ...was,\n payment: {\n kind: 'FAILED',\n /* The provider's own words where it gave any, and a sentence where it did not. */\n reason: status.FailureReason ?? 'Your payment could not be completed.',\n },\n }));\n }\n };\n\n const timer = watching\n ? window.setInterval(() => void ask().catch(() => undefined), POLL_MS)\n : undefined;\n if (askedOnceForRef.current !== cartKey) {\n askedOnceForRef.current = cartKey;\n void ask().catch(() => undefined);\n }\n return () => {\n live = false;\n if (timer !== undefined) window.clearInterval(timer);\n };\n }, [watching, client, state.cart?.Key, state.payment]);\n\n /*\n * THE BUYER GOES ON THE CART, and that is ALL this does. The payment intent is not\n * created here: the payment host's frame creates it when it mounts (GET-first,\n * single-flight), so a widget that also created one would be a second writer racing\n * the host for the same purchase. Charging is authorized by the caller only after\n * this resolves true.\n */\n const saveBuyer = useCallback(\n async (buyer: BuyerDetails) => {\n const cartKey = state.cart?.Key;\n if (client === null || cartKey === undefined) return false;\n try {\n await client.setBuyer(cartKey, buyer);\n return true;\n } catch (cause: unknown) {\n /*\n * ALREADY SET IS ALREADY SAVED. The platform's buyer endpoint is create-once:\n * the first Pay press put the buyer on the cart, and every later press — a\n * decline retried, a buyer who pressed twice — meets `BuyerAlreadySet` where\n * the first attempt met success. The save's purpose is \"a buyer is on this\n * cart before a charge\", which this answer proves true, so it authorizes the\n * charge rather than blocking it. A retry that refused here would strand a\n * declined buyer on a cart they can no longer pay on.\n *\n * The buyer's own details cannot have changed since: the buyer steps answered\n * before Pay was first pressed, and the platform has no update path to call.\n */\n if (cause instanceof ApiError && cause.reason === 'BuyerAlreadySet') return true;\n setState((was) => ({\n ...was,\n payment: {\n kind: 'FAILED',\n reason: cause instanceof Error ? cause.message : String(cause),\n },\n }));\n return false;\n }\n },\n [client, state.cart?.Key],\n );\n\n /*\n * ── A CODE OFF THE TOTAL ─────────────────────────────────────────────────\n *\n * BOTH WRITES ANSWER WITH THE CART, and putting it back in state is the whole of the\n * integration: `quote` is `toQuote(cart)`, so the discounted total reaches the Pay card's\n * title, the header's label and the cart screen without any of them knowing a code was\n * involved.\n *\n * THE HOLD IS NOT RESTARTED. `withExpiry` stamps an expiry on a cart that has none, and\n * a promo write must not be a way to buy more time — so the expiry already on the cart is\n * carried over rather than stamped fresh.\n */\n const [promo, setPromo] = useState<PromoWrite>({ status: 'IDLE' });\n\n const writePromo = useCallback(\n async (write: (client: ScopeClient, cartKey: string) => Promise<Cart>) => {\n const cartKey = state.cart?.Key;\n if (client === null || cartKey === undefined) return false;\n setPromo({ status: 'SAVING' });\n try {\n const cart = await write(client, cartKey);\n setState((was) => ({\n ...was,\n cart: { ...cart, ExpirationTime: was.cart?.ExpirationTime ?? cart.ExpirationTime },\n }));\n setPromo({ status: 'IDLE' });\n return true;\n } catch (cause: unknown) {\n /*\n * A REFUSED CODE IS THE COMMONEST THING THAT HAPPENS HERE — expired, spent, or for\n * a different event — so it becomes a state this card can draw rather than\n * something thrown past it. Anything that is not the platform refusing keeps\n * travelling: see `notices`, which is where a fault belongs.\n */\n if (cause instanceof ApiError) {\n setPromo({ status: 'REFUSED', reason: promoRefusal(cause.message, PROMO_REFUSED) });\n return false;\n }\n throw cause;\n }\n },\n [client, state.cart?.Key],\n );\n\n /*\n * CHECKED FIRST, THEN APPLIED — two calls, and the first one is the only thing that can\n * say WHY.\n *\n * `PUT .../PromoCode` either takes the code or refuses with a transport error, whose\n * message is about the request rather than about the code. `Check` answers\n * `{IsValid, Reason}`, and `Reason` is the platform's own sentence for an expired, spent\n * or wrong-event code — which is what the buyer needs to read to fix it.\n *\n * NARROWED BY THE CART'S EVENT, which is what the widget knows: the endpoint also takes\n * a ticket, a series and an organisation, and the cart carries none of them.\n */\n const applyPromo = useCallback(\n async (code: string): Promise<boolean> => {\n const cart = state.cart;\n if (client === null || cart === null) return false;\n const typed = code.trim();\n setPromo({ status: 'SAVING' });\n\n try {\n const checked = await client.checkPromoCode(typed, cart.EventId);\n if (!checked.IsValid) {\n setPromo({ status: 'REFUSED', reason: promoRefusal(checked.Reason, PROMO_REFUSED) });\n return false;\n }\n } catch (cause: unknown) {\n /* A check that could not be made is not a code that was refused — see `notices`. */\n setPromo({ status: 'IDLE' });\n throw cause;\n }\n\n return writePromo((api, cartKey) => api.setCartPromoCode(cartKey, typed));\n },\n [client, state.cart, writePromo],\n );\n\n const removePromo = useCallback(\n () => writePromo((api, cartKey) => api.clearCartPromoCode(cartKey)),\n [writePromo],\n );\n\n /*\n * THE FRAME'S SUCCESS: money taken AND finalized by the host. The once-marker is\n * written BEFORE the outcome is published, so a reload that interrupts publishing\n * still cannot publish again.\n */\n const settledFromFrame = useCallback(\n (attendeeTicketKey?: string) => {\n const cartKey = state.cart?.Key;\n if (cartKey === undefined) return;\n markPurchaseCompleted(cartKey);\n setWatching(false);\n setState((was) => ({\n ...was,\n /* Omitted rather than nulled where the frame named none — see `PaymentOutcome`. */\n payment: {\n kind: 'PLACED',\n ...(attendeeTicketKey === undefined ? {} : { attendeeTicketKey }),\n },\n }));\n },\n [state.cart?.Key],\n );\n\n /*\n * THE FRAME'S FAILURE: a decline, with the provider's own words. Distinct from a\n * failed buyer save only in where it comes from — both leave the buyer able to\n * correct and try again, because the hold is still running and the order still\n * pending.\n *\n * IT CANNOT DOWNGRADE A SETTLED OUTCOME. A late error after the money was taken — a\n * provider timeout that fires around a success, a duplicate decline from a second\n * callback — used to overwrite PAID or PLACED with FAILED, standing a pay button back\n * up over an order that was already charged. Once the outcome says the money moved,\n * only the finalized word (`settledFromFrame`, deliberately) may still arrive.\n */\n const failedFromFrame = useCallback((reason: string) => {\n setWatching(false);\n setState((was) =>\n was.payment?.kind === 'PAID' || was.payment?.kind === 'PLACED'\n ? was\n : { ...was, payment: { kind: 'FAILED', reason } },\n );\n }, []);\n\n /*\n * MONEY TAKEN, TICKETS NOT FINALIZED — the frame's own TransactionError, whose words\n * the host sends as \"payment was received\". This is the poll's PAID answer reached by\n * a different road: no pay button, no resubmit, the recovery card — a second charge\n * against a completed order is the one mistake this flow must not offer. It does not\n * overwrite PLACED (the finalized word is stronger) and it stops the poll, which has\n * nothing left to learn.\n */\n const paidWithoutFinalizing = useCallback(() => {\n setWatching(false);\n setState((was) =>\n was.payment?.kind === 'PLACED' ? was : { ...was, payment: { kind: 'PAID' } },\n );\n }, []);\n\n /* See `CheckoutOrder.retryPayment` — clearing the failure is all this does. */\n const retryPayment = useCallback(() => {\n setWatching(false);\n setState((was) => (was.payment === undefined ? was : { ...was, payment: undefined }));\n }, []);\n\n /* See `CheckoutOrder.restart` — the guard, the window and the state, then ask again. */\n const restart = useCallback(() => {\n opened.current = null;\n held.current = null;\n setState(IDLE);\n setReservation((was) => was + 1);\n }, []);\n\n /* See `CheckoutOrder.chargeAttempted` — the poll is the frame's backup. */\n const chargeAttempted = useCallback(() => {\n setState((was) => (was.payment === undefined ? was : { ...was, payment: undefined }));\n setWatching(true);\n }, []);\n\n /* The cart's own product answers first; the caller's reading is the fallback. */\n const { currency: filled, ...order } = state;\n return {\n ...order,\n completedPreviously: state.cart !== null && isPurchaseCompleted(state.cart.Key),\n quote: state.cart === null ? undefined : toQuote(state.cart, filled ?? currency),\n hold: state.cart === null ? undefined : toHold(state.cart, Date.now(), held.current),\n saveBuyer,\n promo,\n applyPromo,\n removePromo,\n settledFromFrame,\n failedFromFrame,\n paidWithoutFinalizing,\n retryPayment,\n chargeAttempted,\n restart,\n };\n}\n","/**\n * THE ONCE-MARKER. A purchase is finalized once; a reload, a remount or a second mount\n * of the same cart must not be able to say it again, because everything downstream of\n * \"completed\" — the success card, the host's `onCommit`, any receipt the host writes —\n * is written as if it were news.\n *\n * WRITTEN ON SUCCESS, NEVER ON `completed`. The status endpoint's `completed` says the\n * provider took the money; finalization (`convertToTransaction`) can still fail after\n * it. A marker written there would make a paid-but-unfinalized purchase read as\n * complete after a reload, which is precisely the state that must route to support\n * rather than to a celebration.\n *\n * LOCAL, AND HONEST ABOUT IT. `localStorage` is per-browser, so this gates the one\n * browser that made the purchase; a different browser sees the poll's answer instead.\n * That is enough for the exactly-once rule, which is about the widget not repeating\n * itself — not about making the platform idempotent for the world.\n */\n\nconst PREFIX = 'scopetickets:checkout:completed:';\n\nconst keyFor = (cartKey: string): string => `${PREFIX}${cartKey}`;\n\n/** Whether this browser already finalized a purchase against the cart. */\nexport function isPurchaseCompleted(cartKey: string): boolean {\n try {\n return window.localStorage.getItem(keyFor(cartKey)) !== null;\n } catch {\n /* Storage can be unavailable (private modes, embedders); the rule degrades to\n * exactly-once per mount rather than exactly-once per browser. */\n return false;\n }\n}\n\n/** Record the finalized purchase, before anything is published from it. */\nexport function markPurchaseCompleted(cartKey: string): void {\n try {\n window.localStorage.setItem(keyFor(cartKey), new Date().toISOString());\n } catch {\n /* See `isPurchaseCompleted`: a storage failure must not fail the purchase. */\n }\n}\n","/**\n * WHAT IS IN THE CART, as the cart screen draws it.\n *\n * ONE LINE PER PRODUCT, and the platform's own money on each. A cart holds one ITEM PER\n * HEAD — `itemsFor` sends one per person and the platform answers with one per person —\n * so three adult tickets are three items with a third of the money each. Nobody wants to\n * read that; a line is what a buyer recognises as a thing they chose, and the count on\n * its badge is how many of it they took.\n *\n * \"Peak\" IS THE PRODUCT AND \"(Child)\" IS THE USER TYPE, where one applies — so three Peak\n * tickets bought for one adult and two children are TWO lines, not one. The wire does not\n * say which is which: `CartItem` echoes a name and an amount and nothing about who the\n * ticket is for, though the widget sent a `UserTypeAssignmentKey` on every one of them.\n *\n * SO IT IS READ BACK OFF THE REQUEST, where there was one — see `attributeCartItems`. A\n * cart the widget did not open (a host's own, adopted) has no request to read, and its\n * lines group by product alone until the host or the platform says more.\n */\n\nimport type { BulkAddItemRequest, CartItem } from '@scopetickets/api';\n\n/** One line of the cart. Everything a row draws, and nothing about how. */\nexport type CartLine = {\n /** Stable across a re-price, so React keeps the row rather than replacing it. */\n readonly key: string;\n /** The product, as the platform names it — \"Peak\". */\n readonly name: string;\n /** Who the ticket is for — \"Adult\". Absent until the platform says. */\n readonly userType?: string;\n /** How many, drawn on the thumbnail's own badge. */\n readonly count: number;\n /** What the LINE comes to — every head of it, in minor units. */\n readonly minorUnits: number;\n /**\n * THE EVENT'S OWN ARTWORK, under the ticket silhouette — the design's\n * `AvatarImage-Event`. Absent, the avatar package draws its own fill rather than a gap,\n * which is what a cart adopted from a host that names none gets.\n */\n readonly artwork?: string;\n /** The run these tickets are for — \"Ice Rink\". */\n readonly subject?: string;\n /** The session, already joined: `12:00 - 12:45`. */\n readonly timeslot?: string;\n /** The day, written out: \"Saturday, 12 December\". */\n readonly day?: string;\n};\n\n/**\n * A cart item with the user type it was BOUGHT FOR attached — see `attributeCartItems`,\n * which is the only thing that can attach it.\n */\nexport type AttributedCartItem = CartItem & { readonly userType?: string };\n\n/** One item as the widget ASKED for it, reduced to the part a line needs. */\nexport type RequestedItem = { readonly UserTypeAssignmentKey?: string | null };\n\n/**\n * WHAT WE ASKED FOR, ZIPPED WITH WHAT CAME BACK — the user type per created item.\n *\n * A BULK ADD ANSWERS IN REQUEST ORDER, which is the one assumption here and is why this\n * is a function with a guard rather than a line inside the hook: if the platform returns\n * a different NUMBER of items than were asked for, the correspondence is broken and\n * nothing about it can be trusted, so the answer is `null` — no split — rather than a\n * plausible mislabelling of somebody's money.\n *\n * `names` MAPS KEYS TO WORDS, because the wire deals in assignment keys and a cart line\n * says \"Adult\". An unrecognised key is left unnamed rather than printed raw.\n */\nexport function attributeCartItems(\n requested: readonly RequestedItem[],\n items: readonly CartItem[],\n names: Readonly<Record<string, string>>,\n): readonly AttributedCartItem[] {\n if (requested.length !== items.length) return items;\n\n return items.map((item, at) => {\n const key = requested[at]?.UserTypeAssignmentKey ?? null;\n const named = key === null ? undefined : names[key];\n return named === undefined ? item : { ...item, userType: named };\n });\n}\n\n/** Two heads the same, as far as a bulk add distinguishes them. */\nfunction sameLine(one: BulkAddItemRequest, other: BulkAddItemRequest): boolean {\n return (\n one.ProductKey === other.ProductKey &&\n /* ABSENT AND NULL ARE ONE KEY HERE. The widget omits it where there is no user type\n * and the platform echoes it back as an explicit `null` — see `itemsFor`. */\n (one.UserTypeAssignmentKey ?? null) === (other.UserTypeAssignmentKey ?? null) &&\n one.Timeslot?.LocalStartTime === other.Timeslot?.LocalStartTime &&\n one.Timeslot?.LocalEndTime === other.Timeslot?.LocalEndTime\n );\n}\n\n/**\n * THE HEADS THAT WERE ACTUALLY FILLED — the request with the platform's own list of\n * refusals taken out of it, so a SHORT cart can still be attributed.\n *\n * `attributeCartItems` needs one requested head per returned item and gives up when the\n * counts disagree. That guard is right, but `AllowPartialFulfillment` makes disagreement\n * the ORDINARY case rather than the broken one, so every part-filled cart lost its\n * \"(Child)\" labels and drew bare products. `UnavailableItems` is what closes the gap: the\n * platform says which lines it could not fill, so the rest can be paired as before.\n *\n * ONE MATCH PER REFUSAL, removed as it is found — four children asked for and two refused\n * must drop two, not all four. An entry matching nothing means the answer does not\n * describe the request, and `null` says so rather than shifting every label by one.\n */\nexport function withoutUnfilled(\n requested: readonly BulkAddItemRequest[],\n unfilled: readonly BulkAddItemRequest[],\n): readonly BulkAddItemRequest[] | null {\n const kept = [...requested];\n for (const refused of unfilled) {\n const at = kept.findIndex((head) => sameLine(head, refused));\n if (at === -1) return null;\n kept.splice(at, 1);\n }\n return kept;\n}\n\n/**\n * What every line of a cart shares — the order it belongs to, said once.\n *\n * THE ARTWORK IS IN HERE and not on the item because a cart holds ONE event: every line\n * of it is a ticket to the same thing, so the picture is the order's rather than the\n * product's. A host that stocks per-product artwork says so by supplying `cartLines`\n * itself, where each line carries its own.\n */\nexport type CartLineContext = {\n readonly artwork?: string;\n /**\n * WHAT THE CART WAS FILLED WITH, as the PRODUCT names itself — \"Peak\".\n *\n * The cart's own items do not reliably echo it — `Name` is optional on the wire and `Type`\n * is a category, not a product. Taken off the product for the same reason the currency is:\n * it is a reading of what was bought, not of the receipt.\n */\n readonly productName?: string;\n readonly subject?: string;\n readonly timeslot?: string;\n readonly day?: string;\n};\n\n/**\n * The first of these that is actually a name.\n *\n * BLANK IS ABSENT, and that is the whole reason this is a function rather than a `??` chain:\n * the platform answers a nameless item with an EMPTY STRING, which `??` passes straight\n * through, and the cart drew a heading with nothing in it.\n */\nfunction firstNamed(...candidates: readonly (string | undefined)[]): string {\n for (const candidate of candidates) {\n if (candidate !== undefined && candidate.trim() !== '') return candidate;\n }\n return '';\n}\n\n/**\n * The cart's items as lines: grouped by what they are AND who they are for, counted, and\n * summed.\n *\n * THE USER TYPE IS PART OF THE GROUPING KEY, which is the whole of the design's reading:\n * one adult and two children on the same product are two lines with a 1 and a 2 on them,\n * and the money on each is what those heads came to.\n *\n * `Name`, THEN THE PRODUCT, THEN `Type` — most specific first. `Type` is a category\n * (\"Ticket\") and is the last resort rather than the answer. Each only if it is not blank; see\n * `firstNamed`.\n */\nexport function cartLines(\n items: readonly AttributedCartItem[],\n context: CartLineContext = {},\n): readonly CartLine[] {\n const lines = new Map<string, CartLine>();\n\n for (const item of items) {\n const name = firstNamed(item.Name, context.productName, item.Type);\n const at = `${name}\\u0000${item.userType ?? ''}`;\n const held = lines.get(at);\n lines.set(at, {\n key: held?.key ?? item.Key,\n name,\n ...(item.userType === undefined ? {} : { userType: item.userType }),\n count: (held?.count ?? 0) + 1,\n minorUnits: (held?.minorUnits ?? 0) + item.TotalAmount,\n ...context,\n });\n }\n\n return [...lines.values()];\n}\n","/**\n * WHAT THE ORDER CAME TO — one state rather than a count beside an error.\n *\n * It was `{ shortfall: number, error: Error | null }`, two fields tracking one event, and\n * the pair could not say the case that matters most: a session with nothing left refuses\n * the whole cart, so it arrives as a THROW rather than as a shortfall equal to what was\n * asked. Against two fields that reads as `failed`, indistinguishable from a dropped\n * connection, and inventory gets filed as breakage — see `noticeTelemetry`.\n *\n * Pure: no React, no network, no DOM.\n */\n\nimport { ApiError } from '@scopetickets/api';\n\nexport type OrderFill =\n /** No cart has been asked for yet, or one is in flight. */\n | { readonly status: 'PENDING' }\n /** Every head asked for is held. */\n | { readonly status: 'FILLED' }\n /**\n * FEWER HEADS THAN ASKED FOR ARE HELD, and they are the buyer's — see\n * `AllowPartialFulfillment`. Both numbers are stated rather than derived, so a notice\n * can say either without doing arithmetic to find the other.\n */\n | { readonly status: 'SHORT'; readonly held: number; readonly asked: number }\n /**\n * NOTHING COULD BE HELD. The platform refuses the whole request when it can fill none of\n * it, EVEN WITH the partial-fulfilment flag set. `asked` rides along because the party\n * that met the refusal decides the words — see `raiseFor`.\n */\n | { readonly status: 'SOLD_OUT'; readonly asked: number }\n /** Something broke. The cart, the tickets or the fill did not answer. */\n | { readonly status: 'FAILED'; readonly error: Error };\n\n/**\n * The refusals that mean INVENTORY rather than breakage, narrowed from the platform's own\n * free text — anything this package has not been taught answers `null` and is treated as a\n * fault, which is the safe direction.\n *\n * THE SECOND IS NOT THE MISNOMER IT READS AS: an over-ask against a session that still has\n * stock answers `TimeSlotNotAvailable`, with the slot very much available. Raised with the\n * platform; it means no stock either way.\n */\nconst INVENTORY_REASONS = ['NoTicketsAvailable', 'TimeSlotNotAvailable'] as const;\n\nexport type InventoryReason = (typeof INVENTORY_REASONS)[number];\n\nexport function inventoryReason(cause: unknown): InventoryReason | null {\n if (!(cause instanceof ApiError)) return null;\n return INVENTORY_REASONS.find((known) => known === cause.reason) ?? null;\n}\n\n/** One place draws the distinction, so the hook cannot grow a second opinion about it. */\nexport function fillFromRefusal(cause: unknown, asked: number): OrderFill {\n if (inventoryReason(cause) !== null) return { status: 'SOLD_OUT', asked };\n return { status: 'FAILED', error: cause instanceof Error ? cause : new Error(String(cause)) };\n}\n","/**\n * WHICH PRODUCT A CART IS FILLED WITH — the join between the session a buyer picked and\n * the thing that actually sells it.\n *\n * An event sells one product or several, each stating its own sessions, and the picker\n * draws the UNION of them: choosing 11:00 is choosing a time, not a product. The order\n * chose with `tickets.find((ticket) => ticket.Available)` instead — the first available\n * one, whatever hours it sold — so a night selling 11:00 on one product and 15:00 on\n * another offered the first and filled the cart against the second. The platform answered\n * on a combination that does not exist, in the only words it has for that: `All of the\n * currently selected tickets have been purchased`, on a run with nothing sold.\n */\n\nimport type { EventTimeslot, Ticket, TimeslotRequest } from '@scopetickets/api';\n\n/**\n * Whether the session is part of this order at all — the question that comes first.\n *\n * A host supplying its own `slotsByDay` can collect a session for a run whose products\n * sell none, and sending one then asks for something nobody offers. `HasTimeslot` is the\n * platform saying whether it means its list, which is the flag `useCheckoutData` reads\n * when it decides whether Select Time is reached at all.\n */\nexport function sessionFor(\n tickets: readonly Ticket[],\n session: TimeslotRequest | undefined,\n): TimeslotRequest | undefined {\n return tickets.some((ticket) => ticket.HasTimeslot) ? session : undefined;\n}\n\n/**\n * The platform's own entry for that session on this product, or `undefined` where it\n * sells no such thing — the one place the session's `Total` and `Remaining` are stated.\n *\n * MATCHED ON BOTH ENDS, because both are what the cart is sent: a product selling\n * 11:00–11:45 does not sell the 11:00–14:00 another one does.\n */\nexport function sessionOn(\n ticket: Ticket,\n session: TimeslotRequest | undefined,\n): EventTimeslot | undefined {\n if (session === undefined || !ticket.HasTimeslot) return undefined;\n return (ticket.Timeslots ?? []).find(\n (slot) =>\n slot.LocalStartTime === session.LocalStartTime && slot.LocalEndTime === session.LocalEndTime,\n );\n}\n\n/**\n * Whether this product sells that session. None asked for is not a mismatch — that is how\n * a run selling no sessions is filled at all.\n */\nexport function sellsSession(ticket: Ticket, session: TimeslotRequest | undefined): boolean {\n return session === undefined || sessionOn(ticket, session) !== undefined;\n}\n\n/**\n * The product to fill the cart with, or `undefined` where nothing sells what was asked\n * for.\n *\n * AVAILABLE FIRST, and an unavailable one only where it alone sells the session: the\n * platform stays the authority on inventory rather than being guessed ahead of.\n */\nexport function productForSession(\n tickets: readonly Ticket[],\n session: TimeslotRequest | undefined,\n): Ticket | undefined {\n const sells = tickets.filter((ticket) => sellsSession(ticket, session));\n return sells.find((ticket) => ticket.Available) ?? sells[0];\n}\n","/**\n * A CODE OFF THE ORDER'S TOTAL.\n *\n * THE CART IS THE ANSWER AND THIS IS ONLY THE ASKING: what is applied is `Cart.PromoCode`\n * and what it saved is `Cart.DiscountAmount`, both of which survive a refetch and neither\n * of which is kept here. Only the asking — whether a write is in flight, and how the last\n * one ended — is this file's, because nothing else can say it.\n */\n\nimport { bounded, WIRE_LIMITS } from './wire';\nimport { formatMoney } from './money';\nimport type { Cart } from '@scopetickets/api';\n\n/** What the promo card is DOING. */\nexport type PromoWrite =\n | { readonly status: 'IDLE' }\n | { readonly status: 'SAVING' }\n /** The platform refused it, in its own words. See `promoRefusal`. */\n | { readonly status: 'REFUSED'; readonly reason: string };\n\n/**\n * WHAT A CODE TOOK OFF, already written — `€4.60`, or `null` where nothing did.\n *\n * THE MONEY AND NOT A PERCENTAGE, which the design asked for and no endpoint can answer:\n * `Check` returns `{IsValid, Reason}` and the cart returns minor units, while the RATE\n * lives on a `PromoCode` record nothing here may read. Worked back out of the total it\n * would be a guess printed as a fact — and wrong by construction for a flat-amount code,\n * where €5 off €23 is not \"21.7% saved\" to anybody.\n */\nexport function promoSaved(cart: Cart, currency: string | undefined): string | null {\n if (currency === undefined) return null;\n /*\n * POSITIVE AND FINITE, not just `> 0`. `DiscountAmount` is typed `number` and the wire\n * may simply omit it — and `undefined <= 0` is FALSE, so a guard written the obvious way\n * lets it through and the card says \"€NaN Saved\". Asked of the value rather than of the\n * type, because the type is what was wrong.\n */\n const saved = cart.DiscountAmount;\n if (typeof saved !== 'number' || !Number.isFinite(saved) || saved <= 0) return null;\n return formatMoney(saved, currency);\n}\n\n/** The code on the order, or `null` — bounded, because it reaches the card as text. */\nexport function promoApplied(cart: Cart | null): string | null {\n return cart === null ? null : bounded(cart.PromoCode, WIRE_LIMITS.promoCode);\n}\n\n/**\n * WHAT A REFUSAL SAYS WHERE THE PLATFORM SAID NOTHING USABLE. Deliberately vague: the\n * widget does not know why, and a specific guess would be worse than an honest shrug.\n */\nexport const PROMO_REFUSED = 'That code cannot be used on this order.';\n\n/**\n * WHY A CODE WAS REFUSED, in words a buyer may be shown — and it is prose we did not\n * author, so it is bounded first. Same rule the notice reporter follows for a thrown\n * message, and the same reason: an upstream that one day answers with a stack trace must\n * not put one on the card. Whether a refusal is a fault at all is `useCheckoutOrder`'s\n * decision, where it is made.\n */\nexport function promoRefusal(reason: unknown, fallback: string): string {\n const stated = typeof reason === 'string' ? reason : null;\n return bounded(stated, WIRE_LIMITS.promoReason) ?? fallback;\n}\n\n/**\n * Whether the field's contents are worth sending — trimmed, non-empty, and NOT what is\n * already on the order. The last clause is the button's whole state: the design draws\n * Apply dim over an applied code, and re-sending one can only answer with what is on\n * screen already.\n */\nexport function promoSendable(typed: string, applied: string | null): boolean {\n const value = typed.trim();\n return value.length > 0 && value !== applied;\n}\n","import type { CSSProperties } from 'react';\nimport { Avatar, CountBadge } from '@scopetickets/avatar';\nimport { moneyParts, widestAmount } from '../domain/money';\nimport type { CartLine } from '../domain/cart';\n\n/**\n * `BlackNear/BlackNear100` — `AvatarCount`'s ground on the design, against the package's own\n * default of `RedDark/RedDark100`. How many of a thing is in the cart is INVENTORY, and red\n * said the line had gone wrong. A token, so the value is the theme's rather than a hex here.\n */\nconst COUNT_BADGE_BACKGROUND = 'var(--scopetickets-island-cart-count-background)';\n\nexport type CartLinesProps = {\n readonly lines: readonly CartLine[];\n /** What the whole cart comes to, in minor units — the platform's own figure. */\n readonly totalMinorUnits: number;\n readonly currency: string;\n /** The total row's label. This package's copy lives in `step-cards`. */\n readonly totalLabel: string;\n};\n\n/**\n * WHAT IS IN THE CART — the design's `ItemsInCart`, and the total under it.\n *\n * THE LINE AMOUNTS SHARE ONE COLUMN, as wide as the widest of them, so the symbols stack\n * down the card instead of drifting with the digits. It is published as a COUNT of\n * characters — see `widestAmount` — and spent as `ch` on the mono face, where a character\n * is one advance: no element is measured, and adding a line that is a digit longer moves\n * the whole column by exactly one.\n *\n * THE TOTAL IS IN NEITHER. `3795:8748` sets the whole of `€ 18.00` in `text/bold/lg` —\n * Basier Square Medium 20/24 — where a line's own figure is `text/mono/md`. Drawn as one\n * more row of the column it took a face the design never gives it, and sized that column to\n * a figure sitting nowhere near it.\n */\nexport function CartLines({ lines, totalMinorUnits, currency, totalLabel }: CartLinesProps) {\n const total = moneyParts(totalMinorUnits, currency);\n /* THE LINES ONLY — the total sits outside the column, so it must not size it. */\n const amounts = lines.map((line) => moneyParts(line.minorUnits, currency).amount);\n\n return (\n <div\n className=\"scopetickets-island-cart\"\n style={{ '--scopetickets-island-cart-amount': widestAmount(amounts) } as CSSProperties}\n >\n {lines.map((line) => (\n <CartRow key={line.key} line={line} currency={currency} />\n ))}\n\n {/*\n * TWO HALVES OF ONE LINE, each taking half the width — the label reads from the\n * leading edge and the sum from the trailing one, which is `3795:8747`'s own layout\n * and is why neither is asked to shrink around the other.\n */}\n <div className=\"scopetickets-island-cart__total\">\n <span className=\"scopetickets-island-cart__total-label\">{totalLabel}</span>\n <span className=\"scopetickets-island-cart__total-amount\">\n <span className=\"scopetickets-island-cart__symbol\">{total.symbol}</span>\n <span>{total.amount}</span>\n </span>\n </div>\n </div>\n );\n}\n\nfunction CartRow({ line, currency }: { line: CartLine; currency: string }) {\n return (\n <div className=\"scopetickets-island-cart__row\">\n {/*\n * THE EVENT'S ARTWORK UNDER THE TICKET SILHOUETTE, with how many of it on the badge —\n * `@scopetickets/avatar` owns both shapes, so neither is drawn here. The picture is the\n * ORDER'S rather than the item's: one cart, one event. DECORATIVE, because the row says\n * the product, the user type and the booking in words beside it.\n */}\n <span className=\"scopetickets-island-cart__thumbnail\">\n <Avatar\n subject={{ kind: 'ticket', src: line.artwork ?? '', alt: '' }}\n size={10}\n fill\n accessory={{\n shape: 'circle',\n content: <CountBadge value={line.count} background={COUNT_BADGE_BACKGROUND} />,\n id: `cart:${line.key}`,\n }}\n />\n </span>\n\n <span className=\"scopetickets-island-cart__detail\">\n <span className=\"scopetickets-island-cart__heading\">\n {/*\n * `TicketProductInformation` — the two halves of what this line IS, `$2` apart and\n * `$4` from the price. A group rather than three siblings because one gap on the row\n * cannot say two distances.\n */}\n <span className=\"scopetickets-island-cart__product\">\n <span className=\"scopetickets-island-cart__name\">{line.name}</span>\n {/*\n * PARENTHESISED HERE AND NOT IN THE DATA. The brackets are how this card writes a\n * user type beside a product name; the value is \"Adult\".\n */}\n {line.userType === undefined ? null : (\n <span className=\"scopetickets-island-cart__user-type\">({line.userType})</span>\n )}\n </span>\n <Amount parts={moneyParts(line.minorUnits, currency)} />\n </span>\n\n {/* Everything about the booking, in the design's own order. */}\n <span className=\"scopetickets-island-cart__booking\">\n {line.subject === undefined ? null : (\n <span className=\"scopetickets-island-cart__subject\">{line.subject}</span>\n )}\n {line.timeslot === undefined ? null : (\n <span className=\"scopetickets-island-cart__timeslot\">{line.timeslot}</span>\n )}\n {line.day === undefined ? null : <span>{line.day}</span>}\n </span>\n </span>\n </div>\n );\n}\n\n/** The symbol, then the digits in the shared column. */\nfunction Amount({ parts }: { parts: { symbol: string; amount: string } }) {\n return (\n <span className=\"scopetickets-island-cart__amount\">\n <span className=\"scopetickets-island-cart__symbol\">{parts.symbol}</span>\n <span className=\"scopetickets-island-cart__figure\">{parts.amount}</span>\n </span>\n );\n}\n","import type { RefObject } from 'react';\nimport { useIslandPress } from './island-press';\n\n/** One face the grid offers, as the grid needs it. */\nexport type ProfilePhotoOption = {\n /**\n * THE AVATAR VALUE THIS CELL STANDS FOR — `default:<id>` for one of the platform's\n * stock photos, and an uploaded photo's own url for the cell a buyer made. It is what\n * the account will store, so the grid never has to translate what it hands back.\n */\n readonly value: string;\n /** Where the picture is. */\n readonly url: string;\n /** What this cell is called, for assistive technology. This package holds no copy. */\n readonly label: string;\n};\n\nexport type ProfilePhotoPickerProps = {\n readonly photos: readonly ProfilePhotoOption[];\n /** The chosen value, or empty for a buyer who has not chosen yet. */\n readonly selectedValue: string;\n readonly onSelect: (value: string) => void;\n /** Names the group for assistive technology. */\n readonly label: string;\n /**\n * THE UPLOAD BUTTON IS ON THE CARD, under Continue, where the design puts it — so the\n * file input it opens is reached from out there rather than drawn beside the grid.\n * The input lives here because what it produces is a cell in this grid.\n */\n readonly inputRef: RefObject<HTMLInputElement>;\n readonly onFileChosen: (file: File) => void;\n /** Why the last file was refused, in words, or absent while none was. */\n readonly refusal?: string | null;\n};\n\n/** The Profile Photo step's grid — the design's `SelectableProfilePhotosWrapper`. */\nexport function ProfilePhotoPicker({\n photos,\n selectedValue,\n onSelect,\n label,\n inputRef,\n onFileChosen,\n refusal = null,\n}: ProfilePhotoPickerProps) {\n return (\n <div className=\"scopetickets-island-photos\">\n <div className=\"scopetickets-island-photos__grid\" role=\"radiogroup\" aria-label={label}>\n {photos.map((photo) => (\n <PhotoCell\n key={photo.value}\n photo={photo}\n selected={photo.value === selectedValue}\n onSelect={() => onSelect(photo.value)}\n />\n ))}\n </div>\n\n {/*\n * NOT FOCUSABLE, and not in the accessibility tree. The Upload button IS this\n * control as far as a buyer is concerned — it carries the name and takes the focus\n * — and a second tab stop that opens the same dialog would be one stop with nothing\n * to say about itself.\n */}\n <input\n ref={inputRef}\n type=\"file\"\n accept=\"image/*\"\n tabIndex={-1}\n aria-hidden=\"true\"\n className=\"scopetickets-island-offscreen scopetickets-island-photos__file\"\n onChange={(event) => {\n const file = event.target.files?.[0];\n /*\n * THE INPUT IS CLEARED EITHER WAY. Without it, choosing the same file twice\n * fires no second change — which is exactly what a buyer does after a refusal\n * they have just gone and fixed.\n */\n event.target.value = '';\n if (file !== undefined) onFileChosen(file);\n }}\n />\n\n {refusal === null ? null : (\n <p className=\"scopetickets-island-photos__refusal\" role=\"status\">\n {refusal}\n </p>\n )}\n </div>\n );\n}\n\nfunction PhotoCell({\n photo,\n selected,\n onSelect,\n}: {\n photo: ProfilePhotoOption;\n selected: boolean;\n onSelect: () => void;\n}) {\n // `element`, not `island` — picking a face does not change what the island IS, which\n // is the same reading the payment list's rows are pressed under.\n const press = useIslandPress('element');\n\n return (\n <button\n type=\"button\"\n role=\"radio\"\n aria-checked={selected}\n aria-label={photo.label}\n className=\"scopetickets-island-photos__cell\"\n data-selected={selected ? '' : undefined}\n onClick={onSelect}\n {...press}\n >\n {/*\n * ALT IS EMPTY BY DESIGN: the button already carries the name, and a stock avatar\n * has nothing to say that \"Avatar 3\" does not.\n */}\n <img className=\"scopetickets-island-photos__photo\" src={photo.url} alt=\"\" />\n </button>\n );\n}\n","import type { ReactNode } from 'react';\nimport { CheckIcon } from '@scopetickets/icons';\nimport { useIslandPress } from './island-press';\n\n/**\n * Somebody behind the event, offered for subscription, reduced to what the row draws.\n */\nexport type FollowEntity = {\n readonly key: string;\n readonly name: string;\n /** What kind of entity this is, in words. Drawn under the name. */\n readonly kind: string;\n /** The entity's own artwork, or absent. */\n readonly artwork?: ReactNode;\n};\n\nexport type FollowListProps = {\n readonly entities: readonly FollowEntity[];\n readonly selectedKeys: readonly string[];\n readonly onToggle: (key: string) => void;\n};\n\n/** The Follow Prompt's list — the design. */\nexport function FollowList({ entities, selectedKeys, onToggle }: FollowListProps) {\n return (\n <div className=\"scopetickets-island-follow\">\n {entities.map((entity) => {\n const selected = selectedKeys.includes(entity.key);\n return (\n <FollowRow\n key={entity.key}\n entity={entity}\n selected={selected}\n onToggle={() => onToggle(entity.key)}\n />\n );\n })}\n </div>\n );\n}\n\nfunction FollowRow({\n entity,\n selected,\n onToggle,\n}: {\n entity: FollowEntity;\n selected: boolean;\n onToggle: () => void;\n}) {\n const press = useIslandPress('element');\n\n return (\n <button\n type=\"button\"\n role=\"checkbox\"\n aria-checked={selected}\n aria-label={`${entity.name}, ${entity.kind}`}\n className=\"scopetickets-island-follow__row\"\n data-selected={selected ? '' : undefined}\n onClick={onToggle}\n {...press}\n >\n {entity.artwork === undefined ? null : (\n <span className=\"scopetickets-island-follow__artwork\">{entity.artwork}</span>\n )}\n\n {/*\n * ONE LINE. The design draws the row's Title alone, centred in a 40-tall text block,\n * with the subtitle slot hidden on this variant — so the kind is not drawn. It is still\n * SAID: it is in the row's accessible name, where \"Reboot Events, organiser\"\n * distinguishes two entities that share a name and a picture cannot.\n */}\n <span className=\"scopetickets-island-follow__name\">{entity.name}</span>\n\n {/*\n * The tick sits at the row's TRAILING edge, centred in a wrapper the same 40px square\n * the artwork occupies at the other end. Pure layout: the wrapper has no fill or border\n * of its own — it squares the two ends of the row off against each other and gives a\n * 16px control a 40px target.\n */}\n <span className=\"scopetickets-island-follow__tick-slot\" aria-hidden=\"true\">\n <span className=\"scopetickets-island-follow__tick\">\n {selected ? <CheckIcon fill color=\"currentColor\" /> : null}\n </span>\n </span>\n </button>\n );\n}\n","import { useEffect, useId, useLayoutEffect, useRef, useState, type ReactNode } from 'react';\nimport { ContentFlag, type ContentFlagTone } from './ContentFlag';\n\nexport type TextFieldProps = {\n /** The field's name, and its only label — there is no placeholder. */\n readonly label: string;\n readonly value: string;\n readonly onChange?: (value: string) => void;\n /**\n * The mark at the trailing end, or absent while the field has nothing to say. `none` in\n * the domain's `ContentFlag` is this being omitted.\n */\n readonly flag?: ContentFlagTone;\n /**\n * WHAT THE MARK MEANS, for anyone who cannot see it. `ContentFlag` hides an untitled\n * mark from the accessibility tree, which is right where the field's own text already\n * says what is wrong and wrong where the mark is the ONLY thing saying it — the email\n * field's `warning`, where nothing else on the card mentions the suspected typo.\n */\n readonly flagTitle?: string;\n /**\n * Replaces the flag entirely — the password field's counter ring, which is not one of\n * the three marks., and its reasoning: the ring is a fourth thing a field can show and\n * folding it into the flag set would make the set mean two different kinds of thing.\n */\n readonly trailing?: ReactNode;\n /** A mark at the LEADING end — `InputIconWrapper`. */\n readonly icon?: ReactNode;\n /**\n * A quiet note between the value and the flag, right-aligned — `inputNoteText`, which\n * the design fills with \"2º\". Here it is the phone step's dial code.\n */\n readonly note?: ReactNode;\n /**\n * `text` unless said otherwise. `password` masks and, with\n * `autoComplete=\"new-password\"`, is what asks the browser's password manager to suggest\n * one.\n */\n readonly type?: 'text' | 'password' | 'email' | 'tel';\n /** Drives the on-screen keyboard on a touch device. */\n readonly inputMode?: 'text' | 'email' | 'tel' | 'numeric';\n /**\n * The autofill contract. Passed straight through; see `PASSWORD_RULES` for the one case\n * where a second attribute goes with it.\n */\n readonly autoComplete?: string;\n readonly autoCapitalize?: 'none' | 'words' | 'sentences';\n /**\n * TURN THE PHONE'S HELP OFF, for a value it cannot help with: iOS autocorrects and\n * spell-checks a text input by default, and on an address, a surname or a revealed\n * password that is a phone rewriting an answer only the buyer knows.\n *\n * ONE PROP FOR BOTH ATTRIBUTES — a field either holds prose or it does not.\n */\n readonly prose?: boolean;\n /**\n * Safari's Password Rules string, which is what makes \"Suggest Strong Password\"\n * generate to OUR minimum rather than its own default. Other browsers ignore it.\n */\n readonly passwordRules?: string;\n /**\n * What the return key says, and what it does. Pair them: a key labelled \"next\" that\n * submits is worse than an unlabelled one.\n */\n readonly enterKeyHint?: 'next' | 'done' | 'go';\n readonly onSubmit?: () => void;\n /**\n * The value in `text/mono/md` — Add Password's own instance does this, so a masked\n * password's dots sit on an even rhythm.\n */\n readonly monospace?: boolean;\n /**\n * TAKE FOCUS ON MOUNT — the first field of a step, so a buyer can start typing the\n * answer to the question the card just asked.\n *\n * NOT the `autofocus` ATTRIBUTE, which fires at parse time and belongs to the document:\n * this widget is a guest on somebody's page and its steps mount long after that page\n * loaded. Focused with `preventScroll`, for the same reason — a card that yanked the\n * host's scroll position to itself would be a widget rearranging a site it does not own.\n */\n readonly autoFocus?: boolean;\n /** A value to be confirmed rather than typed — see `ConfirmEmailStep`. */\n readonly placeholder?: string;\n /**\n * THE CEILING THE PLATFORM ITSELF ENFORCES, passed to the input rather than checked\n * after: a buyer who types past the line is stopped by the field they are standing in,\n * not told by a notice two presses later. Omitted where the wire sets no limit.\n */\n readonly maxLength?: number;\n /** Given so a preceding field's return key can move focus here. */\n readonly id?: string;\n readonly name?: string;\n};\n\n/** Figma's `InputTextShort`, ported from. */\nexport function TextField({\n label,\n value,\n onChange,\n flag,\n flagTitle,\n trailing,\n icon,\n note,\n type = 'text',\n inputMode,\n prose = true,\n autoComplete,\n autoCapitalize,\n passwordRules,\n enterKeyHint,\n onSubmit,\n monospace = false,\n placeholder,\n maxLength,\n autoFocus = false,\n id,\n name,\n}: TextFieldProps) {\n const generated = useId();\n /* The design's `state=\"Focused\"`, tracked rather than inferred from a pseudo-class. */\n const [focused, setFocused] = useState(false);\n const inputId = id ?? generated;\n\n /*\n * A controlled field whose owner rewrites what was typed — the phone number grouping\n * itself as it is entered — puts the caret back at the END on every keystroke, so\n * typing into the middle of a number throws you to the finish.\n */\n const inputRef = useRef<HTMLInputElement | null>(null);\n const pending = useRef<{ typed: string; digits: number } | null>(null);\n\n /*\n * ONCE, ON MOUNT. A step is a fresh card and a fresh field, so mounting IS the moment\n * the question is asked — and `autoFocus` is read only then, so a field that gains it\n * later does not steal focus from wherever the buyer has since gone.\n */\n useEffect(() => {\n if (!autoFocus) return;\n inputRef.current?.focus({ preventScroll: true });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n useLayoutEffect(() => {\n const node = inputRef.current;\n const mark = pending.current;\n pending.current = null;\n if (node === null || mark === null) return;\n if (node.value === mark.typed || document.activeElement !== node) return;\n\n let at = 0;\n if (mark.digits > 0) {\n let seen = 0;\n at = node.value.length;\n for (let i = 0; i < node.value.length; i += 1) {\n if (!/\\d/.test(node.value[i] as string)) continue;\n seen += 1;\n if (seen === mark.digits) {\n at = i + 1;\n break;\n }\n }\n }\n node.setSelectionRange(at, at);\n });\n\n const body = (\n <>\n <span className=\"scopetickets-island-field__label\">{label}</span>\n\n {/*\n * The clip. A visual reveal only — the control inside keeps its real, full-size frame\n * at every point.\n */}\n <span className=\"scopetickets-island-field__clip\">\n <span className=\"scopetickets-island-field__row\">\n {icon === undefined ? null : (\n <span className=\"scopetickets-island-field__icon\">{icon}</span>\n )}\n\n <input\n ref={inputRef}\n id={inputId}\n name={name}\n className={`scopetickets-island-field__value${monospace ? ' scopetickets-island-field__value--mono' : ''}`}\n type={type}\n value={value}\n placeholder={placeholder}\n maxLength={maxLength}\n onChange={(event) => {\n const typed = event.target.value;\n const before = typed.slice(0, event.target.selectionStart ?? typed.length);\n pending.current = { typed, digits: (before.match(/\\d/g) ?? []).length };\n onChange?.(typed);\n }}\n onFocus={() => setFocused(true)}\n onBlur={() => setFocused(false)}\n inputMode={inputMode}\n autoComplete={autoComplete}\n autoCapitalize={autoCapitalize}\n {...(prose ? {} : { autoCorrect: 'off', spellCheck: false })}\n enterKeyHint={enterKeyHint}\n // Safari reads this off the DOM attribute; React has no camelCase prop for\n // it, and an unknown lowercase attribute is passed through.\n {...(passwordRules === undefined ? {} : { passwordrules: passwordRules })}\n onKeyDown={(event) => {\n if (event.key !== 'Enter' || onSubmit === undefined) return;\n // The field is inside the island, not inside a form of its own — so Enter\n // has nothing to submit and would do nothing at all.\n event.preventDefault();\n onSubmit();\n }}\n />\n\n {note === undefined ? null : (\n <span className=\"scopetickets-island-field__note\">{note}</span>\n )}\n\n {trailing ?? (flag === undefined ? null : <ContentFlag tone={flag} title={flagTitle} />)}\n </span>\n </span>\n </>\n );\n\n const filled = value.length > 0;\n\n return (\n /*\n * A `<label>`, which is the whole of what the source's Pressable was for: a click\n * anywhere in the card focuses the control it names. It also gives the field its\n * accessible name without an `aria-label` repeating the text that is already on screen.\n */\n <label\n className=\"scopetickets-island-field\"\n htmlFor={inputId}\n // FILLED, not \"has ever been filled\".\n data-filled={filled ? '' : undefined}\n /*\n * THE DESIGN'S OWN `state=\"Focused\"`, and an attribute rather than `:focus-within`\n * in the stylesheet. The two are not equivalent here: the size rule can lean on\n * `:focus-within` because it fires for `[data-filled]` as well and a filled field\n * is the common case, so nobody noticed the focus half never landing. A colour that\n * ONLY changes on focus has no such cover.\n *\n * It is also the half that is testable — a pseudo-class is the browser's business\n * and cannot be asserted, where an attribute the component sets can.\n */\n data-focused={focused ? '' : undefined}\n >\n {body}\n </label>\n );\n}\n","/**\n * THE STEPS THAT COLLECT THE BUYER'S DETAILS — name, email, phone, password.\n *\n * Each holds its own answer and reports whether that answer is valid, so a card can gate\n * its commitment button on it. The predicates are the domain's: a step asks the question\n * and the domain decides what counts as answered.\n */\n\nimport { useEffect, useState, type ReactNode } from 'react';\nimport {\n DEFAULT_COUNTRY_CODE,\n DEFAULT_DIAL_CODE,\n countryByCode,\n countryByDialCode,\n emailFlag,\n emailFlagTitle,\n formatNational,\n isCompleteName,\n isValidEmail,\n isValidPhone,\n phoneFlag,\n routePhoneInput,\n type PhoneField,\n type PhoneValue,\n} from '../domain/contact';\nimport {\n PASSWORD_RULES,\n canSubmitPassword,\n confirmPasswordCounter,\n enterPasswordCounter,\n type PasswordCounter,\n} from '../domain/password';\nimport { TextField } from './TextField';\nimport { CounterRing } from './CounterRing';\nimport { flagTone } from './ContentFlag';\n\n/** How a step tells its card whether its question is answered. */\nexport type AnswerReporting = {\n readonly onAnsweredChange?: (answered: boolean) => void;\n};\n\nexport function useReportAnswered(\n answered: boolean,\n onAnsweredChange: AnswerReporting['onAnsweredChange'],\n): void {\n useEffect(() => {\n onAnsweredChange?.(answered);\n }, [answered, onAnsweredChange]);\n}\n\n/**\n * DEV ONLY. The controls each of the collection steps puts in the card's `Input`\n * region, and the two lists.\n */\n\n/** The domain's fourth state as the component's absence of one. */\n/** The domain's counter as the ring's two props. */\n/** The counter as a ring, or NOTHING while the field is untouched. */\nfunction ringFor(counter: PasswordCounter) {\n if (counter.kind === 'EMPTY') return undefined;\n const props =\n counter.kind === 'COMPLETE'\n ? { progress: 1, complete: counter.flag }\n : { progress: counter.progress };\n return <CounterRing {...props} size={16} />;\n}\n\n/**\n * \"Name\" — the design. Two fields, both required, and the first's return key moves to\n * the second.\n */\n/**\n * Two things the fields did not have, and the phone rows did — which is why only those\n * were being filled.\n */\nexport function StepForm({ children }: { children: ReactNode }) {\n return (\n <form className=\"scopetickets-island-card__fields\" onSubmit={(event) => event.preventDefault()}>\n {children}\n </form>\n );\n}\n\n/**\n * THE NAME AS THE BUYER'S TWO FIELDS — the same shape `BuyerDetails` takes apart, so\n * the widget's collected copy IS the answer and nothing has to be split or joined on the\n * way to the intent.\n */\nexport type NameValue = {\n readonly firstName: string;\n readonly lastName: string;\n};\n\n/**\n * CONTROLLED OR SELF-HELD. The widget passes both props, which is what keeps a typed\n * name when the buyer steps away and back — the card is rebuilt on every step, and an\n * answer held only here did not survive the rebuild. A caller that passes neither gets\n * the step's own memory, which is what the step had before.\n */\nexport function NameStep({\n value,\n onChange,\n onAnsweredChange,\n}: AnswerReporting & {\n readonly value?: NameValue;\n readonly onChange?: (value: NameValue) => void;\n}) {\n const [internal, setInternal] = useState<NameValue>({ firstName: '', lastName: '' });\n const current = value ?? internal;\n const { firstName, lastName } = current;\n const accept = (next: NameValue) => (onChange ? onChange(next) : setInternal(next));\n /*\n * `isCompleteName`, not a hand-rolled emptiness check: `BuyerDetails` takes the two\n * halves apart, so both are required and neither may be whitespace. One of four domain\n * predicates the gate finally spends.\n */\n useReportAnswered(isCompleteName(firstName, lastName), onAnsweredChange);\n\n return (\n <StepForm>\n <TextField\n id=\"contact-given-name\"\n autoFocus\n name=\"given-name\"\n label=\"First Name\"\n value={firstName}\n onChange={(next) => accept({ ...current, firstName: next })}\n autoComplete=\"given-name\"\n autoCapitalize=\"words\"\n /* A name is not prose, and a phone correcting one is a phone guessing. */\n prose={false}\n enterKeyHint=\"next\"\n // The source chains focus with a ref and an imperative handle; on the web the\n // id is enough, and it is one the browser already understands.\n onSubmit={() => document.getElementById('contact-family-name')?.focus()}\n />\n <TextField\n id=\"contact-family-name\"\n name=\"family-name\"\n label=\"Last Name\"\n value={lastName}\n onChange={(next) => accept({ ...current, lastName: next })}\n autoComplete=\"family-name\"\n autoCapitalize=\"words\"\n prose={false}\n enterKeyHint=\"done\"\n />\n </StepForm>\n );\n}\n\n/** \"Email Address\" — the design. CONTROLLED the same way Name is; see there. */\nexport function EmailStep({\n value,\n onChange,\n onAnsweredChange,\n}: AnswerReporting & {\n readonly value?: string;\n readonly onChange?: (email: string) => void;\n}) {\n const [internal, setInternal] = useState('');\n const email = value ?? internal;\n const accept = (next: string) => (onChange ? onChange(next) : setInternal(next));\n /*\n * THE SAME PREDICATE THE FLAG DRAWS. `emailFlag` is `isValidEmail` plus a reading of\n * whether the buyer has typed enough to be told off yet, so gating on the flag would\n * hold Continue shut on an address the field calls good.\n */\n useReportAnswered(isValidEmail(email), onAnsweredChange);\n\n return (\n <StepForm>\n <TextField\n id=\"contact-email\"\n autoFocus\n name=\"email\"\n label=\"Email\"\n value={email}\n onChange={accept}\n type=\"email\"\n inputMode=\"email\"\n autoComplete=\"email\"\n autoCapitalize=\"none\"\n /* An address autocorrected on the way in is an address nobody can be reached at. */\n prose={false}\n enterKeyHint=\"done\"\n flag={flagTone(emailFlag(email))}\n flagTitle={emailFlagTitle(email)}\n />\n </StepForm>\n );\n}\n\n/** \"Phone Number\" — the design, and it is TWO fields. CONTROLLED the same way Name is. */\nexport function PhoneStep({\n value,\n onChange,\n onAnsweredChange,\n}: AnswerReporting & {\n readonly value?: PhoneValue;\n readonly onChange?: (value: PhoneValue) => void;\n}) {\n const [internal, setInternal] = useState<PhoneValue>({\n dialCode: DEFAULT_DIAL_CODE,\n national: '',\n });\n const phone = value ?? internal;\n const { dialCode, national } = phone;\n const country = countryByDialCode(dialCode);\n /*\n * AGAINST THE COUNTRY, which is the whole point of the check: the same digits are a\n * valid number in one plan and not in another. A dial code nobody recognises has no\n * plan to check against, so it cannot be answered.\n */\n useReportAnswered(country !== null && isValidPhone(national, country), onAnsweredChange);\n\n /*\n * One handler for both rows. WHERE a string belongs is `routePhoneInput`'s to decide,\n * not this component's — a browser is free to ignore both autofill tokens and put a\n * whole number, national or international, in either row.\n */\n const accept = (raw: string, field: PhoneField) => {\n const routed = routePhoneInput(raw, field, phone);\n const named = countryByDialCode(routed.dialCode) ?? countryByCode(DEFAULT_COUNTRY_CODE);\n const next = { ...routed, national: formatNational(routed.national, named) };\n if (onChange) onChange(next);\n else setInternal(next);\n };\n\n return (\n <StepForm>\n <TextField\n // Named as well as labelled: a browser's autofill reads `name` and `id`\n // alongside `autocomplete`, and the ids `useId` generates say nothing to it.\n id=\"phone-country-code\"\n name=\"country-code\"\n label=\"Country Code\"\n value={dialCode}\n onChange={(raw) => accept(raw, 'dialCode')}\n type=\"tel\"\n inputMode=\"tel\"\n autoComplete=\"tel-country-code\"\n prose={false}\n // The country the code names, right-aligned beside it — the design.\n note={country?.name}\n />\n <TextField\n id=\"phone-national\"\n autoFocus\n name=\"phone-national\"\n label=\"Phone Number\"\n value={national}\n onChange={(raw) => accept(raw, 'national')}\n type=\"tel\"\n inputMode=\"tel\"\n autoComplete=\"tel-national\"\n prose={false}\n enterKeyHint=\"done\"\n // Read against the country the row above names, and against the default while\n // it names none — a length is still worth checking.\n flag={flagTone(phoneFlag(national, country ?? countryByCode(DEFAULT_COUNTRY_CODE)))}\n />\n </StepForm>\n );\n}\n\n/**\n * \"Add Password\" — the design, whose counting is ported exactly: see\n * `@/domain/password` for why the confirm field's ring measures itself against the\n * FIRST FIELD's current length rather than against the rule.\n */\nexport function PasswordStep({\n revealed,\n accountEmail,\n onAnsweredChange,\n onPasswordChange,\n}: {\n readonly revealed: boolean;\n /**\n * WHOSE PASSWORD THIS IS — the address the account is being made with, for the\n * browser's own save prompt. See the field below.\n */\n readonly accountEmail?: string;\n /**\n * WHERE THE PASSWORD GOES. Reporting only that the step is ANSWERED is all a card\n * needs and not enough to make an account with — `POST /api/Users` wants the value,\n * two steps from here.\n *\n * ONLY WHEN IT IS WHOLE. A half-typed password reported on every keystroke would put a\n * dozen partial copies through the flow to no purpose; this hands over the one that\n * passed `canSubmitPassword`, and an empty string whenever it stops passing.\n */\n readonly onPasswordChange?: (password: string) => void;\n} & AnswerReporting) {\n const [password, setPassword] = useState('');\n const [confirm, setConfirm] = useState('');\n /*\n * BOTH FIELDS, not just the first: `canSubmitPassword` is long enough AND confirmed,\n * which is the rule the second ring counts against.\n */\n const submittable = canSubmitPassword(password, confirm);\n useReportAnswered(submittable, onAnsweredChange);\n\n useEffect(() => {\n onPasswordChange?.(submittable ? password : '');\n }, [submittable, password, onPasswordChange]);\n\n const type = revealed ? 'text' : 'password';\n\n return (\n <StepForm>\n {/*\n * THE USERNAME THE PASSWORD BELONGS TO. A browser offering to save a password reads\n * the account off the FORM, not off the flow: with no `autocomplete=\"username\"`\n * anywhere in it, Chrome's prompt came up with an empty Email field and saved a\n * credential nobody could sign in with.\n *\n * NOT DRAWN, because the card already asked for this address and had it confirmed\n * two steps ago — a second copy of it here is a field the buyer would reasonably try\n * to edit. Out of the layout and out of the accessibility tree, like the photo\n * step's file input, and `readOnly` so nothing can be typed into what is not shown.\n */}\n {accountEmail === undefined ? null : (\n <input\n type=\"text\"\n name=\"username\"\n autoComplete=\"username\"\n value={accountEmail}\n readOnly\n tabIndex={-1}\n aria-hidden=\"true\"\n className=\"scopetickets-island-offscreen\"\n />\n )}\n <TextField\n id=\"new-password\"\n autoFocus\n name=\"new-password\"\n label=\"Enter Password\"\n value={password}\n onChange={setPassword}\n type={type}\n monospace\n autoComplete=\"new-password\"\n /*\n * REVEALED, THIS IS A TEXT INPUT — so a phone would capitalise its first letter\n * and autocorrect the rest of a password the buyer is reading back to check.\n */\n autoCapitalize=\"none\"\n prose={false}\n passwordRules={PASSWORD_RULES}\n enterKeyHint=\"next\"\n onSubmit={() => document.getElementById('confirm-password')?.focus()}\n trailing={ringFor(enterPasswordCounter(password))}\n />\n <TextField\n id=\"confirm-password\"\n name=\"confirm-password\"\n label=\"Confirm Password\"\n value={confirm}\n onChange={setConfirm}\n type={type}\n monospace\n autoComplete=\"new-password\"\n autoCapitalize=\"none\"\n prose={false}\n enterKeyHint=\"done\"\n trailing={ringFor(confirmPasswordCounter(password, confirm))}\n />\n </StepForm>\n );\n}\n\n/**\n * CONFIRM EMAIL — the design.\n *\n * @Zsolt — AUTH SURFACE. The address is PRE-FILLED from the order, because the buyer has\n * already given it: what this card is for is consent, not collection. They are being told\n * which address is about to become their account and given the chance to make it a\n * different one before a code goes to an inbox they cannot read.\n *\n * Editable for exactly that reason, and the same validity rule as the order's own email\n * step — a different rule for the same value would let one card accept what the other\n * rejects.\n */\nexport function ConfirmEmailStep({\n initialEmail,\n onEmailChange,\n onAnsweredChange,\n}: AnswerReporting & {\n readonly initialEmail: string;\n readonly onEmailChange?: (email: string) => void;\n}) {\n /*\n * PRE-FILLED WITH THE ORDER'S OWN ADDRESS. This step shows WHICH address is about to\n * become the account, so it has to be legible as the buyer's own — grey placeholder\n * text is not, and it shipped that way for a day on the argument that a value invites\n * editing what you came to agree to.\n *\n * CLEARING IT STILL ACCEPTS IT: the placeholder is kept for that state and the answer\n * below falls back to the order's address, so an empty field is consent and not a dead\n * end.\n */\n const [typed, setTyped] = useState(initialEmail);\n /* What the step answers with — what they typed, or what they left. */\n const email = typed.trim() === '' ? initialEmail : typed;\n useReportAnswered(isValidEmail(email), onAnsweredChange);\n\n return (\n <StepForm>\n <TextField\n id=\"account-email\"\n autoFocus\n name=\"email\"\n label=\"Email\"\n value={typed}\n placeholder={initialEmail}\n onChange={(next) => {\n setTyped(next);\n onEmailChange?.(next.trim() === '' ? initialEmail : next);\n }}\n type=\"email\"\n inputMode=\"email\"\n autoComplete=\"email\"\n autoCapitalize=\"none\"\n prose={false}\n enterKeyHint=\"done\"\n /* Against the ANSWER, so an untouched field reads as the good address it is. */\n flag={flagTone(emailFlag(email))}\n flagTitle={emailFlagTitle(email)}\n />\n </StepForm>\n );\n}\n","/** The password rules, and what the two fields' counters are counting. */\n\nimport type { ContentFlag } from './contact';\n\n/**\n * Fifteen, not eight: length is the only property that reliably costs an attacker\n * anything, and a long passphrase is easier to type than a short one full of\n * punctuation — which is also why `PASSWORD_RULES` below asks for nothing but length.\n */\nexport const MIN_PASSWORD_LENGTH = 15;\n\n/**\n * What the browser's password manager is told to generate — the web counterpart of the\n * `passwordRules` prop handed to the first field.\n */\nexport const PASSWORD_RULES = `minlength: ${MIN_PASSWORD_LENGTH};`;\n\n/** How full one field's counter ring is, 0..1, and what it becomes when full. */\nexport type PasswordCounter =\n /**\n * NOTHING TYPED, so there is nothing to say and no mark to draw. It was `COUNTING` at\n * zero, which drew an empty ring on a field the buyer had not touched — and on the\n * confirm field a second one from the moment the step opened.\n */\n | { readonly kind: 'EMPTY' }\n /** Still filling. `progress` is 0..1 and never exceeds 1. */\n | { readonly kind: 'COUNTING'; readonly progress: number }\n /** Full, and what that means here — the ring gives way to a mark. */\n | { readonly kind: 'COMPLETE'; readonly flag: Extract<ContentFlag, 'success' | 'error'> };\n\nconst counting = (count: number, target: number): PasswordCounter => ({\n kind: 'COUNTING',\n // `target` of 0 is text typed into the confirm field with nothing above it to copy —\n // nothing to count toward, so the ring sits empty rather than dividing by zero and\n // filling completely.\n progress: target > 0 ? Math.min(count / target, 1) : 0,\n});\n\n/** The ENTER field's counter: it fills toward the minimum and then says so. */\nexport function enterPasswordCounter(password: string): PasswordCounter {\n if (password.length === 0) return { kind: 'EMPTY' };\n if (password.length >= MIN_PASSWORD_LENGTH) return { kind: 'COMPLETE', flag: 'success' };\n return counting(password.length, MIN_PASSWORD_LENGTH);\n}\n\n/**\n * The CONFIRM field's counter, and the target is the thing to notice: it is the first\n * field's CURRENT LENGTH, not the minimum. the source passes\n * `target={password.length}`.\n */\nexport function confirmPasswordCounter(password: string, confirm: string): PasswordCounter {\n /*\n * ITS OWN value, not the one above it: the confirm field is empty when nothing has been\n * copied into it, whatever is waiting to be copied.\n */\n if (confirm.length === 0) return { kind: 'EMPTY' };\n if (password.length === 0 || confirm.length < password.length) {\n return counting(confirm.length, password.length);\n }\n return { kind: 'COMPLETE', flag: confirm === password ? 'success' : 'error' };\n}\n\n/**\n * Whether the pair can be submitted, which is the length rule AND the match, not either\n * alone.\n */\nexport function canSubmitPassword(password: string, confirm: string): boolean {\n return password.length >= MIN_PASSWORD_LENGTH && confirm.length > 0 && confirm === password;\n}\n","import { useEffect, useId, useRef, useState, type ChangeEvent, type KeyboardEvent } from 'react';\nimport {\n normalisePasscode,\n PASSCODE_LENGTH,\n passcodeCaretIndex,\n passcodeComplete,\n} from '../domain/passcode';\n\n/**\n * The six boxes the code is typed into — the design.\n *\n * ONE INPUT BEHIND SIX BOXES, not six inputs. Six would each need their own focus\n * shuffling, their own backspace rule, and would defeat the two things that actually get\n * a code entered: PASTING it from the mail, and `autocomplete=\"one-time-code\"`, which is\n * how a phone offers the code from its own notification. Both hand over the whole string\n * at once, and neither has anywhere to put it if the field is six controls wide.\n *\n * So the boxes are drawn, and the input is a real one stretched invisibly across them.\n * The caret is CSS on whichever box is next; the browser's own is hidden.\n */\nexport type PasscodeFieldProps = {\n readonly value: string;\n readonly onChange: (value: string) => void;\n /** Fired when the last box is filled, and on Enter with a full code. */\n readonly onComplete?: () => void;\n /** The platform said the code was wrong — the boxes say so. */\n readonly invalid?: boolean;\n /**\n * WHAT IS WRONG, IN WORDS. A red border and an `aria-invalid` say that something is,\n * and nothing at all about what — `ContentFlag`'s own note draws the same line: a mark\n * is decorative wherever the field's text already says it, and wrong where the mark is\n * the only thing saying it. A screen reader otherwise announces \"invalid\" and stops.\n */\n readonly message?: string;\n readonly disabled?: boolean;\n /**\n * TAKE FOCUS ON MOUNT — the card has just asked for the code, so this is the moment\n * to be ready for it. Not the `autofocus` ATTRIBUTE, and focused with `preventScroll`,\n * for the reasons `TextField` gives: this widget is a guest on somebody's page.\n */\n readonly autoFocus?: boolean;\n /** Names the group for assistive technology. */\n readonly label: string;\n};\n\nexport function PasscodeField({\n value,\n onChange,\n onComplete,\n invalid = false,\n message,\n disabled = false,\n autoFocus = false,\n label,\n}: PasscodeFieldProps) {\n const inputId = useId();\n const messageId = `${inputId}-message`;\n const inputRef = useRef<HTMLInputElement>(null);\n const code = normalisePasscode(value);\n /*\n * NO CARET ONCE THE CODE IS WHOLE. There is nothing left to type, so a cell still\n * lit reads as a seventh digit being waited for. The field keeps FOCUS — Enter has\n * to reach it — and only stops pointing at anything.\n */\n const complete = passcodeComplete(code);\n const caret = complete ? -1 : passcodeCaretIndex(code);\n\n /* ONCE, ON MOUNT — as `TextField` does, and for the same reasons. */\n useEffect(() => {\n if (!autoFocus) return;\n inputRef.current?.focus({ preventScroll: true });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n const handleChange = (event: ChangeEvent<HTMLInputElement>) => {\n const next = normalisePasscode(event.target.value);\n onChange(next);\n if (next.length === PASSCODE_LENGTH) onComplete?.();\n };\n\n const handleKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {\n if (event.key !== 'Enter') return;\n if (code.length !== PASSCODE_LENGTH) return;\n event.preventDefault();\n onComplete?.();\n };\n\n return (\n <div className=\"scopetickets-island-passcode\">\n <input\n ref={inputRef}\n id={inputId}\n className=\"scopetickets-island-passcode__input\"\n // The whole point of the single input. `one-time-code` is what makes a phone\n // offer the code straight from the notification.\n autoComplete=\"one-time-code\"\n inputMode=\"numeric\"\n // Digits only, so a numeric keypad is what comes up and a stray letter is\n // refused by the field rather than stripped after the fact.\n pattern=\"[0-9]*\"\n type=\"text\"\n maxLength={PASSCODE_LENGTH}\n value={code}\n onChange={handleChange}\n onKeyDown={handleKeyDown}\n disabled={disabled}\n aria-label={label}\n aria-invalid={invalid || undefined}\n aria-describedby={message === undefined ? undefined : messageId}\n />\n {/*\n * PRESENTATION ONLY. The input above carries the value, the label and the\n * validity, so these are hidden rather than announced as six empty things.\n */}\n <div className=\"scopetickets-island-passcode__boxes\" aria-hidden=\"true\">\n {Array.from({ length: PASSCODE_LENGTH }, (_, index) => (\n <span\n key={index}\n className=\"scopetickets-island-passcode__box\"\n data-filled={index < code.length ? '' : undefined}\n // The caret only shows where the field has focus, which `:focus-within`\n // on the group decides — a highlighted box on an unfocused field would\n // claim a caret that is somewhere else entirely.\n data-caret={index === caret ? '' : undefined}\n data-invalid={invalid ? '' : undefined}\n >\n {code[index] ?? ''}\n </span>\n ))}\n </div>\n {/*\n * ANNOUNCED WHEN IT APPEARS. The refusal arrives from a call rather than from\n * anything the buyer just did, so a reader that only speaks on focus would never\n * mention it — `role=\"status\"` is the polite one, which is right for a message the\n * buyer is about to act on rather than an interruption.\n */}\n {message === undefined ? null : (\n <p id={messageId} role=\"status\" className=\"scopetickets-island-passcode__message\">\n {message}\n </p>\n )}\n </div>\n );\n}\n\n/**\n * VERIFY EMAIL's own body — the boxes, and the code the buyer is typing into them.\n *\n * @Zsolt — AUTH SURFACE, and the seam. It owns the CODE and reports when there is a whole\n * one; it does not own the passcode STATE, because that belongs to whatever is making the\n * calls. Hand `state` and `onVerify` in when there is something to call — see\n * `AccountCreationGateway` — and this becomes the live step without changing shape.\n */\n/** What the step says about a code the platform would not take. */\nexport const VERIFY_EMAIL_COPY = {\n /*\n * IT DOES NOT SAY WHICH DIGIT. The platform rejects the CODE, not a position in it —\n * pointing at one would be telling the buyer where to look and being wrong. Nor does it\n * blame them: a code can be stale, or from the mail before last.\n */\n refused: 'That code didn’t work. Check the email and enter it again.',\n} as const;\n\nexport function VerifyEmailStep({\n onAnsweredChange,\n onVerify,\n invalid,\n}: {\n readonly onAnsweredChange?: (answered: boolean) => void;\n readonly onVerify?: (code: string) => void;\n readonly invalid?: boolean;\n}) {\n const [code, setCode] = useState('');\n /*\n * SHOWN UNTIL THE BUYER TOUCHES IT. `invalid` stays true until the next attempt starts,\n * and a refusal still on screen while somebody types their correction is the card\n * arguing with them.\n */\n const [refused, setRefused] = useState(false);\n const complete = passcodeComplete(code);\n\n useEffect(() => {\n onAnsweredChange?.(complete);\n }, [complete, onAnsweredChange]);\n\n /*\n * A REFUSED CODE IS CLEARED. Six wrong digits are six deletes before the buyer can try\n * again, on a keypad, having just been told they got it wrong — and there is nothing in\n * the old code worth keeping, since the platform has already refused it whole.\n */\n useEffect(() => {\n if (invalid !== true) return;\n setCode('');\n setRefused(true);\n }, [invalid]);\n\n return (\n <div className=\"scopetickets-island-card__fields\">\n <PasscodeField\n autoFocus\n label=\"Verification code\"\n value={code}\n onChange={(next) => {\n setRefused(false);\n setCode(next);\n }}\n onComplete={() => onVerify?.(code)}\n invalid={refused}\n message={refused ? VERIFY_EMAIL_COPY.refused : undefined}\n />\n </div>\n );\n}\n","/**\n * WHAT EVERY CARD SAYS, and the badge, buttons and dismiss that go with it.\n *\n * The widget owns its own words. A host defers a step because it does not want to draw\n * one, so it cannot be asked to supply the copy for the step it just handed over.\n */\n\nimport type { ReactNode } from 'react';\nimport {\n AsteriskIcon,\n BellIcon,\n CalloutWithHeartIcon,\n CameraIcon,\n CloudWithArrowUpInIcon,\n KeyholeInSquareIcon,\n PasskeyIcon,\n PlusInCircleIcon,\n PaperPlaneToTopLeftIcon,\n PaymentCardIcon,\n PercentInStickerIcon,\n PhoneToRightIcon,\n TextCursorWithRectangleIcon,\n TextCursorWithRedactedTextIcon,\n} from '@scopetickets/icons';\nimport { ScopeTicketsWordmarkMark } from './brand-marks';\nimport { statusMark } from './status-glyphs';\nimport { AUTH_COPY } from '../domain/auth-copy';\nimport { MAX_PHOTO_BYTES, type PhotoRefusalCode } from '../domain/profile-photo';\nimport {\n noticeLeadRole,\n type Notice,\n type NoticeAction,\n type NoticeSeverity,\n} from '../domain/notices';\nimport type { AuthCardId } from '../domain/auth';\nimport {\n funnelCredentials,\n funnelPasswordVisible,\n funnelSubmittable,\n type AuthFunnel,\n} from '../domain/auth-funnel';\nimport type { Credentials } from '../domain/sign-in';\nimport { CredentialFields } from './CredentialFields';\nimport type { IconProps } from '@scopetickets/icons';\nimport type { AvatarAccessory } from '@scopetickets/avatar';\n\n/*\n * THE CIRCLE ARM, NAMED. `AvatarAccessory` is discriminated on `shape` and only two of\n * its three arms carry `content`, so a caller handed the whole union cannot read one\n * without narrowing first. A status badge is always circular — its ground is round, and a\n * square notch would clip it — so saying so in the type spares every caller that check.\n */\ntype CircleAccessory = Extract<AvatarAccessory, { shape: 'circle' }>;\nimport type { PurchaseStepId } from '../domain/purchase-steps';\nimport {\n STATUSES,\n STATUS_TONES,\n statusToneVars,\n type StatusName,\n type StatusTone,\n} from '@scopetickets/icons/status';\nimport type { IslandAction } from './IslandCard';\nimport { payButtonRole } from './PaymentMethods';\nimport { holdRemaining, type EscrowHold } from './island-escrow';\nimport { CountdownTimer } from './CountdownTimer';\n\ntype StepBadge = { readonly shape: 'square' | 'circle'; readonly content: ReactNode };\n\nconst STEP_BADGES: Partial<Record<PurchaseStepId, StepBadge>> = {\n /* More Information's ASTERISK — the design. */\n /*\n * ROUND, not square. The two question badges and the passkey sit in a square notch;\n * this one and Create Account's plus do not.\n */\n /*\n * ROUND, not square — the two question badges and the passkey sit in a square notch;\n * this one and Create Account's plus do not.\n */\n DETAILS: { shape: 'circle', content: <AsteriskIcon fill spin appearance=\"metal\" /> },\n /*\n * Metal is an SVG FILTER whose canvas is 28x28 for a 20x20 glyph, and it normally hangs\n * outside the layout box. A SQUARE badge slot CLIPS — by design; a badge clipped to a\n * rounded square is what a badge IS, and `AvatarImageElement-Square` carries\n * `overflow-clip` in the node too — so at `$25` the svg came out 70x70 in a 50x50 slot\n * and ten pixels a side were cut. Invisible on a mark that stops short of its own box;\n * on `TextCursorWithRedactedText`, whose cursor reaches the edge, it severed the mark.\n * Reported as the icon clipping rather than filling its frame.\n */\n NAME: {\n shape: 'square',\n content: <TextCursorWithRectangleIcon fill appearance=\"metal\" />,\n },\n EMAIL: {\n shape: 'square',\n content: <PaperPlaneToTopLeftIcon fill appearance=\"metal\" />,\n },\n PASSWORD: {\n shape: 'square',\n content: <TextCursorWithRedactedTextIcon fill appearance=\"metal\" />,\n },\n /* the design — a handset, in the square notch like the other questions. */\n PHONE: { shape: 'square', content: <PhoneToRightIcon fill appearance=\"metal\" /> },\n /*\n * A CAMERA OVER THE FACE BEING CHOSEN — the design, in the square notch. The badge says\n * what the hero beneath it is FOR on this card: the avatar is not reporting who is\n * signed in, it is wearing what has just been picked.\n */\n PROFILE_PHOTO: { shape: 'square', content: <CameraIcon fill appearance=\"metal\" /> },\n FOLLOW: { shape: 'square', content: <BellIcon fill appearance=\"metal\" /> },\n /*\n * A HEART IN A CALLOUT — the design's badge on this card, in the square notch the other\n * marks here sit in. It says what the hero underneath is for: the avatar is not\n * reporting who is signed in, it is being asked a question.\n */\n FEEDBACK: { shape: 'square', content: <CalloutWithHeartIcon fill appearance=\"metal\" /> },\n /*\n * NO `CREATE_ACCOUNT` ENTRY, AND THAT IS THE POINT. Its badge is on its CARD —\n * `AUTH_CARDS.ADD_TO_ACCOUNT`, which is the authority for everything the design draws —\n * and the gallery's rule that a card's own badge wins over the step's is what fetches\n * it. Listing it here as well would be the second copy this record's own header warns\n * about.\n */\n /*\n * the design’s badge is a card mark on a BLUE FILLED rounded square, which is an\n * accessory treatment nothing else in this flow uses — every other badge is a bare\n * metal glyph. The glyph is drawn; the blue field is not, because no token in the\n * export we have says what that fill is. Raised in.\n */\n PAYMENT: { shape: 'square', content: <PaymentCardIcon fill appearance=\"metal\" /> },\n /*\n * ROUND, like Details and Create Account's plus — the sticker is a mark rather than a\n * picture, and the square slot is for the ones that read as pictures in a frame.\n *\n * It also keeps the sticker off the clip the note above describes: a square slot cuts\n * the metal filter's canvas at the badge's own edge, and this glyph reaches its.\n */\n PROMO: { shape: 'circle', content: <PercentInStickerIcon fill appearance=\"metal\" /> },\n /*\n * THE SAME MARK THE EMAIL STEP WEARS. The buyer is looking at their address again, and\n * a second glyph for the same subject would suggest a different one.\n */\n CONFIRM_EMAIL: {\n shape: 'square',\n content: <PaperPlaneToTopLeftIcon fill appearance=\"metal\" />,\n },\n /*\n * @Zsolt — AUTH SURFACE. `3735:45219` — the SQUARE notch, and the set's own passkey\n * mark, which is the one `SIGN_IN_RECOGNISED` already draws on \"Use Passkey\". A\n * keyhole shipped here first and is a different idea: a keyhole is a lock, and a\n * passkey is the thing that opens one without a key.\n */\n PASSKEY: { shape: 'square', content: <PasskeyIcon fill appearance=\"metal\" /> },\n /*\n * NO `PAYMENT_SUCCESS` ENTRY ANY MORE. It drew a bare metal check in the circular\n * notch, and the design now gives it the same status tag the failure wears — a green\n * wash under a ring, not a glyph on the ground. So it moves to `STEP_STATUS`, which is\n * the only thing that can build one, and an entry here would be unreachable anyway:\n * a status wins over a step badge where a step declares both.\n */\n};\n\n/**\n * THE STATUS BADGE — the `Element=StatusIcon` variant, as the step that wears it.\n *\n * A NAME AND NOT A NODE, unlike `STEP_BADGES`, because a status badge cannot be built\n * here. Its ring is a PADDING — a length, `$1` at `$10` and `$2` at `$25` — so the badge\n * has to be made at the size it will be drawn at, and this file does not know that. The\n * widget builds it; see `statusAccessory`.\n *\n * ONLY PROCESSING SO FAR, and deliberately. The steps after it carry badges the design\n * gave them — Follow's bell, Create Account's plus — and a status would be a second badge\n * arguing with the first. Adding one elsewhere is a line here.\n */\nexport const STEP_STATUS: Partial<Record<PurchaseStepId, StatusName>> = {\n /*\n * The warning tone's exclamation — `Disputed` is the set's word for it. The system\n * worked and something needs deciding, which is exactly what this card is: nothing has\n * gone wrong, and the buyer is about to give up something they hold.\n */\n ABANDON: 'Disputed',\n /* Drawn as `Pending`, which is this status's own word for itself. */\n PROCESSING: 'Processing',\n /*\n * The `error` tone, which is the red ring the design draws. It does not turn — nothing\n * is still happening; see `statusAccessory`.\n */\n PAYMENT_FAILED: 'Failed',\n /*\n * `AvatarImageElement-Circle` — the success tone's green wash and its check, which is\n * what this card wears now in place of the bare metal glyph it used to.\n *\n * `Paid` AND NOT A NAME OF THIS FLOW'S OWN: it is the platform's word for the state the\n * order is actually in, and taking the status package's own tone and glyph is what\n * keeps this card in step with every other place the same state is drawn.\n *\n * It reverses the note above about these two cards differing in kind — they no longer\n * do. Both report a state the order is in; one of those states is simply the good one.\n */\n PAYMENT_SUCCESS: 'Paid',\n};\n\n/**\n * THE RING IS `$1` AT `$10` AND `$2` AT `$25` — the reference file's own two values, and\n * the reason a status badge is built at the size it is drawn at rather than declared as a\n * node in `step-cards`.\n *\n * IT IS A LENGTH AND NOT A PROPORTION, which is what makes the two necessary: the glyph is\n * the remainder, the box minus twice the ring, so a badge built for one slot and dropped\n * into the other draws a ring of the wrong weight. The avatar's circular slot is 48 at\n * `$25` and 20 at `$10`, which is exactly the pair the status tag documents itself\n * against.\n *\n * `@scopetickets/icons` standardises on `$1` everywhere and says why — the file's `$10`\n * case states `$1` across and `$2` down on a 20 box, which cannot both hold. These are\n * the file's values, passed explicitly through the override the package provides for it.\n */\nexport const STATUS_RING = { 25: 8, 10: 4 } as const;\n\n/**\n * THE BADGE'S OWN GLYPH, where the status's is not the one the design draws.\n *\n * EMPTY AGAIN. It held `PAYMENT_SUCCESS`, whose mark the design drew inside a ring whereas\n * `Paid` is a bare tick — and that override is gone because the design has moved the whole\n * composition: success, warning and failure are now solid marks chosen by TONE rather than\n * glyphs chosen by step. See `STATUS_MARK`.\n *\n * Kept rather than deleted because the seam is the point — a status whose glyph the design\n * overrides is a thing that will happen again, and it still outranks the tone's mark, which\n * is right: an override is a GLYPH, so it goes back in the ring and the wash with the rest\n * of them.\n */\nconst STEP_STATUS_GLYPH: Partial<Record<PurchaseStepId, (props: IconProps) => JSX.Element>> = {};\n\n/** The tone's two colours, as the status package spends them — its own vars, its own fallbacks. */\nfunction toneColours(tone: StatusTone) {\n const vars = statusToneVars(tone);\n return {\n background: `var(${vars.background}, ${STATUS_TONES.dark[tone].background})`,\n foreground: `var(${vars.foreground}, ${STATUS_TONES.dark[tone].foreground})`,\n };\n}\n\n/**\n * The status badge for a step, or `null`. Circular and UNCROPPED, which is what the round\n * ground needs — a square notch would clip it to a rounded rectangle.\n *\n * ── WHY THE RING IS DRAWN HERE RATHER THAN BY `StatusTag` ────────────────────\n *\n * The tag renders its own glyph and takes neither a substitute nor a `spin`, and this\n * card needs both: a different mark, and that mark turning. Drawing the ring is fifteen\n * lines — a tone, a padding and a circle — against reaching past the tag's API from the\n * stylesheet, which is what the first version did.\n *\n * NOTHING ABOUT THE STATUS IS RESTATED. The glyph, the label and the tone still come from\n * `STATUSES`, so a status renamed or recoloured upstream still arrives here; what is local\n * is only the ring it sits in.\n */\nexport function statusAccessory(step: PurchaseStepId, size: 25 | 10): CircleAccessory | null {\n const status = STEP_STATUS[step];\n if (status === undefined) return null;\n return statusBadge(status, size, STEP_STATUS_GLYPH[step]);\n}\n\n/**\n * THE SAME BADGE FROM A STATUS RATHER THAN FROM A STEP, because a notice has a severity\n * and no step — see `NOTICE_STATUS`. The step lookup above is the only other way in, and\n * both build the one badge.\n */\nexport function statusBadge(\n status: StatusName,\n size: 25 | 10,\n override?: (props: IconProps) => JSX.Element,\n): CircleAccessory {\n const spec = STATUSES[status];\n const tone = toneColours(spec.tone);\n /*\n * THE MARK THAT IS THE WHOLE BADGE, OR NOTHING — and its PRESENCE is the composition.\n *\n * `statusMark` carries the design's three solid marks: a disc filling the slot in the\n * tone's own colour with the symbol knocked out of it. A badge drawing one needs no wash\n * behind it and no ring around it — it IS the disc — so the same lookup that picks the\n * artwork decides the ground and the inset, and the two cannot be set to disagree.\n *\n * An OVERRIDE outranks it and goes back to the wash: see `STEP_STATUS_GLYPH`.\n */\n const mark = override === undefined ? statusMark(spec.tone) : undefined;\n const Glyph = override ?? mark ?? spec.icon;\n\n return {\n shape: 'circle',\n content: (\n <span\n role=\"img\"\n aria-label={spec.label}\n style={{\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n flex: 'none',\n boxSizing: 'border-box',\n width: '100%',\n height: '100%',\n padding: mark === undefined ? STATUS_RING[size] : 0,\n borderRadius: '50%',\n /*\n * A SOLID MARK SITS ON NOTHING, and the hole in it is how the card shows through\n * — which is the design's own drawing. A wash behind it would fill that hole with\n * a pale version of the same colour and the mark would all but vanish.\n */\n background: mark === undefined ? tone.background : 'transparent',\n }}\n >\n {/*\n * THE MARK TURNS, NOT THE BADGE. The icon set is explicit that a rotation belongs on\n * the glyph: put one on the slot and the badge swings around the avatar instead of\n * spinning where it sits.\n *\n * ── WHY NOT `spin` ──────────────────────────────────────────────────────\n *\n * `spin` turns a GROUP INSIDE THE VIEWBOX, and an SVG clips to its viewBox — so it\n * is safe exactly for a glyph drawn INSIDE the circle its box contains, and the icon\n * set's own spinning mark is authored that way: the asterisk reaches 10.3 against an\n * inscribed radius of 10, which is control points overshooting a curve and nothing\n * more. Its own spin is fine and always was.\n *\n * These are not that. `ArrowsCircling` reaches 15.1 and the design's slow mark 21.5\n * against 16, so turning either inside its viewBox sweeps the extremities out of the\n * box and cuts them off — which is what happened here, on a glyph that was also the\n * wrong one. Turning the SVG ELEMENT instead rotates a CSS box, which clips to\n * nothing, and is right whatever the glyph. The class lands on the svg.\n *\n * BY TONE AND NOT BY NAME. What turns is a status still HAPPENING, which is what\n * `processing` means; a settled one would be a badge fidgeting about nothing.\n */}\n <Glyph\n fill\n color={tone.foreground}\n className={spec.tone === 'processing' ? 'scopetickets-island-status-turning' : undefined}\n />\n </span>\n ),\n /* Named so a change of status crosses rather than cuts — see `AvatarAccessory.id`. */\n id: `status:${status}`,\n };\n}\n\n/** The same badges, each NAMED by the step that owns it. */\nexport const STEP_ACCESSORY = Object.fromEntries(\n Object.entries(STEP_BADGES).map(([step, badge]) => [step, { ...badge, id: `step:${step}` }]),\n) as Partial<Record<PurchaseStepId, StepBadge & { readonly id: string }>>;\n\n/**\n * THE SUBTITLE THAT THANKS SOMEBODY, or thanks nobody in particular.\n *\n * The design writes \"Thank you, Alex!\" over \"Your order has been placed.\" A GUEST HAS NO\n * NAME TO USE — they took the route that declines to give one — so the first line drops\n * to \"Thank you!\" rather than addressing an empty space. The second line never changes:\n * it is the fact, and the fact is the same either way.\n */\nexport function paymentSuccessSubtitle(firstName: string | null): string {\n const thanks = firstName === null ? 'Thank you!' : `Thank you, ${firstName}!`;\n return `${thanks}\\nYour order has been placed.`;\n}\n\n/**\n * WELCOME, BY NAME — the design `3781:7383`, whose title is \"Welcome, Alex!\". An account\n * cannot be made without the name the order carries, so the nameless reading should be\n * unreachable; it is kept for the reason the payment's is.\n */\nexport function accountCreatedTitle(firstName: string | null): string {\n return firstName === null ? 'Welcome!' : `Welcome, ${firstName}!`;\n}\n\n/**\n * WHAT A STOPPED CLOCK SAYS — see `timedOutViewProps` for the card it draws.\n *\n * The words stand where the countdown would: a card whose title is `00:00` says the number\n * and not what it means. \"They may still be available\" is the design's own hedge and is\n * the honest one — the tickets went back to the pool, and whether anybody has taken them\n * since is not something this widget knows.\n */\nexport const HOLD_VIEW = {\n title: 'Your Order Timed Out',\n subtitle: 'Your tickets have been released. They may still be available.',\n tryAgain: 'Try Again',\n close: 'Close',\n} as const;\n\n/**\n * Steps whose header button CLOSES rather than steps back, against the gallery's own\n * rule that only the first step has nothing behind it.\n */\n/**\n * THE STEPS A BUYER MAY NOT LEAVE — the payment, and everything between it and their\n * booking.\n *\n * ── WHY THESE AND NOT THE WHOLE FLOW ────────────────────────────────────────\n *\n * Before the payment, leaving costs the buyer nothing they cannot get back: the order is\n * released and they may start again. From the moment the money moves it is no longer a\n * purchase they are in the middle of, it is a purchase they have MADE — and every card\n * after it is either telling them so or offering something on top. A cross on any of them\n * would offer to leave a thing that has already happened.\n *\n * THE DECLINE IS NOT IN THE SET, deliberately. `PAYMENT_FAILED` means the money did NOT\n * move: the order is still pending, the hold is still running, and a buyer whose card was\n * refused must be able to give up rather than be held on a card they cannot answer.\n *\n * `PROCESSING` is here as well as `sealed`, which is the stronger statement — no header\n * AND the host's page held. The two agree; this one is the set that says why.\n */\nexport const UNCLOSABLE_STEPS: ReadonlySet<PurchaseStepId> = new Set<PurchaseStepId>([\n 'PROCESSING',\n 'PAYMENT_SUCCESS',\n 'FEEDBACK',\n 'CREATE_ACCOUNT',\n 'CONFIRM_EMAIL',\n 'VERIFY_EMAIL',\n 'PASSWORD',\n 'PROFILE_PHOTO',\n 'ACCOUNT_CREATING',\n 'ACCOUNT_CREATED',\n 'PASSKEY',\n 'FOLLOW',\n]);\n\n/**\n * Steps whose header button CLOSES rather than steps back, against the gallery's own\n * rule that only the first step has nothing behind it.\n */\nexport const STEP_DISMISS: Partial<Record<PurchaseStepId, 'back' | 'close'>> = {\n SIGN_IN: 'close',\n /*\n * NOTHING BEHIND AN OFFER. The order is placed by the time either of these is on\n * screen, so there is no step to go back to — and the older stack draws both with\n * `headerAction={{ kind: 'CLOSE' }}` for exactly that reason.\n */\n CREATE_ACCOUNT: 'close',\n FOLLOW: 'close',\n /*\n * The order is placed and the card behind this one was the acknowledgement of it — so\n * there is nothing to go back TO, exactly as on the two offers above.\n */\n FEEDBACK: 'close',\n /* The design draws a cross: the account is made and the card behind this was a wait. */\n ACCOUNT_CREATED: 'close',\n /*\n * BACK, NOT CLOSE — the design draws an arrow. There IS somewhere behind this one: the\n * address it sent the code to, which is the thing a buyer who mistyped it needs to get\n * at. Every other card in this chunk closes because the offer it belongs to has nothing\n * behind it; this one is mid-sub-flow.\n */\n VERIFY_EMAIL: 'back',\n};\n\n/**\n * A NOTICE AS THE PROPS THAT DRAW IT — one card, from data, standing in front of the flow.\n *\n * NOT A STEP IN THE WALK, deliberately: a notice is not something a buyer set out to do,\n * it has no cost, and putting one in `PURCHASE_STEPS` would make it part of the flow's own\n * sequence — which is the screen-per-failure the notices doctrine forbids. It stands in\n * front, like the cart's screen and the timed-out card, and the walk underneath is\n * untouched.\n *\n * THE SEVERITY PAINTS THE LEAD, so the button cannot disagree with the badge above it —\n * see `noticeLeadRole`. Everything else is the notice's own words.\n */\nexport function noticeViewProps(notice: Notice, press: (action: NoticeAction) => () => void) {\n const close = notice.actions.find((action) => action.id === 'CLOSE') ?? notice.actions[0];\n return {\n expanded: true,\n /* A card with no header is left by its own Close, which every notice carries. */\n onToggle: close === undefined ? () => {} : press(close),\n title: notice.title,\n subtitle: notice.subtitle,\n actionLabel: 'Open',\n actions: notice.actions.map((action) => ({\n /* The ID is the key: two buttons on one notice are never the same action. */\n key: action.id,\n role: action.kind === 'CONFIRM' ? noticeLeadRole(notice.severity) : ('secondary' as const),\n label: action.label,\n onPress: press(action),\n })),\n };\n}\n\n/** THE SIGN-IN FUNNEL'S WORDS — the card `SIGN_IN_WITH` and `ENTER_PASSWORD` both open. */\nexport const FUNNEL_COPY = {\n title: 'Sign In',\n subtitle: 'Enter your email and password.',\n /*\n * IT NAMES NEITHER FIELD. Saying which of the two was wrong answers \"does this address\n * have an account?\" for anybody who asks, so the pair is refused together.\n */\n refused: 'That email and password did not match. Please try again.',\n working: 'Checking your details…',\n} as const;\n\n/**\n * THE FUNNEL AS A CARD — a builder and not a component, like `noticeViewProps` beside it:\n * both islands own their own hero and surface, so what is shared is the CONTENT.\n */\nexport function funnelViewProps(\n funnel: AuthFunnel,\n handlers: {\n readonly onChange: (change: Partial<Credentials>) => void;\n readonly onSubmit: () => void;\n readonly onClose: () => void;\n },\n) {\n const credentials = funnelCredentials(funnel) ?? { email: '', password: '' };\n const working = funnel.status === 'SUBMITTING';\n return {\n expanded: true,\n /* The way out is the header's, and it is a BACK: a card stands behind this one. */\n dismiss: 'back' as const,\n onToggle: handlers.onClose,\n title: FUNNEL_COPY.title,\n subtitle:\n funnel.status === 'REFUSED'\n ? FUNNEL_COPY.refused\n : working\n ? FUNNEL_COPY.working\n : FUNNEL_COPY.subtitle,\n actionLabel: AUTH_COPY.SIGN_IN,\n input: (\n <CredentialFields\n email={credentials.email}\n password={credentials.password}\n onEmailChange={(email) => handlers.onChange({ email })}\n onPasswordChange={(password) => handlers.onChange({ password })}\n passwordVisible={funnelPasswordVisible(funnel)}\n onSubmit={handlers.onSubmit}\n />\n ),\n /*\n * ONE BUTTON. `FORGOT_PASSWORD` belongs here in the design and is not drawn yet:\n * `POST /api/Users/PasswordReset` exists and the card that would receive the buyer\n * afterwards does not.\n */\n actions: [\n {\n key: 'funnel-submit',\n role: 'primary' as const,\n label: AUTH_COPY.SIGN_IN,\n disabled: !funnelSubmittable(funnel),\n onPress: handlers.onSubmit,\n },\n ],\n };\n}\n\n/**\n * THE BADGE A NOTICE WEARS — the status set's own, so its tone and its glyph agree with\n * the severity that chose them. `Disputed` is the set's warning-toned exclamation: the\n * system worked and something needs adjusting.\n */\nexport const NOTICE_STATUS: Readonly<Record<NoticeSeverity, StatusName>> = {\n WARNING: 'Disputed',\n FAILURE: 'Failed',\n};\n\n/**\n * THE CART'S OWN SCREEN — the design `3791:7839`, reached from the header's summary pill.\n *\n * IT IS THE HOLD'S SCREEN TOO, and that is the merge: `3803:7120` was a bare countdown\n * behind the header's escrow half and this was a statement of account behind its cart\n * half, each answering half of what a buyer pressing either was asking — what am I\n * holding, and for how long.\n *\n * IT STILL LIVES BESIDE THE FLOW: nothing in the walk leads to it, the order is not\n * changed by opening it, and the way out is the one button on it. What it says is a\n * statement of account, which is why its title is the SUBJECT — \"My Cart\" — rather than a\n * question, and is set a step larger than every other card's.\n */\n/**\n * THE PROMO STEP'S OWN WORDS — the header's way in, and the card it opens.\n *\n * \"Maximum one per Order\" is the wire's own rule said out loud: a cart carries ONE\n * `PromoCode` string, so applying a second replaces the first rather than stacking.\n */\nexport const PROMO_COPY = {\n /** The trailing half of the commit pill. */\n open: 'Promo Code',\n title: 'Promo Code',\n subtitle: 'Maximum one per Order.',\n field: 'Promo Code',\n apply: 'Apply',\n remove: 'Remove',\n /** What the card says once a code is on the order. `saved` is already written money. */\n saved: (saved: string) => `${saved} Saved`,\n /** The mark on an accepted field, for anyone who cannot see it. */\n accepted: 'Accepted',\n} as const;\n\nexport const CART_VIEW = {\n title: 'My Cart',\n total: 'Total',\n back: 'Back',\n /**\n * The cart target's own name. It is a GLYPH now — the total that used to sit beside it\n * is the Pay card's title — so this is the only thing that says what pressing it opens.\n */\n label: (total: string) => `Your cart, ${total}`,\n /**\n * WHAT THE TOTAL ABOVE IT INCLUDES — one sentence, true whether or not a clock is\n * running, which is why neither cart screen chooses between two lines any more.\n *\n * IT REPLACED THE COUNTDOWN, which moved to the card the buyer pays from: the cart\n * screen is where somebody checks what they are buying, and the clock belongs where\n * they decide to pay for it. This is the only place that argument is made.\n */\n subtitle: 'Includes all taxes and service fees.',\n /**\n * THE HOLD, IN WORDS — `3793:8723`. Drawn on the PAY card, over the hero's own ring:\n * the card says the clock twice, and both are readings of one `EscrowHold`.\n *\n * See `CART_VIEW.subtitle` for why it is no longer said here.\n */\n remaining: (clock: string) => `You have ${clock} to complete your purchase.`,\n} as const;\n\n/**\n * THE SAME SCREEN, WITH NOTHING BOUGHT YET — the island at rest on a cart the host is\n * still filling.\n *\n * ONE CARD AND NOT TWO. What is in the cart is what is in the cart, so the rows, the\n * column and the total are the ones above; this differs in the two places a resting cart\n * genuinely differs. Its subtitle does not count a clock down unless there is one, and its\n * buttons go FORWARD — the screen beside the flow is left by going back to the flow, and\n * there is no flow yet to go back to.\n *\n * \"CHECK OUT\" IS THE PACKAGE'S OWN WORD FOR THIS DOOR. `PURCHASE_STEPS` puts it on the\n * pill a buyer meets the moment their tickets are in hand, and for the same reasons: it\n * overstates nothing (guest checkout is behind it) and it does not promise a purchase on\n * an event that is free.\n */\n/**\n * WHAT THE WIDGET IS FOR, said once — the opening pill's word, and the first card's\n * button. It is not a step's name: a buyer who has pressed nothing yet is being asked\n * whether they want tickets at all, and every step name answers a question they have not\n * been asked.\n */\nexport const OPENING_LABEL = 'Get Tickets';\n\nexport const RESTING_CART = {\n /*\n * NO SUBTITLE OF ITS OWN ANY MORE. It chose between two lines on a fact that has\n * nothing to do with what a cart contains; both screens now draw `CART_VIEW.subtitle`.\n */\n checkOut: 'Check Out',\n /*\n * CLOSING IS COLLAPSING, exactly as it is on the timed-out card: `onToggle` puts the\n * island back to its pill, and the cart is still there behind it. Not \"Continue\n * Shopping\" — this widget does not own the page it sits on and cannot promise there is\n * anything to go back to.\n */\n close: 'Close',\n /** While the checks behind Check Out are running — see `runCheckoutPreflight`. */\n checking: 'Checking…',\n} as const;\n\n/**\n * The resting cart as the props that draw it. The hero is the caller's, as it is for every\n * other card here.\n *\n * THE HOLD IS STILL TAKEN THOUGH IT NO LONGER PICKS THE SUBTITLE, because the hero's ring\n * is still drawn from it.\n */\nexport function restingCartViewProps(\n input: ReactNode,\n hold: EscrowHold | undefined,\n onCheckOut: () => void,\n onClose: () => void,\n /** Whether the checks are running, which shuts the button and says so. */\n checking: boolean,\n) {\n return {\n variant: 'cart' as const,\n title: CART_VIEW.title,\n subtitle: CART_VIEW.subtitle,\n input,\n actions: [\n {\n key: 'cart-check-out',\n role: 'primary' as const,\n label: checking ? RESTING_CART.checking : RESTING_CART.checkOut,\n disabled: checking,\n onPress: onCheckOut,\n },\n {\n key: 'cart-close',\n role: 'secondary' as const,\n label: RESTING_CART.close,\n onPress: onClose,\n },\n ],\n };\n}\n\n/**\n * The cart screen as the PROPS that turn a card into it — the hero and its badge are the\n * caller's, because the avatar is the buyer's and this file draws none.\n */\nexport function cartViewProps(input: ReactNode, hold: EscrowHold, onBack: () => void) {\n return {\n variant: 'cart' as const,\n expanded: true,\n onToggle: onBack,\n title: CART_VIEW.title,\n subtitle: CART_VIEW.subtitle,\n actionLabel: 'Open',\n input,\n actions: [\n { key: 'cart-back', role: 'secondary' as const, label: CART_VIEW.back, onPress: onBack },\n ],\n };\n}\n\n/**\n * THE CLOCK AS THE HERO'S ELEMENT — the badge both cards that know about the hold wear:\n * the cart screen `3791:7839`, and the timed-out card `3803:7329` it becomes.\n *\n * IT USED TO BE THE WHOLE HERO — a bare `$25` ring where the avatar goes. As an accessory\n * it is the composition every other card here uses: a subject, and a mark saying what is\n * being asked of it.\n *\n * `solid`, NOT `metal`. Metal is a 19-primitive SVG filter and the avatar pops an accessory\n * in by SCALING it; a filter cannot survive that, so the ring pixelated and stuttered on the\n * way in. Metal remains reviewable at `?timer`.\n *\n * DECORATIVE, because the words beneath say the countdown exactly.\n */\nexport function holdBadge(hold: EscrowHold): CircleAccessory {\n return {\n shape: 'circle',\n content: <CountdownTimer remaining={holdRemaining(hold)} appearance=\"solid\" size=\"100%\" />,\n id: 'view:hold',\n };\n}\n\n/**\n * THE CLOCK STOPPED — the design `3803:7329`, and the card the whole island gives itself\n * over to once a hold has run out.\n *\n * ── TWO ANSWERS, AND THEY ARE THE TWO THINGS LEFT TO DO ─────────────────────\n *\n * The news has been read; what remains is whether the buyer wants these tickets or not.\n * TRY AGAIN is re-entry — the walk returns to its first stop and the island stays OPEN, so\n * they carry straight on. CLOSE is leaving — the same reset, collapsed.\n *\n * NEITHER MINTS A CART HERE, which is what kept Try Again off this card before. It hands\n * the buyer back to the flow, and the flow opens a cart when it reaches a step that needs\n * one — so the card that says the tickets went in the meantime is the step that knows,\n * exactly as it was when Close was the only way through.\n *\n * WHAT THEY ANSWERED SURVIVES either way: they said two adults for Saturday and gave their\n * email, and none of that stopped being true when the clock did. It is the CART that is\n * new, because the old one is gone.\n *\n * A HOST'S OWN EXPIRED HOLD IS NOT OURS TO RENEW, and Try Again cannot pretend otherwise:\n * `restart` throws away the cart THIS widget opened, so where the hold came from a prop it\n * is still expired and this card comes back. That is the truth about their reservation\n * rather than a state we are stuck in — see `useAssertedHold`.\n */\nexport function timedOutViewProps(expanded: boolean, onTryAgain: () => void, onClose: () => void) {\n return {\n variant: 'hold' as const,\n expanded,\n onToggle: onClose,\n /* Never drawn — the pill belongs to the flow now. Kept because the prop is required. */\n actionLabel: HOLD_VIEW.close,\n title: HOLD_VIEW.title,\n subtitle: HOLD_VIEW.subtitle,\n actions: [\n /* ActionBlue and it leads: buying the tickets again is what this card is FOR. */\n {\n key: 'hold-retry',\n role: 'action' as const,\n label: HOLD_VIEW.tryAgain,\n onPress: onTryAgain,\n },\n {\n key: 'hold-close',\n role: 'secondary' as const,\n label: HOLD_VIEW.close,\n onPress: onClose,\n },\n ],\n };\n}\n\n/**\n * Which steps wear the PICKER LAYOUT — the standard header pinned over a scrolling run,\n * and no hero.\n */\n/** Which steps wear the PICKER LAYOUT — no hero, so the card opens on the run. */\nexport const PICKER_LAYOUT: Partial<Record<PurchaseStepId, boolean>> = {\n DATE: true,\n TIME: true,\n};\n\n// ── Sign In ─────────────────────────────────────────────────\n\n/**\n * A card's button as this file describes one — the role and the words, plus whatever\n * mark the design puts beside them. `onPress` is the gallery's, since a fixture has\n * nowhere to send anybody.\n */\nexport type CardAction = Pick<IslandAction, 'role' | 'mark'> & {\n /**\n * A `ReactNode` because the pay button composes a brand mark into its own words — \"Pay\n * with [mark] • 1123\", as the design draws it.\n */\n readonly label: ReactNode;\n /** What the button DOES, for the few that do anything. */\n readonly onPress?: () => void;\n /**\n * THE DETOUR THIS BUTTON OPENS — the other half of `PurchaseStep.detourFrom`, which\n * says which card a step hangs off but not what opens it.\n *\n * Declared rather than handled, because this file is data and has no state to set. A\n * button without it falls through to advancing the flow, and on the last card that\n * means committing: \"Select Payment Method\" was placing the order.\n */\n readonly opens?: PurchaseStepId;\n /**\n * THIS BUTTON ATTEMPTS THE PAYMENT AGAIN. Declared rather than handled, like `opens` —\n * what a retry DOES depends on who reported the failure, and this file knows neither.\n */\n readonly retries?: boolean;\n /**\n * SHUT, whatever the step's own answer says. The primary is gated on the step being\n * answered; this is for a button that is unavailable for a reason of its own — Re-send\n * serving its cooldown, and nothing else so far.\n */\n readonly disabled?: boolean;\n /**\n * THIS BUTTON CHOOSES THE ACCOUNT ROUTE — the offer's Create Account, and the only\n * thing that opens the sub-flow behind it.\n *\n * Declared rather than handled, like `opens` and `retries`: what it costs is the walk's\n * question, and this file is data with no state to set. Without it the widget walks\n * `GUEST` at every checkpoint, `makingAccount` never becomes true, and the five steps\n * after the offer are skipped — which is what happens today.\n */\n readonly takesAccount?: boolean;\n /**\n * THIS BUTTON CHARGES. Declared rather than handled, like `opens` and `retries`: what\n * paying DOES depends on whether there is a platform behind the widget, and this file\n * knows neither that nor who the buyer is.\n */\n readonly pays?: boolean;\n /**\n * THIS BUTTON CHOOSES A PAYMENT METHOD — Review's method buttons. Declared rather\n * than handled, like `opens`: which frame the choice mounts, and what the buyer\n * save has to do with it, is the widget's to decide, and this file is data with no\n * state to set.\n *\n * `'wallet'` IS THE DEVICE'S ONE WALLET, not a method of its own: this file cannot\n * know whether that is Apple Pay or Google Pay — the widget's device sniff decides\n * at runtime, and relabels the button to match. See `detect-digital-wallet`.\n */\n readonly picks?: 'card' | 'revolut_pay' | 'wallet';\n /**\n * THIS BUTTON OPENS THE DEVICE'S FILE DIALOG — the photo step's Upload. Declared rather\n * than handled for the reason the rest are: the input it opens belongs to the grid on\n * the card, and this file draws no controls.\n */\n readonly uploads?: boolean;\n /**\n * THIS BUTTON SENDS THE RATING — the feedback card's Continue, and the only thing that\n * does. Declared rather than handled, like `pays`: the number is on the card and the\n * call is the data layer's, and this file has neither.\n *\n * WITHOUT IT THE PRESS WOULD STILL ADVANCE, which is exactly the fall-through\n * `pressFor` exists to stop — a Continue that moves the buyer on and quietly drops what\n * they just said. The Skip beside it has no flag for that reason: dropping the rating\n * IS what Skip does.\n */\n readonly rates?: boolean;\n};\n\n/** THE FIVE AUTH CARDS — every card the three checkpoints draw between them. */\nexport type AuthCard = {\n readonly copy: { readonly title: string; readonly subtitle: string };\n readonly actions: readonly CardAction[];\n /**\n * The badge on the hero, and the hole it sits in — or absent where the design hides it.\n * See `DevAvatar.accessory` for why the shape travels with the node.\n */\n readonly accessory?: {\n readonly shape: 'square' | 'circle';\n readonly content: ReactNode;\n /**\n * Names this badge for the avatar's own transition — see `STEP_ACCESSORY`, and\n * `AvatarAccessory.id` in the package.\n */\n readonly id: string;\n };\n /* THERE IS NO `cartSummary` FLAG, AND THERE WAS. */\n};\n\n/** \"Sign in with\" + the Scope Tickets WORDMARK. */\nconst SIGN_IN_WITH_WORDMARK: CardAction = {\n role: 'primary',\n label: AUTH_COPY.SIGN_IN_WITH,\n mark: {\n side: 'trailing',\n spacing: 'joined',\n node: <ScopeTicketsWordmarkMark height={12} title=\"Scope Tickets\" />,\n },\n};\n\n/** The keyhole badge both returning-buyer cards wear. */\nconst KEYHOLE_BADGE = {\n shape: 'square',\n content: <KeyholeInSquareIcon fill appearance=\"metal\" />,\n /*\n * NAMED, like every step badge — it is square, and so are six others. See\n * `STEP_ACCESSORY` for what the name is for.\n */\n id: 'card:keyhole',\n} as const;\n\n/**\n * The unrecognised cards' subtitle — and it DELIBERATELY DIVERGES FROM THE NODE, which\n * says \"Sign in below.\"\n */\nconst MAY_QUALIFY = 'You may qualify for better pricing.';\n\nexport const AUTH_CARDS: Record<AuthCardId, AuthCard> = {\n /* 1.1 Idle-Unrecognised — the design `Login-Idle-Unrecognised`. */\n SIGN_IN_UNRECOGNISED: {\n copy: { title: 'Already Have An Account?', subtitle: MAY_QUALIFY },\n /*\n * NO CREATE ACCOUNT. It offered a route that no longer exists here: an account is\n * made AFTER paying now, out of an order that already carries everything one needs,\n * and the sub-flow that does it hangs off `ADD_TO_ACCOUNT`. Offering it before the\n * order would either be a second way in that goes nowhere, or a demand for details\n * the buyer is about to type anyway.\n *\n * The card's own question is unchanged and answers itself: this is for people who\n * ALREADY have an account.\n */\n actions: [SIGN_IN_WITH_WORDMARK],\n /*\n * NO ACCESSORY: `element=\"Hidden\"`. The hero is the guest placeholder and nothing else\n * — badges it with the Scope Tickets glyph, and the node no longer does.\n */\n },\n /* 2.1 OrderCreated-Unrecognised — the design. */\n SIGN_IN_UNRECOGNISED_GUEST: {\n copy: { title: 'Already Have An Account?', subtitle: MAY_QUALIFY },\n actions: [\n SIGN_IN_WITH_WORDMARK,\n /*\n * A UI-COMPLETE STUB, as it was before: there is no guest-checkout flow to send it to.\n * What blocks it is P11 — the order requirements a guest would have to satisfy, which\n * the platform exposes no way to ask for.\n */\n { role: 'secondary', label: AUTH_COPY.CONTINUE_AS_GUEST },\n ],\n },\n /*\n * 1.2 AND 2.2 — the design `Login-Idle-Recognised`, drawn at BOTH checkpoints. Its\n * variant name says Idle, which is now only half true.\n */\n SIGN_IN_RECOGNISED: {\n copy: { title: 'Welcome Back!', subtitle: 'Please sign in to continue.' },\n actions: [\n {\n role: 'primary',\n label: AUTH_COPY.USE_PASSKEY,\n /*\n * the design, a 16px `RightIcon`. `currentColor`, so it inverts with the button it sits\n * on exactly as the header's glyphs do. SEPARATE spacing, not joined: the label says\n * the whole thing on its own and the glyph accompanies it.\n */\n mark: { side: 'trailing', node: <PasskeyIcon size={16} color=\"currentColor\" /> },\n },\n { role: 'secondary', label: AUTH_COPY.ENTER_PASSWORD },\n { role: 'secondary', label: AUTH_COPY.SIGN_OUT },\n ],\n accessory: KEYHOLE_BADGE,\n },\n /* 1.3 Idle-Authenticated — the design `Login-Idle-SignedIn`. */\n ACCOUNT_READY: {\n copy: { title: 'Welcome Back!', subtitle: 'You’re ready to go.' },\n actions: [{ role: 'secondary', label: AUTH_COPY.SIGN_OUT }],\n accessory: KEYHOLE_BADGE,\n },\n /* 3.1 OrderSuccess-Unrecognised — the design `SignupPrompt`. */\n ADD_TO_ACCOUNT: {\n copy: {\n title: 'Add to Account',\n subtitle: 'Enjoy faster checkout and access to discounts.',\n },\n actions: [\n { role: 'primary', label: AUTH_COPY.CREATE_ACCOUNT, takesAccount: true },\n { role: 'secondary', label: AUTH_COPY.SIGN_IN },\n /*\n * NOTHING IS LOST BY DECLINING. The order is placed and the tickets are theirs; this is\n * an offer, not a gate.\n */\n { role: 'secondary', label: AUTH_COPY.SKIP },\n ],\n /*\n * the design draws a plus in a CIRCLE over the hero — round, where the two question\n * badges and the passkey sit in a square notch. Not a guess: there is only one\n * plus-in-a-circle in the set that is an outline.\n */\n accessory: {\n shape: 'circle',\n content: <PlusInCircleIcon fill appearance=\"metal\" />,\n id: 'card:account-plus',\n },\n },\n};\n\n/**\n * WHAT THE PRESS THAT CREATES THE ORDER SAYS, in place of the \"Continue\" the card would\n * otherwise carry. Which card that is belongs to the walk and not to this table — see\n * `pressCreatesOrder` — so the label is held here and written over the primary at render,\n * the way the pay button is rebuilt from the chosen method.\n */\nexport const CREATE_ORDER_LABEL = 'Place Order';\n\n/**\n * WHAT THE PASSKEY CARD'S PRIMARY SAYS — named here beside the card's own stack, and read\n * from there by the thing that actually draws it. The button is an iframe on a Scope\n * origin, because only a document under the RP id may make a credential, so the words\n * have to cross a document boundary to be painted. They stay declared in one place.\n */\nexport const PASSKEY_BUTTON_LABEL = 'Add Passkey';\n\n/**\n * WHAT THE HEADER'S COMPOSE STEPS ARE, TAKEN TOGETHER — the group's name, and the only\n * copy the funnel needs: each mark inside it is named by its own step (`PurchaseStep.name`),\n * so this says what the row of them IS rather than repeating them.\n */\nexport const COMPOSE_FUNNEL_LABEL = 'Your ticket selection';\n\n/** The card's own buttons per step, with the roles the source gives them. */\nexport const STEP_CARD_ACTIONS: Record<PurchaseStepId, readonly CardAction[]> = {\n // Disabled in the source while nobody is coming, since nothing downstream can be\n // priced for a party of none.\n PARTY: [{ role: 'primary', label: 'Continue' }],\n /*\n * THE ORDERCREATED-UNRECOGNISED CARD, which is what this step shows when nothing is\n * known about the buyer.\n */\n SIGN_IN: AUTH_CARDS.SIGN_IN_UNRECOGNISED_GUEST.actions,\n NAME: [{ role: 'primary', label: 'Continue' }],\n EMAIL: [{ role: 'primary', label: 'Continue' }],\n PHONE: [{ role: 'primary', label: 'Continue' }],\n DATE: [{ role: 'primary', label: 'Continue' }],\n TIME: [{ role: 'primary', label: 'Continue' }],\n DETAILS: [{ role: 'primary', label: 'Continue' }],\n // ONE BUTTON.\n /*\n * THE CARD FORM'S OWN BUTTON, AND IT CHARGES. This card was a list with a Confirm on it,\n * which meant choosing a method and paying were two presses on two cards. The list is\n * gone — the buyer arrived here by pressing \"Pay with Card\", so the method is already\n * answered and what is left to do is the money. The widget writes the quote's own\n * headline over this; what stands is the reading with no quote to state.\n */\n /*\n * THE CARD SCREEN — the field, the press that charges, and the way back.\n *\n * This step was `Select Payment Method`, a list of SAVED methods over a single live\n * row. There are no saved methods; what the buyer needs here is the field and a button\n * under it. `Pay Now` is an ACTION and not a primary for the reason every other\n * money press is: it commits, and a primary is what Enter reaches.\n *\n * `Back` carries no handler of its own and needs none — an action on a detour closes\n * the detour, which returns the buyer to the wallets they stepped past.\n */\n PAYMENT: [\n { role: payButtonRole('CARD'), pays: true, label: 'Pay Now' },\n { role: 'secondary', label: 'Back' },\n ],\n /*\n * ONE BUTTON, AND WHAT IT SAYS DEPENDS ON WHETHER A CODE IS ON THE ORDER — Apply, or\n * Remove. Built at the call site for that reason; this is the shape it falls back to.\n */\n PROMO: [{ role: 'primary', label: PROMO_COPY.apply }],\n /*\n * CONFIRM LEADS AND IT IS THE DESTRUCTIVE ONE, which is the design's own order. The\n * buyer arrived here by pressing the way out, so the thing they asked for is the thing\n * on top; Return to Order is the correction.\n */\n ABANDON: [\n { role: 'primary', label: 'Confirm' },\n { role: 'secondary', label: 'Return to Order' },\n ],\n /*\n * THE SAME METHOD OFFERED AGAIN, and a way to a different one — the design. The retry\n * is an ACTION and not a primary for the reason Review's Pay button is: it commits\n * money, and a primary is what Enter reaches.\n */\n PAYMENT_FAILED: [\n {\n role: payButtonRole('CARD'),\n retries: true,\n /* The words are the widget's — there is no card on file to name. See the note above. */\n label: 'Try Again',\n },\n ],\n /* One button, and it is a primary: nothing is being committed, only acknowledged. */\n PAYMENT_SUCCESS: [{ role: 'primary', label: 'Continue' }],\n /*\n * CONTINUE SENDS AND SKIP DOES NOT, which is the whole difference between them — both\n * go to the same next card, as the Follow prompt's one button does. Skip is not\n * decoration: a buyer who does not want to rate has no other way past, because Continue\n * is shut until a star is chosen and the header's cross closes the island rather than\n * advancing it.\n *\n * `rates` IS DECLARED HERE AND HANDLED BY THE WIDGET, like `pays` and `takesAccount`:\n * this file is data and holds no rating to send.\n */\n FEEDBACK: [\n { role: 'primary', rates: true, label: 'Continue' },\n { role: 'secondary', label: 'Skip' },\n ],\n /* The same card in the other half of the flow, and the same one button. */\n ACCOUNT_CREATED: [{ role: 'primary', label: 'Continue' }],\n /*\n * THE WAYS TO PAY, AS BUTTONS AND NOT AS A LIST — `CtaCard`'s `Pay-NoSaved` variant.\n * There is nothing saved to offer, so there is nothing to pick FROM: each method is its\n * own press, and the card the buyer lands on after the order is made is the card they\n * pay from.\n *\n * REVOLUT PAY IS LIVE: the frame behind it is the payment host's own, and the provider\n * button it mounts IS the entry — so the press here only CHOOSES the method (and saves\n * the buyer, which gates the entry); the frame appears in the bay beneath, and the\n * charge is pressed on the provider's own button inside it. THE WALLET IS THE SAME\n * SHAPE: its frame prewarms with the rest, the payment host asks the device whether\n * the wallet can pay, and the button stays shut until the answer is yes — gating the\n * widget applies, because availability is the device's to grant, not this file's.\n *\n * 'Apple Pay' IS THE FIXTURE'S LABEL, not the device's answer: the widget relabels the\n * row for the wallet the device actually offers, from its own sniff corrected by the\n * host's `canMakePayment()` word — see `wallet-report`.\n *\n * THEIR WORDS STAND IN FOR THEIR MARKS. Both are somebody else's trademark, and this\n * package is published: see the manifest note in `brand-marks`, which takes two marks\n * as its stated exception and says a third is the signal to revisit rather than extend.\n * The marks arrive with the integration, from the provider's own SDK, which is what\n * their brand rules ask for anyway.\n */\n /*\n * ONE BUTTON, AND IT IS THE CARD FIELD'S.\n *\n * This card used to name three METHODS and commit to none of them: Apple Pay and\n * Revolut Pay picked a method, \"Pay with Card\" opened a list, and the money was\n * pressed a card later. The list was `Select Payment Method`, which is a SAVED-methods\n * surface — there are no saved methods, so it was a chooser over one live option and a\n * door to the only field that takes a number.\n *\n * The three providers are now on this card as themselves: the wallet's own button, the\n * Revolut button and the card field are each a live frame in the bay, drawn by the\n * provider that honours them. A button here that said \"Apple Pay\" would be a second,\n * fake copy of one already on screen.\n *\n * WHAT IS LEFT IS THE ONE PRESS NO PROVIDER DRAWS FOR US. A typed card has no button\n * of its own inside the frame — the host submits the field when the parent asks — so\n * the charge for that one method is pressed here, beneath the field, and the wallets\n * keep their own.\n */\n /*\n * THE WALLETS DRAW THEMSELVES; THE CARD IS A DOOR.\n *\n * The two provider entries on this card are live frames — the device's wallet and\n * Revolut Pay, each painted and pressed inside the document that honours it — so this\n * card states no button for either. A third that said \"Apple Pay\" would be a fake copy\n * of one already on screen.\n *\n * Typing a card is the one method with no provider button to offer, and it needs room\n * the other two do not: a field, and a press that commits. That is a SCREEN, not a row\n * — see `PAYMENT`, which hangs off this card as a detour. Secondary, because the\n * wallets above it are the faster path and the design leads with them.\n */\n REVIEW: [{ role: 'secondary', label: 'Pay with Card', opens: 'PAYMENT', picks: 'card' }],\n // None.\n PROCESSING: [],\n /* Nothing to press, for the reason Processing has nothing to press. */\n /*\n * THE `ORDER_SUCCESS` CHECKPOINT'S CARD, and this step is where it is drawn.\n * Referenced, not re-typed — the node gained a `SIGN_IN` button between the two that\n * used to be here, and a second copy would still be showing two.\n */\n CREATE_ACCOUNT: AUTH_CARDS.ADD_TO_ACCOUNT.actions,\n /* the design — one button under the pre-filled address. */\n CONFIRM_EMAIL: [{ role: 'primary', label: 'Confirm' }],\n /*\n * TWO, AND THE SECOND COUNTS ITSELF DOWN. Re-send carries the cooldown in its own\n * label — \"Re-send (30s)\" — because a disabled button that does not say why reads as\n * broken. The seconds are filled in by the card; see `resendRemainingSeconds`.\n */\n VERIFY_EMAIL: [\n { role: 'primary', label: 'Verify' },\n { role: 'secondary', label: 'Re-send' },\n ],\n /*\n * @Zsolt — AUTH SURFACE. `3735:45233` and `3735:45235`, in the node's own words. Skip\n * is not optional furniture: a device with no authenticator, or a buyer who does not\n * want one, still has to reach the password step, and this is the only way past.\n */\n PASSKEY: [\n { role: 'primary', label: PASSKEY_BUTTON_LABEL },\n { role: 'secondary', label: AUTH_COPY.SKIP },\n ],\n /* Nothing to press while it is happening. */\n ACCOUNT_CREATING: [],\n /*\n * \"Show Entered Text\" belongs HERE per the design, and is rendered in the input region\n * instead — see `PasswordStepSample` for why, and for what moves it back.\n */\n PASSWORD: [{ role: 'primary', label: 'Continue' }],\n /*\n * CONTINUE, AND A WAY TO BRING YOUR OWN — the design, in that order. Upload is a\n * SECONDARY and not a second primary: the grid is the answer this card asks for, and a\n * device's file dialog is the long way round it.\n */\n PROFILE_PHOTO: [\n { role: 'primary', label: 'Continue' },\n {\n role: 'secondary',\n label: 'Upload',\n uploads: true,\n mark: { side: 'leading', node: <CloudWithArrowUpInIcon size={14} color=\"currentColor\" /> },\n },\n ],\n /*\n * ONE BUTTON, and its label follows the selection: with nothing ticked there is nothing\n * to confirm, so it reads as skipping ahead. Either way it goes to the same place. the\n * older stack says \"Continue to Tickets\"/\"Skip to Tickets\"; the design says \"Continue\n * to Ticket\", singular, and the node wins. The fixture shows the selected reading — the\n * sample starts with one ticked.\n */\n FOLLOW: [{ role: 'primary', label: 'Continue to Ticket' }],\n};\n\n/**\n * THE CREDIT UNDER THE MONEY, on the card the buyer pays from — `CtaCard`'s own.\n *\n * IT WAS TAKEN OFF BOTH PAYMENT CARDS ONCE, as a credit rather than something a buyer\n * needs while deciding to pay, and because the wordmark was already on the button beneath\n * it. That second reason is gone: the buttons name METHODS now — Apple Pay, Revolut Pay,\n * the card — so without this line nothing on the card says whose checkout it is.\n *\n * THE MARK IS NOT ANNOUNCED. \"Powered by\" and the wordmark are one phrase, and a title on\n * the mark would have assistive technology read the name twice.\n */\nexport const POWERED_BY: ReactNode = (\n <span className=\"scopetickets-island-credit\">\n Powered by\n <ScopeTicketsWordmarkMark height={12} />\n </span>\n);\n\n/** The hero copy per step, quoted. */\nexport const STEP_CARD_COPY: Record<PurchaseStepId, { title: string; subtitle: string }> = {\n PARTY: { title: 'Party Size', subtitle: 'Let us know who’s coming.' },\n SIGN_IN: AUTH_CARDS.SIGN_IN_UNRECOGNISED_GUEST.copy,\n NAME: { title: 'Name', subtitle: 'What should we call you?' },\n /*\n * the design titles this \"Email Address\" and labels the field \"Email\"; the older stack\n * titles it \"Primary Email Address\" and labels the field \"Email Address\". The node wins\n * on both — it is the newer of the two — and the subtitle is the one thing they agree\n * on.\n */\n EMAIL: { title: 'Email Address', subtitle: 'How should we contact you?' },\n /* No node for this step, so both lines are carried over unchanged. */\n /*\n * the design exists after all — it was found on the second pass. Its own subtitle is\n * \"Gis your digits\", replaced with the line the email step already uses. The node is\n * placeholder copy here, not the authority it is for the layout.\n */\n /*\n * Title from the design. THE SUBTITLE DELIBERATELY DIVERGES FROM THE NODE, which says\n * \"Gis your digits\". Recorded here so the next pass against the design does not\n * \"correct\" it back.\n */\n PHONE: { title: 'Phone Number', subtitle: 'How should we contact you?' },\n // NEITHER TITLE IS DRAWN ON THE CARD, and since the splash was deleted nothing on the\n // card says them either.\n DATE: { title: 'Select Day', subtitle: '' },\n TIME: { title: 'Select Time', subtitle: '' },\n DETAILS: {\n title: 'We Need Some Information',\n subtitle: 'Before we can place your order, we need some details.',\n },\n /*\n * THE METHOD SURFACE, BACK TO BEING ONE — the rows are Card and Revolut Pay, and\n * the card form expands in the bay beneath the row once Card is the chosen one.\n * Review's own copy on the powered-by line is why this says what it asks for.\n */\n PAYMENT: {\n /* The card's own name for itself, and the same words as the button that opened it. */\n title: 'Pay with Card',\n /*\n * THE WIDGET WRITES THE HOLD HERE, exactly as it does on Review — the same purchase,\n * the same clock, and two cards that are meant to be one shape. What stands here is\n * the no-hold reading, which is the same thing this table holds for every card whose\n * subtitle is written over.\n */\n subtitle: '',\n },\n /*\n * NO MONEY THE CARD CANNOT VOUCH FOR. The widget writes the quote's own headline\n * over this title. What stands here is the no-quote reading: the step's own name.\n * The fee line is gone because the wire carries one total and no breakdown.\n */\n REVIEW: {\n title: 'Review Order',\n subtitle: '',\n },\n PROMO: { title: PROMO_COPY.title, subtitle: PROMO_COPY.subtitle },\n ABANDON: {\n title: 'Are You Sure?',\n subtitle: 'Your tickets will be released for others to buy.',\n },\n PROCESSING: {\n title: 'Payment Processing',\n subtitle: 'This may take a moment.\\nYour bank may ask you to approve the payment.',\n },\n /*\n * IT NAMES THE BANK, which is the whole difference from Processing. That card says the\n * payment is moving; this one says what it is waiting ON — which is the only new\n * information a buyer has gained by waiting, and the reason to change the card at all\n * rather than leave them watching a badge turn.\n */\n /*\n * THE SUBTITLE IS THE PROVIDER'S OWN WORDS. The design writes `ReasonCode` there — a\n * slot rather than a sentence — so what stands here is what a card with no reason to\n * hand can honestly say, and the widget replaces it with the real one.\n */\n PAYMENT_FAILED: {\n title: 'Payment Failed',\n subtitle: 'Your payment could not be completed.',\n },\n /* The guest reading. `paymentSuccessSubtitle` writes the one with a name in it. */\n PAYMENT_SUCCESS: {\n title: 'Payment Successful',\n subtitle: 'Thank you!\\nYour order has been placed.',\n },\n /*\n * BOTH LINES ARE THE NODE'S, and the subtitle was left alone deliberately. An\n * instruction — \"Choose a star to rate your experience\" — was the obvious content pass,\n * since five dots are a quieter affordance than five outlined stars would be. It was not\n * taken: the card's whole ask is optional, and a line that tells somebody how to operate\n * a control is a line that asserts they ought to. \"We’d love your feedback\" asks, which\n * is what this card is doing.\n */\n FEEDBACK: { title: 'How Was Your Purchase?', subtitle: 'We’d love your feedback.' },\n CREATE_ACCOUNT: AUTH_CARDS.ADD_TO_ACCOUNT.copy,\n /*\n * \"This will be your account email\" is doing the work: the address came off the order,\n * and the buyer is being told what it is about to BECOME rather than asked for it\n * again. The second line is a promise about the next card, which is what stops the\n * code's arrival being a surprise.\n */\n CONFIRM_EMAIL: {\n title: 'Confirm Email',\n subtitle: 'This will be your account email.\\nWe will verify with a code.',\n },\n VERIFY_EMAIL: {\n title: 'Verify Email',\n subtitle: 'Please check your email for a code from us.',\n },\n /* @Zsolt — AUTH SURFACE. `3735:45220`, both lines. */\n PASSKEY: { title: 'Create a Passkey', subtitle: 'For faster login.' },\n PASSWORD: { title: 'Add Password', subtitle: 'Secure your account.' },\n PROFILE_PHOTO: { title: 'Profile Photo', subtitle: 'Select an avatar or upload your own.' },\n /*\n * PRESENT TENSE, AND NO PROMISE. The card is up while the call is out, so it says what\n * is happening rather than what will have happened — see `ACCOUNT_CREATING_FLOOR_MS`\n * for why it is up for a moment even when the call is quick.\n */\n ACCOUNT_CREATING: {\n title: 'Creating Account',\n subtitle: 'This will only take a moment.',\n },\n /*\n * THE NAME IS THE POINT, so the title is written rather than declared —\n * `accountCreatedTitle` does it, as `paymentSuccessSubtitle` does for the other\n * acknowledgement. What stands here is what a card with no name to use can say.\n */\n ACCOUNT_CREATED: { title: 'Welcome!', subtitle: 'Your account has been made.' },\n FOLLOW: { title: 'Stay Up to Date', subtitle: 'Subscribe to the people behind this event.' },\n};\n\n/**\n * THE PHOTO GRID'S OWN WORDS — the group, its cells and the two refusals.\n *\n * A STOCK PHOTO HAS NO NAME. The platform stocks faces, not people, so a cell is named by\n * where it sits — which is the only thing that tells one from another out loud, and is\n * what a buyer counting across a grid would say themselves.\n */\nexport const PROFILE_PHOTO_COPY = {\n group: 'Profile photo',\n photo: (position: number) => `Avatar ${position}`,\n /** The cell an upload makes, which is the one face here that IS somebody's. */\n uploaded: 'Your photo',\n /*\n * THE SIZE IS READ FROM THE RULE rather than typed out beside it: a limit that moves\n * and a sentence that does not is how a card ends up refusing files it would accept.\n */\n refusal: {\n NOT_AN_IMAGE: 'That file is not a photo.',\n TOO_LARGE: `That photo is too big. Please choose one under ${MAX_PHOTO_BYTES / 1024 / 1024}MB.`,\n } satisfies Record<PhotoRefusalCode, string>,\n} as const;\n\n/**\n * THE RATING GROUP'S NAME, said once and only out loud.\n *\n * The card's title is a question — \"How Was Your Purchase?\" — and a question is not a\n * label: a radio group named after it would be announced as a heading that expects an\n * answer in prose. This says what the control IS, and the options say what they are\n * worth; see `ratingLabel`.\n */\nexport const FEEDBACK_COPY = { group: 'Your rating' } as const;\n\n/** THE SIGN-IN FUNNEL'S CREDENTIAL CARD — the design. */\nexport const SIGN_IN_FUNNEL_CARD = {\n copy: {\n /*\n * A ROW, NOT TWO INLINE THINGS. The design is a flex row — `items-center\n * justify-center`, `gap: $2`, with the words `whitespace-nowrap` and the mark at\n * 117.778 x 20 beside them.\n */\n title: (\n <span className=\"scopetickets-island-funnel-title\">\n <span>Sign In to</span>\n <ScopeTicketsWordmarkMark height={20} title=\"Scope Tickets\" />\n </span>\n ),\n subtitle: 'Sign in below.',\n },\n /** the design primary, the design secondary. */\n actions: [\n { role: 'primary', label: AUTH_COPY.SIGN_IN },\n { role: 'secondary', label: AUTH_COPY.FORGOT_PASSWORD },\n ] as readonly CardAction[],\n /*\n * The hero is the guest placeholder at 100px — the design with\n * `avatarContent=\"PlaceholderPerson\"`, and NO BADGE: `element=\"Hidden\"` on the node.\n * Nobody is recognised yet, which is the whole reason this card is asking.\n */\n accessory: undefined,\n /*\n * `showCartSummary` is true on the design here — there IS an order and the hold is\n * still running, unlike the design.\n */\n} as const;\n","/**\n * THE TWO BRAND MARKS THIS WIDGET DRAWS — the Scope Tickets wordmark, and Mastercard.\n *\n * ── WHY SVG PATHS LIVE HERE, AGAINST THE RULE ────────────────────────────────\n *\n * Artwork belongs in `@scopetickets/icons`, and non-icon SVG does not get hand-written\n * into a component. These two are the stated exception, and the reason is the MANIFEST\n * rather than the drawing: they used to come from `@scopetickets/brands`, which is\n * `private: true` and was reached through a tarball in `vendor/`. A published package can\n * depend on neither. `@scopetickets/checkout` is published — see\n * `.github/workflows/release-checkout.yml` — so every consumer would have installed a\n * manifest naming a local path that does not exist on their machine.\n *\n * The alternative was publishing the brands package, which means hosting other people's\n * trademarks on npm under our name. Two marks is a smaller thing to own than that.\n *\n * SO THE RULE STANDS AND THIS IS ITS EDGE: two marks, both fixed geometry, neither one an\n * icon. Anything that IS an icon still comes from the icon set, and a third mark arriving\n * here is the signal to revisit this decision rather than to extend it.\n *\n * ── NOT `IconGlyph`, EITHER ──────────────────────────────────────────────────\n *\n * The icon set is glyphs that are each 1:1 on a 20x20 grid, and every affordance it has\n * assumes that: `size` sets both dimensions, and metal's bleed is stated as a fraction of\n * a 20-unit box. The wordmark is 5.89:1. It would be squashed, or every one of those\n * assumptions would have to be relaxed for a case they were not written for.\n *\n * There is NO METAL here, deliberately: metal is a treatment we apply to our OWN glyphs,\n * and applying it to somebody else's trademark is the kind of alteration a brand\n * guideline forbids.\n */\n\nimport type { CSSProperties } from 'react';\n\n/**\n * One filled outline of a mark. `evenodd` where the source carries it.\n *\n * ── `opacity` IS THE ARTWORK'S, NEVER THE COLOUR'S ───────────────────────────\n *\n * Figma exports these with the fill token's own alpha written onto every path twice, as\n * `opacity` AND `fill-opacity`. That is the COLOUR, and it is dropped: these paint\n * `currentColor`, so the consumer's token already carries its alpha and re-applying it\n * would give 0.81 where the design asks for 0.9.\n *\n * What survives is a per-path opacity that VARIES across a mark, because a variation\n * cannot be the one fill colour — it is composition. Mastercard is the whole reason this\n * field exists: its two circles and their intersection are 0.75, 0.28 and 0.52 of the\n * same text colour, which is what makes the interlock read in both appearances.\n * Flattened to one alpha it is a blob.\n */\ntype BrandPath = {\n readonly d: string;\n readonly evenodd?: true;\n readonly opacity?: number;\n};\n\nexport type BrandMarkProps = {\n /**\n * Rendered HEIGHT, in px. The width follows from the artwork's own ratio, because that\n * ratio is not ours to choose.\n *\n * HEIGHT AND NOT SIZE, which is the whole difference from an icon. A glyph is 1:1 and\n * `size` means both dimensions; a wordmark is 5.89:1, and every place one appears it is\n * set against a line of type — the sign-in button draws the wordmark 12 tall beside a\n * 20px line. So height is the dimension a caller actually holds.\n */\n readonly height?: number;\n /**\n * FILL THE PARENT instead of sizing itself, letting that box own the size. The box still\n * has to carry the mark's own aspect ratio; nothing here will stretch it, because a\n * stretched logo is a misused logo.\n */\n readonly fill?: boolean;\n /**\n * The paint. Defaults to `currentColor`, which is what the design asks for: the sign-in\n * button's wordmark binds `ButtonPrimaryText`, so it inverts with the scheme by\n * following the label beside it rather than by being told twice.\n */\n readonly color?: string;\n /**\n * An accessible name. Omit for a mark that sits beside text already saying the same\n * thing, which is then hidden from assistive technology rather than announced as an\n * unlabelled graphic.\n */\n readonly title?: string;\n readonly className?: string;\n readonly style?: CSSProperties;\n};\n\ntype Props = BrandMarkProps & {\n /** The mark's name, stamped as `data-scopetickets-brand`. */\n readonly mark: string;\n /**\n * The artwork's own box — its viewBox, and not a caller's decision.\n *\n * ONE OBJECT, and the reason is a bug this had: it was `width` and `height` alongside\n * the caller's own `height`, and a mark spreads the caller's props before setting the\n * artwork's. So the artwork's 100 overwrote the caller's 12 and every wordmark rendered\n * at its full height. Two things called `height` that mean different things cannot both\n * be flat props.\n */\n readonly artwork: { readonly width: number; readonly height: number };\n readonly paths: readonly BrandPath[];\n};\n\n/** The mark renderer — one filled outline set, at the artwork's own ratio. */\nfunction BrandMark({\n mark,\n artwork,\n paths,\n height,\n fill = false,\n color = 'currentColor',\n title,\n className,\n style,\n}: Props) {\n const a11y = title\n ? { role: 'img', 'aria-label': title }\n : { 'aria-hidden': true, focusable: false };\n /*\n * BOTH DIMENSIONS, STATED. The height was set and the width left to `aspect-ratio` to\n * resolve — which is one inference too many for a mark that is 5.89:1 and sits in a flex\n * row next to a label. A row that comes out too wide is clipped by the surface's own\n * rounded clip, and what a reader sees is the wordmark cut off at its right edge.\n *\n * `maxWidth` for the case the arithmetic cannot fix: in a box genuinely narrower than\n * the mark, it gives up its size rather than its containing row.\n */\n const drawn = height ?? artwork.height;\n const box = fill\n ? { width: '100%', height: '100%' }\n : { height: drawn, width: (drawn * artwork.width) / artwork.height, maxWidth: '100%' };\n\n return (\n <svg\n {...a11y}\n data-scopetickets-brand={mark}\n className={className}\n viewBox={`0 0 ${artwork.width} ${artwork.height}`}\n style={{\n display: 'block',\n aspectRatio: `${artwork.width} / ${artwork.height}`,\n flex: 'none',\n ...box,\n ...style,\n }}\n >\n {paths.map((path, i) => (\n <path\n key={i}\n d={path.d}\n fill={color}\n {...(path.opacity === undefined ? null : { opacity: path.opacity })}\n {...(path.evenodd ? { fillRule: 'evenodd', clipRule: 'evenodd' } : null)}\n />\n ))}\n </svg>\n );\n}\n\n/*\n * THE INTERLOCK, AND WHY IT IS NOT RED AND ORANGE. This is the mark in ONE colour with\n * the overlap carried by opacity — the form, not the livery. It sits inside a button\n * label (\"Pay with ▮ • 1123\") that inverts with the appearance, and a two-colour logo\n * cannot invert. See `BrandPath.opacity`.\n */\nconst MASTERCARD_PATHS: readonly BrandPath[] = [\n {\n d: 'M16 1.99902C18.429 3.82343 20 6.72831 20 10C20 13.2715 18.4287 16.1756 16 18C13.5713 16.1756 12 13.2715 12 10C12 6.72831 13.571 3.82343 16 1.99902Z',\n opacity: 0.52,\n },\n {\n d: 'M22 0C27.5228 0 32 4.47715 32 10C32 15.5228 27.5228 20 22 20C19.7291 20 17.6358 19.2421 15.957 17.9668C15.9714 17.9777 15.9855 17.9891 16 18C18.4287 16.1756 20 13.2715 20 10C20 6.72831 18.429 3.82343 16 1.99902C17.6713 0.743699 19.7488 0 22 0Z',\n opacity: 0.28,\n },\n {\n d: 'M10 0C4.47715 0 0 4.47715 0 10C0 15.5228 4.47715 20 10 20C12.2709 20 14.3642 19.2421 16.043 17.9668C16.0286 17.9777 16.0145 17.9891 16 18C13.5713 16.1756 12 13.2715 12 10C12 6.72831 13.571 3.82343 16 1.99902C14.3287 0.743699 12.2512 0 10 0Z',\n opacity: 0.75,\n },\n];\n\nexport function MastercardMark(props: BrandMarkProps) {\n return (\n <BrandMark\n {...props}\n mark=\"Mastercard\"\n artwork={{ width: 32, height: 20 }}\n paths={MASTERCARD_PATHS}\n />\n );\n}\n\n/** Ours — the full lockup, glyph and word. */\nconst SCOPE_TICKETS_WORDMARK_PATHS: readonly BrandPath[] = [\n {\n d: 'M147.91988,22.61854L175.16822,22.61854L175.16822,98.80931L193.42213,98.80931L193.42213,22.61854L220.67047,22.61854L220.67047,6.21599L147.91988,6.21599L147.91988,22.61854Z',\n },\n {\n d: 'M241.69328,0c-7.27492,0-10.97898,4.09962-10.97898,10.58206,0,6.74615,3.70406,10.84561,10.97898,10.84561,7.01121,0,10.97898-4.09946,10.97898-10.84561,0-6.48244-3.96777-10.58206-10.97898-10.58206Z',\n },\n { d: 'M232.69887,30.02669H250.42383V98.80926000000001H232.69887Z' },\n {\n d: 'M294.7326,84.39129c-10.05178,0-15.07843-7.01121-15.07843-19.97339,0-12.83168,5.02665-19.97339,15.07843-19.97339,7.53997,0,12.30291,4.76159,12.96353,11.77145h17.85698c-.92568-15.34366-10.97898-27.38017-30.82051-27.38017-21.55953,0-33.20047,14.68169-33.20047,35.58211,0,21.16413,12.03651,35.58211,33.59738,35.58211,19.44463,0,29.49792-11.64094,30.5568-27.11645h-17.85833c-.79248,6.87801-5.42221,11.50774-13.09539,11.50774Z',\n },\n {\n d: 'M399.35578,31.34911L399.35578,30.02652L378.72176,30.02652L354.77925,56.74607L354.77925,.92568L337.97981,.92568L337.97981,98.80927L354.77925,98.80927L354.77925,67.72504L379.38104,98.80927L400.67971,98.80927L400.67971,97.48668L371.57736,61.90457L399.35578,31.34911Z',\n },\n {\n d: 'M434.13868,28.83579c-22.08981,0-32.93693,16.13748-32.93693,35.71396,0,19.84154,11.90465,35.45025,33.20064,35.45025,17.72513,0,28.96781-10.18515,30.82186-22.61992h-17.32956c-1.32124,4.23283-5.55407,7.93688-13.4923,7.93688-10.18515,0-14.9454-6.61429-15.07995-16.00562h46.82748v-6.87801c0-18.78266-11.50909-33.59755-32.01125-33.59755ZM419.45699,57.53854c.39557-7.80368,4.76025-13.88787,14.68169-13.88787,9.25947,0,13.62416,6.08418,13.88787,13.88787h-28.56955Z',\n },\n {\n d: 'M511.6454,84.52314c-6.08418,0-8.86391-2.77703-8.86391-9.25947v-30.15855h16.53574v-15.0786h-16.53574V11.90465h-1.32124l-15.74191,3.70271v14.41916h-11.90465v15.0786h11.24269v33.99446c0,12.16971,6.35058,20.90042,21.56238,20.90042,5.82047,0,10.84712-1.05888,12.96219-1.7195v-14.81489h-1.32124c-1.9859.66062-4.10097,1.05753-6.61429,1.05753Z',\n },\n {\n d: 'M568.78182,57.67174l-12.56662-2.24827c-4.36468-.92702-7.00986-2.77838-7.00986-6.21738,0-3.70406,3.83457-6.21738,9.78959-6.21738,7.27357,0,10.84443,3.96911,10.84443,8.73071h17.46141c0-13.09539-10.84712-22.88363-28.04213-22.88363-17.46141,0-27.38017,8.99442-27.38017,20.2371,0,12.69848,8.99307,18.784,20.1039,20.90042l11.11083,2.11641c5.42491,1.05753,7.93823,3.17395,7.93823,6.61295,0,3.5722-3.57086,6.35058-11.37723,6.35058-8.06739,0-12.16836-4.10097-12.16836-9.39267h-17.72513c.39557,14.41798,9.92144,24.33942,29.89349,24.33942,16.66759,0,29.23421-7.67183,29.23421-21.42918,0-13.62416-8.99576-18.6508-20.10659-20.89907Z',\n },\n {\n d: 'M123.04929,16.46569l-3.10576-3.10576c-9.52524-9.52524-24.96881-9.52524-34.49413,0l-3.10569,3.10576c-9.52532,9.52532-24.96889,9.52532-34.49413,0l-3.10576-3.10576c-9.52524-9.52524-24.96881-9.52524-34.49413,0l-3.10569,3.10576c-9.52532,9.52532-9.52532,24.96889,0,34.49413l40.70558,40.7055c9.52524,9.52532,24.96881,9.52532,34.49413,0l40.7055-40.7055c9.52532-9.52524,9.5254-24.96881.00008-34.49413ZM111.39323,39.30415l-40.70605,40.7048c-2.01462,2.01587-4.36772,2.31675-5.59003,2.31675-1.22356,0-3.57667-.30088-5.59128-2.31675L18.80106,39.30415c-2.01587-2.01587-2.318-4.36835-2.318-5.59191,0-1.22294.30088-3.57541,2.31675-5.59066l3.10529-3.10467c2.01587-2.01587,4.36897-2.31675,5.59128-2.31675,1.22356,0,3.57667.30088,5.59128,2.31549l3.10404,3.10467c7.72249,7.72186,17.98613,11.97362,28.90543,11.97362,10.91805,0,21.18169-4.25176,28.90293-11.97237l3.10655-3.10717c2.01336-2.01336,4.36647-2.31424,5.59003-2.31424,1.22231,0,3.57541.30088,5.59003,2.31549l3.1078,3.10717c3.08273,3.0821,3.08273,8.09796-.00125,11.18131Z',\n },\n];\n\nexport function ScopeTicketsWordmarkMark(props: BrandMarkProps) {\n return (\n <BrandMark\n {...props}\n mark=\"ScopeTicketsWordmark\"\n artwork={{ width: 588.88842, height: 100 }}\n paths={SCOPE_TICKETS_WORDMARK_PATHS}\n />\n );\n}\n","/**\n * WHAT MAY BECOME SOMEBODY'S FACE — the one rule the photo step enforces on a file it did\n * not choose.\n *\n * `accept=\"image/*\"` decides what the picker OFFERS and guarantees nothing: a browser\n * hands back whatever was dragged onto it. So a chosen file is external input, and the two\n * things knowable before anything is drawn are checked here, apart from the DOM.\n */\n\nimport type { Environment } from '@scopetickets/api';\nimport { artworkOrigin } from './artwork';\n\n/**\n * ONE OF THE STOCK FACES A NEW ACCOUNT CAN BE GIVEN — the platform's, exactly as the\n * calendar's days are: the widget owns the grid's layout and none of its faces.\n */\nexport type ProfilePhoto = {\n /** The id inside the `default:<id>` value an account stores. */\n readonly id: string;\n /** Where the picture is. */\n readonly url: string;\n};\n\n/** Why a chosen file cannot become a profile photo. */\nexport type PhotoRefusalCode =\n /** Not a picture at all — a PDF, a video, a file with no type. */\n | 'NOT_AN_IMAGE'\n /** A picture, and far more of one than a 100px avatar can be made from. */\n | 'TOO_LARGE';\n\n/**\n * EIGHT MEGABYTES — what a page will hold in memory to draw a circle 100 pixels across,\n * not a storage limit. A phone's own camera clears it; a raw export does not.\n */\nexport const MAX_PHOTO_BYTES = 8 * 1024 * 1024;\n\n/** The part of a `File` this rule reads, so the rule can be tested without one. */\nexport type ChosenFile = { readonly type: string; readonly size: number };\n\n/** Why this file is refused, or `null` where it is fine. */\nexport function photoRefusal(file: ChosenFile): PhotoRefusalCode | null {\n if (!file.type.startsWith('image/')) return 'NOT_AN_IMAGE';\n if (file.size > MAX_PHOTO_BYTES) return 'TOO_LARGE';\n return null;\n}\n\n/**\n * THE PLATFORM'S OWN STOCK FACES, and the widget can name them because they are not a\n * matter of taste: the id inside the `default:<id>` an account stores has to be the one\n * the native app stored, or a buyer who picked a face on their phone is shown a different\n * one here. There is exactly one correct list, so asking every integration to supply it\n * was asking each of them to copy a constant they were not allowed to vary.\n *\n * NO ART IS SHIPPED. These are ten ids and a path; the pictures stay on the CDN, where\n * one buyer's browser caches them across every site that mounts this widget. The rule\n * `@scopetickets/avatar` states — the package owns the value scheme, the consumer owns\n * the images — is about not bundling somebody's photographs, and this does not.\n */\nconst DEFAULT_PROFILE_PHOTO_IDS = [\n '3454b415-64c4-4b0e-8765-0231406846b2',\n '37e705ca-c374-4db4-89ab-3866d9bf6547',\n '6ee50fc2-01fc-4339-8b47-e620af2b2f1a',\n '72ba9d81-d5ee-4408-9aab-4e5375a1df88',\n '800f1a9e-13a3-4203-aa7f-2e023e4053f6',\n '869a96db-f1f9-4263-858c-e9324e956b25',\n '8796f069-98a0-4fff-8864-e70fa5236066',\n '8b855cbe-8af2-40df-9e12-419946978a97',\n 'acebd89b-e025-4acd-9541-9678598f3e40',\n 'd58b20d4-d8e9-4471-b8f7-012108a93e10',\n] as const;\n\n/**\n * A SITE-ROOT PATH, joined to the configured CDN — the same shape `Theme.Backgrounds`\n * arrives in and the same reason `artworkOrigin` exists: the path is the platform's and\n * the host is this integration's, so a sandbox build must not be left pointing at\n * production's files.\n */\nconst DEFAULT_PROFILE_PHOTO_PATH = '/assets/images/user_default';\n\n/**\n * THE TWO SETS THE PLATFORM PUBLISHES, as the folders it publishes them in.\n *\n * `256` IS WHAT THE WIDGET DRAWS, and is the default for that reason. The picker's cells\n * are 64px and the largest hero is 100, so this is 2.5x the biggest thing it is ever put\n * in — which is the headroom a retina screen wants and no more. The whole set is ~290KB.\n *\n * `1024` IS THE ORIGINAL, and nothing here asks for it: every avatar this package draws is\n * 100px or under, so it would be ten times the bytes for pixels no screen resolves. It is\n * named rather than left out because it exists, and because the day something draws a face\n * at full width the choice is this argument rather than a new path.\n */\nexport type ProfilePhotoSize = 256 | 1024;\n\n/** The stock set as the picker and the hero both need it, for the configured platform. */\nexport function defaultProfilePhotos(\n environment: Environment = 'production',\n size: ProfilePhotoSize = 256,\n): ProfilePhoto[] {\n const origin = artworkOrigin(environment);\n return DEFAULT_PROFILE_PHOTO_IDS.map((id) => ({\n id,\n url: `${origin}${DEFAULT_PROFILE_PHOTO_PATH}/${size}/${id}.jpeg`,\n }));\n}\n","/**\n * WHAT A BUYER IS TOLD WHEN THE ORDER DID NOT DO WHAT THEY ASKED.\n *\n * ONE CARD DRAWN FROM DATA — never a screen per failure, and never failure UI inside a\n * step. Adding a case is an entry here and a raise from the site that knows: see\n * `raiseFor` and the two effects in `ScopeTicketsCheckout` that call it.\n *\n * ONE VOCABULARY IN TWO PACKAGES, and that is a debt rather than a design. `@scopetickets\n * /sdk` has said all of this since before the island existed — the same two severities,\n * the same action ids, the same reporting rule — and `packages/checkout` cannot reach it:\n * neither package depends on the other, and the island exists to be the lean one. So the\n * vocabulary is copied, and the WORDING is too wherever the SDK has already said the same\n * thing to a buyer — copy that has been read beats copy invented twice. When the notices\n * module moves somewhere both can use, this file is what it replaces; the names are\n * deliberately identical so that merge is a deletion.\n *\n * Pure: no React, no network, no DOM.\n */\n\nimport type { AccountCreationProgress, AccountOutcome } from './account-creation';\nimport type { BookingState, HolderSave } from './booking';\nimport type { FeedbackSubmission } from './feedback';\nimport type { OrderFill } from './order-fill';\nimport type { AuthFunnel } from './auth-funnel';\nimport type { PasskeySignIn } from './sign-in';\n\n/**\n * WARNING: the system worked and something needs adjusting, so there is a way forward.\n * FAILURE: something broke — leave, or try again where there is anything to try.\n *\n * IT IS LOAD-BEARING. It decides how a notice is reported and how its lead button is\n * painted, so neither can disagree with the other: a sold-out ticket is inventory, and\n * filing warnings as faults buries the real ones within a week of a busy on-sale.\n */\nexport type NoticeSeverity = 'WARNING' | 'FAILURE';\n\n/** What a button DOES, kept apart from what it says: the label is copy and will change. */\nexport type NoticeActionId =\n /** Take the order as it stands — the smaller sale, completed. */\n | 'CONTINUE'\n /** Back to the party step with the order intact, to ask for something else. */\n | 'CHANGE_ORDER'\n /**\n * Make the call again. Only ever offered where there IS something to try — see\n * `ORDER_NOT_OPENED`, which deliberately has no retry because nothing could be retried\n * with.\n */\n | 'RETRY'\n /**\n * Give up on the account and go on to the ticket. Only reachable after payment, which\n * is what makes it a real way out rather than an abandoned purchase: the tickets are\n * already the buyer's.\n */\n | 'SKIP_ACCOUNT'\n /** Leave. Every notice offers one. */\n | 'CLOSE';\n\nexport type NoticeId =\n /**\n * FEWER TICKETS THAN WERE ASKED FOR ARE HELD. The platform fills what it can — see\n * `AllowPartialFulfillment` — so this is a smaller order the buyer already owns, which\n * is why it leads with taking it rather than with changing it.\n */\n | 'ORDER_PART_FILLED'\n /**\n * NOT ONE OF THEM COULD BE HELD, for a party of more than one. The flag fills what it\n * can, and where it can fill NOTHING the platform refuses outright — so this is the\n * bottom of the same range as `ORDER_PART_FILLED` and not a different kind of event.\n */\n | 'ORDER_NOT_ENOUGH'\n /** The same refusal met by a buyer on their own, where there is no party to speak of. */\n | 'ORDER_SOLD_OUT'\n /** The order could not be opened at all: no cart, and nothing to check out. */\n | 'ORDER_NOT_OPENED'\n /**\n * The verification code could not be SENT. Distinct from a code that was refused, which\n * is the buyer mistyping and is answered by the boxes themselves — validation, not a\n * failure of ours.\n */\n | 'ACCOUNT_CODE_NOT_SENT'\n /** Everything was answered and `POST /api/Users` would not take it. */\n | 'ACCOUNT_NOT_CREATED'\n /**\n * The buyer rated their purchase and the rating did not reach us. THE ONLY NOTICE HERE\n * ABOUT SOMETHING THE BUYER DOES NOT NEED — the order is placed either way, and a\n * rating is a courtesy they have already paid. It is raised anyway because the\n * alternative is a press that silently did nothing: they chose four stars, pressed\n * Continue, and nothing on the platform has heard of it.\n */\n | 'FEEDBACK_NOT_SENT'\n /**\n * The device signed something and the platform would not take it — or the challenge in\n * front of it never arrived. NOT a buyer who waved the prompt away, which is a normal\n * thing to do and raises nothing; see `usePasskeySignIn`, which draws that line.\n */\n | 'SIGN_IN_NOT_COMPLETED'\n /**\n * The password door could not be reached — the call did not go, or did not come back.\n * NOT a password the platform refused, which is the buyer typing and is answered by the\n * card itself.\n */\n | 'SIGN_IN_UNREACHABLE'\n /**\n * THE BOOKING WOULD NOT LOAD. The money moved, the tickets exist, and the one request\n * that says who they are for did not come back — so the buyer is looking at a card that\n * cannot list anything. NOT a cart that never became a transaction, which is an answer\n * and gets a card of its own rather than a failure.\n */\n | 'BOOKING_NOT_LOADED'\n /**\n * THE PLATFORM WOULD NOT TAKE THE TICKETHOLDER. A refusal, not a failure to reach — the\n * details went and came back declined, which is a WARNING because the system worked and\n * something about the answer needs adjusting.\n */\n | 'TICKETHOLDER_REFUSED'\n /**\n * The ticketholder's details never reached the platform. The ticket is unchanged and the\n * buyer is still holding what they typed, so this is the one of the two that is a fault.\n */\n | 'TICKETHOLDER_NOT_SAVED';\n\nexport type NoticeAction = {\n readonly id: NoticeActionId;\n /** CONFIRM is the one likeliest to end in a sale, and is drawn as the lead. */\n readonly kind: 'CONFIRM' | 'SECONDARY';\n readonly label: string;\n};\n\nexport type Notice = {\n readonly id: NoticeId;\n readonly severity: NoticeSeverity;\n /** Title Case. */\n readonly title: string;\n /** Sentence case. Never reported — see `noticeTelemetry`. */\n readonly subtitle: string;\n /** In order, so the first is the lead. */\n readonly actions: readonly NoticeAction[];\n};\n\nconst confirm = (id: NoticeActionId, label: string): NoticeAction => ({\n id,\n kind: 'CONFIRM',\n label,\n});\nconst secondary = (id: NoticeActionId, label: string): NoticeAction => ({\n id,\n kind: 'SECONDARY',\n label,\n});\n\n/**\n * The notices whose words are the same every time. One so far: a notice whose words depend\n * on what the flow knows gets a builder instead.\n */\nexport const NOTICES: Readonly<Record<Exclude<NoticeId, 'ORDER_PART_FILLED'>, Notice>> = {\n /* Its wording is the SDK's `NOT_ENOUGH`, and the solo one below its `soldOutNotice`. */\n ORDER_NOT_ENOUGH: {\n id: 'ORDER_NOT_ENOUGH',\n severity: 'WARNING',\n /*\n * NO NUMBER, because the refusal that raises this carries none. Where a count does\n * exist the buyer is already holding those tickets and gets `ORDER_PART_FILLED`, which\n * is the better card of the two.\n */\n title: 'Not Enough Tickets Left',\n subtitle: \"There aren't enough tickets left for everyone in your order.\",\n actions: [confirm('CHANGE_ORDER', 'Change Order'), secondary('CLOSE', 'Close')],\n },\n ORDER_SOLD_OUT: {\n id: 'ORDER_SOLD_OUT',\n severity: 'WARNING',\n title: 'Sold Out',\n subtitle: 'Someone just bought the last one.',\n /* \"Change Order\" asks a party to be smaller, and there is no smaller than one. */\n actions: [confirm('CHANGE_ORDER', 'See What’s Left'), secondary('CLOSE', 'Close')],\n },\n ORDER_NOT_OPENED: {\n id: 'ORDER_NOT_OPENED',\n severity: 'FAILURE',\n title: 'We Could Not Start Your Order',\n /*\n * THE CHARGE PROMISE IS KEEPABLE HERE and only because of where this is raised: there\n * is no cart, so there was nothing to charge against. A notice reachable from after a\n * payment must never carry this sentence — see `carriesChargePromise`.\n */\n subtitle: 'Something went wrong before we could hold your tickets. Nothing has been charged.',\n /*\n * NO RETRY, because there is nothing to retry with: `useCheckoutOrder` opens a cart\n * ONCE and has no way to open another — the guard that stops a second cart also stops\n * a second attempt. A button that appears to work is worse than one that is not there.\n */\n actions: [secondary('CLOSE', 'Close')],\n },\n /*\n * THE COUNTERPART OF THE CHARGE PROMISE, and the reason both of these say it. Before a\n * payment the reassurance a buyer needs is that no money moved; after one it is the\n * opposite — the money moved and the tickets are THEIRS, whatever else just failed.\n * Both of these are only reachable from after `PAYMENT_SUCCESS`, so neither may carry\n * \"Nothing has been charged\" (see `carriesChargePromise`) and both must say this\n * instead.\n */\n ACCOUNT_CODE_NOT_SENT: {\n id: 'ACCOUNT_CODE_NOT_SENT',\n severity: 'FAILURE',\n title: 'We Could Not Send Your Code',\n subtitle: 'Your tickets are safe. We could not email a verification code just now.',\n /* There IS something to retry with — the address is in hand and the send is repeatable. */\n actions: [confirm('RETRY', 'Try Again'), secondary('SKIP_ACCOUNT', 'Skip')],\n },\n ACCOUNT_NOT_CREATED: {\n id: 'ACCOUNT_NOT_CREATED',\n severity: 'FAILURE',\n title: 'We Could Not Create Your Account',\n subtitle: 'Your tickets are safe. Something went wrong while setting up your account.',\n /*\n * The password is deliberately kept on a failed creation so this button has something\n * to send — see `useAccountCreation`, where it is spent only on success.\n */\n actions: [confirm('RETRY', 'Try Again'), secondary('SKIP_ACCOUNT', 'Skip')],\n },\n /*\n * AFTER A PAYMENT TOO, so it makes the same promise its two neighbours do and not the\n * other one — see `carriesChargePromise`.\n *\n * IT LEADS WITH THE RETRY AND NOT WITH LEAVING, though leaving costs the buyer nothing:\n * the rating is still in hand — `FeedbackSubmission.FAILED` keeps it — so one press\n * sends what they already chose, and a Close in the lead would ask them to abandon work\n * they have done rather than spend it.\n *\n * NO `SKIP_ACCOUNT`: that gives up on an account, which has nothing to do with this and\n * may not even be on offer. Close is the way out, as it is on every notice.\n */\n FEEDBACK_NOT_SENT: {\n id: 'FEEDBACK_NOT_SENT',\n severity: 'FAILURE',\n title: 'We Could Not Send Your Rating',\n subtitle: 'Your tickets are safe. Your rating did not reach us just now.',\n actions: [confirm('RETRY', 'Try Again'), secondary('CLOSE', 'Close')],\n },\n /*\n * BEFORE A PAYMENT, ALWAYS — signing in is offered at `IDLE` and `ORDER_CREATED` and the\n * offer after one is `ADD_TO_ACCOUNT`. So neither promise above is this one's to make:\n * there may be no order at all, and there is certainly no charge.\n */\n SIGN_IN_NOT_COMPLETED: {\n id: 'SIGN_IN_NOT_COMPLETED',\n severity: 'FAILURE',\n title: 'We Could Not Sign You In',\n /* It NAMES the passkey: \"something went wrong\" would leave them pressing it again. */\n subtitle:\n 'Your passkey could not be checked just now. You can try again, or use your password.',\n /*\n * NOT `SKIP_ACCOUNT`, which gives up on MAKING one and is only a way out because the\n * tickets are paid for. Close leaves the card behind the island, still offering both.\n */\n actions: [confirm('RETRY', 'Try Again'), secondary('CLOSE', 'Close')],\n },\n /*\n * ITS TWIN, AND THE WORDS ARE THE DIFFERENCE: the one above points at the password, and\n * this one IS the password, so it has nowhere else to point.\n */\n SIGN_IN_UNREACHABLE: {\n id: 'SIGN_IN_UNREACHABLE',\n severity: 'FAILURE',\n title: 'We Could Not Sign You In',\n subtitle: 'Something went wrong reaching your account. Your details were not the problem.',\n actions: [confirm('RETRY', 'Try Again'), secondary('CLOSE', 'Close')],\n },\n /*\n * ── AFTER THE MONEY MOVED, ALL THREE ────────────────────────────────────────\n *\n * My Booking is only reachable once a purchase is placed, so none of these may carry\n * \"Nothing has been charged\" and each has to say the opposite instead: the tickets exist\n * and this is about reading or editing them, not about whether they are the buyer's.\n */\n BOOKING_NOT_LOADED: {\n id: 'BOOKING_NOT_LOADED',\n severity: 'FAILURE',\n title: 'We Could Not Open Your Booking',\n subtitle: 'Your tickets are safe. We could not load them just now.',\n /* There IS something to retry with: the cart key is in hand and the read is repeatable. */\n actions: [confirm('RETRY', 'Try Again'), secondary('CLOSE', 'Close')],\n },\n /*\n * A WARNING AND NOT A FAILURE, which is the whole distinction this set turns on: the\n * platform was reached, it read the details, and it said no. Something needs adjusting\n * and there is a way forward — which is also why the lead goes BACK to the form rather\n * than repeating a request that was already answered.\n */\n TICKETHOLDER_REFUSED: {\n id: 'TICKETHOLDER_REFUSED',\n severity: 'WARNING',\n title: 'We Could Not Save Those Details',\n subtitle: 'Check the name and email address on this ticket, then try again.',\n actions: [confirm('CONTINUE', 'Back To Details'), secondary('CLOSE', 'Close')],\n },\n TICKETHOLDER_NOT_SAVED: {\n id: 'TICKETHOLDER_NOT_SAVED',\n severity: 'FAILURE',\n title: 'We Could Not Save Those Details',\n /*\n * IT SAYS WHAT IS STILL TRUE OF THE TICKET, because that is the buyer's real question:\n * an edit that did not land leaves the ticket exactly as it was, and a ticket in\n * somebody else's name still admits whoever carries it.\n */\n subtitle: 'Your ticket is unchanged and still valid. The change did not reach us just now.',\n actions: [confirm('RETRY', 'Try Again'), secondary('CLOSE', 'Close')],\n },\n};\n\n/**\n * WHAT WENT WRONG WITH THE BOOKING, or nothing — the same shape as `raiseForFeedback`, and\n * the same rule: only a state that IS a failure raises one.\n *\n * TWO SOURCES, ONE ANSWER. The read and the save cannot both be the matter at once — the\n * Edit card is only reachable from a booking that loaded — so the read is asked first and\n * the save is asked of the card the buyer is actually standing on.\n */\nexport function raiseForBooking(booking: BookingState, save: HolderSave): Notice | null {\n if (booking.status === 'ERROR') return NOTICES.BOOKING_NOT_LOADED;\n if (save.status === 'REFUSED') return NOTICES.TICKETHOLDER_REFUSED;\n if (save.status === 'FAILED') return NOTICES.TICKETHOLDER_NOT_SAVED;\n return null;\n}\n\n/**\n * ONLY N TICKETS ARE HELD — the notice the count made possible.\n *\n * The SDK's own `NOT_ENOUGH` says what this replaces: \"No number, because the platform\n * refuses on availability without saying how many remain. With a count this becomes 'Only\n * 4 Tickets Left' and leads with Book 4 Instead — the strongest card in the set.\" The\n * count exists now, and it is better than a count: the tickets are already the buyer's,\n * so the lead button takes them rather than offering to try for them.\n */\nexport function partFilledNotice(held: number, asked: number): Notice {\n const tickets = held === 1 ? '1 Ticket' : `${held} Tickets`;\n return {\n id: 'ORDER_PART_FILLED',\n severity: 'WARNING',\n title: `Only ${tickets} Left`,\n subtitle: `We held ${held} of the ${asked} you asked for. The rest have gone.`,\n actions: [\n confirm('CONTINUE', `Continue With ${tickets}`),\n secondary('CHANGE_ORDER', 'Change Order'),\n ],\n };\n}\n\n/**\n * WHAT THE ORDER'S STATE RAISES, or nothing at all — one place, so the flow does not grow\n * a second opinion about which card it is on.\n *\n * IT TAKES THE OUTCOME RATHER THAN READINGS OF IT. This was a shortfall beside a boolean,\n * and it had to rank them: a cart that filled short is an order the buyer HAS, while a\n * failure on the same state can be a later call going wrong against it, and telling\n * somebody their order failed while they hold four tickets is worse than telling them\n * about the four. With one state there is nothing to rank — see `OrderFill`.\n */\nexport function raiseFor(fill: OrderFill): Notice | null {\n switch (fill.status) {\n case 'PENDING':\n case 'FILLED':\n return null;\n case 'SHORT':\n return partFilledNotice(fill.held, fill.asked);\n case 'SOLD_OUT':\n return fill.asked > 1 ? NOTICES.ORDER_NOT_ENOUGH : NOTICES.ORDER_SOLD_OUT;\n case 'FAILED':\n return NOTICES.ORDER_NOT_OPENED;\n default: {\n const exhaustive: never = fill;\n return exhaustive;\n }\n }\n}\n\n/**\n * WHAT THE ACCOUNT SUB-FLOW RAISES, or nothing — the counterpart of `raiseFor`, and\n * separate from it because the two answer to different states and can both be true.\n *\n * THE LATER FAILURE WINS. A buyer whose account could not be created has got further than\n * one whose code never arrived, and telling them about the code they already used would\n * be answering a question they have finished with.\n *\n * A REFUSED CODE RAISES NOTHING. That is the buyer mistyping six digits, which the boxes\n * answer themselves — a notice for it would be a card in front of somebody who only needs\n * to look at what they typed.\n */\nexport function raiseForAccount(\n progress: AccountCreationProgress,\n outcome: AccountOutcome,\n): Notice | null {\n if (outcome.status === 'FAILED') return NOTICES.ACCOUNT_NOT_CREATED;\n const { email } = progress;\n if (email.status === 'CONFIRMED' && email.passcode.status === 'SEND_FAILED') {\n return NOTICES.ACCOUNT_CODE_NOT_SENT;\n }\n return null;\n}\n\n/**\n * WHAT SIGNING IN RAISES, or nothing — the third source, and separate for the reason the\n * other two are separate: a buyer can meet it where neither has anything to say.\n *\n * ONLY `FAILED`, ON EITHER. A dismissed device prompt lands on `IDLE` and a wrong password\n * on `REFUSED`; both are the card's to answer and neither is a fault to report.\n */\nexport function raiseForSignIn(signIn: PasskeySignIn, funnel: AuthFunnel): Notice | null {\n /*\n * THE FUNNEL FIRST, because it is the door the buyer is standing in: a passkey failure\n * behind an open password card is news about something they have already moved on from.\n */\n if (funnel.status === 'FAILED') return NOTICES.SIGN_IN_UNREACHABLE;\n return signIn.status === 'FAILED' ? NOTICES.SIGN_IN_NOT_COMPLETED : null;\n}\n\n/**\n * WHAT THE RATING RAISES, or nothing — the fourth source, and the only one that is about\n * something the buyer could walk away from without losing anything.\n *\n * ONLY `FAILED`. `UNSENT` is the ordinary state of a card nobody has pressed and of a\n * buyer who skipped, and neither is a fault: a rating that was never offered is not a\n * rating that was lost.\n */\nexport function raiseForFeedback(submission: FeedbackSubmission): Notice | null {\n return submission.status === 'FAILED' ? NOTICES.FEEDBACK_NOT_SENT : null;\n}\n\n/**\n * WHETHER A BUYER CAN LEAVE THIS CARD. A card a buyer cannot leave is worse than the\n * failure it is reporting.\n *\n * A PREDICATE BECAUSE IT WAS GOT WRONG. The rule lived as an expression inside a test —\n * `CLOSE` or `CONTINUE` — and the first notice added after it offered neither, because it\n * had its own way out and the expression had never heard of it. Which ids COUNT as\n * leaving is a fact about the vocabulary, so it belongs beside the vocabulary.\n */\nexport function noticeOffersWayOut(notice: Notice): boolean {\n return notice.actions.some(\n (action) =>\n /* Dismiss the island. */\n action.id === 'CLOSE' ||\n /* Take the smaller order and go on. */\n action.id === 'CONTINUE' ||\n /*\n * Give up on the account and go on to the ticket — a way out only because it is\n * reachable after payment alone. Before one it would be leaving the purchase.\n */\n action.id === 'SKIP_ACCOUNT',\n );\n}\n\n/**\n * How a notice is FILED: a warning is a breadcrumb on the trail to the next fault, an\n * exception is the fault. The same rule the reporter in `@scopetickets/sdk` applies, and\n * the reason severity cannot be decorative.\n */\nexport function noticeTelemetry(severity: NoticeSeverity): 'BREADCRUMB' | 'EXCEPTION' {\n return severity === 'WARNING' ? 'BREADCRUMB' : 'EXCEPTION';\n}\n\n/**\n * WHICH ROLE THE LEAD BUTTON TAKES, from severity alone. A warning leads with the ordinary\n * primary — there is a sale at the end of it; a failure leads with the action paint, which\n * is what the island gives a button that is not a step forward.\n */\nexport function noticeLeadRole(severity: NoticeSeverity): 'primary' | 'action' {\n return severity === 'WARNING' ? 'primary' : 'action';\n}\n\n/**\n * Whether a notice claims nothing has been charged. \"Nothing has been charged\" is only\n * keepable BEFORE a payment is submitted, so a notice reachable from after one must not\n * carry it — asserted rather than described; see the test.\n */\nexport function carriesChargePromise(notice: Notice): boolean {\n return notice.subtitle.includes('Nothing has been charged');\n}\n","import { TextField } from './TextField';\n\nexport type CredentialFieldsProps = {\n readonly email: string;\n readonly password: string;\n readonly onEmailChange: (email: string) => void;\n readonly onPasswordChange: (password: string) => void;\n /**\n * Whether the password field is ON SCREEN. Not whether it exists — see the note below,\n * and `passwordRevealed` in `@/domain/auth-funnel`, which is what decides it.\n */\n readonly passwordVisible: boolean;\n /**\n * Submits from either field's return key. The card's own button calls the same thing.\n */\n readonly onSubmit?: () => void;\n};\n\n/** The sign-in funnel's two fields — the design’s `InputWrapper`. */\nexport function CredentialFields({\n email,\n password,\n onEmailChange,\n onPasswordChange,\n passwordVisible,\n onSubmit,\n}: CredentialFieldsProps) {\n return (\n <form\n className=\"scopetickets-island-credentials\"\n autoComplete=\"on\"\n // Nothing to submit to — the island is a step machine, not a page of forms.\n onSubmit={(event) => event.preventDefault()}\n data-revealed={passwordVisible ? '' : undefined}\n >\n <TextField\n id=\"signin-email\"\n name=\"username\"\n label=\"Email\"\n value={email}\n onChange={onEmailChange}\n type=\"email\"\n inputMode=\"email\"\n // `username` alone: the `webauthn` token only means something with a\n // conditionally-mediated request, and the passkey check is explicit opt-in —\n // nothing arms one.\n autoComplete=\"username\"\n autoCapitalize=\"none\"\n enterKeyHint=\"next\"\n onSubmit={() => document.getElementById('signin-password')?.focus()}\n />\n\n {/*\n * Always rendered, always full-size. The wrapper's height is the reveal; this element's\n * box never changes.\n */}\n <div className=\"scopetickets-island-credentials__password\">\n <TextField\n id=\"signin-password\"\n name=\"current-password\"\n label=\"Enter Password\"\n value={password}\n onChange={onPasswordChange}\n type=\"password\"\n // `current-password`, NOT `new-password`.\n autoComplete=\"current-password\"\n autoCapitalize=\"none\"\n enterKeyHint=\"go\"\n onSubmit={onSubmit}\n // `text/mono/md` — the node draws the dots on an even rhythm.\n monospace\n />\n </div>\n </form>\n );\n}\n","/** STui's `RadioIcon` — 16px, and the ONE drawing of it. */\nexport function RadioDot({ selected }: { selected: boolean }) {\n return (\n <span\n className=\"scopetickets-island-radio\"\n // The ROW announces the state. This is the picture of it.\n aria-hidden=\"true\"\n data-selected={selected ? '' : undefined}\n />\n );\n}\n","import type { CSSProperties, ReactNode } from 'react';\nimport { RadioDot } from './RadioDot';\nimport { useIslandPress } from './island-press';\n\n/** One way to pay, as the list needs it. */\n/** WHO DRAWS THE BUTTON, which is the only thing this distinction decides. */\nexport type PaymentKind = 'WALLET' | 'CARD';\n\nexport type PaymentMethod = {\n readonly key: string;\n readonly kind: PaymentKind;\n /**\n * Drawn WHERE THE RADIO WOULD BE, for a row that is chosen the same way but is not a\n * stored method — \"Add New Card\". The design gives it a mark rather than a radio, and\n * it is still one of the six rows you pick between.\n */\n readonly icon?: ReactNode;\n /**\n * What the row says. Once the marks ship, the mark says it and this names the row for\n * assistive technology instead.\n */\n readonly label: string;\n /** The brand's own logo, when there is one to draw. */\n readonly mark?: ReactNode;\n /**\n * A card's last four, in the mono numerals — `• 2468`. PART OF THE LOCKUP: it says\n * which Mastercard, so it sits against the mark rather than at the row's trailing edge.\n * The pay button composes the same two into one phrase.\n */\n readonly detail?: string;\n /**\n * A SUBTITLE for the method — Figma's own \"Earn 2x RevPoints\", a second thing said\n * about it rather than a continuation of its name. It takes the rest of the row and\n * ends flush with the trailing padding.\n */\n readonly perk?: string;\n /**\n * THE ROW CANNOT BE CHOSEN — the wallet before the payment host has said the device\n * can pay (or has said it cannot). A row that cannot be pressed still owes the buyer\n * the reason, which is `note`.\n */\n readonly disabled?: boolean;\n /**\n * WHY A DISABLED ROW IS DISABLED, in the trailing slot a perk occupies — \"Checking\n * availability…\" while the host has not answered, \"Unavailable on this device\" when\n * it answered no. Drawn only while the row cannot be pressed.\n */\n readonly note?: string;\n};\n\nexport type PaymentMethodsProps = {\n readonly methods: readonly PaymentMethod[];\n readonly selectedKey: string;\n readonly onSelect: (key: string) => void;\n /** Names the group for assistive technology. This package holds no copy. */\n readonly label: string;\n};\n\nfunction PaymentRow({\n method,\n selected,\n onSelect,\n}: {\n method: PaymentMethod;\n selected: boolean;\n onSelect: () => void;\n}) {\n // `element`, not `island` — choosing how to pay does not change what the island IS,\n // and compressing the whole surface for it would promise a transformation that is not\n // coming.\n const press = useIslandPress('element');\n\n return (\n <button\n type=\"button\"\n role=\"radio\"\n aria-checked={selected}\n disabled={method.disabled}\n className=\"scopetickets-island-pay__row\"\n onClick={onSelect}\n {...press}\n >\n {/*\n * A row that is not a stored method draws its own mark here — see\n * `PaymentMethod.icon`. It is still chosen the same way, so the row is still a\n * radio and the highlight still lands on it.\n */}\n {method.icon === undefined ? (\n <RadioDot selected={selected} />\n ) : (\n <span className=\"scopetickets-island-pay__mark\" aria-hidden=\"true\">\n {method.icon}\n </span>\n )}\n <span className=\"scopetickets-island-pay__content\">\n {/*\n * THE MARK, WHERE THERE IS ONE — and it is the CALLER's, passed in as\n * `PaymentMethod.mark`. Google Pay has no lockup in the file at all, so its row falls\n * back to its own name. That fallback is the reason `label` exists alongside `mark`\n * rather than the type being a union over the payment kinds — see\n * `PaymentMethod`.\n */}\n {method.mark ?? <span className=\"scopetickets-island-pay__label\">{method.label}</span>}\n {method.detail === undefined ? null : (\n <span className=\"scopetickets-island-pay__detail\">{method.detail}</span>\n )}\n {method.perk === undefined ? null : (\n <span className=\"scopetickets-island-pay__perk\">{method.perk}</span>\n )}\n {method.note === undefined ? null : (\n /* THE PERK'S SLOT, because the note is the same trailing text at the same\n * weight — the difference is only why it is there. */\n <span className=\"scopetickets-island-pay__perk\">{method.note}</span>\n )}\n </span>\n </button>\n );\n}\n\n/** The Payment Methods list — the design. */\n/** Which button role the pay action takes for a given method. */\nexport function payButtonRole(kind: PaymentKind): 'action' | 'primary' {\n return kind === 'WALLET' ? 'primary' : 'action';\n}\n\nexport function PaymentMethods({ methods, selectedKey, onSelect, label }: PaymentMethodsProps) {\n // Clamped at 0 so an unknown key parks the highlight on the first row rather than\n // translating it off the top of the list — the source's own `Math.max`.\n const selectedIndex = Math.max(\n 0,\n methods.findIndex((method) => method.key === selectedKey),\n );\n\n return (\n <div\n className=\"scopetickets-island-pay\"\n role=\"radiogroup\"\n aria-label={label}\n style={{ '--scopetickets-island-pay-index': selectedIndex } as CSSProperties}\n >\n <span className=\"scopetickets-island-pay__highlight\" aria-hidden=\"true\" />\n {methods.map((method) => (\n <PaymentRow\n key={method.key}\n method={method}\n selected={method.key === selectedKey}\n onSelect={() => onSelect(method.key)}\n />\n ))}\n </div>\n );\n}\n","/** The escrow hold, as pure data. */\nimport { clampRemaining } from './island-timer';\n\nexport type EscrowHold = {\n /**\n * Seconds left on the hold. May be negative — a countdown past its deadline is the\n * ordinary case, not an error, and both readings below floor at zero.\n */\n readonly secondsLeft: number;\n /** The whole window, in seconds, which is what makes the ring a FRACTION. */\n readonly durationSeconds: number;\n};\n\nconst SECONDS_PER_MINUTE = 60;\nconst MILLISECONDS_PER_SECOND = 1000;\n\n/** How much of the hold is left, 0..1 — `CountdownTimer`'s `remaining`. */\nexport function holdRemaining(hold: EscrowHold): number {\n // `clampRemaining` and not a second clamp written here: it already floors a deadline\n // that has passed, caps a viewer's clock running behind the server's, and answers a\n // zero duration (which divides to a non-finite) as EXPIRED rather than full.\n return clampRemaining(hold.secondsLeft / hold.durationSeconds);\n}\n\n/**\n * THE SAME HOLD, SOME TIME LATER — a snapshot turned into a deadline by the instant it\n * was taken at.\n *\n * `EscrowHold` IS A SNAPSHOT AND NOT A DEADLINE, which is the whole reason this exists.\n * \"540 seconds left\" is only true at the moment it is said, so a host that asserts one and\n * then re-renders is asserting the same 540 for as long as its own state holds — and the\n * ring drawn from it sits still while the clock it is counting runs on. The fix is not to\n * distrust the host: it is to remember WHEN they said it.\n *\n * THE WINDOW DOES NOT MOVE. Only what is left of it does — the ring's denominator is the\n * whole hold, and that is a fact about the reservation rather than about now.\n */\nexport function holdSince(hold: EscrowHold, assertedAt: number, now: number): EscrowHold {\n return {\n secondsLeft: hold.secondsLeft - (now - assertedAt) / MILLISECONDS_PER_SECOND,\n durationSeconds: hold.durationSeconds,\n };\n}\n\n/** Whether two holds are the same ASSERTION — see `holdSince`, which stamps a new one. */\nexport function sameHold(a: EscrowHold, b: EscrowHold): boolean {\n return a.secondsLeft === b.secondsLeft && a.durationSeconds === b.durationSeconds;\n}\n\n/**\n * WHETHER THE HOLD HAS RUN OUT — the tickets are released and there is nothing left for\n * the flow to be about.\n *\n * A PREDICATE RATHER THAN A COMPARISON AT EACH SITE: `holdRemaining` and `formatHold`\n * both floor rather than going negative, so this is the only place a hold at `-4` can be\n * told from one at `0` — and three readings have to agree about it.\n */\nexport function holdExpired(hold: EscrowHold): boolean {\n return hold.secondsLeft <= 0;\n}\n\n/**\n * The hold as `mm:ss` — `01:30`, and the ONE place it is written in words: the cart\n * screen's sentence. The header pill says the total.\n */\nexport function formatHold(hold: EscrowHold): string {\n const total = Math.max(0, Math.ceil(hold.secondsLeft));\n const minutes = Math.floor(total / SECONDS_PER_MINUTE);\n const seconds = total % SECONDS_PER_MINUTE;\n\n return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;\n}\n","import type { CSSProperties } from 'react';\nimport { IconGlyph, type IconAppearance } from '@scopetickets/icons';\nimport { timerPaths, trackPaths } from './island-timer';\n\n/**\n * Each layer fills the stack. A shared object, because two identical inline styles are\n * two things that can drift apart.\n */\nconst LAYER: CSSProperties = { position: 'absolute', inset: 0 };\n\n/**\n * The groove the ring runs in — a 5% tint of whatever the theme contrasts with. See\n * `--scopetickets-island-timer-track` in `island.css`.\n */\nconst TRACK_FILL = 'var(--scopetickets-island-timer-track, rgba(230, 230, 230, 0.05))';\n\n/** A countdown, as a ring that drains and a hand that sweeps. */\nexport type CountdownTimerProps = {\n /**\n * How much of the clock is left, 0..1 — a FRACTION, never seconds. The indicator has no\n * idea how long the timer is and does not need one: 100% is the hand at 12 whether that\n * is ten minutes or ten seconds.\n */\n readonly remaining: number;\n /** The size of the 1:1 box. Any CSS length; a number is taken as px. */\n readonly size?: number | string;\n /**\n * `solid` — the glyph fill, and what every timer in the island draws today. `metal` —\n * the set's own treatment. Both are the package's; neither is described here.\n */\n readonly appearance?: IconAppearance;\n /** Draw the groove the ring runs in. Default `true`. */\n readonly track?: boolean;\n /**\n * Override the fill. Omit and it takes `--scopetickets-icon-solid-fill` like every\n * glyph, which is what almost every caller wants — the ring and the hand then match the\n * icons beside them rather than the text.\n */\n readonly color?: string;\n /**\n * An accessible name. Omit — as most callers should — and this is hidden from assistive\n * technology rather than announced as an unlabelled graphic.\n */\n readonly title?: string;\n readonly className?: string;\n readonly style?: CSSProperties;\n};\n\nexport function CountdownTimer({\n remaining,\n size = '1em',\n appearance = 'solid',\n track = true,\n color,\n title,\n className,\n style,\n}: CountdownTimerProps) {\n return (\n <span\n className={className}\n // The box the layers are stacked in.\n style={{\n position: 'relative',\n display: 'block',\n width: size,\n height: size,\n flex: 'none',\n ...style,\n }}\n >\n {track ? (\n <span style={LAYER}>\n <IconGlyph\n glyph=\"TimerTrack\"\n paths={trackPaths()}\n // Never metal, and never the icon fill: a groove is the surface behind,\n // showing through.\n color={TRACK_FILL}\n fill\n />\n </span>\n ) : null}\n\n <span style={LAYER}>\n <IconGlyph\n // The design-system name, as `IconTimer.svg` and Figma's `Icon=Timer` have\n // it.\n glyph=\"Timer\"\n paths={timerPaths(remaining)}\n appearance={appearance}\n color={color}\n title={title}\n className={className}\n // `fill` puts the box at 100%, and `style` — which `IconGlyph` merges LAST,\n // after its own box — replaces it with whatever length the caller asked for.\n fill\n />\n </span>\n </span>\n );\n}\n","import type { ReactNode } from 'react';\nimport type { AvatarAccessory, AvatarAssets } from '@scopetickets/avatar';\nimport type { ProfilePhoto } from '../domain/profile-photo';\n\n/**\n * THE HERO EVERY FACE OF THE ISLAND WEARS — the buyer, and whatever the card in front of\n * them is asking for.\n *\n * ITS OWN MODULE BECAUSE THERE ARE TWO ISLANDS NOW. The widget at rest draws a hero and\n * so does the widget walking a purchase, and neither owns the other; leaving these in\n * `ScopeTicketsCheckout` would have meant the resting island importing the flow to draw a\n * face.\n */\n\n/**\n * NAMES THE HERO ACROSS EVERY REBUILD IT SURVIVES — see `AvatarProps.transitionKey`.\n *\n * The island discards its whole subtree on each step and draws a third copy in the carry\n * overlay, so without a name nothing on screen has a previous state to animate from and\n * a badge change CUTS instead of crossing. `island-avatar-continuity.test.tsx` is the\n * proof, and it is written against this exact shape.\n *\n * ONE AVATAR PER KEY, and this one is a constant — two of these widgets on a page would\n * claim to be the same avatar and hand each other their badges. The alternative is a key\n * per instance, and the package's own note rules that out: keys are never cleaned up, so\n * they must come from a bounded set. One island per page is the design.\n *\n * IT IS ALSO WHAT CROSSES THE TWO ISLANDS. The resting card and the first step of a\n * purchase are different components, and the same name is what lets the face carry from\n * one to the other rather than cutting when the buyer checks out.\n */\nexport const HERO_TRANSITION_KEY = 'checkout:hero';\n\n/**\n * AND MY BOOKING'S, WHICH IS A DIFFERENT FACE.\n *\n * A NAME SAYS \"THESE INSTANCES ARE THE SAME AVATAR\", so it must not be shared by two heroes\n * that are not. The flow's is the BUYER, carried from card to card as they answer; the\n * booking's is the RUN's artwork wearing a date, and then a ticketholder's initials. Sharing\n * the key would have the buyer's face hand its badge to a picture of an ice rink on the way\n * in — see `AvatarProps.transitionKey`, whose own note says one avatar per key.\n *\n * A constant for the same reason the other is: keys are never cleaned up, so they come from\n * a bounded set, and one booking island per page is the design.\n */\nexport const BOOKING_TRANSITION_KEY = 'booking:hero';\n\n/**\n * A badge as `step-cards` writes one — either shape, and NAMED, which is what lets the\n * avatar tell a question badge from a keyhole badge and cross between them.\n */\nexport type StepAccessory = {\n readonly shape: 'square' | 'circle';\n readonly content: ReactNode;\n readonly id?: string;\n};\n\n/**\n * The badge on the hero, or none.\n *\n * Written out per shape rather than passed through, because `AvatarAccessory` is a union\n * DISCRIMINATED on `shape` and a badge whose shape is `'square' | 'circle'` matches\n * neither arm until it is narrowed. The notch is cut from the shape — see the package —\n * so this is the point at which \"either\" has to become \"which\".\n */\nexport function heroAccessory(badge: StepAccessory | undefined): AvatarAccessory | null {\n if (badge === undefined) return null;\n return badge.shape === 'square'\n ? { shape: 'square', content: badge.content, id: badge.id }\n : { shape: 'circle', content: badge.content, id: badge.id };\n}\n\n/**\n * WHERE THE PIXELS COME FROM for a `default:<id>` — the avatar package owns the value\n * scheme and the consumer owns the images, which is its own stated contract, so a hero\n * cannot draw a stock face until it is handed the set that face was chosen from.\n *\n * BOTH ISLANDS NEED IT AND NEITHER OWNS IT: an authenticated buyer's stored avatar is a\n * `default:<id>` whether or not there is an order, so the account card at rest resolves\n * one exactly as the flow's hero does.\n */\nexport function avatarAssetsFor(photos: readonly ProfilePhoto[]): AvatarAssets {\n return {\n defaults: Object.fromEntries(photos.map((photo) => [photo.id, { normal: photo.url }])),\n };\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { Avatar } from '@scopetickets/avatar';\nimport { buyerAvatarValue, unassociatedPrompt } from '../domain/auth';\nimport { runCheckoutPreflight } from '../domain/checkout-preflight';\nimport { cartLines as cartLinesFrom, type CartLine } from '../domain/cart';\nimport { AUTH_COPY } from '../domain/auth-copy';\nimport { formatMoney, quoteLines } from '../domain/money';\nimport { raiseForSignIn, type NoticeAction, type NoticeId } from '../domain/notices';\nimport { passkeySignInCeremony } from '../domain/sign-in';\nimport { funnelOpen, funnelOpenedBy } from '../domain/auth-funnel';\nimport type { OrderIntent } from '../domain/order-intent';\nimport { ENVIRONMENT_URLS } from '@scopetickets/api';\nimport type { PurchaseStepId } from '../domain/purchase-steps';\nimport type { AuthSessionStore } from '../data/useAuthSession';\nimport { useCheckoutClient } from '../data/useCheckoutData';\nimport { useSignInGateway } from '../data/useSignInGateway';\nimport { usePasskeySignIn } from '../data/usePasskeySignIn';\nimport { useAuthFunnel } from '../data/useAuthFunnel';\nimport { useSessionGuard } from '../data/useSessionGuard';\nimport { useCheckoutOrder } from '../data/useCheckoutOrder';\nimport { useTicketFacts } from '../data/useTicketFacts';\nimport { CheckoutIsland } from './CheckoutIsland';\nimport { CartLines } from './CartLines';\nimport { avatarAssetsFor, heroAccessory, HERO_TRANSITION_KEY } from './island-hero';\nimport { holdExpired } from './island-escrow';\nimport {\n AUTH_CARDS,\n CART_VIEW,\n holdBadge,\n funnelViewProps,\n noticeViewProps,\n NOTICE_STATUS,\n RESTING_CART,\n restingCartViewProps,\n statusBadge,\n} from './step-cards';\nimport { PasskeyButton } from './PasskeyButton';\nimport type { CheckoutProps } from './ScopeTicketsCheckout';\n\n/**\n * THE ISLAND AT REST — what a host mounts on a page that is not checking anybody out yet.\n *\n * IT HAS TWO FACES AND ONE MOUNT, which is the whole reason it is one component. An empty\n * cart draws the `IDLE` checkpoint's card — sign in, welcome back, or \"you're ready to\n * go\". A cart with something in it draws the cart. Mounting those as two components would\n * make the change between them a REMOUNT, and a remount has nothing to transition from:\n * the island's two planes cross-fade and its surface morphs because the `contentKey`\n * changed underneath one host, not because one host replaced another.\n *\n * WHAT MAKES IT REACT. Everything below is derived from props on every render, so a host\n * that adds a product — the SDK holds its `Cart` in React state and re-renders on every\n * change — gets the new rows without telling the widget anything. A line ADDED does not\n * change the `contentKey`, deliberately: `IslandHost` observes the plane and grows the\n * surface to fit it, which is the difference between a cart that morphs and one that\n * cross-fades to itself. See the ResizeObserver there, whose comment names this case.\n *\n * WHAT IT DOES NOT DO IS POLL. A cart the widget only READ is read once — this library\n * runs inside somebody else's page, and a request every two seconds for the life of that\n * page is not ours to spend. A host whose cart changes hands in `cartLines` and `quote`,\n * which is the same contract the multi-page guide already states.\n */\nexport type RestingIslandProps = Omit<CheckoutProps, 'intent' | 'opensOn' | 'session'> & {\n /**\n * WHO IS BUYING, AND IT IS NOT THIS COMPONENT'S. The store is held above both faces of\n * the widget — see `ScopeTicketsCheckout` — because a buyer who signs in HERE and then\n * presses Check Out must arrive at the flow as the person they just became. Owned\n * locally, that sign-in would be dropped the moment the purchase island mounted and\n * seeded itself from the host's prop again.\n */\n readonly auth: AuthSessionStore;\n /**\n * WHAT IS BEING BOUGHT INTO, where there is anything. Absent is the unassociated mount:\n * the account card, and no cart face at all — a cart with nothing to check out into is\n * not a cart, it is a list.\n */\n readonly intent?: OrderIntent;\n /**\n * WHERE CHECK OUT GOES, with the step the checks resolved to. A callback rather than\n * this component mounting the flow itself: which island is showing is the widget's own\n * decision, and it is made in one place — see `ScopeTicketsCheckout`.\n */\n readonly onCheckOut?: (opensAt: PurchaseStepId) => void;\n};\n\nexport function RestingIsland({\n appKey,\n source,\n intent,\n userTypes = [],\n cart,\n cartLines,\n profilePhotos = [],\n auth,\n quote,\n hold,\n initialPresentation = 'card',\n mode = 'system',\n align = 'bottom',\n placement = 'page',\n simulate = false,\n onCheckOut,\n}: RestingIslandProps) {\n const session = auth.session;\n /* Seeded once, and then the prop has no further say — see `initialPresentation`. */\n const [expanded, setExpanded] = useState(initialPresentation === 'card');\n const toggle = useCallback(() => setExpanded((was) => !was), []);\n const close = useCallback(() => setExpanded(false), []);\n\n const client = useCheckoutClient(appKey, source);\n const avatarAssets = useMemo(() => avatarAssetsFor(profilePhotos), [profilePhotos]);\n const userTypeNames = useMemo(\n () => Object.fromEntries(userTypes.map((type) => [type.key, type.name])),\n [userTypes],\n );\n\n /*\n * THE HOST'S OWN CART, READ. `useCheckoutOrder` adopts rather than opens — the host made\n * this cart to hold the stock, and a second one for the same purchase is the failure the\n * `cart` prop exists to prevent. Nothing is added to it here: what is in it is the host's\n * statement, and this island's whole premise is that the host is still filling it.\n */\n const order = useCheckoutOrder(\n client,\n { eventKey: undefined, composition: {}, timeslot: undefined },\n undefined,\n cart !== undefined,\n cart?.key,\n userTypeNames,\n );\n\n const drawnQuote = quote ?? order.quote;\n const drawnHold = hold ?? order.hold;\n /*\n * THE HOLD ONLY WHILE IT IS STILL RUNNING. A ring at zero over a card that says nothing\n * about a clock is worse than no ring: the flow gives a lapsed hold a card of its own,\n * and this island has no order to have lost. Read once, because the badge and the\n * card's own sentence are two readings of it and must not disagree.\n */\n const running = drawnHold !== undefined && !holdExpired(drawnHold) ? drawnHold : undefined;\n /*\n * IS THERE MONEY TO DRAW — the cart screen's own question, asked here for the same\n * reason: the card is a statement of account and a total with no symbol in front of it\n * is a number a buyer would act on. A `NONE` quote carries no currency either.\n */\n const money =\n drawnQuote === undefined || drawnQuote.kind === 'NONE'\n ? undefined\n : { minorUnits: drawnQuote.minorUnits, currency: drawnQuote.currency };\n\n /* A host's own lines win, as they do in the flow: it may hold the split the wire does not. */\n const lines: readonly CartLine[] = useMemo(\n () => cartLines ?? cartLinesFrom(order.items, {}),\n [cartLines, order.items],\n );\n\n /*\n * WHETHER THE CART IS THE FACE. All three have to be true and each says something\n * different: there is somewhere to check out INTO, there is something IN it, and there\n * is a total to put under it.\n */\n const showsCart =\n intent !== undefined && onCheckOut !== undefined && lines.length > 0 && money !== undefined;\n\n const tickets = useTicketFacts(client, intent?.subject, intent?.day);\n const [checking, setChecking] = useState(false);\n /*\n * THE PRESS OUTLIVES THE COMPONENT. Reaching a destination is what unmounts this island,\n * and a host can take the widget off its page while the checks are still in flight — so\n * what comes back is dropped rather than written into a component that has gone.\n */\n const live = useRef(true);\n useEffect(() => {\n live.current = true;\n return () => {\n live.current = false;\n };\n }, []);\n\n const checkOut = useCallback(() => {\n if (intent === undefined || onCheckOut === undefined || checking) return;\n setChecking(true);\n runCheckoutPreflight({ intent, session, tickets })\n .then((outcome) => {\n if (!live.current) return;\n setChecking(false);\n onCheckOut(outcome.destination);\n })\n .catch(() => {\n /*\n * UNREACHABLE, AND CAUGHT ANYWAY. `runPreflight` turns a thrown check into a\n * destination — that is what `onError` is for — so nothing here rejects. A press\n * that silently did nothing would be the worst failure this button has, so the\n * button reopens rather than staying shut on a promise nobody can see.\n */\n if (live.current) setChecking(false);\n });\n }, [intent, onCheckOut, checking, session, tickets]);\n\n /*\n * THE CARD, AND WHAT THE PILL THAT OPENS IT SAYS — one value per face, so the two can\n * never disagree about which island this is.\n */\n const prompt = unassociatedPrompt(session.auth);\n const authCard = AUTH_CARDS[prompt.card];\n const heroSize = expanded ? 25 : 10;\n\n /*\n * ASKED OFF THE CARD AND NOT OFF THE SESSION, because `authPrompt` is what knows a\n * recognised buyer is offered a passkey — a second reading of that here is a second\n * thing to keep in step.\n */\n const offersPasskeySignIn = prompt.card === 'SIGN_IN_RECOGNISED';\n const passkeyEnvironment = ENVIRONMENT_URLS[source?.environment ?? 'production'];\n const signIns = useSignInGateway(client, simulate);\n const signIn = usePasskeySignIn(\n signIns,\n passkeyEnvironment.passkeyRpId,\n offersPasskeySignIn,\n auth,\n );\n\n /*\n * ONE SOURCE OF NOTICES WHERE THE FLOW HAS THREE: no order to fill and no account being\n * made, so signing in is the whole of what can go wrong here.\n */\n /* The funnel is not a step and has no stop in any walk, so an island with no walk can draw it. */\n const funnel = useAuthFunnel(signIns, auth);\n\n useSessionGuard(client, auth);\n\n const [noticeAnswered, setNoticeAnswered] = useState<NoticeId | null>(null);\n const raised = raiseForSignIn(signIn.state, funnel.state);\n const notice = raised === null || noticeAnswered === raised.id ? null : raised;\n const pressNotice = useCallback(\n (action: NoticeAction) => () => {\n /* A retry is not an answer — see the same rule in `ScopeTicketsCheckout`. */\n setNoticeAnswered(action.id === 'RETRY' ? null : (raised?.id ?? null));\n if (action.id === 'RETRY') {\n if (raised?.id === 'SIGN_IN_NOT_COMPLETED') signIn.retry();\n /* Reopened on nothing at all: `FAILED` carries no address and no password. */\n if (raised?.id === 'SIGN_IN_UNREACHABLE') funnel.open();\n }\n if (action.id === 'CLOSE') setExpanded(false);\n },\n [raised, signIn, funnel],\n );\n\n /* THE CLOCK OVER THE BUYER'S FACE — the badge the cart screen inside the flow wears. */\n const badge =\n showsCart && running !== undefined\n ? holdBadge(running)\n : heroAccessory(showsCart ? undefined : authCard.accessory);\n\n const hero = (\n <Avatar\n subject={{ kind: 'user', avatar: buyerAvatarValue(session.auth), assets: avatarAssets }}\n size={heroSize}\n fill\n accessory={badge}\n transitionKey={HERO_TRANSITION_KEY}\n />\n );\n\n /* In front of both faces: the cart underneath has not changed, and Close returns to it. */\n if (notice !== null) {\n return (\n <CheckoutIsland\n mode={mode}\n align={align}\n placement={placement}\n contentKey={`IDLE:NOTICE:${notice.id}`}\n avatar={\n <Avatar\n subject={{ kind: 'user', avatar: buyerAvatarValue(session.auth), assets: avatarAssets }}\n size={25}\n fill\n accessory={statusBadge(NOTICE_STATUS[notice.severity], 25)}\n transitionKey={HERO_TRANSITION_KEY}\n />\n }\n {...noticeViewProps(notice, pressNotice)}\n />\n );\n }\n\n /* Behind the notice and in front of everything else; the way back is the header's arrow. */\n if (funnelOpen(funnel.state)) {\n return (\n <CheckoutIsland\n mode={mode}\n align={align}\n placement={placement}\n /* One key for the whole funnel — see the same card in `ScopeTicketsCheckout`. */\n contentKey=\"IDLE:FUNNEL\"\n avatar={hero}\n {...funnelViewProps(funnel.state, {\n onChange: funnel.change,\n onSubmit: funnel.submit,\n onClose: funnel.close,\n })}\n />\n );\n }\n\n if (showsCart) {\n const total = formatMoney(money.minorUnits, money.currency);\n return (\n <CheckoutIsland\n mode={mode}\n align={align}\n placement={placement}\n expanded={expanded}\n /*\n * ONE KEY FOR THE WHOLE CART, however many rows are in it. Changing it per row\n * would cross-fade the card to itself every time the host added a ticket; leaving\n * it alone is what lets the surface simply grow. The face it changes against is\n * the account card, which is the transition worth having.\n */\n contentKey=\"IDLE:CART\"\n onToggle={toggle}\n avatar={hero}\n /*\n * THE PILL STATES THE CART AND ITS PRICE, and its action names the door the whole\n * island leads to — which is what `PURCHASE_STEPS` already does with this word:\n * the Sign In step's pill says \"Check Out\" and pressing it opens a card, not a\n * checkout. `CART_VIEW.label` is NOT this: that names the header's summary\n * control, which is a different control on a different card.\n */\n pillCopy={{ title: total, subtitle: CART_VIEW.title }}\n actionLabel={RESTING_CART.checkOut}\n {...restingCartViewProps(\n <CartLines\n lines={lines}\n totalMinorUnits={money.minorUnits}\n currency={money.currency}\n totalLabel={CART_VIEW.total}\n />,\n running,\n checkOut,\n close,\n checking,\n )}\n />\n );\n }\n\n const lead = drawnQuote === undefined ? null : quoteLines(drawnQuote);\n\n return (\n <CheckoutIsland\n mode={mode}\n align={align}\n placement={placement}\n expanded={expanded}\n contentKey={`IDLE:${prompt.card}`}\n onToggle={toggle}\n /* Nothing stands behind it: the way out of the one card is out of the island. */\n dismiss=\"close\"\n avatar={hero}\n title={authCard.copy.title}\n subtitle={authCard.copy.subtitle}\n /*\n * NO ORDER, NO PRICE, so the pill drops its text column rather than borrowing the\n * card's copy — which is what supplying this at all means. See `pillCopy`.\n */\n pillCopy={{ title: lead?.headline, subtitle: lead?.qualifier ?? undefined }}\n actionLabel={prompt.actionLabel}\n /*\n * THE PRIMARY IS AN IFRAME ON THE ONE CARD THAT OFFERS A PASSKEY. Only a document\n * under the RP id may use a credential and activation does not cross a frame, so\n * the button is drawn over there and stands here as the card's own content — the\n * same arrangement the flow's copy of this card uses.\n */\n input={\n offersPasskeySignIn ? (\n <PasskeyButton\n hostUrl={passkeyEnvironment.passkeyHostUrl}\n ceremony={passkeySignInCeremony(signIn.state)}\n label={AUTH_COPY.USE_PASSKEY}\n onResult={signIn.onResult}\n />\n ) : undefined\n }\n actions={authCard.actions\n .filter((action) => !(offersPasskeySignIn && action.label === AUTH_COPY.USE_PASSKEY))\n .map((action, position) => ({\n key: `${prompt.card}-${position}`,\n role: action.role,\n mark: action.mark,\n label: action.label,\n /*\n * THE LIST IS NO LONGER EMPTY. The passkey is not in it at all — it is the frame\n * above — and what is left unwired is `FORGOT_PASSWORD`, which is on no card.\n */\n onPress: funnelOpenedBy(action.label)\n ? () => funnel.open()\n : action.label === AUTH_COPY.SIGN_OUT\n ? () => {\n /* Both halves — see the same press in `ScopeTicketsCheckout`. */\n void signIns?.signOut();\n auth.signedOut();\n }\n : () => {},\n }))}\n />\n );\n}\n","/**\n * A generic, ordered sequence of checks run before committing a buyer to a flow. Ported\n * (UP-16), unchanged in substance — it had no React and no Reanimated in it, which is\n * exactly why it crosses to the web intact.\n */\n\nexport type PreflightStepResult<D> =\n /** This check has nothing to say; go on to the next one. */\n | { readonly status: 'CONTINUE' }\n /** This check decided. Nothing after it runs. */\n | { readonly status: 'RESOLVED'; readonly destination: D };\n\nexport type PreflightStep<C, D> = {\n /**\n * Stable id, for tracing which check decided — the one thing that is genuinely hard to\n * reconstruct afterwards when a flow goes somewhere unexpected.\n */\n readonly id: string;\n readonly run: (context: C) => Promise<PreflightStepResult<D>>;\n};\n\nexport const CONTINUE = { status: 'CONTINUE' } as const;\n\nexport function resolveTo<D>(destination: D): PreflightStepResult<D> {\n return { status: 'RESOLVED', destination };\n}\n\nexport type PreflightOutcome<D> = {\n readonly destination: D;\n /**\n * Every step that ran, in order, ending with whichever one resolved. Empty only when\n * there are no steps at all.\n */\n readonly ranStepIds: readonly string[];\n /**\n * The step that resolved, or `null` when every step continued and the fallback was\n * used.\n */\n readonly resolvedBy: string | null;\n};\n\nexport type RunPreflightOptions<D> = {\n /**\n * Used when every step continues. Passed in rather than defaulted here so this module\n * stays free of any particular flow's idea of \"normal\".\n */\n readonly fallback: D;\n /**\n * Turns a thrown step into a destination. A check that throws must not take the whole\n * flow down with it, and only the caller knows what its own failure state is.\n */\n readonly onError: (error: unknown, stepId: string) => D;\n};\n\n/** Runs `steps` in order and returns where to go. */\nexport async function runPreflight<C, D>(\n steps: readonly PreflightStep<C, D>[],\n context: C,\n { fallback, onError }: RunPreflightOptions<D>,\n): Promise<PreflightOutcome<D>> {\n const ranStepIds: string[] = [];\n\n for (const step of steps) {\n ranStepIds.push(step.id);\n let result: PreflightStepResult<D>;\n try {\n result = await step.run(context);\n } catch (error) {\n return { destination: onError(error, step.id), ranStepIds, resolvedBy: step.id };\n }\n if (result.status === 'RESOLVED') {\n return { destination: result.destination, ranStepIds, resolvedBy: step.id };\n }\n }\n\n return { destination: fallback, ranStepIds, resolvedBy: null };\n}\n","/**\n * THE CHECKS BEHIND \"CHECK OUT\" — what runs between a buyer pressing it and the flow\n * opening, and which card it opens on.\n *\n * `preflight.ts` is the machine and has no idea what a purchase is. This is the purchase:\n * six checks in the buyer's own order, each answering \"is this one still to be asked?\",\n * the first that says yes deciding where the flow opens, and Order Review when none of\n * them does. Every id here is a `PurchaseStep.preflightStepId` — the steps have named\n * their own check since they were written, and nothing ran them.\n *\n * ── WHY IT IS ASYNC, WHICH IS THE WHOLE REASON IT IS NOT `walkPurchase` ──────\n *\n * The walk answers from an intent that is already in hand. Two of these cannot: whether\n * the day sells sessions and whether the event asks its own questions are the TICKETS'\n * to say, and `PurchaseStep.excusedWhen` for Select Time spells out what a synchronous\n * answer costs — \"a sync answer would report 'no timeslots' for a request still in flight\n * and walk the buyer straight past the picker\". So those two READ, at the moment they are\n * reached, and the four that can answer from the intent run first and often spare the\n * request entirely.\n *\n * ── AND WHY IT IS NOT A SECOND SOURCE OF TRUTH ──────────────────────────────\n *\n * Every synchronous check here asks `excusedByIntent`, which is the same function the\n * walk's `FlowSituation.excused` is built from. Nothing restates a rule: this decides\n * WHEN each rule is asked and what a read adds to it. `checkout-preflight.test.ts` binds\n * the destination to `walkPurchase`'s first stop given the same facts, so a rule that\n * changes in one place and not the other fails there rather than in a buyer's flow.\n */\n\nimport { authPrompt, requirementGate, type AuthSession } from './auth';\nimport { excusedByIntent, type OrderIntent } from './order-intent';\nimport { CONTINUE, resolveTo, runPreflight, type PreflightStep } from './preflight';\nimport type { PreflightOutcome } from './preflight';\nimport type { PurchaseStepId } from './purchase-steps';\n\n/**\n * WHAT ONLY THE TICKETS CAN SAY. Both come off one `getEventTickets`, which is why they\n * are one value: two readers would be two requests for one answer.\n */\nexport type TicketFacts = {\n /** `HasTimeslot` on any ticket of the event the buyer's day resolved to. */\n readonly sellsSessions: boolean;\n /** Whether those tickets carry questions of their own — see `OrderIntent.asksQuestions`. */\n readonly asksQuestions: boolean;\n};\n\nexport type CheckoutPreflightContext = {\n /** Everything the host and the buyer have answered so far. */\n readonly intent: OrderIntent;\n /** Who is buying, as the sign-in check reads it. */\n readonly session: AuthSession;\n /**\n * THE READ, INJECTED. A domain module does not hold a client — and the caller is also\n * the only thing that can answer this ONCE for a whole run, which it must: two checks\n * ask, and a buyer pressing Check Out should not pay for the same request twice.\n */\n readonly tickets: () => Promise<TicketFacts>;\n};\n\n/**\n * WHERE A CHECK SENDS A BUYER — declared apart from the checks for two reasons, and both\n * are about failure rather than tidiness.\n *\n * A CHECK THAT THROWS STILL HAS TO LAND SOMEWHERE. `runPreflight` hands a thrown step to\n * `onError`, and the honest destination is the card that check guards: a read that failed\n * has not said the question does not arise, so the buyer meets it rather than being\n * carried past a question nobody answered. Select Time GATES without its picker — see\n * `stepAnswered` — which is what makes that the safe direction.\n *\n * AND IT BINDS THE IDS TO THE STEPS. Every key is a `PurchaseStep.preflightStepId`, and\n * `checkout-preflight.test.ts` asserts the two lists are the same set.\n */\nexport const PREFLIGHT_GUARDS: Readonly<Record<string, PurchaseStepId>> = {\n 'party-size': 'PARTY',\n 'series-date': 'DATE',\n 'select-time': 'TIME',\n 'signed-in': 'SIGN_IN',\n /* The first of the three it covers, which is the order the buyer meets them in. */\n 'order-requirements': 'NAME',\n questionnaire: 'DETAILS',\n};\n\n/**\n * WHERE A PURCHASE OPENS WHEN NOTHING IS LEFT TO ASK — the button that charges, which is\n * what \"everything is answered\" means.\n */\nexport const NOTHING_LEFT_TO_ASK: PurchaseStepId = 'REVIEW';\n\n/** The three the account can answer, in the order the flow asks them. */\nconst REQUIREMENTS = ['NAME', 'EMAIL', 'PHONE'] as const;\n\nexport const CHECKOUT_PREFLIGHT: readonly PreflightStep<\n CheckoutPreflightContext,\n PurchaseStepId\n>[] = [\n {\n id: 'party-size',\n /* Cheapest first, and it costs no request and no account — the step's own blurb. */\n run: async ({ intent }) =>\n excusedByIntent(intent).includes('PARTY') ? CONTINUE : resolveTo('PARTY'),\n },\n {\n id: 'series-date',\n /* An event subject settles the day by being an event; a series with one has answered. */\n run: async ({ intent }) =>\n excusedByIntent(intent).includes('DATE') ? CONTINUE : resolveTo('DATE'),\n },\n {\n id: 'select-time',\n run: async ({ intent, tickets }) => {\n /* A slot already chosen needs no read: the question has been answered. */\n if (excusedByIntent(intent).includes('TIME')) return CONTINUE;\n const { sellsSessions } = await tickets();\n return sellsSessions ? resolveTo('TIME') : CONTINUE;\n },\n },\n {\n id: 'signed-in',\n /*\n * THE CHECKPOINT DECIDES, not this. `authPrompt` owns all nine cells; a bypass there\n * is an authenticated buyer, a guest, or a host that handed the identity in, and all\n * three walk past without a card.\n */\n run: async ({ session }) =>\n authPrompt('ORDER_CREATED', session).kind === 'CARD' ? resolveTo('SIGN_IN') : CONTINUE,\n },\n {\n id: 'order-requirements',\n /*\n * THE INTENT FIRST, THEN THE ACCOUNT — the order `walkPurchase` uses. A host that\n * supplied the buyer's name has answered it, and an account answers what the host did\n * not. A lapsed session's details are not spendable; `requirementGate` says why.\n */\n run: async ({ intent, session }) => {\n const excused = excusedByIntent(intent);\n for (const requirement of REQUIREMENTS) {\n if (excused.includes(requirement)) continue;\n if (requirementGate(session.auth, requirement).kind === 'ANSWERED') continue;\n return resolveTo(requirement);\n }\n return CONTINUE;\n },\n },\n {\n id: 'questionnaire',\n run: async ({ intent, tickets }) => {\n /* Answers already collected are answers; the gate has nothing left to gate. */\n if (intent.answers !== undefined) return CONTINUE;\n const { asksQuestions } = await tickets();\n return asksQuestions ? resolveTo('DETAILS') : CONTINUE;\n },\n },\n];\n\n/**\n * RUN THEM, AND SAY WHERE THE FLOW OPENS. The outcome carries `ranStepIds` and\n * `resolvedBy` as well, which is the one thing that is genuinely hard to reconstruct\n * afterwards when a buyer lands somewhere unexpected.\n */\nexport function runCheckoutPreflight(\n context: CheckoutPreflightContext,\n): Promise<PreflightOutcome<PurchaseStepId>> {\n return runPreflight(CHECKOUT_PREFLIGHT, context, {\n fallback: NOTHING_LEFT_TO_ASK,\n onError: (error, stepId) => {\n /*\n * SAID OUT LOUD. A check that failed sends the buyer to the card it guards, which\n * looks from the outside exactly like a check that decided — and the difference is\n * the whole of what somebody debugging needs.\n */\n if (typeof console !== 'undefined') {\n console.warn(\n `[ScopeTicketsCheckout] the '${stepId}' check failed, so the flow opens on the ` +\n 'card it guards rather than passing it.',\n error,\n );\n }\n return PREFLIGHT_GUARDS[stepId] ?? NOTHING_LEFT_TO_ASK;\n },\n });\n}\n","import { useCallback, useMemo, useRef } from 'react';\nimport type { ScopeClient } from '@scopetickets/api';\nimport type { TicketFacts } from '../domain/checkout-preflight';\nimport type { OrderSubject } from '../domain/order-intent';\n\n/**\n * THE ONE READ BEHIND \"CHECK OUT\" — whether the day sells sessions, and whether the event\n * asks its own questions.\n *\n * Both come off `getEventTickets`, so they are one request rather than two: `HasTimeslot`\n * decides the first (never the presence of a `Timeslots` array — see `useCheckoutData`,\n * which learned that the expensive way) and `Questions` the second.\n *\n * ── WHY A READ AND NOT THE HOOK NEXT DOOR ────────────────────────────────────\n *\n * `useCheckoutData` holds both facts already, and reading them from there would have been\n * free. It would also have been wrong at the only moment that matters: its answer is\n * `undefined` until its request lands, and a preflight that took that for \"no sessions\"\n * would walk the buyer past the picker — which is the failure `PurchaseStep.excusedWhen`\n * for Select Time is written about. So this asks, at the moment it is asked.\n *\n * ONCE PER PRESS. The two checks that need it both call the function this returns, and it\n * hands back the same promise for the same subject and day — one request for one press,\n * and a fresh one the next time anything about the order changes.\n */\nexport function useTicketFacts(\n client: ScopeClient | null,\n subject: OrderSubject | undefined,\n /** The chosen day, for a series. Ignored on an event subject, which carries its own. */\n day: string | undefined,\n): () => Promise<TicketFacts> {\n /*\n * KEYED, so a buyer who changes their day and presses again is not answered about the\n * old one. Held in a ref rather than state because nothing DRAWS this: it is a request\n * in flight, and re-rendering the island when it lands is the caller's business.\n */\n const cached = useRef<{ key: string; facts: Promise<TicketFacts> } | null>(null);\n const key = useMemo(\n () => (subject === undefined ? '' : `${subject.kind}:${subject.key}:${day ?? ''}`),\n [subject, day],\n );\n\n return useCallback(() => {\n if (cached.current?.key === key) return cached.current.facts;\n const facts = read(client, subject, day);\n cached.current = { key, facts };\n return facts;\n }, [client, subject, day, key]);\n}\n\n/**\n * NOTHING ASKED IS NOTHING TO ASK ABOUT. With no client or no subject there is no request\n * to make, and the honest answer is the one that adds no step: a preflight cannot invent\n * a question the platform never said was there.\n */\nconst NOTHING: TicketFacts = { sellsSessions: false, asksQuestions: false };\n\nasync function read(\n client: ScopeClient | null,\n subject: OrderSubject | undefined,\n day: string | undefined,\n): Promise<TicketFacts> {\n if (client === null || subject === undefined) return NOTHING;\n\n const eventKey = await eventKeyFor(client, subject, day);\n if (eventKey === null) return NOTHING;\n\n const tickets = await client.getEventTickets(eventKey);\n return {\n sellsSessions: tickets.some((ticket) => ticket.HasTimeslot),\n asksQuestions: tickets.some((ticket) => (ticket.Questions ?? []).length > 0),\n };\n}\n\n/**\n * WHICH EVENT'S TICKETS. An event subject IS the answer; a series is a run of them and the\n * day is what resolves which — the same join `useCheckoutData` makes, and the reason a\n * series with no day chosen has no tickets to read. It never reaches here: `series-date`\n * runs first and resolves to the calendar.\n */\nasync function eventKeyFor(\n client: ScopeClient,\n subject: OrderSubject,\n day: string | undefined,\n): Promise<string | null> {\n if (subject.kind === 'event') return subject.key;\n if (day === undefined) return null;\n\n const info = await client.getSeriesInfo(subject.key);\n return info.Events.find((event) => event.Date.slice(0, 10) === day)?.Key ?? null;\n}\n","import { useCallback, useMemo, useState, type ReactNode } from 'react';\nimport {\n Avatar,\n type AvatarAccessory,\n type AvatarSize,\n type AvatarAssets,\n} from '@scopetickets/avatar';\nimport {\n backFrom,\n dressBooking,\n holderChanged,\n holderComplete,\n holderName,\n occasionTime,\n ticketAt,\n ticketGate,\n ticketQualifier,\n ticketTitle,\n type Booking,\n type BookingOccasion,\n type BookingRecord,\n type BookingScreen,\n type BookingTicket,\n type TicketAttribution,\n type Ticketholder,\n} from '../domain/booking';\nimport { emailFlag, emailFlagTitle, isValidEmail } from '../domain/contact';\nimport { flagTone } from './ContentFlag';\nimport { raiseForBooking, type NoticeAction } from '../domain/notices';\nimport { useBooking, useBookingGateway } from '../data/useBooking';\nimport { useTicketCodes } from '../data/useTicketCodes';\nimport { useCheckoutClient, type CheckoutSource } from '../data/useCheckoutData';\nimport { CheckoutIsland } from './CheckoutIsland';\nimport { QuickActions } from './QuickActions';\nimport { TextField } from './TextField';\nimport { TicketCodePager, TicketCodes, type TicketCodeEntry } from './TicketCodes';\nimport { TicketsInBooking, type TicketRow } from './TicketsInBooking';\nimport {\n BOOKING_BADGES,\n BOOKING_COPY,\n CodeGlyph,\n EditGlyph,\n SendGlyph,\n bookingDismiss,\n} from './booking-cards';\nimport { formatDayDate, formatWeekdayAndDate } from './island-calendar';\nimport { BOOKING_TRANSITION_KEY } from './island-hero';\nimport { NOTICE_STATUS, noticeViewProps, statusBadge } from './step-cards';\nimport type { IslandAlignment, IslandPlacement } from './island-geometry';\nimport type { IslandMode } from './island-theme';\n\nexport type BookingIslandProps = {\n /** WHICH IMPLEMENTATION IS ASKING — the Bearer token, as everywhere else here. */\n readonly appKey: string;\n readonly source?: CheckoutSource;\n /**\n * THE CART THE BOOKING WAS MADE FROM, and not the transaction's key.\n *\n * `Transactions/ByKey/{cartKey}` is the one endpoint that answers with a holder per\n * ticket, and it takes this. The transaction's own key comes back inside the response and\n * is what a save is addressed to — see `bookingGateway`.\n */\n readonly cartKey: string;\n /**\n * WHAT WAS BOUGHT INTO. The caller's, because the platform does not answer for it — see\n * `BookingOccasion`, where that is argued.\n */\n readonly occasion: BookingOccasion;\n /** The product and the user type per ticket, where the caller knows them. */\n readonly attribution?: TicketAttribution;\n /**\n * THE BUYER'S OWN FACE, for the pill and for nothing else — see the root card, where the\n * collapsed island shows WHOSE booking this is and the opened one shows WHAT it is.\n *\n * Absent draws the guest placeholder, which is what a booking opened on its own page by\n * a host that has no session gets: `buyerAvatarValue` never answers null, so this is\n * only ever unset by a caller that does not know.\n */\n readonly buyerAvatar?: string;\n /** Where a `default:<id>` gets its pixels — see `avatarAssetsFor`. */\n readonly buyerAvatarAssets?: AvatarAssets;\n /**\n * THE TICKETS, WHERE THE CALLER HAS ALREADY READ THEM — see `useBooking`'s own note. A\n * host mounting this on a cold page has not, and leaves it out.\n */\n readonly seed?: BookingRecord;\n /**\n * THE WALLET BADGE, AS THE HOST'S OWN NODE — not a press this widget paints a button for.\n *\n * ── WHY THIS ONE IS A `ReactNode` WHERE EVERY OTHER CONTROL HERE IS A CALLBACK ──\n *\n * \"Add to Apple Wallet\" is APPLE'S MARK, and its size, corner, ground, lock-up and\n * wording are theirs to specify and ours to reproduce exactly or not at all. Painting an\n * approximation of it in this design system's tokens — which is what a callback would\n * oblige — produces a black pill with the right words and none of the right anything\n * else, sitting on a card where every other control is ours.\n *\n * There is no `.pkpass` endpoint on the platform either, so the press has nothing here to\n * do. Both halves are the host's, so the whole control is: it is given the slot the design\n * draws it in, centred above the rule, and this file neither paints it nor presses it.\n *\n * ABSENT DRAWS NOTHING, which is what the platform can honour today.\n */\n readonly walletBadge?: (ticketKey: string) => ReactNode;\n readonly initialPresentation?: 'pill' | 'card';\n readonly mode?: IslandMode;\n readonly align?: IslandAlignment;\n readonly placement?: IslandPlacement;\n};\n\n/** Nothing is asked for until the codes card is open — one array, so the hook's key holds. */\nconst NO_CODES: readonly string[] = [];\n\n/**\n * MY BOOKING — the last face of the widget, and the only one that is not a purchase.\n *\n * ── FOUR CARDS AND ONE MOUNT ─────────────────────────────────────────────────\n *\n * The booking, every code, one ticket, and who that ticket is for. They are one component\n * for the reason `RestingIsland`'s two faces are: the island's planes cross-fade and its\n * surface morphs because the `contentKey` changed underneath ONE host. Four components would\n * make every move between them a remount, and a remount has nothing to transition from.\n *\n * ── IT IS NOT A WALK ─────────────────────────────────────────────────────────\n *\n * Nothing here is a step. There is no order to complete, nothing is excused, and no card\n * gates the one after it — so there is no `PurchaseStep`, no preflight and no `at` index.\n * What there is instead is a TREE, and `backFrom` is the whole of it.\n *\n * ── AND IT IS REACHABLE TWICE ────────────────────────────────────────────────\n *\n * `ScopeTicketsCheckout` hands over to it when a purchase finishes, and a host can mount it\n * on its own page with a cart key. Both are the same component with the same props, which is\n * why the occasion arrives as data rather than being read out of a flow that may not exist.\n */\nexport function BookingIsland({\n appKey,\n source,\n cartKey,\n occasion,\n attribution = {},\n buyerAvatar,\n buyerAvatarAssets,\n seed,\n walletBadge,\n initialPresentation = 'card',\n mode = 'system',\n align = 'bottom',\n placement = 'page',\n}: BookingIslandProps) {\n /* Seeded once, and then the prop has no further say — `RestingIsland`'s own reading. */\n const [expanded, setExpanded] = useState(initialPresentation === 'card');\n\n const [screen, setScreen] = useState<BookingScreen>({ kind: 'BOOKING' });\n /**\n * WHAT THE BUYER HAS TYPED, or `null` when the form is not open.\n *\n * SEEDED BY THE PRESS THAT OPENS THE CARD rather than by an effect watching the screen.\n * An effect would re-seed on every render that changed the record — which is exactly what\n * a successful save does — and wipe what the buyer was typing as they typed it.\n */\n const [draft, setDraft] = useState<Ticketholder | null>(null);\n\n const client = useCheckoutClient(appKey, source);\n const gateway = useBookingGateway(client);\n const booking = useBooking(gateway, cartKey, seed);\n\n /*\n * DRESSED ON EVERY RENDER AND DELIBERATELY NOT MEMOISED. The fold is a `map` over a\n * handful of rows; a `useMemo` keyed on two objects most callers write inline would run\n * every render anyway and cost a comparison on top. See `dressBooking`.\n */\n const dressed =\n booking.state.status === 'LOADED'\n ? dressBooking(booking.state.record, occasion, attribution)\n : null;\n\n /*\n * THE SCREEN, WITH A DEAD TICKET FORGIVEN.\n *\n * `TICKET` and `EDIT` name a ticket by key, and a key the booking does not carry has no\n * card to draw. Unreachable while a record only ever has its holders amended, and answered\n * rather than thrown: a crash inside somebody else's page is not this widget's to cause.\n *\n * DERIVED, NOT SET. Correcting it with `setScreen` from a render is legal and is one more\n * thing that can loop; there is nothing to remember, because the next render asks again.\n */\n const showing = resolveScreen(screen, dressed);\n\n /*\n * THE CODES ARE ASKED FOR WHEN THE CARD OPENS AND NOT BEFORE. A booking of six that is\n * never opened costs the platform nothing; see `useTicketCodes`, which fetches the whole\n * run at once because the carousel shows a neighbour on each side.\n */\n const codeKeys = useMemo(\n () =>\n showing.kind === 'CODES' && dressed !== null ? dressed.tickets.map((t) => t.key) : NO_CODES,\n [showing.kind, dressed],\n );\n const codes = useTicketCodes(gateway, codeKeys);\n\n /* The booking is handed to `backFrom` because the form's way out depends on it — see the\n gate. Both readings ask the same call, so the glyph and the press cannot disagree. */\n const dismiss = bookingDismiss(backFrom(showing, dressed));\n /*\n * THE ISLAND'S ONE CONTROL, in both states — and it was only ever wired for one.\n *\n * Every card passes this as `onToggle`, which is the PILL's action as well as the\n * header's way out. Collapsed, the only thing it can mean is \"open\"; it meant\n * `setExpanded(false)` instead, so a booking mounted as a pill could not be opened at\n * all and the press did nothing. `toggle` was declared for exactly this and then\n * overridden by every card that spread `common`.\n *\n * Expanded it is what it always was: back where there is somewhere to go, out where\n * there is not.\n */\n const onDismiss = useCallback(() => {\n if (!expanded) {\n setExpanded(true);\n return;\n }\n const to = backFrom(showing, dressed);\n if (to === null) setExpanded(false);\n else setScreen(to);\n }, [expanded, showing, dressed]);\n\n const openTicket = useCallback(\n (ticketKey: string) => setScreen({ kind: 'TICKET', ticketKey }),\n [],\n );\n const openCodes = useCallback((at: number) => setScreen({ kind: 'CODES', at }), []);\n /** Where a copy of the ticket is being sent — the card's own field. */\n const [sendTo, setSendTo] = useState('');\n const openEdit = useCallback((ticket: BookingTicket) => {\n setDraft(ticket.holder);\n setScreen({ kind: 'EDIT', ticketKey: ticket.key });\n }, []);\n /*\n * THE FIELD OPENS ON THE HOLDER'S OWN ADDRESS, where the ticket has one — a buyer sending\n * a ticket to the person it belongs to should not have to type what the card already\n * knows, and one sending it elsewhere clears a field rather than filling one.\n *\n * AND A STANDING OUTCOME IS PUT AWAY. \"Sent to alex@…\" belongs to the send that produced\n * it; carrying it onto a fresh card would tell a buyer their ticket had gone before they\n * pressed anything.\n */\n const openSend = useCallback(\n (ticket: BookingTicket) => {\n booking.clearSend();\n setSendTo(ticket.holder.email);\n setScreen({ kind: 'SEND', ticketKey: ticket.key });\n },\n [booking],\n );\n\n /**\n * THE ONE THING ON THESE FOUR CARDS THAT WRITES, and its whole aftermath.\n *\n * ONE FUNCTION BECAUSE THERE ARE TWO WAYS IN: the form's own Save, and Try Again on the\n * notice a failed save raised. Written twice, the second would be the one that forgot to\n * take the buyer back to the ticket — and a retry that silently worked while leaving them\n * on the form looks exactly like one that did nothing.\n *\n * THE DRAFT IS DROPPED ONLY ON SUCCESS. A refused save leaves what they typed in front of\n * them; reopening the form after a save that landed seeds from the record.\n */\n const commitHolder = useCallback(\n (ticket: BookingTicket, holder: Ticketholder) => {\n void booking.saveHolder(ticket, holder).then((took) => {\n if (!took) return;\n setDraft(null);\n setScreen({ kind: 'TICKET', ticketKey: ticket.key });\n });\n },\n [booking],\n );\n\n /*\n * WHAT A FAILED SAVE WOULD BE SENT AGAIN — the ticket it was for and the holder that was\n * typed, or `null` where the buyer is not on the form. Derived rather than remembered:\n * both halves are already state, and a third copy taken at the moment of failure is a\n * third thing to keep in step.\n */\n const retryable =\n showing.kind === 'EDIT' && dressed !== null && draft !== null\n ? (() => {\n const ticket = ticketAt(dressed, showing.ticketKey);\n return ticket === null ? null : { ticket, holder: draft };\n })()\n : null;\n\n // ── What went wrong, in front of everything ───────────────\n /*\n * THE NOTICE IS A READING OF THE STATE AND NOTHING ELSE — no \"already answered\" flag\n * beside it.\n *\n * THAT FLAG IS THE OBVIOUS THING TO REACH FOR AND IT IS A BUG HERE. Every button on\n * every one of these notices CLEARS the state that raised it, so the flag would be\n * redundant on the way in and wrong on the way out: it holds the last id that was\n * dismissed, and the second refusal of the same corrected save carries the same id — so\n * a buyer who fixed their address, saved, and was refused again would be shown nothing\n * at all. See `RestingIsland`, which can keep one because a passkey refusal there is not\n * something the card underneath can clear.\n */\n const notice = raiseForBooking(booking.state, booking.save);\n const pressNotice = useCallback(\n (action: NoticeAction) => () => {\n switch (action.id) {\n case 'RETRY':\n /*\n * TWO DIFFERENT RETRIES, one word. A booking that would not load is asked for\n * again; a save that never reached the platform is SENT again, with what the\n * buyer typed — it is still in hand, which is the whole reason the form keeps it.\n */\n if (booking.state.status === 'ERROR') booking.retry();\n else if (retryable !== null) commitHolder(retryable.ticket, retryable.holder);\n else booking.clearSave();\n return;\n case 'CONTINUE':\n /* \"Back To Details\" — the form is still behind this card with what they typed. */\n booking.clearSave();\n return;\n case 'CLOSE':\n /*\n * THE FAILURE HAS BEEN READ. Clearing the save puts the buyer back on their form\n * rather than on this card when they open the island again; a read that failed is\n * deliberately NOT cleared, because there is nothing else to draw.\n */\n booking.clearSave();\n setExpanded(false);\n return;\n default:\n /* The other two ids belong to the order and to the account, and reach no card here. */\n return;\n }\n },\n [booking, commitHolder, retryable],\n );\n\n const common = { mode, align, placement, expanded, onToggle: onDismiss } as const;\n\n if (notice !== null) {\n return (\n <CheckoutIsland\n {...common}\n contentKey={`BOOKING:NOTICE:${notice.id}`}\n avatar={\n <Avatar\n subject={{ kind: 'event', src: occasion.artwork ?? '', alt: '' }}\n size={25}\n fill\n accessory={statusBadge(NOTICE_STATUS[notice.severity], 25)}\n transitionKey={BOOKING_TRANSITION_KEY}\n />\n }\n {...noticeViewProps(notice, pressNotice)}\n />\n );\n }\n\n // ── Before there is anything to draw ──────────────────────\n if (dressed === null) {\n const waiting = booking.state.status === 'LOADING';\n return (\n <CheckoutIsland\n {...common}\n contentKey={waiting ? 'BOOKING:LOADING' : 'BOOKING:NONE'}\n dismiss=\"close\"\n avatar={\n <Avatar\n subject={{ kind: 'event', src: occasion.artwork ?? '', alt: '' }}\n size={expanded ? 25 : 10}\n fill\n transitionKey={BOOKING_TRANSITION_KEY}\n />\n }\n title={waiting ? BOOKING_COPY.loadingTitle : BOOKING_COPY.noneTitle}\n subtitle={waiting ? BOOKING_COPY.loadingSubtitle : BOOKING_COPY.noneSubtitle}\n pillCopy={{ title: occasion.name, subtitle: formatDayDate(occasion.day) }}\n actionLabel={BOOKING_COPY.title}\n /*\n * NO BUTTON WHILE IT LOADS. A wait with a Close under it invites a buyer to leave\n * the thing they are waiting for; the header's cross is still there for anyone who\n * means it.\n *\n * AND ASKING AGAIN LEADS WHEN IT IS OVER — see `BOOKING_COPY.noneSubtitle`. The read\n * can be earlier than the platform's own indexing of a transaction it finalized a\n * second ago, so an empty answer is not necessarily a lasting one.\n */\n actions={\n waiting\n ? []\n : [\n {\n key: 'booking-none-retry',\n role: 'primary',\n label: BOOKING_COPY.retry,\n onPress: booking.retry,\n },\n {\n key: 'booking-none-close',\n role: 'secondary',\n label: BOOKING_COPY.close,\n onPress: () => setExpanded(false),\n },\n ]\n }\n />\n );\n }\n\n const pill = {\n title: occasion.name,\n subtitle: formatDayDate(occasion.day),\n };\n\n // ── The root ──────────────────────────────────────────────\n if (showing.kind === 'BOOKING') {\n const time = occasionTime(occasion);\n const rows: readonly TicketRow[] = dressed.tickets.map((ticket) => {\n const named = holderName(ticket.holder);\n return {\n key: ticket.key,\n holder: named ?? BOOKING_COPY.awaiting,\n awaiting: named === null,\n qualifier: ticket.userType ?? ticket.product,\n /*\n * OFFERED EXACTLY WHERE IT DELIVERS. Every ticket a read can draw can be named —\n * the save is addressed by the ticket's own key, which is in hand — so the pill\n * appears on every row with nobody on it and never promises a form the platform\n * would refuse. See `BookingGateway.saveHolder`.\n */\n ...(named === null ? { add: BOOKING_COPY.add } : {}),\n };\n });\n\n return (\n <CheckoutIsland\n {...common}\n contentKey=\"BOOKING:ROOT\"\n dismiss={dismiss}\n onToggle={onDismiss}\n /*\n * ── THE PILL IS WHOSE, THE CARD IS WHAT ─────────────────────────────\n *\n * OPENED, the hero is the RUN with the day on it: the buyer is looking at a\n * booking and what they need is which one.\n *\n * COLLAPSED, it is the BUYER with the run on it — the same two pictures, swapped.\n * A pill is one small circle on somebody else's page and it is the widget's whole\n * presence there; drawn as the event it is an advert for a thing already bought,\n * and drawn as the buyer it is their booking, waiting.\n */\n avatar={\n expanded ? (\n <Avatar\n subject={{ kind: 'event', src: occasion.artwork ?? '', alt: '' }}\n size={25}\n fill\n accessory={BOOKING_BADGES.day(occasion.day, 25)}\n transitionKey={BOOKING_TRANSITION_KEY}\n />\n ) : (\n <Avatar\n subject={{ kind: 'user', avatar: buyerAvatar ?? null, assets: buyerAvatarAssets }}\n size={10}\n fill\n accessory={{\n shape: 'square',\n content: (\n <Avatar\n subject={{ kind: 'event', src: occasion.artwork ?? '', alt: '' }}\n size={10}\n fill\n />\n ),\n id: 'booking:run',\n }}\n transitionKey={BOOKING_TRANSITION_KEY}\n />\n )\n }\n title={BOOKING_COPY.title}\n /* Two lines, and the design sets them as two: the run, then the day it ran. */\n subtitle={\n <span className=\"scopetickets-island-booking__lines\">\n <span>{occasion.name}</span>\n <span>{formatDayDate(occasion.day)}</span>\n </span>\n }\n /*\n * NO WORDS BESIDE IT — and SUPPLIED EMPTY rather than omitted, which is the whole\n * of `pillCopy`'s contract: leaving it out keeps the CARD's copy, so the pill would\n * have gone on saying \"Booking Details\" over the run.\n *\n * Every other screen's pill borrows the run and the day, because there the island\n * is standing in for a card the buyer was reading. This one is the widget at rest:\n * the face says whose booking it is and the button says what pressing it does, and\n * the run's name between them is a third thing to read before either.\n */\n pillCopy={{}}\n actionLabel={BOOKING_COPY.myBooking}\n input={\n <div className=\"scopetickets-island-booking\">\n {/*\n * THE SESSION, ABOVE THE TICKETS AND BELOW THE DAY — the design's own line, a\n * step brighter than the two above it because it is the only part of the\n * occasion that is not already on the hero.\n */}\n {time === null ? null : <p className=\"scopetickets-island-booking__time\">{time}</p>}\n <TicketsInBooking tickets={rows} onOpen={openTicket} />\n </div>\n }\n actions={[\n {\n key: 'booking-codes',\n role: 'secondary',\n label: BOOKING_COPY.showCodes,\n mark: { side: 'leading', node: <CodeGlyph /> },\n onPress: () => openCodes(0),\n },\n ]}\n />\n );\n }\n\n // ── Every code ────────────────────────────────────────────\n if (showing.kind === 'CODES') {\n const entries: readonly TicketCodeEntry[] = dressed.tickets.map((ticket) => {\n const name = holderName(ticket.holder) ?? BOOKING_COPY.awaiting;\n return {\n key: ticket.key,\n qualifier: ticketQualifier(ticket),\n name,\n avatar: holderFace(ticket.holder),\n day: formatDayDate(occasion.day),\n time: occasion.startTime,\n code: codes[ticket.key] ?? { status: 'LOADING' },\n codeLabel: BOOKING_COPY.codeLabel(name),\n codeMissing: BOOKING_COPY.codeMissing,\n };\n });\n\n return (\n <CheckoutIsland\n {...common}\n contentKey=\"BOOKING:CODES\"\n dismiss={dismiss}\n onToggle={onDismiss}\n /* NO HERO. The card opens on the tickets, which is the picker layout's own argument:\n the buyer pressed Show QRs and what they asked for is the run itself. */\n pillCopy={pill}\n actionLabel={BOOKING_COPY.codes}\n input={\n <TicketCodes\n tickets={entries}\n at={showing.at}\n onAtChange={openCodes}\n label={BOOKING_COPY.codesRegion}\n />\n }\n /*\n * THE PAGER STANDS WHERE THE BUTTONS STAND, in the same wrapper — see\n * `IslandCardProps.footer`. It is not an `IslandAction` because it is one label\n * between two presses, but it is the card's control and it belongs at the card's\n * foot: drawn inside the content instead, it would sit in the scroll and take the\n * gutter a second time.\n */\n actions={[]}\n footer={\n <TicketCodePager\n at={showing.at}\n count={entries.length}\n onAtChange={openCodes}\n position={BOOKING_COPY.position(showing.at)}\n positionOf={BOOKING_COPY.positionOf(entries.length)}\n previousLabel={BOOKING_COPY.previous}\n nextLabel={BOOKING_COPY.next}\n />\n }\n />\n );\n }\n\n /* Non-null past `resolveScreen`, which is what turns an unknown key back into the root. */\n const ticket = ticketAt(dressed, showing.ticketKey) as BookingTicket;\n\n const name = holderName(ticket.holder) ?? BOOKING_COPY.awaiting;\n const qualifier = ticketQualifier(ticket);\n\n // ── One ticket ────────────────────────────────────────────\n if (showing.kind === 'TICKET') {\n return (\n <CheckoutIsland\n {...common}\n contentKey={`BOOKING:TICKET:${ticket.key}`}\n dismiss={dismiss}\n onToggle={onDismiss}\n title={ticketTitle(ticket.holder) ?? BOOKING_COPY.ticketFallbackTitle}\n subtitle={\n <span className=\"scopetickets-island-booking__lines\">\n {qualifier === null ? null : <span>{qualifier}</span>}\n <span>{formatWeekdayAndDate(occasion.day)}</span>\n {occasionTime(occasion) === null ? null : <span>{occasionTime(occasion)}</span>}\n </span>\n }\n pillCopy={{ title: name, subtitle: qualifier ?? occasion.name }}\n actionLabel={BOOKING_COPY.title}\n input={\n <div className=\"scopetickets-island-booking scopetickets-island-booking--ticket\">\n {walletBadge === undefined ? null : (\n <div className=\"scopetickets-island-booking__wallet\">{walletBadge(ticket.key)}</div>\n )}\n {/* The design's `ConstructionLine` — the quick actions are not the card's copy. */}\n <span className=\"scopetickets-island-booking__rule\" aria-hidden=\"true\" />\n <QuickActions\n actions={[\n {\n key: 'ticket-code',\n glyph: <CodeGlyph size={24} />,\n lines: BOOKING_COPY.showCodeLines,\n onPress: () => openCodes(indexOfTicket(dressed.tickets, ticket.key)),\n },\n {\n key: 'ticket-holder',\n glyph: <EditGlyph size={24} />,\n lines: BOOKING_COPY.editHolderLines,\n onPress: () => openEdit(ticket),\n },\n {\n key: 'ticket-send',\n glyph: <SendGlyph size={24} />,\n lines: BOOKING_COPY.sendTicketLines,\n /*\n * ADDRESSED BY THE NUMERIC ID, which some tickets arrive without — the\n * summary-only fallback, where the list did not answer. Drawn and inert\n * rather than missing, so two tickets side by side offer the same three\n * controls; the Edit action beside it needs no such mercy, being addressed\n * by the key every ticket has.\n */\n disabled: ticket.attendeeTicketId <= 0,\n onPress: () => openSend(ticket),\n },\n ]}\n />\n </div>\n }\n actions={[]}\n />\n );\n }\n\n // ── A copy of it, to an address ───────────────────────────\n if (showing.kind === 'SEND') {\n const sending = booking.send.status === 'SENDING';\n const sent = booking.send.status === 'SENT' ? booking.send : null;\n const failed = booking.send.status === 'FAILED';\n /*\n * THE ADDRESS HAS TO BE ONE, and the card says so with the same mark the holder form\n * uses — the platform would refuse a malformed one anyway, and being told by the field\n * you are standing in beats being told by a card two presses later.\n *\n * AND NOT THE ONE ALREADY SENT TO. Pressing Send again on an unchanged field is a\n * second email to the same inbox, which is the one mistake a `GET` that sends mail\n * makes easy — so the button goes quiet until the buyer changes something.\n */\n const address = sendTo.trim();\n const sendable = isValidEmail(address) && !sending && address !== sent?.email;\n\n return (\n <CheckoutIsland\n {...common}\n contentKey={`BOOKING:SEND:${ticket.key}`}\n dismiss={dismiss}\n onToggle={onDismiss}\n avatar={holderFace(ticket.holder, {\n size: expanded ? 25 : 10,\n accessory: BOOKING_BADGES.send,\n transitionKey: BOOKING_TRANSITION_KEY,\n })}\n title={BOOKING_COPY.sendTicket}\n subtitle={\n sent !== null\n ? BOOKING_COPY.sentTo(sent.email)\n : failed\n ? BOOKING_COPY.sendFailed\n : BOOKING_COPY.sendPrompt\n }\n pillCopy={{ title: name, subtitle: BOOKING_COPY.sendTicket }}\n actionLabel={BOOKING_COPY.sendTicket}\n input={\n <div className=\"scopetickets-island-booking__form\">\n <TextField\n id=\"send-ticket-email\"\n label={BOOKING_COPY.email}\n value={sendTo}\n onChange={setSendTo}\n type=\"email\"\n inputMode=\"email\"\n autoComplete=\"email\"\n autoCapitalize=\"none\"\n prose={false}\n enterKeyHint=\"go\"\n flag={\n sent !== null && address === sent.email ? 'success' : flagTone(emailFlag(sendTo))\n }\n flagTitle={\n sent !== null && address === sent.email ? undefined : emailFlagTitle(sendTo)\n }\n />\n </div>\n }\n actions={[\n {\n key: 'send-ticket',\n role: 'primary',\n label: sending ? BOOKING_COPY.sending : BOOKING_COPY.send,\n disabled: !sendable,\n onPress: () => void booking.sendTicket(ticket, address),\n },\n ]}\n />\n );\n }\n\n // ── Who the ticket is for ─────────────────────────────────\n const held = draft ?? ticket.holder;\n const saving = booking.save.status === 'SAVING';\n const sendable = holderComplete(held) && holderChanged(ticket.holder, held);\n const change = (field: keyof Ticketholder) => (value: string) =>\n setDraft({ ...held, [field]: value });\n\n return (\n <CheckoutIsland\n {...common}\n contentKey={`BOOKING:EDIT:${ticket.key}`}\n dismiss={dismiss}\n onToggle={onDismiss}\n /*\n * THE HOLDER'S OWN FACE OR NONE — see `holderFace`. Every ticket this widget sells\n * today comes back without one, so this card is usually heroless, and that is the\n * design's answer rather than a gap to fill: the pencil badge said what the card was\n * for, and it was sitting on a mark made out of the name in the field below it.\n */\n avatar={holderFace(held, {\n size: expanded ? 25 : 10,\n accessory: BOOKING_BADGES.edit,\n transitionKey: BOOKING_TRANSITION_KEY,\n })}\n title={BOOKING_COPY.editHolder}\n subtitle={qualifier ?? undefined}\n pillCopy={{ title: name, subtitle: BOOKING_COPY.editHolder }}\n actionLabel={BOOKING_COPY.editHolder}\n input={\n <div className=\"scopetickets-island-booking__form\">\n {/*\n * `maxLength` 50 ON ALL THREE, because that is the platform's own `maxLength` on\n * every field the save carries — without it a buyer who types past the line is\n * told by a notice two presses later rather than by the field they are standing\n * in. See `SetItemAttendeeRequest`, which is the wire's own shape.\n */}\n <TextField\n label={BOOKING_COPY.firstName}\n value={held.firstName}\n onChange={change('firstName')}\n maxLength={50}\n autoComplete=\"given-name\"\n autoCapitalize=\"words\"\n prose={false}\n enterKeyHint=\"next\"\n />\n <TextField\n label={BOOKING_COPY.lastName}\n value={held.lastName}\n onChange={change('lastName')}\n maxLength={50}\n autoComplete=\"family-name\"\n autoCapitalize=\"words\"\n prose={false}\n enterKeyHint=\"next\"\n />\n <TextField\n label={BOOKING_COPY.email}\n value={held.email}\n onChange={change('email')}\n maxLength={50}\n type=\"email\"\n inputMode=\"email\"\n autoComplete=\"email\"\n autoCapitalize=\"none\"\n prose={false}\n enterKeyHint=\"done\"\n /* The one field in this package that checks itself as it is typed — the same\n mark and the same suspected-typo warning the flow's own email step draws. */\n flag={flagTone(emailFlag(held.email))}\n flagTitle={emailFlagTitle(held.email)}\n />\n </div>\n }\n actions={[\n {\n key: 'edit-save',\n role: 'primary',\n label: saving ? BOOKING_COPY.saving : BOOKING_COPY.save,\n disabled: saving || !sendable,\n onPress: () => commitHolder(ticket, held),\n },\n ]}\n />\n );\n}\n\n/**\n * WHICH CARD A SCREEN ACTUALLY LANDS ON — the two corrections, both DERIVED.\n *\n * A TICKET THAT IS NOT IN THE BOOKING becomes the root. Unreachable while a record only\n * ever has its holders amended, and answered rather than thrown: a crash inside somebody\n * else's page is not this widget's to cause.\n *\n * AND A TICKET NOBODY IS NAMED ON OPENS ITS FORM — see `ticketGate`, which is the rule and\n * is asked here rather than at the press. The row, the row's own `Add` pill and the header's\n * Back all go through this, so there is one answer to \"what is behind this ticket\" instead\n * of three that can drift apart.\n *\n * THE FORM SEEDS ITSELF FROM THE RECORD when it is reached this way — `draft ?? ticket.\n * holder` is what the card reads, so a screen that became `EDIT` without a press has\n * exactly what a press would have put there.\n */\nfunction resolveScreen(screen: BookingScreen, booking: Booking | null): BookingScreen {\n if (booking === null) return screen;\n if (screen.kind !== 'TICKET' && screen.kind !== 'EDIT') return screen;\n\n const gate = ticketGate(booking, screen.ticketKey);\n switch (gate.kind) {\n case 'ABSENT':\n return { kind: 'BOOKING' };\n case 'CLOSED':\n return { kind: 'EDIT', ticketKey: screen.ticketKey };\n case 'OPEN':\n return screen;\n default: {\n const exhaustive: never = gate;\n return exhaustive;\n }\n }\n}\n\n/** Which ticket in the run, so Show QR from a ticket opens on THAT ticket's code. */\nfunction indexOfTicket(tickets: readonly BookingTicket[], key: string): number {\n return Math.max(\n tickets.findIndex((ticket) => ticket.key === key),\n 0,\n );\n}\n\n/**\n * A TICKETHOLDER'S FACE, AND ONLY WHERE THE PLATFORM HOLDS ONE.\n *\n * ── INITIALS ARE NOT A FACE ──────────────────────────────────────────────────\n *\n * They are a thing this package can always manufacture, which is exactly why they are the\n * wrong answer on a ticket: the mark claims to show somebody, and what it shows is two\n * letters taken off a name printed an inch to its left. It says nothing the row does not\n * and it makes every ticket in a booking look like it has a photo.\n *\n * So an absent photo draws NOTHING — not a generated mark, and not some substitute of this\n * file's own devising. The card closes up around its words, which is what the design does\n * with a holder it has no picture for.\n *\n * ── ONE FUNCTION, BECAUSE TWO CARDS ASK IT ───────────────────────────────────\n *\n * The codes card puts a face over each ticket and the Edit card wears one as its hero. The\n * Edit card drew `initials:` here — the exact mark this rule exists to forbid, on the one\n * screen where the name it is derived from is being typed two lines below it. Written out\n * at each site, the rule held in one place and not the other; asked once, it cannot.\n *\n * `undefined` AND NOT `null`: both slots take the node from a caller, and `IslandCard`\n * reserves the hero's 100 pixels for anything that is not absent.\n */\nfunction holderFace(\n holder: Ticketholder,\n /* The hero states a size per presentation and a badge; a ticket's own face takes both defaults. */\n { size = 10, accessory, transitionKey }: HolderFaceSlot = {},\n): ReactNode | undefined {\n if (holder.photo === null) return undefined;\n\n return (\n <Avatar\n subject={{ kind: 'user', avatar: holder.photo, alt: '' }}\n size={size}\n fill\n {...(accessory === undefined ? {} : { accessory })}\n {...(transitionKey === undefined ? {} : { transitionKey })}\n />\n );\n}\n\n/**\n * Where a face is being drawn. Spread rather than passed through, because `Avatar` reads\n * an absent `accessory` and a `null` one as the same thing and a `transitionKey` names an\n * avatar ACROSS rebuilds — one key per avatar, so a row of ticket faces must not carry the\n * hero's.\n */\ntype HolderFaceSlot = {\n readonly size?: AvatarSize;\n readonly accessory?: AvatarAccessory;\n readonly transitionKey?: string;\n};\n","import { useEffect, useState } from 'react';\nimport type { BookingGateway } from '../domain/booking';\nimport { ticketCodeDataUrl } from '../domain/ticket-code';\n\n/**\n * ONE TICKET'S CODE, as one value.\n *\n * A union rather than a picture beside an error, so \"still fetching\" cannot be mistaken for\n * \"came back empty\" — which is the difference between a ticket that is about to appear and\n * a buyer standing at a gate with nothing to show.\n */\nexport type TicketCode =\n | { readonly status: 'LOADING' }\n /** Ready to draw: a `data:` URL an `<img>` can take. See `ticketCodeDataUrl`. */\n | { readonly status: 'DRAWN'; readonly src: string }\n | { readonly status: 'ERROR' };\n\nconst LOADING: TicketCode = { status: 'LOADING' };\n\n/** Every code on the card, keyed by the ticket key each was drawn from. */\nexport type TicketCodes = Readonly<Record<string, TicketCode>>;\n\n/**\n * THE CODES FOR A RUN OF TICKETS.\n *\n * ── ALL OF THEM, AND ONLY WHEN THEY ARE ASKED FOR ────────────────────────────\n *\n * The carousel shows one code and half of each neighbour, so a booking of four needs four\n * codes the moment it opens — fetching the visible one and chasing the rest as the buyer\n * scrolls would put a blank ticket under every swipe. What keeps that honest is the CALLER:\n * `keys` is empty until the codes screen is open, so a buyer who never presses Show QRs\n * costs the platform nothing.\n *\n * ── WHY THE KEYS ARE JOINED ──────────────────────────────────────────────────\n *\n * An array is a new identity on every render, so the effect keys on the run's contents\n * rather than on the array holding them. A newline is the separator because a ticket key is\n * a URL-safe token and cannot contain one — a comma is not safe on that argument.\n *\n * ── AND WHY A FAILED CODE IS NOT A NOTICE ────────────────────────────────────\n *\n * One code failing is one blank ticket in a run of four, and the card says so in place —\n * see `TicketCode`'s `ERROR`, which the ticket draws as a stated absence. Raising a notice\n * would take the whole booking off screen to report a picture.\n */\nexport function useTicketCodes(\n gateway: BookingGateway | null,\n keys: readonly string[],\n): TicketCodes {\n const [codes, setCodes] = useState<TicketCodes>({});\n const run = keys.join('\\n');\n\n useEffect(() => {\n const wanted = run === '' ? [] : run.split('\\n');\n if (gateway === null || wanted.length === 0) {\n setCodes({});\n return undefined;\n }\n\n let live = true;\n setCodes(Object.fromEntries(wanted.map((key) => [key, LOADING])));\n\n for (const key of wanted) {\n gateway\n .code(key)\n .then((svg) => {\n if (!live) return;\n /*\n * ONE KEY AT A TIME, FOLDED INTO WHATEVER HAS LANDED. The requests finish in\n * whatever order the network gives them, so each writes its own entry rather than\n * replacing the map — the first to land would otherwise erase the others' pending\n * marks and the run would draw as one ticket.\n */\n setCodes((was) => ({\n ...was,\n [key]:\n svg === null ? { status: 'ERROR' } : { status: 'DRAWN', src: ticketCodeDataUrl(svg) },\n }));\n })\n .catch(() => {\n if (!live) return;\n setCodes((was) => ({ ...was, [key]: { status: 'ERROR' } }));\n });\n }\n\n return () => {\n live = false;\n };\n }, [gateway, run]);\n\n return codes;\n}\n","import type { ReactNode } from 'react';\nimport { useIslandPress } from './island-press';\n\n/** One quick action: a glyph in a ring, and what it does, in two short words. */\nexport type QuickAction = {\n readonly key: string;\n readonly glyph: ReactNode;\n /**\n * THE WORDS, AS LINES. The design sets \"Show / QR\" and \"Edit / Ticketholder\" on two lines\n * each, and it is not a wrap — it is where the phrase breaks. A single string broken by\n * the column's width would put \"Edit Ticket\" over \"holder\" on a narrow card, so the break\n * is the caller's and the accessible name is the lines joined.\n */\n readonly lines: readonly string[];\n readonly disabled?: boolean;\n readonly onPress: () => void;\n};\n\nexport type QuickActionsProps = {\n readonly actions: readonly QuickAction[];\n};\n\n/**\n * THE ROW OF QUICK ACTIONS under a ticket — the design's `QuickAction`, twice.\n *\n * NOT BUTTONS IN THE CARD'S OWN STACK, and the difference is what they mean. The stack at\n * the foot of a card is what the card is FOR — Save, Continue, Close — and these are the\n * two things a buyer might do with a ticket they are already looking at. The design draws\n * them above the stack, apart, under a hairline, and gives them a shape of their own.\n *\n * EQUAL COLUMNS whatever the count, so two read as a pair rather than as one control and a\n * leftover.\n */\nexport function QuickActions({ actions }: QuickActionsProps) {\n return (\n <div className=\"scopetickets-island-quick\">\n {actions.map((action) => (\n <QuickActionButton key={action.key} action={action} />\n ))}\n </div>\n );\n}\n\nfunction QuickActionButton({ action }: { action: QuickAction }) {\n const press = useIslandPress('element');\n\n return (\n <button\n type=\"button\"\n className=\"scopetickets-island-quick__action\"\n aria-label={action.lines.join(' ')}\n /* Drawn and inert, never removed — see `IslandAction.disabled`, which is the same\n reading for the same reason: a control that vanishes is a control a buyer goes\n looking for. */\n aria-disabled={action.disabled === true ? true : undefined}\n onClick={action.disabled === true ? undefined : action.onPress}\n data-disabled={action.disabled === true ? '' : undefined}\n {...press}\n >\n <span className=\"scopetickets-island-quick__ring\" aria-hidden=\"true\">\n {action.glyph}\n </span>\n {/* The label is inside the button's own name above, so the lines are decoration. */}\n <span className=\"scopetickets-island-quick__label\" aria-hidden=\"true\">\n {action.lines.map((line) => (\n <span key={line}>{line}</span>\n ))}\n </span>\n </button>\n );\n}\n","import {\n useCallback,\n useLayoutEffect,\n useRef,\n useState,\n type CSSProperties,\n type PointerEvent,\n type ReactNode,\n} from 'react';\nimport { ArrowLeftIcon, ArrowRightIcon } from '@scopetickets/icons';\nimport { TicketCode, type TicketCodeProps } from './TicketCode';\nimport { fitTicketEdge, TICKET_EDGE_FALLBACK, type TicketEdgeTokens } from './island-ticket-edge';\nimport { useIslandPress } from './island-press';\n\n/** One ticket in the run: everything its own card draws, plus what names it. */\nexport type TicketCodeEntry = TicketCodeProps & { readonly key: string };\n\nexport type TicketCodesProps = {\n readonly tickets: readonly TicketCodeEntry[];\n /** Which ticket is on screen, counted from zero. */\n readonly at: number;\n /** Reported as the run moves — from the live offset, not once it has settled. */\n readonly onAtChange: (at: number) => void;\n /** Names the run for assistive technology. */\n readonly label: string;\n};\n\n/**\n * THE CODES, ONE AT A TIME, WITH THE NEXT ONE SHOWING.\n *\n * ── IT IS THE WEEK STRIP, WITH TICKETS IN IT ─────────────────────────────────\n *\n * The mechanism is `CalendarWeekSection`'s and deliberately so: a scroll-snapping pager that\n * BLEEDS past the content column on both sides, so the ends of the previous and next tickets\n * show. Stopping at the column cuts the run off mid-air with nothing to say there is\n * anywhere to scroll to — which on a booking of one ticket and a booking of four look\n * identical.\n *\n * THE BLEED IS THE CARD'S OWN INLINE PADDING, referenced rather than restated. One bleed is\n * `$7`, which is enough of a neighbouring ticket to read as a ticket rather than a stripe.\n *\n * ── WHY THE INDEX IS REPORTED AND NOT OWNED ──────────────────────────────────\n *\n * The pager button under the run says \"1 of 3\" and its arrows move the run, so the number\n * and the scroll position are two readings of one fact. Owned here, the button would need\n * to reach in for it; owned by the caller, both come from the same value. What this keeps\n * is the SCROLL, which is the browser's.\n */\nexport function TicketCodes({ tickets, at, onAtChange, label }: TicketCodesProps) {\n const wrapRef = useRef<HTMLDivElement | null>(null);\n const pagerRef = useRef<HTMLDivElement | null>(null);\n const pageRefs = useRef<(HTMLDivElement | null)[]>([]);\n /*\n * THE LAST INDEX THIS COMPONENT REPORTED. Without it the two halves fight: scrolling\n * reports a page, the caller stores it, and the effect below reads the new value as an\n * instruction to scroll there — mid-gesture, under the finger. Compared here, a value that\n * came back from our own report moves nothing and only the ARROWS reposition the run.\n */\n const reported = useRef(at);\n const [run, setRun] = useState<CodeRun | null>(null);\n\n /*\n * HOW WIDE A TICKET IS, AND THEREFORE HOW THE RUN IS LAID OUT — measured here rather than\n * left to CSS, because a ticket's width is not a percentage of anything: it is a whole\n * number of cutouts, so it lands up to one cutout short of the room on offer. See\n * `codeRun`, which is the arithmetic.\n */\n const measure = useCallback(() => {\n const node = wrapRef.current;\n if (!node) return;\n const next = codeRun(node.clientWidth, readCodeTokens(node));\n setRun((current) => (sameRun(current, next) ? current : next));\n }, []);\n\n useLayoutEffect(() => {\n measure();\n const node = wrapRef.current;\n if (!node || typeof ResizeObserver === 'undefined') return undefined;\n const observer = new ResizeObserver(() => measure());\n observer.observe(node);\n return () => observer.disconnect();\n }, [measure]);\n\n /** How far one ticket is from the next — a page plus the seam after it. */\n const strideOf = (pager: HTMLDivElement): number => {\n const first = pageRefs.current[0];\n const second = pageRefs.current[1];\n if (first && second) return second.offsetLeft - first.offsetLeft;\n return first?.offsetWidth ?? pager.clientWidth;\n };\n\n /** The dimming, on the live offset — and which ticket the edge is nearest. */\n const paint = useCallback(() => {\n const pager = pagerRef.current;\n if (!pager) return;\n const stride = strideOf(pager);\n if (stride <= 0) return;\n const offset = pager.scrollLeft / stride;\n\n pageRefs.current.forEach((page, index) => {\n if (!page) return;\n page.style.setProperty(\n '--scopetickets-island-code-distance',\n String(Math.min(Math.abs(index - offset), 1)),\n );\n });\n\n const page = Math.min(Math.max(Math.round(offset), 0), Math.max(tickets.length - 1, 0));\n if (page === reported.current) return;\n reported.current = page;\n onAtChange(page);\n }, [tickets.length, onAtChange]);\n\n /** Where the run rests, applied BEFORE paint. */\n useLayoutEffect(() => {\n const pager = pagerRef.current;\n if (!pager) return;\n if (at !== reported.current) {\n reported.current = at;\n /* `scrollTo` rather than the property, so an arrow press GLIDES and a first layout\n does not — the browser honours `behavior: smooth` only once there is somewhere to\n glide from. */\n pager.scrollTo({ left: at * strideOf(pager), behavior: 'smooth' });\n }\n paint();\n }, [at, paint, run]);\n\n /*\n * ── DRAGGING THE RUN ────────────────────────────────────────────────────────\n *\n * A MOUSE ONLY. Touch and trackpad already scroll this natively and far better than\n * anything here could; taking their pointer would replace a momentum scroll with a\n * translation. A mouse has no such gesture, and a run of tickets that a finger can throw\n * and a cursor cannot even nudge is a control that works on half the devices it is on.\n *\n * SNAPPING IS OFF WHILE THE DRAG IS LIVE, because mandatory snapping and a script setting\n * `scrollLeft` every frame are two things steering one scroller: the browser pulls back to\n * the nearest page between moves and the run judders against the cursor. It is turned back\n * on at the end, and the release is what chooses the page.\n */\n const drag = useRef<{ x: number; from: number; moved: boolean } | null>(null);\n const [dragging, setDragging] = useState(false);\n\n const onPointerDown = (event: PointerEvent<HTMLDivElement>) => {\n const pager = pagerRef.current;\n if (!pager || event.pointerType !== 'mouse' || (event.buttons & 1) !== 1) return;\n drag.current = { x: event.clientX, from: pager.scrollLeft, moved: false };\n };\n\n const onPointerMove = (event: PointerEvent<HTMLDivElement>) => {\n const pager = pagerRef.current;\n const held = drag.current;\n if (!pager || held === null) return;\n const dx = event.clientX - held.x;\n\n if (!held.moved) {\n /* Below the threshold it is a click and belongs to whatever was clicked. */\n if (Math.abs(dx) < CODE_DRAG_SLOP) return;\n held.moved = true;\n setDragging(true);\n event.currentTarget.setPointerCapture(event.pointerId);\n }\n pager.scrollLeft = held.from - dx;\n };\n\n const release = useCallback(() => {\n const pager = pagerRef.current;\n const held = drag.current;\n drag.current = null;\n if (!pager || held === null || !held.moved) return;\n setDragging(false);\n\n /*\n * THE RELEASE CHOOSES THE PAGE rather than handing the scroller back and letting\n * snapping decide. The two would usually agree; where they did not, the number under the\n * run would say one ticket and the run would rest on another.\n */\n const stride = strideOf(pager);\n if (stride <= 0) return;\n const landed = Math.min(\n Math.max(Math.round(pager.scrollLeft / stride), 0),\n Math.max(tickets.length - 1, 0),\n );\n reported.current = landed;\n pager.scrollTo({ left: landed * stride, behavior: 'smooth' });\n onAtChange(landed);\n }, [tickets.length, onAtChange]);\n\n if (tickets.length === 0) return null;\n\n return (\n <div className=\"scopetickets-island-codes\" ref={wrapRef}>\n <div\n ref={pagerRef}\n className=\"scopetickets-island-codes__pager\"\n /*\n * A group rather than a scroll region: the pager button below is the control that\n * names which ticket is showing, and announcing this as scrollable promises a\n * gesture assistive technology would have to make to reach the others.\n */\n role=\"group\"\n aria-label={label}\n data-dragging={dragging ? '' : undefined}\n style={run === null ? undefined : runStyle(run)}\n onScroll={paint}\n onPointerDown={onPointerDown}\n onPointerMove={onPointerMove}\n onPointerUp={release}\n onPointerCancel={release}\n >\n {tickets.map((ticket, index) => (\n <div\n key={ticket.key}\n className=\"scopetickets-island-codes__page\"\n ref={(node) => {\n pageRefs.current[index] = node;\n }}\n >\n <TicketCode {...ticket} />\n </div>\n ))}\n </div>\n </div>\n );\n}\n\n/** How far a mouse must travel before it is a drag rather than a click. */\nconst CODE_DRAG_SLOP = 4;\n\n/** How the run is laid out, in px — all three derived from one measurement. */\ntype CodeRun = {\n /** One ticket's outside width: a whole number of cutouts, rails included. */\n readonly frame: number;\n /** Half the leftover, at each end of the run, so EVERY page can come to rest centred. */\n readonly pad: number;\n /** The seam between two tickets — what is left of the pad once the peek is taken out. */\n readonly gap: number;\n};\n\n/**\n * WHAT A RUN OF TICKETS MEASURES.\n *\n * ── THE TICKET IS THE COLUMN'S; THE RUN IS THE CARD'S ────────────────────────\n *\n * `available` is the CARD's full width, because the run bleeds into the card's own inline\n * padding and the neighbours enter from the card's edge rather than from the content\n * column's. A ticket, though, is sized against the COLUMN — that is the measure the design\n * draws it at, and at `$2`/`$6`/`$3` in a 326 card it comes out at exactly the 256 the node\n * carries.\n *\n * ── WHY THE FRAME IS NOT A PERCENTAGE OF ANYTHING ────────────────────────────\n *\n * A ticket is a whole number of cutouts, so it lands up to one cutout short of the room it\n * was offered. A page sized to the column would hold one with an arbitrary band of nothing\n * at each side, and what shows past the card's edge would be that nothing rather than the\n * next ticket. So the page is sized to the FRAME, which only `fitTicketEdge` can say.\n *\n * ── AND WHY THE PADDING IS WHAT CENTRES IT ───────────────────────────────────\n *\n * With half the leftover as padding at each end, page `k` comes to rest centred at exactly\n * `k * (frame + gap)` — including the first, at zero, and the last. `scroll-snap-align:\n * center` on its own cannot do that: the first and last pages have nothing beyond them to\n * centre against and stick to the ends.\n *\n * THE PEEK IS THEN A SUBTRACTION. At rest the neighbour's near edge stands `pad - gap` from\n * the card's edge, so a seam of `pad - peek` puts exactly `peek` of the next ticket on\n * screen.\n */\nfunction codeRun(available: number, tokens: CodeTokens): CodeRun | null {\n const fit = fitTicketEdge(available - 2 * tokens.inset, 0, tokens.edge);\n if (!fit.ok) return null;\n\n const pad = (available - fit.frame) / 2;\n /* The bleed is `inset` at each end and the frame is at most the column, so `pad >= inset`\n — but a host that tunes the peek past it would otherwise ask for a negative seam. */\n return { frame: fit.frame, pad, gap: Math.max(pad - tokens.peek, 0) };\n}\n\nfunction runStyle(run: CodeRun): CSSProperties {\n return {\n '--scopetickets-island-code-frame': `${run.frame}px`,\n '--scopetickets-island-code-pad': `${run.pad}px`,\n '--scopetickets-island-code-gap': `${run.gap}px`,\n } as CSSProperties;\n}\n\n/** Sub-pixel jitter from a ResizeObserver must not re-lay a run that has not moved. */\nfunction sameRun(current: CodeRun | null, next: CodeRun | null): boolean {\n if (current === null || next === null) return current === next;\n return current.frame === next.frame && Math.abs(current.pad - next.pad) < 0.5;\n}\n\ntype CodeTokens = {\n /** How far the neighbouring tickets enter the card — `$4`, the design's own. */\n readonly peek: number;\n /** The card's own inline padding: what the run bleeds by, and what a ticket is sized in. */\n readonly inset: number;\n readonly edge: TicketEdgeTokens;\n};\n\n/** The run's own numbers, off the theme, so a host that re-tunes the scale re-lays the run. */\nfunction readCodeTokens(node: Element): CodeTokens {\n const fallback = { peek: 16, inset: 28, edge: TICKET_EDGE_FALLBACK };\n if (typeof getComputedStyle !== 'function') return fallback;\n const style = getComputedStyle(node);\n const px = (name: string, miss: number): number => {\n const value = Number.parseFloat(style.getPropertyValue(name));\n return Number.isFinite(value) && value > 0 ? value : miss;\n };\n const edge = {\n edge: px('--scopetickets-island-space-2', TICKET_EDGE_FALLBACK.edge),\n segment: px('--scopetickets-island-space-6', TICKET_EDGE_FALLBACK.segment),\n pad: px('--scopetickets-island-space-3', TICKET_EDGE_FALLBACK.pad),\n gap: px('--scopetickets-island-space-2', TICKET_EDGE_FALLBACK.gap),\n };\n return {\n peek: px('--scopetickets-island-space-4', 16),\n inset: px('--scopetickets-island-padding-inline', 28),\n edge,\n };\n}\n\nexport type TicketCodePagerProps = {\n readonly at: number;\n readonly count: number;\n readonly onAtChange: (at: number) => void;\n /** \"1\" — the ticket being read, full strength. */\n readonly position: string;\n /** \" of 3\" — the run it is out of, a step quieter. See `BOOKING_COPY.positionOf`. */\n readonly positionOf: string;\n /** What the two arrows are called, for anyone who cannot see them. */\n readonly previousLabel: string;\n readonly nextLabel: string;\n};\n\n/**\n * WHICH TICKET IS SHOWING, AND THE TWO WAYS TO CHANGE IT — the design's pill under the run.\n *\n * ── NOT ONE OF THE CARD'S OWN BUTTONS, AND IT CANNOT BE ─────────────────────\n *\n * `IslandAction` is one label and one press. This is one label between TWO presses, so it\n * lives in the card's content where a control with its own shape belongs, and the codes\n * card draws no button stack at all. The way out of it is the header's Back arrow, which is\n * what the design gives it.\n *\n * ── THE ENDS ARE SHUT, NOT WRAPPED ──────────────────────────────────────────\n *\n * A run of three that goes 3 -> 1 reads as a bug the first time and as a lost ticket the\n * second. The arrow at an end is drawn and declines, exactly as every other stopped control\n * here does — see `IslandAction.disabled`.\n *\n * ── AND A BOOKING OF ONE STILL GETS IT ──────────────────────────────────────\n *\n * It used to be withheld below two, on the argument that \"1 of 1\" between two dead arrows\n * is three controls describing a run with no alternatives. What that actually produced was\n * a card that changes SHAPE with the size of the booking: one ticket and the run sits on\n * the card's floor, two and a pill appears under it. The count is the thing that varies,\n * not the card, and both arrows decline here exactly as the end of any longer run does.\n */\nexport function TicketCodePager({\n at,\n count,\n onAtChange,\n position,\n positionOf,\n previousLabel,\n nextLabel,\n}: TicketCodePagerProps) {\n return (\n <div className=\"scopetickets-island-codes__pager-control\">\n <PagerArrow\n label={previousLabel}\n disabled={at <= 0}\n onPress={() => onAtChange(at - 1)}\n glyph={<ArrowLeftIcon size={16} color=\"currentColor\" />}\n />\n {/*\n * `aria-live` because this is the only thing on the card that says which ticket is in\n * front of the buyer, and it changes under a gesture that announces nothing. Polite:\n * it is a position, not news.\n */}\n <span className=\"scopetickets-island-codes__position\" aria-live=\"polite\">\n {position}\n <span className=\"scopetickets-island-codes__position-of\">{positionOf}</span>\n </span>\n <PagerArrow\n label={nextLabel}\n disabled={at >= count - 1}\n onPress={() => onAtChange(at + 1)}\n glyph={<ArrowRightIcon size={16} color=\"currentColor\" />}\n />\n </div>\n );\n}\n\nfunction PagerArrow({\n label,\n disabled,\n onPress,\n glyph,\n}: {\n label: string;\n disabled: boolean;\n onPress: () => void;\n glyph: ReactNode;\n}) {\n const press = useIslandPress('element');\n return (\n <button\n type=\"button\"\n className=\"scopetickets-island-codes__arrow\"\n aria-label={label}\n /* Not the attribute — a disabled button is removed from the tab order, and the run's\n other end is still somewhere a keyboard buyer navigates past. */\n aria-disabled={disabled ? true : undefined}\n data-disabled={disabled ? '' : undefined}\n onClick={disabled ? undefined : onPress}\n {...press}\n >\n {glyph}\n </button>\n );\n}\n","import {\n useCallback,\n useLayoutEffect,\n useRef,\n useState,\n type CSSProperties,\n type ReactNode,\n} from 'react';\nimport {\n fitTicketEdge,\n sameFit,\n TICKET_EDGE_FALLBACK,\n type TicketEdgeFit,\n type TicketEdgeTokens,\n} from './island-ticket-edge';\nimport type { TicketCode as CodeState } from '../data/useTicketCodes';\n\n/**\n * The theme's own numbers, so a host that re-tunes the spacing scale gets a ticket that\n * still tiles. Falls back to what `island.css` carries when the element is mounted in a\n * renderer with no layout — a test, SSR.\n */\nfunction readTicketEdgeTokens(node: Element): TicketEdgeTokens {\n if (typeof getComputedStyle !== 'function') return TICKET_EDGE_FALLBACK;\n const style = getComputedStyle(node);\n const px = (name: string, fallback: number): number => {\n const value = Number.parseFloat(style.getPropertyValue(name));\n return Number.isFinite(value) && value > 0 ? value : fallback;\n };\n return {\n edge: px('--scopetickets-island-space-2', TICKET_EDGE_FALLBACK.edge),\n segment: px('--scopetickets-island-space-6', TICKET_EDGE_FALLBACK.segment),\n pad: px('--scopetickets-island-space-3', TICKET_EDGE_FALLBACK.pad),\n gap: px('--scopetickets-island-space-2', TICKET_EDGE_FALLBACK.gap),\n };\n}\n\nexport type TicketCodeProps = {\n /** \"Peak • Adult\", or absent where the caller knows neither half. */\n readonly qualifier: string | null;\n /** \"Alex Whelan\", or absent where the platform holds no name. */\n readonly name: string | null;\n /**\n * The holder's face — an `Avatar`, composed by the caller as every hero here is. `null`\n * is a real answer and is not a slot: see `TicketRow.artwork`, which draws the same line.\n */\n readonly avatar?: ReactNode;\n /** The booking's day, already in words: \"12 December 2026\". */\n readonly day: string;\n /** When it starts, or absent where the event sells no sessions. */\n readonly time: string | null;\n readonly code: CodeState;\n /** What the code IS, for anyone who cannot see it. */\n readonly codeLabel: string;\n /** What stands in its place when it did not come back. */\n readonly codeMissing: string;\n};\n\n/**\n * ONE TICKET — the code inside its perforated edge, with who it is for printed above.\n *\n * ── THE MEASURE IS CHOSEN, NOT TAKEN ─────────────────────────────────────────\n *\n * The edge tiles one cutout, so neither rail can be a fraction of one. This component\n * measures two things and `fitTicketEdge` decides the rest: the room the parent offers\n * ACROSS, which fixes how many cutouts the top and bottom rails carry, and the HEADER's\n * height, which is what the side rails have to contain once the square code is added under\n * it. See `island-ticket-edge.ts`, which is the whole rule as pure data.\n *\n * MEASURED HERE AND SPENT IN CSS. What crosses is two COUNTS; the stylesheet multiplies\n * them by its own tokens, so a host that re-tunes the scale moves the drawing and the\n * arithmetic together.\n *\n * THE HEADER IS MEASURED AND THE CODE IS NOT. The code's size follows from the width, which\n * is settled before its height is asked for — measuring the whole stack instead would be\n * measuring the answer.\n */\nexport function TicketCode({\n qualifier,\n name,\n avatar,\n day,\n time,\n code,\n codeLabel,\n codeMissing,\n}: TicketCodeProps) {\n /* The ruler, not the ticket: the frame's width is what is being computed, so measuring\n the frame itself would be measuring our own answer. */\n const hostRef = useRef<HTMLDivElement | null>(null);\n const frameRef = useRef<HTMLDivElement | null>(null);\n const headerRef = useRef<HTMLDivElement | null>(null);\n const [fit, setFit] = useState<TicketEdgeFit | null>(null);\n\n const measure = useCallback(() => {\n const host = hostRef.current;\n if (!host) return;\n const header = headerRef.current?.getBoundingClientRect().height ?? 0;\n const next = fitTicketEdge(host.clientWidth, header, readTicketEdgeTokens(host));\n setFit((current) => (sameFit(current, next) ? current : next));\n }, []);\n\n useLayoutEffect(() => {\n measure();\n const host = hostRef.current;\n if (!host || typeof ResizeObserver === 'undefined') return undefined;\n /*\n * THREE BOXES, AND NONE OF THEM IS REDUNDANT. The HOST catches the room on offer\n * changing, which is every island morph. The HEADER catches a longer name wrapping to a\n * second line, which changes the height without changing the width. The FRAME catches\n * the TOKENS changing underneath us: a host that re-tunes `$6` moves the drawing through\n * CSS without the room on offer moving at all, so nothing else here would ever hear\n * about it and the counts would be left describing the old scale.\n *\n * The pass settles because a re-measure that finds the same fit sets no state — see\n * `sameFit`.\n */\n const observer = new ResizeObserver(() => measure());\n observer.observe(host);\n if (headerRef.current) observer.observe(headerRef.current);\n if (frameRef.current) observer.observe(frameRef.current);\n return () => observer.disconnect();\n }, [measure, fit?.ok]);\n\n /*\n * THE HEADER IS DRAWN WHETHER OR NOT THE FRAME IS, and that is what makes the first\n * measurement possible: it is laid out inside a hidden ruler on the pass before there is a\n * ticket to put it in. Once there is one it moves into the centre and the ruler is empty.\n */\n const header = (\n <div className=\"scopetickets-island-ticket__header\" ref={headerRef}>\n <div className=\"scopetickets-island-ticket__holder\">\n <div className=\"scopetickets-island-ticket__who\">\n {qualifier === null ? null : (\n <span className=\"scopetickets-island-ticket__qualifier\">{qualifier}</span>\n )}\n {name === null ? null : <span className=\"scopetickets-island-ticket__name\">{name}</span>}\n </div>\n {avatar === undefined || avatar === null ? null : (\n <span className=\"scopetickets-island-ticket__avatar\">{avatar}</span>\n )}\n </div>\n <div className=\"scopetickets-island-ticket__booking\">\n <span className=\"scopetickets-island-ticket__day\">{day}</span>\n {time === null ? null : <span className=\"scopetickets-island-ticket__time\">{time}</span>}\n </div>\n </div>\n );\n\n return (\n <div className=\"scopetickets-island-ticket\" ref={hostRef}>\n {fit?.ok === true ? (\n <div\n ref={frameRef}\n className=\"scopetickets-island-ticket__frame\"\n style={\n {\n '--scopetickets-island-ticket-columns': fit.columns,\n '--scopetickets-island-ticket-rows': fit.rows,\n } as CSSProperties\n }\n >\n <div className=\"scopetickets-island-ticket__band\">\n <span className=\"scopetickets-island-ticket__corner\" />\n <span className=\"scopetickets-island-ticket__rail\" />\n <span className=\"scopetickets-island-ticket__corner\" />\n </div>\n\n <div className=\"scopetickets-island-ticket__middle\">\n <span className=\"scopetickets-island-ticket__side\">\n <span className=\"scopetickets-island-ticket__rail scopetickets-island-ticket__rail--turned\" />\n </span>\n <div className=\"scopetickets-island-ticket__centre\">\n {header}\n <TicketCodeImage code={code} label={codeLabel} missing={codeMissing} />\n </div>\n <span className=\"scopetickets-island-ticket__side scopetickets-island-ticket__side--flipped\">\n <span className=\"scopetickets-island-ticket__rail scopetickets-island-ticket__rail--turned\" />\n </span>\n </div>\n\n <div className=\"scopetickets-island-ticket__band scopetickets-island-ticket__band--flipped\">\n <span className=\"scopetickets-island-ticket__corner\" />\n <span className=\"scopetickets-island-ticket__rail\" />\n <span className=\"scopetickets-island-ticket__corner\" />\n </div>\n </div>\n ) : (\n /*\n * THE RULER'S OWN PASS. Nothing is drawn and the header is laid out anyway, at the\n * width the ticket will have, so the first measurement is a real one rather than a\n * zero that draws a ticket of one cutout and then jumps.\n */\n <div className=\"scopetickets-island-ticket__ruler\" aria-hidden=\"true\">\n {header}\n </div>\n )}\n </div>\n );\n}\n\n/**\n * The code itself, or a stated absence.\n *\n * SILENCE IS THE ONE THING IT MUST NOT BE. A ticket whose code failed looks exactly like\n * one still loading, and a buyer at a gate cannot tell the difference — so a failure says\n * so in the code's own square, at the code's own size.\n */\nfunction TicketCodeImage({\n code,\n label,\n missing,\n}: {\n code: CodeState;\n label: string;\n missing: string;\n}) {\n if (code.status === 'DRAWN') {\n return (\n <div className=\"scopetickets-island-ticket__code\">\n {/* See the stylesheet: a browser's own image drag would take the run's gesture. */}\n <img src={code.src} alt={label} draggable={false} />\n </div>\n );\n }\n\n return (\n <div\n className=\"scopetickets-island-ticket__code scopetickets-island-ticket__code--bare\"\n data-state={code.status === 'LOADING' ? 'loading' : 'missing'}\n >\n {code.status === 'ERROR' ? (\n <span className=\"scopetickets-island-ticket__missing\">{missing}</span>\n ) : null}\n </div>\n );\n}\n","/**\n * THE TICKET'S PERFORATED EDGE, AS PURE DATA.\n *\n * The edge is one cutout tiled along a rail, so a rail can only ever be a whole number of\n * cutouts long. A ticket that simply took the room it was offered would end its rails\n * mid-notch at every size but the handful that happen to divide — and the scale is a\n * host-tunable token, so \"the handful that divide\" is not something this file gets to know\n * in advance.\n *\n * So the measure is not taken, it is CHOSEN, on BOTH axes:\n *\n * - ACROSS, the rule is the offered width's. The two corners come out of the budget\n * first and the run is the most whole cutouts that fit what is left.\n * - DOWN, the rule is the CONTENT's. The centre holds a name, a date and a square code,\n * and that stack is as tall as it is — so the run is the FEWEST whole cutouts that\n * contain it, and the slack lands as paper at the bottom of the ticket.\n *\n * ── WHY THE TWO AXES DIFFER, AND WHY THAT IS NOT A SECOND RULE ───────────────\n *\n * `@scopetickets/sdk`'s `fitTicketEdge` chooses one count and spends it on all four rails,\n * and it is right to: the ticket there is a code and nothing else, so its centre is square\n * and a run turned through a right angle fits the side exactly. This ticket has a\n * ticketholder and a booking above the code, so its centre is taller than it is wide and\n * there is no single count. The rule is the same one — whole cutouts, never a fraction —\n * asked of two measures instead of one.\n *\n * The two are deliberately separate files rather than one shared with the SDK: this package\n * is mounted by hosts that never touch the SDK, and a widget that pulled a component\n * library in to draw a border would be exactly the dependency `ScopeTicketsCheckout` exists\n * to avoid.\n */\n\n/**\n * The four measurements a ticket is built from, in px, read off the spacing scale at\n * RUNTIME rather than compiled in — a host that re-tunes the scale moves the CSS without\n * this hearing about it, so the numbers are taken from the rendered element.\n */\nexport type TicketEdgeTokens = {\n /**\n * `$2` — the rail's thickness, which is ALSO the corner's side and the cutout's short\n * side. One value in three places, not three that happen to agree: a rail thicker than\n * the cutout leaves a band of uncut material behind every notch.\n */\n readonly edge: number;\n /** `$6` — the cutout's long side, and therefore the pitch a rail repeats at. */\n readonly segment: number;\n /** `$3` — the centre's inset, equal on four sides. */\n readonly pad: number;\n /** `$2` — the seam between the centre's rows, and between the last of them and the code. */\n readonly gap: number;\n};\n\n/**\n * What `island.css` carries today, for a renderer with no layout — a test, SSR.\n *\n * ── 8 / 24 / 12: THE SCALE THE DESIGN WAS DRAWN AT ───────────────────────────\n *\n * `@scopetickets/sdk`'s ticket ships at 12/64/16, tuned on its own `/qr-lab` bench where a\n * ticket stands alone on a page and can afford a long, deep notch. This one is a card in a\n * 270px column, and at that measure the same numbers read as a coarse zigzag rather than a\n * perforation — and the granularity swallows the carousel: a 64px pitch leaves the frame up\n * to 64px short of the room on offer, where 24 leaves at most 24.\n *\n * So the island keeps the drawn values. The two tickets are deliberately free to differ:\n * the scale is a host-tunable token in both packages and the rule that reads it is the same\n * rule, which is the part that had to be shared.\n */\nexport const TICKET_EDGE_FALLBACK: TicketEdgeTokens = {\n edge: 8,\n segment: 24,\n pad: 12,\n gap: 8,\n};\n\n/** The ticket's measurements, all of them, in px. */\nexport type TicketEdgeFrame = {\n /** Whole cutouts across the top and bottom rails. */\n readonly columns: number;\n /** Whole cutouts down each side rail. */\n readonly rows: number;\n /** The frame's outside width, rails included. */\n readonly frame: number;\n /** The centre's width, inside the rails. */\n readonly width: number;\n /** The centre's height, inside the rails — `rows` cutouts, so the side rails tile. */\n readonly height: number;\n /** The code's measure, inside the centre's padding. Square. */\n readonly code: number;\n};\n\n/**\n * Too narrow to draw: below {@link minimumColumns} cutouts the padding has eaten the centre\n * and what is left is a frame around nothing — which is worse than no ticket, because it\n * looks like a code that failed to load.\n */\nexport type TicketEdgeFit =\n | ({ readonly ok: true } & TicketEdgeFrame)\n | { readonly ok: false; readonly reason: 'TOO_NARROW' };\n\n/**\n * The fewest cutouts that still leave a code behind.\n *\n * Derived rather than written down, because the floor moves with the padding rather than\n * with anything a reader could guess: it is the first count whose content survives having\n * the inset taken off both ends, so a padding re-tuned upward raises it by itself.\n */\nexport function minimumColumns({ segment, pad }: TicketEdgeTokens): number {\n return Math.floor((2 * pad) / segment) + 1;\n}\n\n/**\n * THE WHOLE RULE.\n *\n * `available` is the room the parent offers ACROSS. `header` is what stands above the code\n * inside the centre, measured — the ticketholder's row and the booking's, with the seam\n * between them. Everything else follows.\n *\n * Reading the offered width as the RUN's budget rather than the FRAME's is the tempting\n * mistake, and it happens to agree at the size the design was drawn at — which is exactly\n * why it would survive a review against the design, and why the tests sweep scales and\n * widths instead of pinning the one.\n */\nexport function fitTicketEdge(\n available: number,\n header: number,\n tokens: TicketEdgeTokens,\n): TicketEdgeFit {\n const { edge, segment, pad, gap } = tokens;\n\n const columns = Math.floor((available - 2 * edge) / segment);\n if (!Number.isFinite(columns) || columns < minimumColumns(tokens)) {\n return { ok: false, reason: 'TOO_NARROW' };\n }\n\n const width = columns * segment;\n const code = width - 2 * pad;\n\n /*\n * WHAT THE CENTRE NEEDS, and then the fewest whole cutouts that hold it. The header is\n * measured and the code is derived from the width above, so this is never circular: the\n * code's size is decided before its height is asked for.\n *\n * A HEADER OF ZERO IS A REAL ANSWER — the frame before the first measurement, and a\n * ticket whose caller drew no header at all. It yields a centre that is the code plus its\n * inset, rounded up, which is the right ticket for a code on its own.\n */\n const needed = 2 * pad + (header > 0 ? header + gap : 0) + code;\n const rows = Math.max(Math.ceil(needed / segment), 1);\n\n return {\n columns,\n rows,\n width,\n height: rows * segment,\n /* Load-bearing arithmetic rather than a value that happens to equal a token: the frame\n * has to follow the rail when the rail is tuned. */\n frame: width + 2 * edge,\n code,\n ok: true,\n };\n}\n\n/** Sub-pixel jitter from a ResizeObserver must not re-render a ticket that has not moved. */\nexport function sameFit(current: TicketEdgeFit | null, next: TicketEdgeFit): boolean {\n if (current === null) return false;\n if (!current.ok || !next.ok) return current.ok === next.ok;\n return current.columns === next.columns && current.rows === next.rows;\n}\n","import { ArrowRightIcon } from '@scopetickets/icons';\nimport { useIslandPress } from './island-press';\n\n/** One row of the booking: who a ticket is for, what it is, and the way into it. */\nexport type TicketRow = {\n readonly key: string;\n /**\n * WHO HOLDS IT, or the card's own words for nobody — see `BOOKING_COPY.awaiting`. Always\n * a string, because the row always draws this line: a ticket with no holder is the\n * commonest case there is and an empty line would read as a row that failed to load.\n */\n readonly holder: string;\n /** Whether that line is the PLACEHOLDER, which the design sets a step quieter. */\n readonly awaiting: boolean;\n /** \"Adult\" — what the ticket is. */\n readonly qualifier: string | null;\n /**\n * The design's `Add` pill — drawn in place of the arrow on a ticket awaiting details, and\n * always where they can actually be added, the save being key-addressed (see\n * `BookingGateway.saveHolder`). Its presence is also what says the row opens the FORM\n * rather than the ticket.\n */\n readonly add?: string;\n};\n\nexport type TicketsInBookingProps = {\n readonly tickets: readonly TicketRow[];\n readonly onOpen: (key: string) => void;\n};\n\n/**\n * THE TICKETS IN A BOOKING — the design's `TicketsInBooking`.\n *\n * HAIRLINES AND NOT A WELL. The rows are ruled above the first and below each of them, with\n * no fill and no border around the run: the list is part of the card rather than a panel\n * set into it, which is what the surrounding `$3` of inset says too.\n *\n * NO FACE ON A ROW. The design draws none — a booking is a list of tickets on one event, and\n * a column of identical marks beside identical names says nothing that the words do not.\n *\n * EVERY ROW IS A DOOR, and there is no other way to a ticket, so the row is the button and\n * the `Add` pill inside it is an affordance rather than a second target.\n */\nexport function TicketsInBooking({ tickets, onOpen }: TicketsInBookingProps) {\n return (\n <div className=\"scopetickets-island-tickets\">\n {tickets.map((ticket) => (\n <TicketInBookingRow key={ticket.key} ticket={ticket} onOpen={() => onOpen(ticket.key)} />\n ))}\n </div>\n );\n}\n\nfunction TicketInBookingRow({ ticket, onOpen }: { ticket: TicketRow; onOpen: () => void }) {\n const press = useIslandPress('element');\n\n return (\n <button\n type=\"button\"\n className=\"scopetickets-island-tickets__row\"\n /*\n * THE USER TYPE IS IN THE NAME AND NOT ONLY UNDER IT. Three rows reading \"Awaiting\n * Details\" are three identical buttons to anyone who cannot see the \"Adult\"/\"Child\"\n * beneath — which is every booking this widget makes, since the platform names nobody.\n */\n aria-label={\n ticket.qualifier === null ? ticket.holder : `${ticket.holder}, ${ticket.qualifier}`\n }\n onClick={onOpen}\n {...press}\n >\n <span className=\"scopetickets-island-tickets__detail\">\n <span\n className=\"scopetickets-island-tickets__holder\"\n data-awaiting={ticket.awaiting ? '' : undefined}\n >\n {ticket.holder}\n </span>\n {ticket.qualifier === null ? null : (\n <span className=\"scopetickets-island-tickets__qualifier\">{ticket.qualifier}</span>\n )}\n </span>\n\n {/*\n * TWO TRAILING MARKS, AND WHICH ONE IS DRAWN SAYS WHERE THE ROW GOES. A named ticket\n * opens on ITSELF and wears the arrow; one awaiting details opens on the FORM and\n * wears `Add`, which is what the word promises. Both are inside the row's own\n * accessible name above, so neither is a second target.\n */}\n {ticket.add === undefined ? (\n <span className=\"scopetickets-island-tickets__open\" aria-hidden=\"true\">\n <ArrowRightIcon size={16} color=\"currentColor\" />\n </span>\n ) : (\n <span className=\"scopetickets-island-tickets__add\" aria-hidden=\"true\">\n {ticket.add}\n </span>\n )}\n </button>\n );\n}\n","import type { ReactNode } from 'react';\nimport { PaperAndPencilIcon, PaperPlaneToTopRightIcon, QrCodeIcon } from '@scopetickets/icons';\nimport type { AvatarAccessory } from '@scopetickets/avatar';\nimport type { BookingScreen } from '../domain/booking';\nimport { formatDayChip } from './island-calendar';\n\n/**\n * MY BOOKING'S OWN WORDS — the four cards after the money moved.\n *\n * DATA, LIKE `step-cards`. A host defers these screens because it does not want to draw\n * them, so it cannot then be asked what they should say. Nothing here holds state and\n * nothing here presses anything: `BookingIsland` composes the props, and this file is the\n * copy, the badges and the two facts about the header.\n */\n\nexport const BOOKING_COPY = {\n /** The root. A statement of what was bought, which is why the title is a subject. */\n title: 'Booking Details',\n /*\n * WHAT THE COLLAPSED ISLAND OFFERS. \"Booking Details\" names the CARD, which is the right\n * word on a header and the wrong one on a pill nobody has opened yet: a buyer glancing\n * at it is being offered their booking, not a screen about it.\n */\n myBooking: 'My Booking',\n /**\n * WHEN THE PLATFORM NAMES NOBODY — which is every booking this widget makes today, since\n * no attendee is created for a ticket bought through it.\n *\n * \"AWAITING DETAILS\" AND NOT \"TICKETHOLDER\". It says what is true of the ticket rather\n * than what kind of thing the line is: nobody has been named yet, and somebody can be.\n * The design sets it a step quieter than the user type beneath it for the same reason.\n */\n awaiting: 'Awaiting Details',\n /** What is offered on a row nobody is named on, where a name can actually be added. */\n add: 'Add',\n /** The way to every code at once. Plural even for one — see `codes`, which is not. */\n showCodes: 'Show QRs',\n /** The codes screen, and the run inside it. */\n codes: 'Show QR',\n codesRegion: 'Your tickets',\n /** \"1\". Counted from one, because it is being read rather than indexed. */\n position: (at: number) => `${at + 1}`,\n previous: 'Previous ticket',\n next: 'Next ticket',\n /**\n * \"1 of 3\", IN TWO WEIGHTS OF INK — the design sets the position full strength and the\n * run it is out of at Text60, so the number a buyer is looking for reads first.\n *\n * SPLIT HERE RATHER THAN IN THE COMPONENT, because it is a sentence with a part\n * emphasised and that is a fact about the copy. The space belongs to the second half.\n */\n positionOf: (count: number) => ` of ${count}`,\n /** What a code IS, for anyone who cannot see it. */\n codeLabel: (name: string) => `Entry code for ${name}`,\n /**\n * AND WHAT STANDS IN ITS PLACE when it did not come back. It says the ticket is fine,\n * because that is the buyer's real question: a blank square where a code should be reads\n * as a ticket that has been cancelled.\n */\n codeMissing: 'Code unavailable. Your ticket is still valid.',\n /** One ticket. Its title is the holder's — see `ticketTitle`. */\n ticketFallbackTitle: 'Your Ticket',\n editHolder: 'Edit Ticketholder',\n /** The quick actions' two lines each — see `QuickAction.lines`. */\n showCodeLines: ['Show', 'QR'],\n editHolderLines: ['Edit', 'Ticketholder'],\n /** The edit form. */\n firstName: 'First Name',\n lastName: 'Last Name',\n email: 'Email',\n save: 'Save',\n saving: 'Saving…',\n /**\n * SENDING A COPY OF A TICKET, which this widget CAN do now — `SendSingleEmail` is the\n * platform's, and the quick action on a ticket's own card is the way to it.\n *\n * The wallet badge still has no entry here, and that is the point: it is Apple's mark and\n * the host supplies the whole node. See `BookingIslandProps.walletBadge`.\n */\n sendTicketLines: ['Send', 'Ticket'],\n sendTicket: 'Send Ticket',\n sendPrompt: 'Enter recipient email address below.',\n send: 'Send',\n sending: 'Sending…',\n /** Where it went, said back — the card's only proof that anything happened. */\n sentTo: (email: string) => `Sent to ${email}.`,\n sendFailed: 'The ticket could not be sent. Please try again.',\n /** The root card's way out, and every other card's way back. */\n close: 'Close',\n back: 'Back',\n /** While the booking is being read. */\n loadingTitle: 'Opening Your Booking',\n loadingSubtitle: 'One moment.',\n /**\n * A CART THE PLATFORM HOLDS NO TICKETS AGAINST — and it is NOT a terminal card.\n *\n * THE READ CAN BE EARLY. A booking is opened the instant a purchase finishes, which is\n * within a second of the transaction being finalized; a platform that has not finished\n * indexing it answers with nothing, and that answer stops being true a moment later. So\n * this leads with asking again rather than with the confirmation email — a buyer who has\n * just paid and is looking at \"no tickets\" needs a button, not a consolation.\n *\n * IT IS ALSO WHAT A STALE CART KEY LOOKS LIKE on a page mounted cold, where asking again\n * costs one request and answers the same way. One card serves both because the buyer's\n * next move is identical.\n */\n noneTitle: 'No Tickets Here Yet',\n noneSubtitle:\n 'We could not find any tickets on this booking. Try again, or check your email for your confirmation.',\n retry: 'Try Again',\n} as const;\n\n/**\n * WHETHER THE HEADER CLOSES THE ISLAND OR STEPS BACK — the design's own two glyphs, and the\n * only thing telling a buyer which it is.\n *\n * ASKED OF `backFrom` RATHER THAN LISTED, because the two answers are the same answer: a\n * screen with somewhere to go back to draws an arrow, and the one without draws a cross.\n * Written as a table, the table and the navigation could disagree — and the screen that\n * disagreed would be a card a buyer could not leave.\n */\nexport function bookingDismiss(back: BookingScreen | null): 'back' | 'close' {\n return back === null ? 'close' : 'back';\n}\n\n/**\n * THE DAY, AS THE HERO WEARS IT — the design's `AvatarImageElement-Square`, a date over a\n * month in the corner of the run's artwork.\n *\n * NOT A GLYPH, which is why it is a component here rather than an entry in a badge table:\n * every other accessory in this package is a mark from `@scopetickets/icons` and this one is\n * lines of TYPE. A glyph is handed `fill` and scales itself; type does not, which is what\n * makes the size below a parameter rather than something the stylesheet could infer.\n *\n * ── THE MONTH IS DRAWN AT `$25` AND NOT AT `$10` ─────────────────────────────\n *\n * The design draws two different marks, not one mark shrunk: `13259:13450` is a date over\n * a month in a 48 slot, and `13259:13647` is the DATE ALONE in a 20 one. There is no room\n * for the second line — two lines of `heading/md` and `heading/xs` are 36 pixels of text in\n * a 20-pixel box, `nowrap`, so the month spilled across the collapsed pill and out the\n * side of it. The date takes `heading/xs` there, which is the stylesheet's `--sm` half.\n */\nexport function DayChip({ day, size }: { readonly day: string; readonly size: 25 | 10 }) {\n const { date, month } = formatDayChip(day);\n return (\n <span\n className={`scopetickets-island-datemark${size === 10 ? ' scopetickets-island-datemark--sm' : ''}`}\n >\n <span className=\"scopetickets-island-datemark__date\">{date}</span>\n {size === 10 ? null : <span className=\"scopetickets-island-datemark__month\">{month}</span>}\n </span>\n );\n}\n\n/**\n * The hero's mark on each card that has one.\n *\n * THE ROOT WEARS THE DAY and the Edit card wears a PENCIL, and neither is a status: both say\n * what the picture beneath them is for. The two cards in between wear none — the codes card\n * has no hero at all, and the ticket card's copy already names the holder.\n *\n * THE DAY IS BUILT AT THE SIZE IT WILL BE DRAWN AT, which is the same reason `statusBadge`\n * takes one: it is type rather than a glyph, so the presentation the hero is in decides\n * what the mark says. The pencil is a glyph and scales itself, so it needs no size.\n */\nexport const BOOKING_BADGES: {\n readonly day: (day: string, size: 25 | 10) => AvatarAccessory;\n readonly edit: AvatarAccessory;\n readonly send: AvatarAccessory;\n} = {\n day: (day: string, size: 25 | 10) => ({\n shape: 'square',\n content: <DayChip day={day} size={size} />,\n id: 'booking:day',\n }),\n edit: {\n shape: 'square',\n content: <PaperAndPencilIcon fill appearance=\"metal\" />,\n id: 'booking:edit',\n },\n /* The same plane the quick action wears, so the card says what the press that opened it did. */\n send: {\n shape: 'square',\n content: <PaperPlaneToTopRightIcon fill appearance=\"metal\" />,\n id: 'booking:send',\n },\n};\n\n/**\n * THE MARK ON THE WAY TO THE CODES, used in both places that lead there: the root card's\n * button and the ticket card's quick action. One glyph, because it is one destination — two\n * would say they were different screens.\n *\n * ── IT STATES A SIZE, AND `fill` WOULD BE A BUG ──────────────────────────────\n *\n * `fill` makes a glyph `width: 100%; height: 100%` as an INLINE STYLE, which is right only\n * where the parent has a width of its own. Both of these sit in parents that shrink to fit\n * — the button's mark slot states a height and lets the content say how wide it is, and the\n * quick action's ring is padding around its glyph — so `100%` resolves against a box that is\n * waiting to be told, and the browser falls back to an `<svg>`'s intrinsic 300px. On screen\n * that is a mark slot 300 wide with the label shoved off the end of the button, and a ring\n * the size of the card. An inline style also outranks any width this stylesheet sets, so\n * the CSS could not correct it either.\n *\n * The two sizes are the design's own: `$4` beside a label, `$6` inside a ring.\n */\nexport function CodeGlyph({ size = 16 }: { readonly size?: number }): ReactNode {\n return <QrCodeIcon size={size} color=\"currentColor\" />;\n}\n\n/** And the mark on the way to the form. */\nexport function EditGlyph({ size = 16 }: { readonly size?: number }): ReactNode {\n return <PaperAndPencilIcon size={size} color=\"currentColor\" />;\n}\n\nexport function SendGlyph({ size = 16 }: { readonly size?: number }): ReactNode {\n return <PaperPlaneToTopRightIcon size={size} color=\"currentColor\" />;\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport {\n allowedFrameOrigin,\n buildCancelRequestedMessage,\n buildConfigMessage,\n buildFrameUrl,\n buildSubmitConfirmedMessage,\n buildSubmitRejectedMessage,\n buildTriggerSubmitMessage,\n CARRIED_CHECKOUT_PARAMS,\n parseFrameEvent,\n type FrameIdentity,\n type FrameMessage,\n type PaymentMethodStatus,\n type PaymentPresentation,\n} from '@scopetickets/api';\nimport { WIRE_LIMITS, isBounded } from '../domain/wire';\n\n/**\n * ROOM TO MEASURE IN. The payment host will not mount its field into a box with no size,\n * so the frame cannot report a height until it has one — which makes the opening value a\n * bootstrap rather than a guess at the answer.\n *\n * NOTHING MAY SHOW A FRAME AT THIS HEIGHT. It used to be covered for free — the bay stayed\n * shut until the host reported, and the card frame was all the bay held. It is not free\n * any more: the bay also carries the two provider buttons, whose height is known at mount\n * (`PROVIDER_BUTTON_HEIGHT`), so the bay opens for them straight away. A caller that\n * reveals a card frame before its `onHeight` shows 280px of empty box and then a collapse.\n */\nconst MOUNTING_HEIGHT = 280;\n\n/**\n * HOW LONG THE BAY WAITS FOR A REAL HEIGHT BEFORE OPENING ANYWAY.\n *\n * Waiting is what makes the morph smooth — but a wait with no end is a buyer looking at a\n * card that has no field on it and no way to get one, because a `RESIZE` that never\n * arrives is indistinguishable from one that is late. The frame is mounted and the field\n * is in it either way; this only decides whether the bay opens to a measured number or a\n * bootstrap one. Late and correct beats never.\n *\n * SIX SECONDS AND NOT ONE, because a real host takes about five. At `1_200` this stopped\n * being a safety net and became the common path: it fired first, handed up the bootstrap,\n * and the card opened at 280px of nothing for as long as the host still needed — then\n * collapsed. A net has to be slack enough that the ordinary case never touches it.\n */\nconst HEIGHT_WAIT_MS = 6_000;\n\n/*\n * THE FRAME'S ERROR IS NOT THE BUYER'S SENTENCE. The host sends its own codes and the\n * platform's own message, and both are ours to translate before they reach a card —\n * `InitError` names the seam that failed, not anything a buyer can act on, and the cart\n * that was not found is the ten-minute lifetime expiring under them. What they get is\n * the instruction the state actually calls for: a new booking.\n */\nconst CART_NOT_FOUND = /cart was not found/i;\nexport function frameFailureWords(payload: { code: string; message: string }): string {\n if (payload.code === 'InitError' && CART_NOT_FOUND.test(payload.message)) {\n return 'The cart expired, please start a new booking';\n }\n return `${payload.code} ${payload.message}`.trim() || 'Your payment could not be completed.';\n}\n\n/*\n * THE FAILURE AS IT ARRIVED, CODE INTACT. The code is the line between a retryable\n * decline and news that must never be retried: `TransactionError` means the money was\n * taken and only the ticketing failed, and a caller that flattens it to its words — as\n * this component once did — hands the retry decision to a string it cannot read. The\n * words ride along for the card that shows them; the code is the caller's to route on.\n */\nexport type FrameFailure = {\n readonly code: string;\n readonly message: string;\n readonly words: string;\n};\nexport function frameFailure(payload: { code: string; message: string }): FrameFailure {\n return { code: payload.code, message: payload.message, words: frameFailureWords(payload) };\n}\n\n/** One frame's method — the host's own wire word, and the widget's method model. */\nexport type FrameMethod = 'card' | 'revolut_pay' | 'apple_pay' | 'google_pay';\n\n/** Whether an `apple_pay`/`google_pay` frame's method is one of the wallets. Accepts the\n * widget's own choice union, whose `''` (nothing chosen yet) is never a wallet. */\nexport const isWalletFrameMethod = (\n method: FrameMethod | '',\n): method is 'apple_pay' | 'google_pay' => method === 'apple_pay' || method === 'google_pay';\n\n/**\n * THE FRAME'S HANDSHAKE, in one place: the payment host's iframe asks for the buyer\n * (`SUBMIT_REQUESTED`), the parent answers (`SUBMIT_CONFIRMED` with the camelCase\n * name/email the host's card submit reads) or refuses it, and the frame eventually\n * answers the whole exchange with `SUCCESS` or `ERROR`.\n *\n * WHO OWNS THE BUYER: the island does. The frame never sees buyer details until this\n * component hands them over on request, and the phone never crosses at all — it goes\n * to the cart via the platform's own `setBuyer`, not into the card host.\n *\n * REVOLUT'S OWN HALF IS THE MESSAGE SET the card never sends: the provider button reports\n * itself busy (`METHOD_STATUS processing`), says where its journey is being shown\n * (`PRESENTATION inline|external`), and can be cancelled mid-flight by the parent\n * (`CANCEL_REQUESTED`, honoured for revolut_pay only). Outcomes are still only the\n * frame's `SUCCESS`/`ERROR`: `METHOD_STATUS`'s error payloads are field status, never\n * charge results — the host's own cancel sequence ends in an error-shaped message that\n * means nothing was taken.\n */\nexport function IslandPaymentFrame({\n hostUrl,\n cartKey,\n apiKey,\n checkoutSessionId,\n theme,\n method,\n active,\n submitSignal,\n cancelSignal,\n onSubmitRequested,\n onSuccess,\n onError,\n onHeight,\n onStatusChange,\n onPresentation,\n onCancelled,\n onDiagnostic,\n onReady,\n heightOverride,\n label,\n retry = false,\n}: {\n readonly hostUrl: string;\n readonly cartKey: string;\n readonly apiKey: string;\n /**\n * THE ISLAND'S OWN SESSION IDENTITY for this cart, carried in the frame URL so the\n * host's provider-return URLs can hand the buyer back to the checkout they came\n * from with something to resume by. Absent, the host says `unknown` — see its\n * `checkoutSessionId` read. One id per cart, minted by the island.\n */\n readonly checkoutSessionId?: string;\n /**\n * THE ISLAND'S OWN APPEARANCE, as the host's `parseTheme` reads it (`themeMode`), sent\n * with the config so the provider's own buttons — whose variant is light or dark —\n * match the surface they sit in. Resolved by the caller when the mode is `system`.\n */\n readonly theme?: Readonly<Record<string, string>>;\n /**\n * WHICH METHOD THIS FRAME HOSTS. The frame's own URL carries it (the host mounts the\n * provider document for one method per frame) and so does every message's identity check.\n */\n readonly method: FrameMethod;\n /**\n * WHAT TO CALL THIS FRAME, where the caller knows better than the method does.\n *\n * A wallet frame's method is its SLOT and not its contents — nothing asks the device for\n * a particular wallet, so an `apple_pay` frame is routinely where Google Pay ends up.\n * Naming the frame from the method then told a screen reader the opposite of what was\n * inside it. Changing the method to match is not the fix and cannot be: the method is in\n * the URL, the URL is this frame's key, and a device that answered would remount the\n * frame it was answering about.\n */\n readonly label?: string;\n /**\n * Render-persistent identity. True when a buyer is on this cart and this method is the\n * chosen one; false keeps the frame prewarmed — its document stays mounted, which is\n * the whole point of two persistent frames, but it gets no `selectedMethod` in its\n * config and answers no charges.\n */\n readonly active: boolean;\n /** Bump to ask the frame to submit its field. Nothing is sent while inactive. */\n readonly submitSignal: number;\n /**\n * Bump to cancel an in-flight provider journey. Nothing is sent while inactive, and\n * the host honours the request for `revolut_pay` only — the card method has no cancel,\n * so the signal is a no-op there and is never bumped on that path.\n */\n readonly cancelSignal: number;\n /** The buyer for the charge, camelCase for the host's card submit. */\n readonly onSubmitRequested: () => { firstName: string; lastName: string; email: string } | null;\n /**\n * Money taken AND finalized by the payment host. The only PLACED source.\n *\n * IT NAMES THE TICKET IT MADE, where the host named one — the first attendee ticket on\n * the transaction it has just converted. `undefined` where the message carried none, or\n * carried something that is not a key this package will pass on; see the guard below.\n */\n readonly onSuccess: (attendeeTicketKey: string | undefined) => void;\n /** A decline, with the provider's own words — and its code, which the caller routes\n * on: `TransactionError` is money taken without tickets and must never be retried. */\n readonly onError: (failure: FrameFailure) => void;\n /**\n * THE HEIGHT THE HOST REPORTS, the first time it reports one and on every change.\n *\n * Lifted out rather than kept here because the card that OPENS the bay has to know it:\n * a bay that expands before the frame has said how tall it is expands to a guess, and\n * the correction is a visible collapse. See `frameVisible`.\n */\n /**\n * The frame's height, and WHETHER IT WAS MEASURED.\n *\n * `measured: false` is the bootstrap — `MOUNTING_HEIGHT`, handed up when the host has\n * not answered in time. A caller that treats the two alike reveals an empty box at the\n * bootstrap size and then collapses it when the real number lands, which is the exact\n * settle the height contract exists to prevent. Size the box with either; reveal on\n * `measured` alone.\n */\n readonly onHeight?: (height: number, measured: boolean) => void;\n /**\n * THE FIELD'S OWN STATE, as the host reports it: busy with a click, or back to ready\n * — possibly with an error the FIELD wants named, which is never a charge outcome.\n */\n readonly onStatusChange?: (status: PaymentMethodStatus) => void;\n readonly onReady?: () => void;\n /** The iframe's height, in px or any CSS length — `100%` during the fullscreen journey. */\n readonly heightOverride?: number | string;\n /** WHERE THE PROVIDER'S JOURNEY IS BEING SHOWN — inline, or away in a tab or app. */\n readonly onPresentation?: (presentation: PaymentPresentation) => void;\n /**\n * THE HOST'S OWN CANCELLED WORD — the popup was closed, or this parent asked. It\n * arrives FIRST in a three-message recovery sequence; see `onStatusChange` for the\n * other two.\n */\n readonly onCancelled?: () => void;\n /** Telemetry, allow-listed by the protocol; nothing in the flow reads it. */\n readonly onDiagnostic?: (diagnostic: FrameMessage & { type: 'SCOPE_PAYMENT_DIAGNOSTIC' }) => void;\n /**\n * THE EPOCH FLAG — true on every remount after a provider return killed the host\n * page. It changes the frame URL (which is the iframe's React key, so the frame\n * remounts) and tells the fresh host page to treat the stored attempt as dead and\n * mint a new order for the same cart; see `buildFrameUrl`'s own `retry`.\n */\n readonly retry?: boolean;\n}) {\n const frame = useRef<HTMLIFrameElement>(null);\n /*\n * WHAT THE FRAME IS GIVEN TO START WITH, and it is not what it ends at. The payment\n * host defers mounting its field until the target has a size — so the frame needs room\n * before it can measure itself, and this is that room. It is never seen: the bay stays\n * shut until a real height has been reported.\n */\n const [height, setHeight] = useState(MOUNTING_HEIGHT);\n const identity = useMemo<FrameIdentity>(\n () => ({ instanceId: crypto.randomUUID(), method }),\n [cartKey, hostUrl, method],\n );\n const origin = allowedFrameOrigin(hostUrl);\n const url = buildFrameUrl(hostUrl, cartKey, identity, {\n parentOrigin: window.location.origin,\n checkoutSessionId,\n /*\n * THE CHECKOUT PAGE'S OWN EVENT PARAM RIDES ALONG, so the provider's return URLs\n * can hand the buyer back to the checkout they came from. A site names its event\n * `event` or `eventKey`; both are carried when present, and the host's redirect\n * URLs carry them back — see `CARRIED_CHECKOUT_PARAMS` in the protocol.\n *\n * THE DEBUG KEYS RIDE TOO, so a desktop QA pass can force the wallet the device\n * cannot offer (`scopeWalletDebug`) and watch the host's traffic\n * (`scopePaymentDebug`) — the same carry the SDK's own PaymentFrame makes.\n */\n carriedParams: [...CARRIED_CHECKOUT_PARAMS, 'scopeWalletDebug', 'scopePaymentDebug'],\n parentSearchParams: new URLSearchParams(window.location.search),\n retry,\n });\n\n /** Whether the iframe has navigated to the host yet — see the config post below. */\n const loaded = useRef(false);\n /** Whether the host has ever told us a height — see `HEIGHT_WAIT_MS`. */\n const reported = useRef(false);\n const generation = useRef(0);\n\n /* Callbacks are read through a ref so a parent re-render never re-runs the listener. */\n const callbacks = useRef({\n onSubmitRequested,\n onSuccess,\n onError,\n onHeight,\n onStatusChange,\n onPresentation,\n onCancelled,\n onDiagnostic,\n onReady,\n });\n callbacks.current = {\n onSubmitRequested,\n onSuccess,\n onError,\n onHeight,\n onStatusChange,\n onPresentation,\n onCancelled,\n onDiagnostic,\n onReady,\n };\n\n useEffect(() => {\n const post = (message: FrameMessage) =>\n frame.current?.contentWindow?.postMessage(message, origin);\n /*\n * ACTIVATION IS THE CONFIG, AND THE CONFIG IS THE ONLY PATH — there is no\n * `SELECTED_METHOD` message for a parent to send. A prewarmed frame gets the same\n * config minus `selectedMethod`, which is what keeps its provider document from\n * arming itself: the revolut host mounts its provider button on frame ready and\n * leaves it mounted across active/prewarm, and what it does NOT do is answer\n * activation for a method that was never selected.\n */\n const configure = () =>\n post(\n buildConfigMessage(identity, {\n apiKey,\n ...(theme === undefined ? {} : { theme: Object.fromEntries(Object.entries(theme)) }),\n ...(active ? { selectedMethod: method } : {}),\n }),\n );\n const listener = (event: MessageEvent) => {\n const message = parseFrameEvent(event, {\n allowedOrigin: origin,\n source: frame.current?.contentWindow,\n identity,\n });\n if (!message) return;\n if (message.type === 'SCOPE_PAYMENT_READY') {\n configure();\n callbacks.current.onReady?.();\n }\n /*\n * THE HOST'S OWN ASK, sent the moment its listener exists — before its document\n * had one, the config this parent posted at mount time was lost with every other\n * message a document without ears ever receives, and the host's rescue (its READY,\n * resent on this very branch) only fires after an initialisation that needs the\n * key it was waiting for. Answering here is what closes that loop.\n */\n if (message.type === 'SCOPE_PAYMENT_CONFIG_REQUESTED') {\n configure();\n }\n if (message.type === 'SCOPE_PAYMENT_RESIZE') {\n reported.current = true;\n setHeight(message.payload.height);\n callbacks.current.onHeight?.(message.payload.height, true);\n }\n if (message.type === 'SCOPE_PAYMENT_SUBMIT_REQUESTED') {\n const buyer = callbacks.current.onSubmitRequested();\n if (buyer === null) {\n post(buildSubmitRejectedMessage(identity, 'Validation failed'));\n return;\n }\n post(buildSubmitConfirmedMessage(identity, buyer));\n }\n if (message.type === 'SCOPE_PAYMENT_METHOD_STATUS') {\n callbacks.current.onStatusChange?.(message.payload);\n }\n if (message.type === 'SCOPE_PAYMENT_PRESENTATION') {\n if (message.payload.attemptGeneration < generation.current) return;\n generation.current = message.payload.attemptGeneration;\n callbacks.current.onPresentation?.(message.payload);\n }\n if (message.type === 'SCOPE_PAYMENT_CANCELLED') callbacks.current.onCancelled?.();\n if (message.type === 'SCOPE_PAYMENT_DIAGNOSTIC') callbacks.current.onDiagnostic?.(message);\n if (message.type === 'SCOPE_PAYMENT_SUCCESS') {\n /*\n * BOUNDED, BECAUSE IT CAME OFF A `postMessage`. The protocol checks the cart key\n * and lets the rest of the payload through, so this field arrives with whatever\n * shape the sender chose — and it goes on to the platform as an\n * `AttendeeTicketKey`, whose own model says 50. Anything else is `undefined`,\n * which is a case the rating card already handles; it is not a reason to refuse a\n * payment that has already succeeded.\n */\n const ticket = message.payload.attendeeTicketKey;\n callbacks.current.onSuccess(isBounded(ticket, WIRE_LIMITS.key) ? ticket : undefined);\n }\n if (message.type === 'SCOPE_PAYMENT_ERROR')\n callbacks.current.onError(frameFailure(message.payload));\n };\n window.addEventListener('message', listener);\n /*\n * ONLY INTO A DOCUMENT THAT HAS ARRIVED. A fresh iframe still carries the PARENT's\n * origin until it navigates, and a config addressed to the host's origin is refused\n * outright —\n *\n * Unable to post message to http://localhost:3001.\n * Recipient has origin http://localhost:3000.\n *\n * — which is harmless but fills the console, and became the normal case once the\n * frames started mounting a step before they are shown. The host asks for its config\n * the moment its listener exists (`SCOPE_PAYMENT_CONFIG_REQUESTED`) and announces\n * itself with READY, so both paths above already cover a frame configured late. This\n * only skips the speculative post while the document is still on its way.\n */\n if (loaded.current) configure();\n return () => window.removeEventListener('message', listener);\n }, [active, apiKey, identity, method, origin, theme]);\n\n /*\n * AND THE BAY IS NOT HELD SHUT BY A MESSAGE THAT DOES NOT COME. The host reports its\n * height once its field is mounted; if that has not happened by now, the mounting\n * height is handed up so the card opens on something rather than waiting forever.\n */\n useEffect(() => {\n if (!active) return;\n const timer = window.setTimeout(() => {\n if (!reported.current) callbacks.current.onHeight?.(MOUNTING_HEIGHT, false);\n }, HEIGHT_WAIT_MS);\n return () => window.clearTimeout(timer);\n }, [active]);\n\n /*\n * THE TRIGGER AND THE CANCEL, both parent-initiated and both inert on a prewarmed\n * frame — a bump means nothing while the frame is not the chosen method.\n *\n * DELIVERED ONCE PER BUMP, NEVER ONCE PER ACTIVATION. `active` is a dependency of\n * these effects because a bump that lands mid-recovery still has to be delivered\n * when the frame is next chosen — but an effect that re-runs on activation ALSO\n * re-runs its body, and the body posts. Without the delivered marker, walking away\n * from the card and back would resubmit the last charge, and re-arming Revolut Pay\n * after its Cancel button would cancel the fresh attempt the host had just prepared.\n * The marker is the sequence number the host can trust: a signal is posted the first\n * time (this frame, or a later one) is active with it, and never again until the\n * island bumps it.\n */\n const post = useCallback(\n (message: FrameMessage) => frame.current?.contentWindow?.postMessage(message, origin),\n [origin],\n );\n const deliveredSubmitRef = useRef(0);\n const deliveredCancelRef = useRef(0);\n useEffect(() => {\n if (submitSignal === 0 || !active) return;\n if (deliveredSubmitRef.current === submitSignal) return;\n deliveredSubmitRef.current = submitSignal;\n post(buildTriggerSubmitMessage(identity));\n }, [submitSignal, active, identity, post]);\n\n useEffect(() => {\n if (cancelSignal === 0 || !active) return;\n if (deliveredCancelRef.current === cancelSignal) return;\n deliveredCancelRef.current = cancelSignal;\n post(buildCancelRequestedMessage(identity));\n }, [cancelSignal, active, identity, post]);\n\n return (\n <iframe\n key={url}\n ref={frame}\n src={url}\n onLoad={() => {\n loaded.current = true;\n }}\n title={\n label ??\n (method === 'card'\n ? 'Secure card payment'\n : method === 'revolut_pay'\n ? 'Revolut Pay'\n : method === 'apple_pay'\n ? 'Apple Pay'\n : 'Google Pay')\n }\n allow=\"payment\"\n style={{ display: 'block', width: '100%', height: heightOverride ?? height, border: 0 }}\n />\n );\n}\n","/**\n * WHICH WALLET THE CHECKOUT OFFERS — asked of the BROWSER, not of the operating system.\n *\n * Per the design the pay card shows a SINGLE wallet button, and it has to be chosen before\n * the payment frame mounts: the choice rides in the frame's URL and cannot change without\n * remounting it.\n *\n * ── IT USED TO READ THE PLATFORM, AND ON A MAC THAT MEANT NO WALLET AT ALL ──\n *\n * The rule was iOS, macOS or Safari → Apple Pay, everything else → Google Pay, with\n * \"Chrome on macOS therefore picks Apple Pay\" written down as the product's own call.\n * `navigator.platform` says `MacIntel` in every browser on a Mac, and only Safari can\n * present Apple Pay — no other browser on macOS defines `ApplePaySession`. So Chrome and\n * Firefox on macOS mounted an `apple_pay` frame, the host asked Revolut for `applePay`,\n * `canMakePayment()` could only answer no, and the island draws nothing for a wallet that\n * answered no. Google Pay — which those browsers DO support — was never asked for.\n *\n * ── SO IT ASKS THE ONE QUESTION THAT DECIDES IT ─────────────────────────────\n *\n * `ApplePaySession` is the capability itself rather than a proxy for it, and it is what\n * Revolut's own widget gates on. Safari on iOS, iPadOS and macOS answers yes and keeps\n * Apple Pay, which is the product's call where the product's call is actually available;\n * every browser that cannot present Apple Pay gets the wallet it CAN present. Nothing\n * about the user agent string is parsed any more, so no masquerade has to be caught.\n *\n * STILL A HINT, NOT AN ANSWER. This decides which wallet method rides in the payment\n * frame's URL and the first paint of a label. Whether the wallet can actually take money\n * is the payment host's `canMakePayment()`, reported back on\n * `SCOPE_PAYMENT_METHOD_STATUS` with the wallet it resolved — see `wallet-report`, which\n * corrects this in both directions.\n */\nexport type DigitalWalletKind = 'apple' | 'google';\n\n/** What a browser that can present Apple Pay exposes, and all this module wants of it. */\ntype ApplePayCapable = { readonly canMakePayments?: () => boolean };\n\n/**\n * WHETHER APPLE PAY CAN BE PRESENTED HERE AT ALL.\n *\n * `canMakePayments` is the device question — is there a secure element to pay with — and\n * NOT `canMakePaymentsWithActiveCard`, which is the card question and is a promise, asked\n * far too late to decide a frame's URL. A buyer with the hardware and no card set up is\n * offered the button and told by Apple's own sheet, which is where that belongs.\n *\n * IT CAN THROW rather than answer: a document that is not a secure context, or one framed\n * without `allow=\"payment\"`, raises instead of returning false. A throw is not an Apple\n * Pay this page can present, which is the same answer as `false`.\n */\nfunction applePayPresentable(): boolean {\n const session = (window as { ApplePaySession?: ApplePayCapable }).ApplePaySession;\n if (session?.canMakePayments === undefined) return false;\n try {\n return session.canMakePayments() === true;\n } catch {\n return false;\n }\n}\n\nexport const detectDigitalWallet = (): DigitalWalletKind => {\n /* No window is no browser to ask, and Google Pay is the wider of the two guesses. */\n if (typeof window === 'undefined') return 'google';\n return applePayPresentable() ? 'apple' : 'google';\n};\n\n/** The payment host's word for a wallet — the frame's slot, and the key a charge is recorded under. */\nexport type WalletFrameMethod = 'apple_pay' | 'google_pay';\n\n/** One wallet, in the payment host's spelling. */\nexport const walletFrameMethod = (kind: DigitalWalletKind): WalletFrameMethod =>\n kind === 'apple' ? 'apple_pay' : 'google_pay';\n\n/**\n * THE SLOT THE WALLET FRAME MOUNTS IN, which is all this decides.\n *\n * It is fixed for the life of the frame — the word is in the frame's URL, and the URL is\n * its React key — so it cannot follow the device's answer even in principle. What the\n * device answered is `walletInPlay`, and that is what the button says and what a charge\n * is recorded as.\n */\nexport const walletHostMethod = (): WalletFrameMethod => walletFrameMethod(detectDigitalWallet());\n","import type { PaymentMethodStatus } from '@scopetickets/api';\nimport type { DigitalWalletKind } from './detect-digital-wallet';\n\n/**\n * WHAT THE WALLET FRAME HAS SAID ABOUT ITSELF — the three states a row or button that\n * offers the device's one wallet can be in, from the payment host's own words.\n *\n * NOT A JOURNEY. Availability is whether the wallet CAN be pressed at all; the charge\n * itself is the journey (`RevolutJourney`), which wallets join through the same\n * `METHOD_STATUS` processing words every provider method sends. Keeping the two apart\n * is what stops \"the frame is not ready\" from being read as \"the wallet cannot pay\".\n */\nexport type WalletReport =\n | { readonly kind: 'checking' }\n | { readonly kind: 'unavailable' }\n | { readonly kind: 'available'; readonly wallet: DigitalWalletKind };\n\n/**\n * A FOLD, BECAUSE MOST OF WHAT A WALLET FRAME SAYS IS NOT ABOUT AVAILABILITY. The\n * availability words are three — the host's `canMakePayment()` answered no\n * (`WalletUnavailable`/`WalletInitError`, or `ready: false`), or answered yes (the\n * status that carries the `wallet` it resolved). Everything else — a click's\n * `processing`, a decline's `WalletPaymentError`, the cancellation housekeeping —\n * describes a CHARGE, and a charge that failed must not read as a wallet that vanished:\n * the row stays pressable so the buyer can try again.\n */\nexport function walletReport(\n state: WalletReport,\n status: PaymentMethodStatus,\n sniffed: DigitalWalletKind,\n): WalletReport {\n if (status.ready === false) return { kind: 'unavailable' };\n if (status.error?.code === 'WalletUnavailable' || status.error?.code === 'WalletInitError') {\n return { kind: 'unavailable' };\n }\n if (status.wallet !== undefined) {\n /* THE HOST'S WORD WINS OVER THE SNIFF — the sniff only picked the frame URL; this is\n * `canMakePayment()`'s answer, mapped in BOTH DIRECTIONS because a frame sniffed as\n * Apple's can be answered Google's and vice versa. The field is parsed to exactly\n * these two words; there is no third case to fall back from. */\n return { kind: 'available', wallet: status.wallet === 'applePay' ? 'apple' : 'google' };\n }\n if (status.ready === true && status.error === undefined && status.processing !== true) {\n /* AN OLDER HOST THAT NAMES NO WALLET still gets a usable row: the sniff stands in\n * for it, ONCE. A host that has already named its wallet is not unsaid by the\n * housekeeping statuses that follow a charge — they simply repeat no wallet — and a\n * wallet that answered no stays no. */\n if (state.kind === 'checking') return { kind: 'available', wallet: sniffed };\n return state;\n }\n return state;\n}\n\n/**\n * WHICH WALLET IS ACTUALLY IN PLAY — the host's answer wherever it has given one, and the\n * sniff only until it does.\n *\n * THE ONE READING, spent by everything that has to name the wallet: the button's words,\n * and the method the island records when a wallet charges. Those were two readings, and\n * the second one never heard the host at all — a Mac in sandbox charged with Google Pay\n * and reported `apple_pay` to the integrator, because the sniff was asked instead of the\n * answer. Nothing asks the device for a particular wallet any more (see the payment host,\n * which passes no `preferredPaymentMethod`), so the sniff is now only what the button is\n * called for the moment before the device speaks.\n */\nexport function walletInPlay(report: WalletReport, sniffed: DigitalWalletKind): DigitalWalletKind {\n return report.kind === 'available' ? report.wallet : sniffed;\n}\n\n/** The row/button words for the report, host-corrected where the host spoke. */\nexport function walletLabel(report: WalletReport, sniffed: DigitalWalletKind): string {\n return walletInPlay(report, sniffed) === 'apple' ? 'Apple Pay' : 'Google Pay';\n}\n\n/** The trailing note a row that cannot be pressed owes the buyer, or none. */\nexport function walletNote(report: WalletReport): string | undefined {\n if (report.kind === 'checking') return 'Checking availability…';\n if (report.kind === 'unavailable') return 'Unavailable on this device';\n return undefined;\n}\n","import type { PaymentMethodStatus } from '@scopetickets/api';\n\nexport type RevolutJourney =\n | { kind: 'idle' }\n | { kind: 'processing'; mode?: 'inline_provisional' | 'external_handoff' }\n | { kind: 'recovering' }\n | { kind: 'unresolved' };\n\n/** Field errors describe recovery, never a charge outcome. */\nexport function revolutStatus(state: RevolutJourney, status: PaymentMethodStatus): RevolutJourney {\n if (state.kind === 'unresolved') return state;\n if (state.kind === 'recovering') {\n if (status.error?.code === 'PaymentProcessing' || status.error?.code === 'PaymentRetryError')\n return { kind: 'unresolved' };\n return !status.processing && !status.error ? { kind: 'idle' } : state;\n }\n if (status.processing) return state.kind === 'processing' ? state : { kind: 'processing' };\n return state;\n}\n\n/**\n * HOW MUCH ROOM THE INLINE JOURNEY GETS, derived from the viewport rather than\n * guessed. The journey is the provider's own checkout page; the 480px box clipped it\n * into a scrolled window (2026-09-11 screenshot), so the bay now opens to:\n *\n * - MOBILE: near the whole screen, with the island's own hero and title suppressed —\n * the journey IS the card. The remainder is the island's padding and the Cancel\n * button beneath the frame.\n * - DESKTOP: most of the viewport, capped — the island grows to carry it.\n *\n * STILL A WIDGET-SIDE COMPROMISE: the honest number is the provider document's own\n * height, which needs the host ResizeObserver follow-up. This is the best number the\n * widget can know without it.\n */\nexport const JOURNEY_FULL_MAX = 760;\n\nexport type Viewport = { readonly width: number; readonly height: number };\n\nexport function journeyPresentation(viewport: Viewport): {\n height: number;\n fullscreen: boolean;\n} {\n if (viewport.width <= 640) {\n /*\n * THE WHOLE SCREEN, CHROME INCLUDED. The provider's own page needs a height no\n * reserve can guarantee (782px at phone widths, wider screens shave little off\n * it), so the journey goes edge to edge: anything held back leaves the page a\n * scroll it did not choose — a hair on tall phones, half the page on small ones.\n * Nothing is lost to the buyer for it: the provider page carries the amount and\n * its own way out, and the island's chrome returns with it on every exit.\n */\n return {\n height: Math.max(360, viewport.height),\n fullscreen: true,\n };\n }\n return {\n height: Math.max(420, Math.min(Math.round(viewport.height * 0.8), JOURNEY_FULL_MAX)),\n fullscreen: false,\n };\n}\n","/**\n * THE PROVIDER RETURN'S WORD HOME, when the checkout it belongs to is still standing.\n *\n * An away journey that ends in a redirect leaves the provider's failure/cancel page\n * somewhere on the site's own origin — for the popup, in a window beside the checkout;\n * for the mobile handoff, in the tab the checkout used to be; for the inline journey, in\n * an iframe INSIDE the checkout's own payment bay, which is the one case where the\n * checkout itself is still alive to hear the news. The old SDK passed the news by marker\n * on remount (`providerReturnMarker` in `@scopetickets/sdk`), which only works when the\n * checkout is the next page load; the island never unmounts, so the return page says so\n * directly: same-origin `postMessage` to the top window, which for the inline journey is\n * the island's page. The island answers with its own in-app escape — back to the payment\n * method selection — and no navigation happens at all.\n *\n * The message is scoped OUTSIDE the payment protocol's `SCOPE_PAYMENT_*` prefix on\n * purpose: the protocol speaks frame-to-frame with an identity handover, and this is a\n * page speaking to its own site. Origin equality is the whole trust boundary — the\n * island listens only for its own origin, which is also the only origin allowed to be\n * the top window of a same-origin return page.\n */\n\n/** The wire shape. `status` matches the payment host's redirect URLs. */\nexport interface ProviderReturnSignal {\n readonly type: 'SCOPE_PROVIDER_RETURN';\n readonly payload: {\n readonly status: 'cancel' | 'failure' | 'success';\n readonly cartKey: string;\n readonly method?: string;\n };\n}\n\nexport function buildProviderReturnSignal(\n payload: ProviderReturnSignal['payload'],\n): ProviderReturnSignal {\n return { type: 'SCOPE_PROVIDER_RETURN', payload };\n}\n\n/**\n * Read a message event as the signal, or null. Origin must be the reader's own — the\n * return page lives on the checkout page's origin, and nothing else may speak for it.\n */\nexport function parseProviderReturnSignal(\n event: { readonly origin: string; readonly data: unknown },\n ownOrigin: string,\n): ProviderReturnSignal | null {\n if (event.origin !== ownOrigin) return null;\n if (typeof event.data !== 'object' || event.data === null) return null;\n const { type, payload } = event.data as { type?: unknown; payload?: unknown };\n if (type !== 'SCOPE_PROVIDER_RETURN') return null;\n if (typeof payload !== 'object' || payload === null) return null;\n const { status, cartKey, method } = payload as Record<string, unknown>;\n if (\n (status !== 'cancel' && status !== 'failure' && status !== 'success') ||\n typeof cartKey !== 'string' ||\n !cartKey\n ) {\n return null;\n }\n return buildProviderReturnSignal({\n status,\n cartKey,\n ...(method === undefined ? {} : { method: String(method) }),\n });\n}\n\n/**\n * Whether this page is framed by its own origin's top window — the inline journey's\n * shape. A cross-origin top refuses the comparison; that is the answer, not an error.\n */\nexport function framedByOwnOrigin(): boolean {\n try {\n return window.top !== window && window.top?.location.origin === window.location.origin;\n } catch {\n return false;\n }\n}\n\n/**\n * SAY IT HOME. Posts the signal to the top window when that is the checkout's own page;\n * a popup's or a tab's top is the page itself, and posting to itself would be noise, so\n * it stays quiet there (those journeys are already covered: the popup's checkout hears\n * the provider's own events, and the tab's checkout is the next page load).\n */\nexport function signalProviderReturn(payload: ProviderReturnSignal['payload']): void {\n if (!framedByOwnOrigin()) return;\n window.top?.postMessage(buildProviderReturnSignal(payload), window.location.origin);\n}\n","import { useEffect, useMemo, useRef, useState } from 'react';\nimport { ENVIRONMENT_URLS, ScopeClient, type Environment } from '@scopetickets/api';\nimport { markPurchaseCompleted } from './data/purchase-completion';\nimport { framedByOwnOrigin, signalProviderReturn } from './provider-return-signal';\n\n/**\n * THE RETURN PAGE FOR A PAYMENT THAT LEFT THE BROWSER — the Revolut app-handoff and the\n * popup's landing, mounted by the site at `/revolut-return` on the checkout page's own\n * origin (the host's redirect URLs point there; see the payment host's Checkout route).\n *\n * The widget is unmounted by then: navigation took the buyer away, so nothing of the\n * purchase survives on this page — not the client, not the island, not `onCommit`. This\n * component is what stands in: it builds its own API client from the key, converts the\n * cart on success, and hands completion to the site through `onCompleted` or a redirect\n * to `returnPath`. That `onCommit` can never fire here is a documented divergence on the\n * TwinkleTown checklist, not an oversight.\n */\nexport interface PaymentReturnProps {\n /** The site's public API key — the same one the checkout widget mounts with. */\n readonly apiKey: string;\n /**\n * Which platform the cart lives on. The default matches the widget's own\n * (`production`); a site that mounts the widget on sandbox must say so here too.\n */\n readonly environment?: Environment;\n /**\n * Where the buyer's checkout page lives, shown as the way back when the payment\n * did not complete (cancelled or failed). The site's own route; no default.\n */\n readonly checkoutPath?: string;\n /**\n * Where to send the buyer after a successful conversion, when `onCompleted` is\n * not given. Navigation replaces this page — the buyer should not come \"back\" to\n * a return URL.\n */\n readonly returnPath?: string;\n /**\n * Completion news for the site, called once after the cart is converted and the\n * once-marker is written — see `purchase-completion.ts` for why the order of those\n * two is the rule and not a detail.\n */\n readonly onCompleted?: (cartKey: string) => void;\n}\n\ntype ReturnState =\n | { status: 'processing' }\n | { status: 'completed' }\n | { status: 'cancelled' }\n | { status: 'failed'; message: string };\n\n/** The host's Callback route and this component read the same rule off the same words. */\nconst CART_ALREADY_CONVERTED_MESSAGE =\n 'Cart was altered while attempting to confirm the transaction';\n\n/** The checkout page's own params a return hands back — the names the host carries. */\nconst CARRIED_CHECKOUT_PARAMS = ['event', 'eventKey', 'cartKey', 'checkoutSessionId'] as const;\n\n/*\n * The way back goes to the checkout it came from, carrying what the checkout needs to\n * start AND WHAT IT WAS ALREADY HOLDING: the event the buyer was buying, and the cart\n * the interrupted payment belonged to. The cart key is the purchase identity — the\n * mobile handoff that landed here replaced the checkout document, so nothing of the\n * reservation survives on the page it returns to, and a way back that drops the cart\n * restarts the booking from nothing while the old hold runs its ten minutes out. A\n * checkout page that receives one can reconcile against it; one that ignores it is no\n * worse off than the bare event it used to get. A bare `checkoutPath` starts nothing —\n * it is the checkout's front door with no event behind it.\n */\nfunction checkoutReturnUrl(checkoutPath: string, search: string): string {\n const params = new URLSearchParams();\n const parsed = new URLSearchParams(search);\n for (const name of CARRIED_CHECKOUT_PARAMS) {\n const value = parsed.get(name);\n if (value !== null) params.set(name, value);\n }\n const query = params.toString();\n return query === '' ? checkoutPath : `${checkoutPath}?${query}`;\n}\n\n/**\n * `status=success` with nothing to convert is not a success the site can bank, and\n * neither is a `status` this component has never heard of; both land on the failure\n * view rather than on a false \"done\".\n */\nfunction readReturnQuery(search: string): { status: string | null; cartKey: string | null } {\n const params = new URLSearchParams(search);\n return { status: params.get('status'), cartKey: params.get('cartKey') };\n}\n\nexport function PaymentReturn({\n apiKey,\n environment = 'production',\n checkoutPath,\n returnPath,\n onCompleted,\n}: PaymentReturnProps) {\n const [state, setState] = useState<ReturnState>({ status: 'processing' });\n /* The effect runs once per mount; React's development double-invoke must not\n * convert or publish twice. */\n const ran = useRef(false);\n\n const client = useMemo(() => {\n if (apiKey === '') return null;\n const urls = ENVIRONMENT_URLS[environment];\n return new ScopeClient({\n apiKey,\n orgKey: '',\n environment,\n apiUrl: urls.apiUrl,\n paymentHostUrl: urls.paymentHostUrl,\n });\n }, [apiKey, environment]);\n\n useEffect(() => {\n if (ran.current) return;\n ran.current = true;\n /*\n * THE STILL-STANDING CHECKOUT HEARS THIS FIRST — AND THE FRAMED PAGE THEN VANISHES.\n * On the inline journey this page is an iframe inside the checkout's own payment\n * bay, where it is the corpse of the host page the provider's redirect destroyed.\n * The island's card is the UI there; this page's own words and button would only\n * double it. So framed means: say the news once to the top window (whose epoch\n * remount replaces this document wholesale), then blank the iframe so nothing of\n * the dead journey stays on screen. The popup and tab journeys stay navigational:\n * the checkout behind a popup hears the provider's own events, and a tab's checkout\n * is the next page load.\n */\n const { status, cartKey } = readReturnQuery(window.location.search);\n if ((status === 'cancel' || status === 'failure') && cartKey !== null) {\n signalProviderReturn({ status, cartKey });\n if (framedByOwnOrigin()) {\n window.location.replace('about:blank');\n return;\n }\n }\n if (client === null) {\n setState({ status: 'failed', message: 'PaymentReturn is missing its API key.' });\n return;\n }\n\n if (status === 'cancel') {\n setState({ status: 'cancelled' });\n return;\n }\n if (status === 'failure') {\n setState({ status: 'failed', message: 'Payment was not completed' });\n return;\n }\n\n if (status === 'success' && cartKey !== null) {\n /*\n * SUCCESS'S OWN WORD HOME, when the checkout still stands around this page.\n * Framed means the inline journey: the host page that would have converted the\n * cart and said SUCCESS is the corpse this page replaced, so THIS page is the\n * converter — and the island needs the finalized word, or its status poll parks\n * the buyer on the \"received, support will complete it\" card while the order\n * actually exists. CONVERSION FIRST, SIGNAL SECOND: the island may only claim\n * placed once the transaction does, and then this page vanishes like the failure\n * does — the island's success step is the UI.\n */\n const publish = () => {\n if (framedByOwnOrigin()) {\n signalProviderReturn({ status: 'success', cartKey });\n window.location.replace('about:blank');\n return;\n }\n setState({ status: 'completed' });\n if (onCompleted !== undefined) onCompleted(cartKey);\n else if (returnPath !== undefined) window.location.replace(returnPath);\n };\n void client\n .convertCartToTransaction(cartKey)\n .then(() => {\n /* THE MARKER BEFORE THE NEWS. A later widget mount on this cart must read\n * the marker, not the poll: the poll answers \"completed\", which without\n * this writes PAID-recovery — the false state the P0 plan forbids. */\n markPurchaseCompleted(cartKey);\n publish();\n })\n .catch((cause: unknown) => {\n const message = cause instanceof Error ? cause.message : String(cause);\n /* The widget's live frame may have converted this cart already; the cart\n * being gone is the conversion having worked. */\n if (message.includes(CART_ALREADY_CONVERTED_MESSAGE)) {\n markPurchaseCompleted(cartKey);\n publish();\n return;\n }\n setState({ status: 'failed', message });\n });\n return;\n }\n\n setState({ status: 'failed', message: 'Invalid return parameters' });\n }, [client, onCompleted, returnPath, checkoutPath]);\n\n /*\n * THE WAY BACK CLOSES WHAT OPENED THIS PAGE. Three journeys land here, and each has\n * its own way out. The desktop popup closes — the checkout it belongs to is still\n * standing in the tab that opened it, and navigating the popup would draw a second\n * checkout over a live one. The mobile handoff lands on a tab, which a page cannot\n * close, so it is sent to `checkoutPath`. And the inline journey loads the provider's\n * UI in an iframe, so this page is that iframe's content — the way back is the TOP\n * window, same-origin with it on the site's own origin, because navigating the iframe\n * itself would nest a checkout inside the checkout's payment bay. `replace` everywhere\n * for the same reason the success path uses it: the buyer should not come \"back\" to a\n * return URL.\n */\n const goBack = () => {\n const destination =\n checkoutPath === undefined ? null : checkoutReturnUrl(checkoutPath, window.location.search);\n window.close();\n window.setTimeout(() => {\n if (window.closed || destination === null) return;\n try {\n if (window.top !== null && window.top !== window) window.top.location.replace(destination);\n else window.location.replace(destination);\n } catch {\n /* A cross-origin top window refuses its location; the frame sends itself. */\n window.location.replace(destination);\n }\n }, 150);\n };\n const wayBack =\n checkoutPath === undefined && !window.opener ? null : (\n <button type=\"button\" onClick={goBack} className=\"scopetickets-payment-return__back\">\n Return to checkout\n </button>\n );\n\n if (state.status === 'processing') {\n return (\n <div className=\"scopetickets-payment-return scopetickets-payment-return--processing\">\n <p>Completing your payment...</p>\n </div>\n );\n }\n\n if (state.status === 'completed') {\n return (\n <div className=\"scopetickets-payment-return scopetickets-payment-return--success\">\n <p>Payment successful!</p>\n <p>You can close this window.</p>\n </div>\n );\n }\n\n if (state.status === 'cancelled') {\n return (\n <div className=\"scopetickets-payment-return scopetickets-payment-return--cancelled\">\n <p>Payment was cancelled.</p>\n {wayBack}\n </div>\n );\n }\n\n return (\n <div className=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C;AAAA,IACF,GAAG,GAAG;AAAA,EACR;AACA,QAAM,UACJ,iBAAiB,UAAa,CAAC,OAAO,SAAS,OAC7C,gBAAAN,MAAC,YAAO,MAAK,UAAS,SAAS,QAAQ,WAAU,qCAAoC,gCAErF;AAGJ,MAAI,MAAM,WAAW,cAAc;AACjC,WACE,gBAAAA,MAAC,SAAI,WAAU,uEACb,0BAAAA,MAAC,OAAE,wCAA0B,GAC/B;AAAA,EAEJ;AAEA,MAAI,MAAM,WAAW,aAAa;AAChC,WACE,gBAAAC,OAAC,SAAI,WAAU,oEACb;AAAA,sBAAAD,MAAC,OAAE,iCAAmB;AAAA,MACtB,gBAAAA,MAAC,OAAE,wCAA0B;AAAA,OAC/B;AAAA,EAEJ;AAEA,MAAI,MAAM,WAAW,aAAa;AAChC,WACE,gBAAAC,OAAC,SAAI,WAAU,sEACb;AAAA,sBAAAD,MAAC,OAAE,oCAAsB;AAAA,MACxB;AAAA,OACH;AAAA,EAEJ;AAEA,SACE,gBAAAC,OAAC,SAAI,WAAU,mEACb;AAAA,oBAAAD,MAAC,OAAE,4BAAc;AAAA,IACjB,gBAAAA,MAAC,OAAG,gBAAM,SAAQ;AAAA,IACjB;AAAA,KACH;AAEJ;","names":["useContext","useRef","jsx","useContext","useRef","jsx","jsxs","useCallback","useEffect","useLayoutEffect","useRef","useState","createContext","useContext","createContext","useContext","jsx","jsx","jsxs","IslandSurface","jsx","jsxs","ISLAND_TRANSITION_MS","useState","useRef","useEffect","useLayoutEffect","plane","useCallback","read","painted","frame","jsx","jsxs","jsx","useCallback","useEffect","useMemo","useRef","useState","Avatar","jsx","cost","size","useCallback","useEffect","useMemo","useRef","useState","useState","useRef","useEffect","useCallback","useMemo","after","jsx","jsxs","jsx","jsxs","useCallback","useRef","useState","jsx","jsxs","after","useEffect","useMemo","useState","useMemo","useState","useEffect","useMemo","result","result","refused","result","useMemo","useMemo","refused","useMemo","useCallback","useEffect","useRef","useState","isPlainObject","useState","useRef","useEffect","useCallback","result","useCallback","useEffect","useRef","useState","useState","useRef","useEffect","useCallback","useEffect","useRef","refused","useRef","useEffect","result","useCallback","useEffect","useState","useState","failed","useEffect","useCallback","result","useCallback","useEffect","useRef","useState","useState","useRef","useCallback","useEffect","passcode","read","useCallback","useState","useState","useCallback","refused","result","useLayoutEffect","useRef","useState","read","useCallback","useEffect","useMemo","useRef","useState","jsx","useRef","useState","useMemo","useCallback","useEffect","jsx","useRef","useState","useLayoutEffect","useCallback","useEffect","useRef","useState","refused","refused","userTypeNames","useState","useRef","useEffect","filled","useCallback","jsx","jsxs","jsx","jsxs","jsx","jsxs","useEffect","useLayoutEffect","useRef","useState","Fragment","jsx","jsxs","useState","useRef","useEffect","useLayoutEffect","useEffect","useState","confirm","jsx","jsxs","useEffect","useState","confirm","useEffect","useId","useRef","useState","jsx","jsxs","useId","useRef","useEffect","useState","refused","jsx","jsx","size","signIn","jsx","jsxs","jsx","jsx","jsxs","jsx","jsxs","size","jsx","jsxs","size","useCallback","useEffect","useMemo","useRef","useState","Avatar","result","useCallback","useMemo","useRef","NOTHING","jsx","cartLines","useState","useCallback","useMemo","userTypeNames","useRef","useEffect","signIn","Avatar","useCallback","useMemo","useState","Avatar","useEffect","useState","useState","useEffect","jsx","jsxs","useCallback","useLayoutEffect","useRef","useState","ArrowLeftIcon","useCallback","useLayoutEffect","useRef","useState","jsx","jsxs","useRef","useState","useCallback","header","useLayoutEffect","jsx","jsxs","useRef","useState","useCallback","useLayoutEffect","page","ArrowLeftIcon","ArrowRightIcon","jsx","jsxs","ArrowRightIcon","jsx","jsxs","size","jsx","jsxs","useState","useMemo","useCallback","ticket","Avatar","pill","name","failed","sendable","size","useCallback","useEffect","useMemo","useRef","useState","jsx","useRef","useState","useMemo","useEffect","post","useCallback","Fragment","jsx","jsxs","useState","useEffect","cartLines","useMemo","userTypeNames","index","useRef","useCallback","refused","signIn","step","placed","read","Avatar","buyerName","useEffect","useMemo","useRef","useState","jsx","jsxs","CARRIED_CHECKOUT_PARAMS","useState","useRef","useMemo","useEffect"]}
|