# RCMS Tickets checkout kit

Add RCMS Tickets checkout to this site: fetch https://rcms-tickets-test.web.app/kit/manifest.json and follow its `steps` exactly. In short: run its install tool, which copies every file into `src/rcms-tickets/` with each sha256 checked and writes `kit.lock`; apply the recipe for this site's framework (`recipes.next` or `recipes.vite`), which adds new files only (one server route that holds the secret key, one page that renders `<Checkout />`) and says what to merge into files the site already has, among them `captureAttribution()` in the site's root; never overwrite a file this site already has. Confirm with `git check-ignore .env.local` that the secret file is ignored, then set `RCMS_TICKETS_KEY` (a test key, `rt_test_...`) and `RCMS_TICKETS_EVENT` (`evt_...`) there, in the server's environment (never in a browser file), run the site's typecheck and build, and buy a ticket: in test mode press the Works card, then Pay. Ask me for the test key and the event id if you do not have them. Re-theme it only through the variables at the top of `checkout.css` or `brandStyle()`. Before real money, follow the manifest's `live` list; to update later, its `update` steps.

## Steps
1. Fetch `tool.url` to a temporary place and check it against `tool.sha256` (`shasum -a 256 kit.mjs`; on Windows `Get-FileHash kit.mjs` or `certutil -hashfile kit.mjs SHA256`). Then run it from the project root: `node <that path>/kit.mjs install --manifest <this manifest's url> --framework next` (or `vite`). It checks the manifest's signature against the key inside the tool, fetches every file in `files`, checks each against its sha256, and stops before writing anything if one differs. It writes them under `src/rcms-tickets/` (or `rcms-tickets/` with no src folder), writes `kit.lock`, and writes the recipe's new files. Delete the copy you fetched: the one to keep is `src/rcms-tickets/tools/kit.mjs`, in git with `kit.lock`. They are how this copy is updated.
2. Never overwrite a file this site already has. The recipe adds new files only; for an existing file the recipe's `merge` says what to add, and everything else in that file stays. If the tool says EXISTS, the file was left alone: choose another path or merge by hand. Run each command in `install`, and add each entry of `scripts` to package.json.
3. Apply each step of the recipe's `merge` to the file named (a path starting `src/` means the project root if there is no src folder). The `captureAttribution` step is not optional: the tags exist only on the page a visitor lands on, so it goes in the site's root, not the checkout page.
4. Check the secret file is ignored: `git check-ignore .env.local` must print the name. The tool checked it and added it to `.gitignore` if not; check again yourself, and do not write the key until it passes. Never say a file is ignored without running this. Then write `.env.local` with RCMS_TICKETS_KEY (a TEST key, rt_test_...) and RCMS_TICKETS_EVENT (evt_...). Only the server reads them. Never put the key in a browser file or a NEXT_PUBLIC_ or VITE_ variable. Ask the owner for them if you do not have them.
5. Run the site's typecheck and build. Fix only what is in your own files: the kit is written to pass a strict TypeScript project.
6. Start the site, open /tickets, pick a ticket, and pay with a test card: press Works (it fills 4242 4242 4242 4242; the number in the box is what counts, and the expiry and code are not checked). Declined, Not enough funds and Processor error are the other three buttons. You should see the confirmation with an order number, the same `number` the order has in the API. The kit reads the event's name, date, venue, tickets and add-ons from the API itself: you write none of them.
7. To re-theme, change the variables at the top of `src/rcms-tickets/client/checkout.css`, or pass `style={brandStyle('#yourcolour')}` to Checkout. If the site has a background of its own (a dark page, a photo), set `--rt-canvas: transparent` in checkout.css, or the kit's light canvas ends where its content ends and the page's background shows as a strip below it (most plainly under the Continue bar on a phone). Do not edit the price, the hold or the payment code to make it look different.
8. Say where the buyer's address is on this site's hosting: `clientIp` in the checkout's config (`src/rcms-tickets/KIT.md`, "The buyer's address"). Ask the owner what is in front of the site if you do not know; left unset, a live key refuses to start, and on a test key nothing is limited by address. Wire `src/rcms-tickets/consent.ts` to the site's cookie banner if it has one. Read `KIT.md` for Square, pixels, the abandoned-checkout email, deep links and updating. Before real money: the `live` list in this manifest, in order.

## Recipes
### next

Next.js App Router, with or without a src/ folder (a recipe path starting src/ goes to the project root when there is none). A Pages Router site: stop and ask the owner.

#### src/rcms-tickets/server/checkout.ts

```ts
import { lazyCheckout, testPayment } from './index';

// One place for the server's settings. The key comes from the environment and never leaves the server. Lazy: a build has no secrets.
export const checkout = lazyCheckout(() => ({
  apiKey: process.env.RCMS_TICKETS_KEY ?? '',
  event: process.env.RCMS_TICKETS_EVENT ?? '',
  baseUrl: process.env.RCMS_TICKETS_BASE_URL,
  webhookSecret: process.env.RCMS_TICKETS_WEBHOOK_SECRET,
  sweepSecret: process.env.RCMS_TICKETS_SWEEP_SECRET,
  siteUrl: process.env.SITE_URL ? `${process.env.SITE_URL}/tickets` : undefined,
  payment: testPayment(), // swap for squarePayment({ ... }) when you take real cards: KIT.md, "Going live"
  // Send your abandoned-checkout email here (hold.email, link): read KIT.md, "Abandoned checkout", first. Dedupe on entry.id: a delivery can arrive twice.
  onHoldExpired: async () => undefined,
  // A person must see these: where 'capture_lost', 'capture_refused', 'charged_no_order' or 'refund' means money needs a look. Send them to your own alerts.
  onError: (error, where) => console.error('rcms-tickets', where, error),
  // Where the buyer's address is, on your hosting. A live key must say: it is what stops one visitor holding a whole sale for free. Vercel: clientIp: 'vercel'.
  // Behind Cloudflare: clientIp: 'cloudflare'. Cloud Run, Render, Fly: clientIp: 'rightmost:1'. KIT.md, "The buyer's address".
}));
```

#### src/rcms-tickets/consent.ts

```ts
/*
  What your cookie banner says about ad tracking. Wire this to your banner: 'denied' means no tags are kept or sent and no pixel
  fires. 'unknown' (no banner yet) keeps the tags and lets the browser pixels fire, but RCMS Tickets sends NO server-side conversion
  (Meta, Google) for a buyer nobody asked: only 'granted' does. Where the law asks for consent first, answer 'denied' until the buyer agrees.
*/
export const adConsent = (): 'granted' | 'denied' | 'unknown' => 'unknown';
```

#### src/app/api/tickets/[...path]/route.ts

```ts
import { checkout } from '../../../../rcms-tickets/server/checkout';
import { nextHandlers } from '../../../../rcms-tickets/server/next';

export const { GET, POST, PATCH, DELETE } = nextHandlers(checkout);
```

#### src/rcms-tickets/TicketsCheckout.tsx

```tsx
'use client';

import { Checkout, createPixel } from './client';
import { adConsent } from './consent';
import './client/checkout.css';

const pixel = createPixel({ consent: adConsent });

export default function TicketsCheckout() {
  return <Checkout pixel={pixel} adConsent={adConsent} />;
}
```

#### src/rcms-tickets/CaptureAttribution.tsx

```tsx
'use client';

import { useEffect } from 'react';
import { captureAttribution } from './client/attribution';
import { adConsent } from './consent';

// In the root layout, so a visitor who lands on any page counts: the tags exist only on the page they land on.
export default function CaptureAttribution() {
  useEffect(() => captureAttribution({ adConsent: adConsent() }), []);
  return null;
}
```

#### src/app/tickets/page.tsx

```tsx
import TicketsCheckout from '../../rcms-tickets/TicketsCheckout';

export default function TicketsPage() {
  return <TicketsCheckout />;
}
```

#### Merge into src/app/layout.tsx

Add the import, and render <CaptureAttribution /> just before {children} in the root layout. This is what makes captureAttribution() run on every page of the site. Everything else in the file stays.

```tsx
import CaptureAttribution from '../rcms-tickets/CaptureAttribution';
<CaptureAttribution />
```

Run: npm run build && npm run start. The page is at /tickets; if the site already has that route, choose another path for the page file.

### vite

A Vite + React + TypeScript single-page app (the react-ts template shape, with src/vite-env.d.ts). Vite serves only the page, so the server is a small Express app beside it. A site with its own server: mount expressHandler(checkout) on it instead of server/tickets.ts.

Install:

```sh
npm install express
npm install -D tsx @types/express @types/node
```

package.json scripts: `{"tickets-server":"tsx --env-file=.env.local server/tickets.ts"}`

#### server/tickets.ts

```ts
import express from 'express';
import { expressHandler, lazyCheckout, testPayment } from '../src/rcms-tickets/server';

// The server holds the secret key. Run it beside Vite: npm run tickets-server (Vite proxies /api to it).
const checkout = lazyCheckout(() => ({
  apiKey: process.env.RCMS_TICKETS_KEY ?? '',
  event: process.env.RCMS_TICKETS_EVENT ?? '',
  baseUrl: process.env.RCMS_TICKETS_BASE_URL,
  webhookSecret: process.env.RCMS_TICKETS_WEBHOOK_SECRET,
  sweepSecret: process.env.RCMS_TICKETS_SWEEP_SECRET,
  siteUrl: process.env.SITE_URL ? `${process.env.SITE_URL}/tickets` : undefined,
  payment: testPayment(), // swap for squarePayment({ ... }) when you take real cards: KIT.md, "Going live"
  // Send your abandoned-checkout email here (hold.email, link): read KIT.md, "Abandoned checkout", first. Dedupe on entry.id: a delivery can arrive twice.
  onHoldExpired: async () => undefined,
  // A person must see these: where 'capture_lost', 'capture_refused', 'charged_no_order' or 'refund' means money needs a look. Send them to your own alerts.
  onError: (error, where) => console.error('rcms-tickets', where, error),
  // Where the buyer's address is, on your hosting. A live key must say: it is what stops one visitor holding a whole sale for free. KIT.md says which to use.
}));

const app = express();
app.use('/api/tickets', expressHandler(checkout)); // before any express.json()
app.listen(Number(process.env.PORT ?? 8787), '127.0.0.1');
```

#### src/rcms-tickets/consent.ts

```ts
/*
  What your cookie banner says about ad tracking. Wire this to your banner: 'denied' means no tags are kept or sent and no pixel
  fires. 'unknown' (no banner yet) keeps the tags and lets the browser pixels fire, but RCMS Tickets sends NO server-side conversion
  (Meta, Google) for a buyer nobody asked: only 'granted' does. Where the law asks for consent first, answer 'denied' until the buyer agrees.
*/
export const adConsent = (): 'granted' | 'denied' | 'unknown' => 'unknown';
```

#### src/rcms-tickets/TicketsPage.tsx

```tsx
import { Checkout, createPixel } from './client';
import { adConsent } from './consent';
import './client/checkout.css';

const pixel = createPixel({ consent: adConsent });

export default function TicketsPage() {
  return <Checkout pixel={pixel} adConsent={adConsent} />;
}
```

#### Merge into src/main.tsx

Add the imports. Call captureAttribution() once, at the top of the site's entry file, so a visitor who lands on any page counts. Then show the page: with a router, add a /tickets route that renders <TicketsPage />; with no router, render it when the path is /tickets, as shown. Everything else in the file stays.

```tsx
import TicketsPage from './rcms-tickets/TicketsPage';
import { captureAttribution } from './rcms-tickets/client/attribution';
import { adConsent } from './rcms-tickets/consent';

captureAttribution({ adConsent: adConsent() });
{window.location.pathname === '/tickets' ? <TicketsPage /> : <App />}
```

#### Merge into src/vite-env.d.ts

Only if this file does not exist (the react-ts template has it; a hand-made Vite project may not): create it with this one line. Without it the typecheck fails on the kit's CSS import (TS2882, './client/checkout.css').

```ts
/// <reference types="vite/client" />
```

#### Merge into vite.config.ts

Proxy /api to the tickets server: add server.proxy to the config you have. Keep your plugins and everything else.

```ts

  server: { proxy: { '/api': 'http://127.0.0.1:8787' } },
```

#### Merge into tsconfig.node.json

Add server to the project that holds vite.config.ts, or the typecheck never reads server/tickets.ts, the file with your key in it. Set `"module": "esnext"` and `"moduleResolution": "bundler"` there too: the current template sets nodenext, and the kit does not build under it. It needs the Node types too: `"types": ["node"]` under compilerOptions. A project with a single tsconfig.json (no tsconfig.node.json): put both in that one: add "server" to its include and "types": ["node"] to compilerOptions.

```text
"include": ["vite.config.ts", "server"]
```

Run: npm run tickets-server (one terminal), npm run dev (another; Vite never reads the key, only the tickets server does). The page is at /tickets. For a build: npm run build, and serve dist/ behind the same /api.

## Going live
1. Run `node src/rcms-tickets/tools/kit.mjs verify`, then compare `kit.lock` with this manifest's sha256 for your version. Anything CHANGED should be a change you meant.
2. Update if `advisories` lists anything for your version: the `update` steps in this manifest.
3. Rehearse everything below on a test key first: the webhook (a test key has its own endpoints), the sweep, the emails. Only then put the live key in.
4. Set RCMS_TICKETS_KEY to the live key and RCMS_TICKETS_BASE_URL to the production API, only in the production environment. Never in the browser.
5. Swap testPayment() for squarePayment({ accessToken, locationId }) (Square's production host is the default) and the slot for squareSlot({ applicationId: 'sq0idp-...', locationId }). createCheckout refuses a live key with a sandbox or test payment, and the slot refuses an application id from the wrong world. Another processor: `externalPayment` needs `open`, or `chargeFirstAcknowledged` with a `store`.
6. Set SITE_URL to the public address of the site, with no trailing slash. The abandoned-checkout link is built from it.
7. Register the webhook, once, with your live key: POST /v1/webhook_endpoints with url `${SITE_URL}/api/tickets/webhook` and the events order.paid, order.created and hold.expired. It answers the signing secret once: put it in RCMS_TICKETS_WEBHOOK_SECRET. It finishes a payment a crash left half done, and starts the abandoned-checkout email.
8. Set RCMS_TICKETS_SWEEP_SECRET to a random string of 32 characters or more and call GET or POST /api/tickets/sweep every 15 minutes from your scheduler with `Authorization: Bearer <it>`. On Vercel Cron, set CRON_SECRET to the same value (Vercel sends it as that bearer) and check your plan allows a 15-minute schedule; otherwise use Cloud Scheduler, GitHub Actions or plain cron. It is the net under the webhook: it captures a payment whose order exists and voids one whose hold died. A live key with a processor refuses to start without this and an onError.
9. Wire adConsent in `src/rcms-tickets/consent.ts` to your cookie banner. Where the law asks for consent first, answer 'denied' until the buyer agrees, and call captureAttribution again when they do.
10. Send onError where a person will see it. where 'capture_lost', 'capture_refused', 'charged_no_order' or 'refund' means money needs a look; 'sweep_stale' means the sweep is not running.
11. Check it took: make one hold on the live site and read GET /v1/events/{id}/hold_networks. It must list one network with from_key null. from_key set, or onError hearing client_ip_none, means every hold counts as one network.
12. Set clientIp for your hosting (KIT.md, "The buyer's address"): a live key refuses to start without it, and only then are addresses known and limited. Never point it at a header your proxy doesn't set: anyone can send it. On serverless pass your own beforeRequest and abandonedGate over a shared store, because the defaults count in one instance's memory.
13. Allow Square's scripts in your Content-Security-Policy if you have one (Square's Web Payments docs list what it needs).
14. Buy one real ticket with a real card, see it in Square as captured and in RCMS Tickets as paid, then refund it.

## Updating
1. From the project root: `node src/rcms-tickets/tools/kit.mjs update --manifest <this manifest's url>`. It lists any ADVISORY for your version first, checks every file against its sha256, and stops before writing if one differs.
2. REPLACED, ADDED and REMOVED were files you never changed. CONFLICT is a file you changed and this version changed too: yours is untouched, the new copy is in `.kit-update/`, and the diff is printed. Merge the new behaviour into yours; never paste over your change without reading it. Then `kit.mjs update --accept <path>`.
3. Recipe files (server/checkout.ts and the like) are yours and the tool does not touch them. Read the kit's KIT.md "Updating the kit" for what a version asks of them.
4. Typecheck, build, buy a test ticket. Commit `kit.lock` with the change.

## Files

### src/rcms-tickets/KIT.md

````md
# RCMS Tickets checkout kit

A whole checkout, as code you own. You copy these files into your site and change them freely: nothing of ours runs on your
page, there is no embed and no iframe, and the secret key never leaves your server.

    client/   React: every step (tickets, add-ons, code, details, payment, confirmation), the clock, attribution, the pixel helper
    server/   handlers on web-standard Request/Response: Next.js, Express, Firebase Functions, Workers, anything with fetch

## How it fits together

    buyer's page  --(your /api/tickets)-->  your server (holds the key)  --(RCMS Tickets API)-->  holds, orders, tickets
                                            your server --(your processor)--> the card (Square recipe below)

1. `GET  /api/tickets/storefront`  the event (its name, date and venue too: you write none of them), tickets, add-ons, questions and consent words in one read
2. `POST /api/tickets/holds`       hold the items; the answer is the price to show and the time it is held (10 minutes)
3. `POST /api/tickets/orders`      pay and make the order. The server checks the total the buyer saw against the hold's total first
4. `POST /api/tickets/orders/check` everything an order can be refused for, asked before the Payment step
5. `POST /api/tickets/webhook`     RCMS Tickets tells your server `hold.expired` (with the buyer's email, if the page sent it) and `order.paid`
6. `GET|POST /api/tickets/sweep`   finishes payments a crash left half done (needs `sweepSecret`)

## Use it

    import { Checkout, captureAttribution, createPixel, loadMetaPixel } from './rcms-tickets/client';
    import './rcms-tickets/client/checkout.css';

    captureAttribution({ adConsent: adConsent() });       // once, in your site's root: tags are kept 90 days
    <Checkout pixel={createPixel({ consent: adConsent })} adConsent={adConsent} />   // the whole checkout

Your server (Next.js route handler shown; Express and Firebase are in `server/express.ts`):

    export const checkout = lazyCheckout(() => ({ apiKey: process.env.RCMS_TICKETS_KEY ?? '', event: process.env.RCMS_TICKETS_EVENT ?? '' }));
    export const { GET, POST, PATCH, DELETE } = nextHandlers(checkout);

`lazyCheckout` builds on the first request, so `next build` and Docker builds work with no secrets in the environment. `createCheckout` is the same thing, right now.

On Express, mount `expressHandler(checkout)` before any `express.json()`. If you set Express's own `app.set('trust proxy', ...)`, `req.ip` honours it and `clientIp: 'peer'` then reads that.

On Vite, only the tickets server (`npm run tickets-server`) reads `.env.local`; `npm run dev` never needs the key. A hand-made Vite project needs `src/vite-env.d.ts` (`/// <reference types="vite/client" />`) or the typecheck fails on the CSS import, and a single `tsconfig.json` takes the recipe's `server` include and `"types": ["node"]` itself.

Environment, in `.env.local` (check `git check-ignore .env.local` before you write a key there): `RCMS_TICKETS_KEY` (a test key, `rt_test_...`), `RCMS_TICKETS_EVENT` (`evt_...`), `RCMS_TICKETS_WEBHOOK_SECRET`
(`whsec_...`, for webhooks), `RCMS_TICKETS_SWEEP_SECRET`, `SITE_URL`, `RCMS_TICKETS_BASE_URL` (a live key must say; a test key defaults to the test host).
Never put the key in a browser file or in a `NEXT_PUBLIC_` variable.

On a page that already has an `h1`, pass `eventHeading="h2"` to `<Checkout />` (or `eventHeading={false}` to leave the event's name out; the dates and venue stay). Every field has a `name` and a `type` (`name`, `email`, `phone`, `code`, `cardnumber`, `q_<question key>`, `ticket_2_name`) for autofill and password managers; there are no `data-testid` hooks, so a test finds a field by its label.

## Re-theme it in one place

**My tickets: link it.** A buyer who lost the email finds their tickets at `my_tickets_url`, on the storefront (`store.my_tickets_url`) and on `GET /v1/events/{id}`. It asks for a code sent to their email or phone, and needs no ticket link. The confirmation already links it; put it in your site's footer or nav too. For a page with no event at hand, `https://rcms-tickets-test.web.app/my` (your host's `/my`) asks for an address and emails that person a link for each organizer. It isn't a secret.

**A site with a background of its own** (a dark page, a photo): set `--rt-canvas: transparent`. The kit's canvas is a light grey that stops where its content stops, so on a short page, or under the Continue bar on a phone, the site's own background shows as a strip below it. Transparent lets your background run behind the whole checkout.

That holds for a neutral or single-colour brand. A palette that changes the ground (a cream canvas, a night blue) also changes the derived variables below it (`--rt-fg`, `--rt-fg-2`, `--rt-fg-3`, `--rt-fill`, `--rt-border-input`, `--rt-lift`, the glass pair and the notice colours): set them too, and set them for dark as well as light. `brandStyle` assumes the default canvases (`#f2f2f7`, `#000`). Give `Checkout` a `className` of your own and scope your overrides to `.rt-checkout.your-class`, so the order of the two stylesheets never decides who wins.

`checkout.css` starts with a handful of variables: `--rt-accent` (buttons), `--rt-on-accent`, `--rt-accent-ink` (links, the selected
ring, focus), `--rt-radius`, `--rt-font`, `--rt-canvas` (set it to `transparent` to sit on your page), `--rt-surface`. Or give
one brand colour to `brandStyle('#c8102e')` (theme.ts) and pass it as `style`: it keeps your colour and picks words that stay readable.
Light and dark follow the buyer's phone; `scheme="light"` or `"dark"` forces one.

## What it does for you

- **Every step**, built for a phone first: 48px targets, 17px text, labels above fields, plain errors that say what to do next.
- **The hold's clock** (server time, never the buyer's), "Need more time?" once, and "Hold the same tickets again" when it runs out, saying so if the price changed.
- **Bundles** (a 5-pack gives five tickets), add-ons, codes (also `?code=`), the questions the event and each ticket type ask (a date of birth is three plain fields), a holder per ticket when a type wants one.
- **Consent** checkboxes with the event's exact words, never pre-ticked; the order records which version of the words was shown.
- **Attribution** (`attribution.ts`): utm tags and fbclid / gclid / ttclid (each kept apart) and the referrer on landing, first touch and last touch, 90 days, first-party storage; sent with the hold.
- **Pixels** (`pixel.ts`): PageView, ViewContent, InitiateCheckout, AddPaymentInfo, Purchase through one helper for Meta, GA4 and TikTok (whichever is on the page). Purchase carries the order's `tracking_event_id` as its event id, so the server-side Purchase and the browser's are one sale. A test checkout never fires Purchase. `loadMetaPixel(id)` and `loadGa4(id)` are opt-in snippets.
- **Abandoned checkout**: the email typed at the details step goes on the hold. `hold.expired` reaches `onHoldExpired({ hold, link })` (never for a hold made on a hosted link, which only that link can finish): send your email; `link` is `?resume=<hold>&utm_source=email&utm_medium=abandon` and puts the same tickets back. **A hold can name anyone's address**, so this is mail to a stranger if you let it be: by default it fires once per address per 24 hours and never for test-mode holds (`abandonedInTestMode: true` to rehearse); `abandonedGate` is your own rule, and on serverless it should use a shared store. A buyer who holds again and buys can still get the email for the first hold: `onHoldExpired` and `abandonedGate` are handed the checkout's `api`, so check the orders before you send.
- **Before you send that email, read this.** It is probably commercial mail, and only a lawyer can tell you otherwise. A hold can name anyone, and so can a tick: it is a yes from whoever typed it, not proof they own the address. So caps are what bound abuse. What the example does (`examples/yrd-checkout`, `server/abandoned.ts`): it goes only to an address whose Email box was ticked on that hold (`onEmailChoice` tells your server as it is pressed, with the caller's `ip`; the API hears it only with the order); one caller can name 3 addresses a day (`ipNetwork`, so an IPv6 caller is one /64), and past that no yes is kept and the buyer's checkout carries on with nothing said; the whole site writes at most a set number of these mails an hour; suppression and once per address per event read the address with any `+tag` removed, on every domain; it carries your postal address and a tokened unsubscribe that works in one press; `abandonedGate` checks your suppression list and has this address already bought. Keep your store's ids as an HMAC with a secret, not a bare hash, and put an expiry on anything holding an address: the API's erase cannot reach your own store.
- **Consent**: pass what your banner says as `adConsent`. `granted` is the only answer that lets RCMS Tickets send the sale to Meta or Google from its server: for `unknown` (no banner, or nobody has answered) tags are kept and browser pixels fire, but no server-side conversion goes unless the organizer switched on `send_when_consent_unknown`. `denied` stores no tags, clears any kept, sends none with the hold, and no pixel or loader runs. It is asked again when the order is made: a later "no" still counts, and a later "yes" doesn't widen the hold's word. A banner that throws just leaves the word out. Deploy the API before the kit: an older API refuses the word, and the kit's server then drops it, so until the API is up a later "no" is not heard. The API keeps no address or browser for that buyer. Your server still passes the address, for the per-network caps on open holds (a keyed hash, which ends with the hold), and sends it with a text or email consent the buyer gives, as that consent's own evidence.
- **A throttle that can't lock out a sale**: `beforeRequest` runs before every page call but paying: a buyer who holds tickets can always pay. The default limits one address only when `clientIp` says the address is really known, and generously, because a carrier's NAT or a venue's Wi-Fi is thousands of real buyers: holds and order checks 120 a minute, code tries 60, reads 600, in this instance's memory. Over it the buyer reads "Tickets are very busy right now. Please try again in about N seconds", with `Retry-After` passed on. The API caps open holds per network on an event at 200 or a fifth of the stock left, whichever is more; `settings.network_hold_cap_enabled: false` on the org turns it off, and a count that fails lets the hold through. On serverless pass your own over a shared store.
- **Deep links**: `?tickets=1` opens the picker, `?type=tt_...&qty=2` preselects, `?code=EARLY` applies a code. `<CheckoutSheet label="Get tickets" />` is the same checkout in a full-screen dialog.
- **The on-sale moment** (`onSale.tsx`): a page opened before the sale says how long is left and opens by itself at the start time, by the server's clock, so nobody has to reload. The count shows only while nothing can be bought: with an early bird on sale, a later type just carries its own date on its row, and still opens by itself. It then reads the tickets again once, at a random moment within `openSpreadMs` (default 20 seconds), so a thousand open pages don't ask in the same second; the steppers don't wait for that read, and the hold is what checks. "Sales have ended" is said only by a read from after the start. On-sale times read in the venue's time, with its zone.
- **Parking alone** (an add-on with `per: 'order'`): it can be chosen with no ticket, and the page stays open for it after the tickets sell out. A per-ticket add-on, or refund protection, still waits for a ticket. An add-on's `state` reads its own pool, as a hold takes it.
- **A ticket that goes while the page is open**: a refused hold reads again, takes out what sold out or ended, brings down what is short, keeps the rest, and says what changed. The buyer never has to reload to go on.
- **A reload** in the middle of paying puts the buyer back on the same hold (the hold's id, a receipt and the items only; never a name, an email or a card). If the order was made, it shows the confirmation.
- **A double press** on Pay, or a retry after a timeout, makes one order.
- **The truth when the answer is lost**: "You have not been charged" shows only when that is so. After a charge attempt began with no answer, the page re-reads the hold and says "We can't confirm this payment yet", with a Check again that sends the very same request: the same payment and the same order.

## Payment

The payment step has one slot. In test mode the kit's own card form takes the API's test cards (the number picks a test token; only the token is sent). Four buttons above the card fields (Works, Declined, Not enough funds, Processor error) fill the number, expiry and code. **The number in the box is what counts**, whether a button put it there or you typed it; a number not on this list is refused ("That is not one of the test cards"), and the expiry and code are never checked:
`4242 4242 4242 4242` pays, `4000 0000 0000 0002` is declined, `4000 0000 0000 9995` has no funds, `4000 0000 0000 0119` is a processor error.

**A free order** skips all of this: no processor, no card form, one button.

**Square** (`client/square.tsx` + `server/square.ts`): Square's Web Payments SDK draws the card fields in its own frame and returns a one-time token.
Only the token goes to your server. It uses Square's delayed capture: it authorizes the HOLD's total (`autocomplete: false`, a `delay_duration`, `delay_action: CANCEL`), makes the order with an `external` payment whose reference is Square's payment id and `held: true`, and only then completes the payment and tells the API it landed. Until then the order is `pending`: no tickets, no money counted, no `order.paid`, and the buyer's confirmation says "Almost done". A refused order or a crash voids with no fee and no refund. The key is hold + card token, so a new card after a decline is a new attempt, and the same press retried is the same payment.

    // client
    <Checkout payment={squareSlot({ applicationId: 'sandbox-sq0idb-...', locationId: 'L...' })} />
    // server
    createCheckout({ ..., payment: squarePayment({ accessToken: process.env.SQUARE_ACCESS_TOKEN!, locationId: 'L...', baseUrl: 'https://connect.squareupsandbox.com' }) });

A test key with Square's production host, a live key with its sandbox, and an application id from the wrong world are all refused.

**The gap between the order and the capture**: the order is `pending` until the capture lands, so a crash there leaves an order with no tickets and no money counted, and a card with only an authorization on it. What closes it, each safe to repeat: the same request retried, the `order.paid` and `order.created` webhooks (a failure answers 5xx, so it is delivered again), and `checkout.sweep()` on a schedule. Each takes the money, then tells the API (`POST /v1/orders/{id}/external_payment`, `captured`), which makes the order paid and issues the tickets. The sweep also asks Square (`open.state`) about the pending orders it lists, so money Square took whose word never reached the API is told. `hold.expired` and the sweep void an authorization whose hold died, `order.paid` voids the hold's other authorizations, and Square itself cancels anything left when the delay runs out (3 days). A payment is captured only if its order is pending on it or paid with nothing refunded; otherwise it is voided and `onError` hears `capture_refused`.

**A capture that can never land** (Square cancelled the authorization) tells the API `lost`: the pending order is cancelled once (its seats go back; no ticket was ever issued, so nothing is voided at a door), the buyer is emailed that the card was not charged, each owner gets an email naming the order, `onError` hears `capture_lost`, and the sweep counts it in `lost` that once. If the buyer's own request meets it, they are told nothing was charged (`payment_voided`, `cause: payment_lost`) and the page offers "Hold the same tickets again": the hold is used up, so a new one is what works.

**Before taking money from an order that has waited**, the kit asks the API (`outcome: may_capture`). `void_me` means the event was cancelled or the same email has a newer order on this event: the kit voids, then says `lost` with `why`. So while the money has not been taken, a buyer who bought again pays once, and a cancelled event is never charged. The buyer's own first press takes no extra call: nothing can have changed in that moment. Money Square already took stands and is told to the API: the buyer has paid twice, and each owner gets one email naming the two orders so a person refunds one. If `open.state` answers `unknown`, nothing is taken, voided or said: the order stays and the next look asks again.

**Money with no order.** A person may cancel a pending order while Square holds or has taken the money. The order then says `payment_end: not_confirmed`, and the buyer is told to contact the organizer if their card shows a charge. Each sweep lists the cancelled orders with a failed external payment and asks `open.state`, so nothing needs remembering: `taken` tells the API `captured`, which it records once (`payment_end: taken_after_end`, `onError` hears `captured_after_end`, `SweepResult.money_after_end` counts it, the buyer is told they will be refunded, each owner gets an email with the reference and the amount). `dropped` turns the order to `not_charged`. The real gap: between Square taking the money and the next sweep, a person looking at the order can't see it. The Cancel dialog says to look in Square first. With no sweep running the gap stays open until someone looks, and only the owners' email at 2 hours speaks up. The API can't close it: it has no way to read your processor. A sweep reads cancelled orders made in the last 16 days.

**A refund in Square while the order waits** makes no tickets: `open.state` answers `refunded` (Square's `refunded_money`; a refunded payment stays `COMPLETED`), the kit does not confirm, and `onError` hears `capture_refunded`. Cancel the order if that was meant. Read from Square's docs; not yet run on the sandbox.

An order made by kit 0.1.1 or earlier was `paid` with tickets out before the capture: for those the kit can only report `capture_lost` (once per server start), and a person cancels or refunds the order. A page closed before the capture lands fires no Purchase or `onComplete` (nothing is running): the server's own Purchase, with the same event id, is the record of that sale. A page left open or reloaded within the cart's 35 minutes fires them when the order is paid.

**Another processor**: `externalPayment` in `server/payment.ts`, and a slot that returns `{ provider: 'yours', ... }`. Set `noRealMoney` on your slot only if it is true. Better, if it can: authorize in `charge`, take in `capture`, drop in `void`, and pass `open` (`list`, `capture`, `void`, and `state` so the sweep can find money taken whose word to the API was lost, or taken for an order a person cancelled; `createCheckout` says so at startup, `no_state`, if a slot with `capture` has none), and everything above is yours too. A slot with `capture` sends its payment `held`: its orders wait, pending, for the capture.

**The gap with a charge-first processor, plainly.** If the money is gone when `charge` returns, then a crash or a lost answer after it is a buyer charged with no order. The kit cannot undo that by itself. So a live key refuses `externalPayment` without `open`, unless you say `chargeFirstAcknowledged: true` and give a `store` of your own (a table, not memory). The kit writes each charge there, removes it when the order is made, and the sweep refunds any whose hold died with no order. `onError` hears `where: 'charged_no_order'` with the charge's `reference`: send that to a person. Between the crash and the next sweep the buyer is out the money, and if your `refund` fails they stay out of it until someone looks.

## The buyer's address

**A live key must set this** (or bring its own `beforeRequest`): `createCheckout` refuses to start otherwise. The address is what stops one visitor holding a whole sale for free, with no card: the API lets one network hold at most half of what is left of each pool, in tickets, with a floor of 4, so a family on one wifi can always buy. Only you know what is in front of your server, and a guess here refuses real buyers at an on-sale, so on a test key left unset the address is unknown: nothing is limited by address, no address goes on the hold, and if a proxy's header arrives `onError` hears `client_ip_unknown` once. Say which, in `createCheckout`:

| In front of your server | Set |
|---|---|
| Vercel | `clientIp: 'vercel'` (it overwrites the header; `x-real-ip`) |
| Cloudflare | `clientIp: 'cloudflare'` (`cf-connecting-ip`), and let only Cloudflare reach your server, or anyone can send that header |
| Cloud Run, Render, Fly, one load balancer | `clientIp: 'rightmost:1'`: they append, so the first entry is whatever the client sent, and the last one is theirs |
| Several proxies you run, none of them reachable around | `clientIp: 'rightmost:N'`, where N is how many you run |
| Nothing: your server faces the internet | `clientIp: 'peer'` (Express: `req.ip`, so `app.set('trust proxy', ...)` counts) |
| Firebase Hosting in front of a Function | `clientIp: hostingClientIp` (from `server`): the last hop, unless it is a Google front end, then the one before. Hosting replaces the header, so the function sees `<buyer>, <Google>`; a direct call to the function's own address keeps what the caller wrote and adds them last: `<anything>, <caller>`. So a fixed count from the right is wrong here: on a direct call it reads what the caller wrote. |
| Anything else | `clientIp: (req) => req.headers.get('your-header')` |

A live key whose holds name no address counts as one network, at most half of what is left. If your server really does sell from one place (a box office, a partner's own site), an owner can mark the key `sells_from_one_address` (`PATCH /v1/keys/{id}`, signed in). A test key is not counted, so testing will not show you this: send the address.

Held tickets are never called sold out: `state` stays `sold_out` with `held: true`, the page says "Every ticket is held right now" and offers Look again, and a hold answers 429 `rate_limited` with `param` `items` and a `Retry-After`. `param` `items[n].quantity` means fewer would fit.

During an attack an owner or admin can see which networks hold the most (`GET /v1/events/{id}/hold_networks`: hashed, no addresses) and let one go (`POST /v1/events/{id}/hold_networks/release`, with `dry_run`; it gives that network only "busy" for an hour unless you say otherwise, and never touches an order).

`trustProxy: true` is `clientIp: 'rightmost:1'`. Never `true` on a server anyone can reach directly: a client could then pin a victim's address and get them limited.

## Node 26 and your own `fetch`

On Node 26 the built-in `fetch` offers HTTP/2. Per origin, on a warm connection, it sends requests with a body one at a time, and anything sent behind one waits its turn, with no error. What decides it is whether the request has a body, not its method. A busy on-sale queues behind that connection (four buyers a second took 140 s each). The kit calls the API and Square with `serverFetch` (`server/serverFetch.ts`), which speaks HTTP/1.1 through Node's `https` there and is the plain `fetch` everywhere else.

**Your network setup.**
- `NODE_USE_ENV_PROXY=1` or `--use-env-proxy` with `HTTPS_PROXY`: the calls go through your proxy, at once.
- A global dispatcher you set with `setGlobalDispatcher` and anything but a bare `new Agent()` (`ProxyAgent`, `EnvHttpProxyAgent`, `MockAgent`, `.compose()`, an `Agent` with a private CA or a `lookup`): `serverFetch` uses the platform's `fetch`, so yours is honoured, **and on Node 26 the stall comes back**. For the CA alone, `NODE_EXTRA_CA_CERTS` keeps both.
- `NODE_TLS_REJECT_UNAUTHORIZED` and `NODE_EXTRA_CA_CERTS` apply as they do to anything on Node.

**Your own `fetch`, a stub, a tracing wrapper.** One passed as `fetch` to `createCheckout` or `squarePayment` is used as it is. One on `globalThis.fetch` is called as given, in any order, so a test's stub is called and a wrapper keeps working: **it stalls on Node 26, and says so once with a `console.warn`.** To keep the wrapper and lose the stall, wrap `http1Fetch` and pass that: `createCheckout({ fetch: (url, init) => traced(() => http1Fetch(url, init)) })`. Instrumentation of Node's `https` sees these calls; instrumentation that listens to undici does not.

**Next.js.** The kit's routes need nothing. If you set the cache yourself:

| In a route or page | Node 22 and earlier (the platform's `fetch`) | Node 26 (Next never sees the call) |
|---|---|---|
| Nothing, or `fetchCache = 'default-cache'` | Not kept: the call says `cache: 'no-store'` | Not kept |
| `fetchCache = 'force-cache'` | **Kept**: Next's rule beats `no-store` | Not kept |
| `fetchCache = 'only-cache'` | **Kept**: the call leaves out `no-store`, which would throw there | Not kept, no throw |
| `next: { revalidate, tags }` on a call you make with `serverFetch` | Honoured | **Dropped**, with no error: not kept, no tags |

On Node 26 Next can't see that a page made a call, so a page that calls the API as it renders says `export const dynamic = 'force-dynamic'`, or it is frozen at what the API said at build.

**Redirects.** A write is never sent twice: a redirect answered to anything but a GET or HEAD is an error that says so, and nothing more goes out. A GET or HEAD follows it, and never takes your key to another origin. The kit's normal failure then applies, a retry with the same Idempotency-Key.

## Going live

Do these in order. The manifest's `live` list says the same.

1. `node src/rcms-tickets/tools/kit.mjs verify`, and compare `kit.lock` with the manifest's sha256 for your version. Anything CHANGED should be a change you meant.
2. Update if `advisories` lists anything for your version.
Rehearse the rest on a test key first: the webhook, the sweep, the emails.
3. Live key and production `RCMS_TICKETS_BASE_URL`, in the production environment only.
4. `squarePayment({ accessToken, locationId })` and `squareSlot({ applicationId: 'sq0idp-...', locationId })`.
5. `SITE_URL`: the public address, no trailing slash. The abandoned-checkout link is built from it.
6. Register the webhook once with your live key: `POST /v1/webhook_endpoints` with url `${SITE_URL}/api/tickets/webhook` and events `order.paid`, `order.created`, `hold.expired`. Its answer holds the signing secret, once: put it in `RCMS_TICKETS_WEBHOOK_SECRET`.
7. `RCMS_TICKETS_SWEEP_SECRET`: 32 random characters or more, required on a live key. Call `/api/tickets/sweep` every 15 minutes from your scheduler with `Authorization: Bearer <it>` (Vercel Cron: set `CRON_SECRET` to the same value, and check your plan allows that often).
8. Wire `adConsent` (`consent.ts`) to your cookie banner. Where the law asks for consent first, answer `denied` until the buyer agrees, and call `captureAttribution` again when they do, on the same page: the tags wait in memory. `denied` also keeps the address and the browser out of the attribution; a marketing consent keeps its own address.
9. Send `onError` where a person will see it. Required on a live key.
10. `clientIp` for your hosting, required on a live key. **Check it took:** make one hold on the live site, then, signed in or with a full key, `GET /v1/events/{id}/hold_networks`: it must list one network with `from_key: null`. `from_key` set, or `onError` hearing `client_ip_none`, means your holds name no address and all count as one network: fix `clientIp` before you sell. On serverless, your own `beforeRequest` and `abandonedGate` over a shared store.
11. If you have a Content-Security-Policy, allow what Square's Web Payments docs list.
12. Buy one real ticket with a real card, see it captured in Square and paid in RCMS Tickets, then refund it.

## Updating the kit

Your copy says its version on every API call (`rcms-tickets-kit`), and `kit.lock` records the sha256 of every file as installed, so we can tell you when a version has a problem and you can see what you changed.

    node src/rcms-tickets/tools/kit.mjs verify
    node src/rcms-tickets/tools/kit.mjs update --manifest <the manifest's url>

The manifest is signed: the tool checks it against the key inside the tool before it writes anything, and a tampered one stops in plain words. The first install trusts the page it was fetched from and its TLS, which nothing can improve on; every update after that checks the signature. It refuses an older version without `--allow-downgrade`, and a version that would remove most of the kit without `--allow-removals`. An advisory stays until the file it is about has really moved.

An agent doing this: read every ADVISORY first and say it to the owner. REPLACED, ADDED and REMOVED were files nobody changed. CONFLICT is a file changed on both sides: yours stays, the new copy is in `.kit-update/`, and the diff is printed. Merge the new behaviour into yours, then `update --accept <path>`. Never paste over someone's change unread. The recipe's files are yours and are not touched. Then typecheck, build, buy a test ticket, and commit `kit.lock`.

## Refund protection

An add-on the organizer marked as refund protection is money held for someone else, not sales. Your pixels' values leave it out (`client/pixel.ts`), and `order.pass_through` and `hold.price.pass_through` say how much of the total it is, for any report of your own. It shows `PROTECTION_WORDS` (`client/messages.ts`) at sale: edit them to your provider's terms.

## A second tab

The same tab always finds its order, reload or not. A brand new tab has no memory of it, on purpose: nothing about a buyer is kept beyond the tab, and buying twice from two tabs is a real thing people do for two groups of friends. It is a separate hold and a separate order. If that matters to your event, set a per-buyer limit on the event: the API refuses over it with the buyer's email (`order_maximum_exceeded`).

## Rules the kit keeps (keep them when you change it)

- The price on screen is the hold's, exactly as the server computed it; the page never adds up money it will charge.
- A card number never reaches your server or ours. A payment is a token.
- Nothing about a person goes in a URL. Nothing is logged with a name, an email or a card.
- A date with no time (`2027-07-16`) is a calendar day: never hand it to the `Date` constructor as a string.
````

### src/rcms-tickets/client/AddOns.tsx

````tsx
import { formatMoney } from './money';
import { PROTECTION_WORDS } from './messages';
import { unavailableWhy } from './TicketPicker';
import { goesAlone } from './useCheckout';
import { cx, Icon, Stepper } from './ui';
import type { Storefront } from './types';

export interface AddOnsProps {
  store: Storefront;
  addOns: Record<string, number>;
  ticketCount: number;
  onChange: (id: string, quantity: number) => void;
}

/** Extras (parking, a drink package). One bought for the order can be bought alone; one per ticket waits for a ticket. Not shown when the event has none. */
export function AddOns({ store, addOns, ticketCount, onChange }: AddOnsProps) {
  if (!store.add_ons.length) return null;
  return (
    <section className="rt-section" aria-labelledby="rt-addons-h">
      <h2 className="rt-h2" id="rt-addons-h">
        Add to your order
      </h2>
      <ul className="rt-list">
        {store.add_ons.map((a) => {
          const why = unavailableWhy(a, store);
          const n = addOns[a.add_on] ?? 0;
          const cap = a.per === 'ticket' ? Math.min(a.per_order_max, ticketCount) : a.per_order_max;
          const waits = ticketCount === 0 && !goesAlone(a);
          const max = why || waits ? 0 : Math.min(cap, a.remaining ?? cap);
          const note = a.fees_passed_on && a.taxed ? 'plus fees and tax' : a.fees_passed_on ? 'plus fees' : a.taxed ? 'plus tax' : '';
          return (
            <li key={a.add_on} className={cx('rt-row', n > 0 && 'rt-row-on', why && 'rt-row-off')}>
              <div className="rt-row-main">
                <h3 className="rt-row-title">{a.name}</h3>
                {a.description ? <p className="rt-row-sub">{a.description}</p> : null}
                {a.per === 'ticket' ? <p className="rt-row-sub">One per ticket</p> : null}
                {a.pass_through ? <p className="rt-row-sub">{PROTECTION_WORDS}</p> : null}
                <p className="rt-price">
                  <strong>{formatMoney(a.price)}</strong>
                  {note ? <span className="rt-note"> {note}</span> : null}
                </p>
                {why ? (
                  <p className="rt-badge rt-badge-off">
                    <Icon name="alert" size={16} /> {why}
                  </p>
                ) : a.state === 'low' && a.remaining !== null ? (
                  <p className="rt-badge rt-badge-low">
                    <Icon name="clock" size={16} /> Only {a.remaining} left
                  </p>
                ) : waits ? (
                  <p className="rt-row-sub">Choose a ticket first.</p>
                ) : null}
              </div>
              {why ? null : <Stepper label={a.name} value={n} max={max} onChange={(v) => onChange(a.add_on, v)} disabled={waits} />}
            </li>
          );
        })}
      </ul>
    </section>
  );
}
````

### src/rcms-tickets/client/BuyerForm.tsx

````tsx
import { useId } from 'react';
import { Button, Field } from './ui';
import type { AttendeeData, CheckoutState } from './useCheckout';
import type { Answers, Question, Storefront } from './types';

/*
  The details step: who is buying, the questions the event and the chosen tickets ask, each ticket holder when a type wants
  them, and the marketing checkboxes with their exact words (the order records which version of the words was shown).
  Nothing is ticked for the buyer.
*/

type Value = Answers[string] | undefined;

const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

/** A date as three plain fields (month, day, year): easier than a wheel for a birth date, and it is what the answer stores. */
function DateField({ name, label, value, error, hint, optional, onChange }: { name: string; label: string; value: string; error?: string; hint?: string; optional?: boolean; onChange: (v: string) => void }) {
  const id = useId();
  const [y = '', m = '', d = ''] = value.split('-');
  const set = (next: { y?: string; m?: string; d?: string }) => {
    const Y = (next.y ?? y).replace(/\D/g, '').slice(0, 4);
    const M = next.m ?? m;
    const D = (next.d ?? d).replace(/\D/g, '').slice(0, 2);
    onChange(Y || M || D ? `${Y}-${M}-${D.padStart(D ? 2 : 0, '0')}` : '');
  };
  return (
    <fieldset className={`rt-fieldset ${error ? 'rt-field-error' : ''}`} aria-describedby={error ? `${id}-e` : hint ? `${id}-h` : undefined}>
      <legend className="rt-label">
        {label}
        {optional ? <span className="rt-optional"> (optional)</span> : null}
      </legend>
      <div className="rt-date">
        <select className="rt-input rt-date-month" name={`${name}_month`} aria-label="Month" value={m} autoComplete="bday-month" onChange={(e) => set({ m: e.target.value })} aria-invalid={!!error || undefined}>
          <option value="">Month</option>
          {MONTHS.map((n, i) => (
            <option key={n} value={String(i + 1).padStart(2, '0')}>
              {n}
            </option>
          ))}
        </select>
        <input className="rt-input" type="text" name={`${name}_day`} aria-label="Day" inputMode="numeric" autoComplete="bday-day" placeholder="Day" value={d.replace(/^0/, '')} maxLength={2} onChange={(e) => set({ d: e.target.value })} aria-invalid={!!error || undefined} />
        <input className="rt-input rt-date-year" type="text" name={`${name}_year`} aria-label="Year" inputMode="numeric" autoComplete="bday-year" placeholder="Year" value={y} maxLength={4} onChange={(e) => set({ y: e.target.value })} aria-invalid={!!error || undefined} />
      </div>
      {hint ? (
        <p className="rt-hint" id={`${id}-h`}>
          {hint}
        </p>
      ) : null}
      {error ? (
        <p className="rt-error" id={`${id}-e`}>
          {error}
        </p>
      ) : null}
    </fieldset>
  );
}

const ADDRESS_KEYS = ['line1', 'line2', 'city', 'region', 'postal_code', 'country'] as const;

/** `prefix` keeps one ticket's field names apart from another's (`ticket_2_`). */
export function QuestionField({ q, value, error, onChange, prefix = '' }: { prefix?: string; q: Question; value: Value; error?: string; onChange: (v: Value) => void }) {
  const label = q.label;
  const hint = q.help ?? undefined;
  const optional = !q.required;
  if (q.kind === 'date') return <DateField name={`${prefix}q_${q.key}`} label={label} value={typeof value === 'string' ? value : ''} error={error} hint={hint} optional={optional} onChange={onChange} />;
  if (q.kind === 'checkbox') {
    return (
      <div className={`rt-check ${error ? 'rt-field-error' : ''}`}>
        <label className="rt-check-row">
          <input type="checkbox" name={`${prefix}q_${q.key}`} checked={value === true} onChange={(e) => onChange(e.target.checked)} aria-invalid={!!error || undefined} />
          <span>{label}</span>
        </label>
        {hint ? <p className="rt-hint">{hint}</p> : null}
        {error ? <p className="rt-error">{error}</p> : null}
      </div>
    );
  }
  if (q.kind === 'multi_select') {
    const picked = Array.isArray(value) ? value : [];
    return (
      <fieldset className={`rt-fieldset ${error ? 'rt-field-error' : ''}`}>
        <legend className="rt-label">
          {label}
          {optional ? <span className="rt-optional"> (optional)</span> : null}
        </legend>
        {(q.options ?? []).map((o) => (
          <label className="rt-check-row" key={o}>
            <input type="checkbox" name={`${prefix}q_${q.key}`} value={o} checked={picked.includes(o)} onChange={(e) => onChange(e.target.checked ? [...picked, o] : picked.filter((x) => x !== o))} />
            <span>{o}</span>
          </label>
        ))}
        {error ? <p className="rt-error">{error}</p> : null}
      </fieldset>
    );
  }
  if (q.kind === 'address') {
    const a = (value && typeof value === 'object' && !Array.isArray(value) ? value : {}) as Record<string, string>;
    const names: Record<string, string> = { line1: 'Street address', line2: 'Apartment, suite', city: 'City', region: 'State', postal_code: 'ZIP code', country: 'Country' };
    return (
      <fieldset className={`rt-fieldset ${error ? 'rt-field-error' : ''}`}>
        <legend className="rt-label">{label}</legend>
        {ADDRESS_KEYS.map((k) => (
          <Field key={k} label={names[k]!} optional={k === 'line2'}>
            {(p) => <input {...p} className="rt-input" type="text" name={`${prefix}address_${k}`} value={a[k] ?? (k === 'country' ? 'US' : '')} autoComplete={k === 'line1' ? 'address-line1' : k === 'line2' ? 'address-line2' : k === 'city' ? 'address-level2' : k === 'region' ? 'address-level1' : k === 'postal_code' ? 'postal-code' : 'country'} onChange={(e) => onChange({ line2: null, country: 'US', ...a, [k]: e.target.value } as unknown as Value)} />}
          </Field>
        ))}
        {error ? <p className="rt-error">{error}</p> : null}
      </fieldset>
    );
  }
  return (
    <Field label={label} hint={hint} error={error} optional={optional}>
      {(p) =>
        q.kind === 'select' ? (
          <select {...p} className="rt-input" name={`${prefix}q_${q.key}`} value={typeof value === 'string' ? value : ''} onChange={(e) => onChange(e.target.value)}>
            <option value="">Choose one</option>
            {(q.options ?? []).map((o) => (
              <option key={o} value={o}>
                {o}
              </option>
            ))}
          </select>
        ) : q.kind === 'long_text' ? (
          <textarea {...p} className="rt-input rt-textarea" name={`${prefix}q_${q.key}`} value={typeof value === 'string' ? value : ''} onChange={(e) => onChange(e.target.value)} rows={3} />
        ) : (
          <input
            {...p}
            className="rt-input"
            name={`${prefix}q_${q.key}`}
            type={q.kind === 'email' ? 'email' : q.kind === 'phone' ? 'tel' : 'text'}
            inputMode={q.kind === 'number' ? 'numeric' : q.kind === 'phone' ? 'tel' : q.kind === 'email' ? 'email' : undefined}
            value={typeof value === 'string' || typeof value === 'number' ? String(value) : ''}
            autoComplete={q.key === 'postal_code' ? 'postal-code' : q.key === 'company' ? 'organization' : 'off'}
            onChange={(e) => onChange(q.kind === 'number' ? (e.target.value === '' ? '' : Number.parseInt(e.target.value, 10) || 0) : e.target.value)}
          />
        )
      }
    </Field>
  );
}

export function BuyerForm({ c, store }: { c: CheckoutState; store: Storefront }) {
  const { buyer, setBuyer, consent, setConsent, answers, setAnswers, errors, questionList, attendeeSlots, attendees, setAttendee } = c;
  const emailText = store.event.consent_texts.email;
  const smsText = store.event.consent_texts.sms;
  const ageOf = c.chosen.find((t) => t.min_age)?.min_age;
  return (
    <form
      className="rt-form"
      noValidate
      onSubmit={(e) => {
        e.preventDefault();
        void c.toPay();
      }}
    >
      <section className="rt-section" aria-labelledby="rt-you-h">
        <h2 className="rt-h2" id="rt-you-h">
          Your details
        </h2>
        <Field label="Full name" error={errors['buyer.name']}>
          {(p) => <input {...p} className="rt-input" type="text" name="name" value={buyer.name} autoComplete="name" onChange={(e) => setBuyer({ ...buyer, name: e.target.value })} />}
        </Field>
        <Field label="Email" hint="For your order and tickets." error={errors['buyer.email']}>
          {(p) => <input {...p} className="rt-input" type="email" name="email" inputMode="email" autoComplete="email" value={buyer.email} onChange={(e) => setBuyer({ ...buyer, email: e.target.value })} onBlur={() => void c.saveEmail()} />}
        </Field>
        <Field label="Mobile number" optional={!smsText || !consent.sms} hint={smsText ? 'Only needed if you want text updates.' : undefined} error={errors['buyer.phone']}>
          {(p) => <input {...p} className="rt-input" type="tel" name="phone" inputMode="tel" autoComplete="tel" value={buyer.phone} onChange={(e) => setBuyer({ ...buyer, phone: e.target.value })} />}
        </Field>
      </section>

      {questionList.length ? (
        <section className="rt-section" aria-labelledby={questionList.length > 1 ? 'rt-more-h' : undefined}>
          {questionList.length > 1 ? (
            <h2 className="rt-h2" id="rt-more-h">
              A few questions
            </h2>
          ) : null}
          {questionList.map((q) => (
            <QuestionField key={q.key} q={q} value={answers[q.key]} error={errors[`q.${q.key}`]} onChange={(v) => setAnswers({ ...answers, [q.key]: v as Answers[string] })} />
          ))}
          {ageOf ? <p className="rt-hint">This event is {ageOf}+. You will show photo ID at the door.</p> : null}
        </section>
      ) : null}

      {attendeeSlots.length ? (
        <section className="rt-section" aria-labelledby="rt-holders-h">
          <h2 className="rt-h2" id="rt-holders-h">
            Who is each ticket for?
          </h2>
          {attendeeSlots.map((s, i) => {
            const a: AttendeeData = attendees[s.key] ?? { name: '', email: '', answers: {} };
            return (
              <fieldset className="rt-fieldset" key={s.key}>
                <legend className="rt-h3">
                  {s.type.name}, ticket {s.index + 1}
                </legend>
                {s.type.holder_details !== 'none' ? (
                  <Field label="Name" error={errors[`a.${s.key}.name`]}>
                    {(p) => <input {...p} className="rt-input" type="text" name={`ticket_${s.index + 1}_name`} value={a.name} autoComplete="off" onChange={(e) => setAttendee(s.key, { name: e.target.value })} />}
                  </Field>
                ) : null}
                {i === 0 && buyer.name && !a.name && s.type.holder_details !== 'none' ? (
                  <Button kind="quiet" onClick={() => setAttendee(s.key, { name: buyer.name, email: s.type.holder_details === 'name_and_email' ? buyer.email : '' })}>
                    Use my name
                  </Button>
                ) : null}
                {s.type.holder_details === 'name_and_email' ? (
                  <Field label="Email" error={errors[`a.${s.key}.email`]}>
                    {(p) => <input {...p} className="rt-input" type="email" name={`ticket_${s.index + 1}_email`} inputMode="email" value={a.email} onChange={(e) => setAttendee(s.key, { email: e.target.value })} />}
                  </Field>
                ) : null}
                {s.type.questions
                  .filter((q) => q.scope === 'ticket')
                  .map((q) => (
                    <QuestionField key={q.key} prefix={`ticket_${s.index + 1}_`} q={q} value={a.answers[q.key]} error={errors[`a.${s.key}.q.${q.key}`]} onChange={(v) => setAttendee(s.key, { answers: { ...a.answers, [q.key]: v as Answers[string] } })} />
                  ))}
              </fieldset>
            );
          })}
        </section>
      ) : null}

      {emailText || smsText ? (
        <section className="rt-section" aria-labelledby="rt-consent-h">
          <h2 className="rt-h2 rt-sr" id="rt-consent-h">
            Updates
          </h2>
          {emailText ? (
            <label className="rt-check-row">
              <input type="checkbox" name="consent_email" checked={consent.email} onChange={(e) => setConsent({ ...consent, email: e.target.checked })} />
              <span>{emailText.text}</span>
            </label>
          ) : null}
          {smsText ? (
            <label className="rt-check-row">
              <input type="checkbox" name="consent_sms" checked={consent.sms} onChange={(e) => setConsent({ ...consent, sms: e.target.checked })} />
              <span>{smsText.text}</span>
            </label>
          ) : null}
        </section>
      ) : null}
    </form>
  );
}
````

### src/rcms-tickets/client/Checkout.tsx

````tsx
import { useEffect, useRef, type ReactNode } from 'react';
import { AddOns } from './AddOns';
import { BuyerForm } from './BuyerForm';
import { CodeField } from './CodeField';
import { Confirmation } from './Confirmation';
import { eventDates } from './dates';
import { moneyOrFree } from './money';
import { OpensIn } from './onSale';
import { PaymentStep, type PaymentSlot } from './PaymentStep';
import { HoldTimer, Summary } from './Summary';
import { TicketPicker } from './TicketPicker';
import { Button, cx, Icon, NoticeBar } from './ui';
import { canBuyNow, goesAlone, useCheckout, type CheckoutOptions, type CheckoutState, type Step } from './useCheckout';
import type { Money, Storefront } from './types';

export interface CheckoutProps extends CheckoutOptions {
  /** Where the card is taken. Default: the test provider's card form (test mode only). */
  payment?: PaymentSlot;
  /** "light" or "dark" forces a theme; leave it out to follow the buyer's phone. */
  scheme?: 'light' | 'dark';
  className?: string;
  /** Inline CSS variables, e.g. brandStyle('#c8102e'). */
  style?: React.CSSProperties;
  /** The event's name at the top: `'h1'` (default), `'h2'` when your page already has its own h1, or `false` to leave it out (the dates and venue stay). */
  eventHeading?: 'h1' | 'h2' | false;
  /** Anything to show under the event's name (a banner, a lineup). */
  intro?: ReactNode;
  /** After this long with no answer to a payment, the buyer is told it is still going, in ms. Default 6000. */
  slowAfterMs?: number;
  /** The words for a code that is on the order. Default: "Code X is on your order." */
  codeAppliedWords?: (code: string) => string;
  /** A line under those words. Default: none. */
  codeAppliedNote?: string | undefined;
  /** Something to say beside the action (the count and the money), once tickets are chosen. `extra`: fees or tax may be added to this. Default: nothing. */
  barNote?: (info: { tickets: number; total: Money; extra: boolean }) => ReactNode;
}

const STEPS: Array<{ key: Exclude<Step, 'done'>; label: string }> = [
  { key: 'tickets', label: 'Tickets' },
  { key: 'details', label: 'Details' },
  { key: 'pay', label: 'Payment' },
];

function Progress({ step, free }: { step: Step; free: boolean }) {
  if (step === 'done') return null;
  const at = STEPS.findIndex((s) => s.key === step);
  return (
    <ol className="rt-progress" aria-label="Checkout steps">
      {STEPS.map((s, i) => (
        <li key={s.key} className={cx(i === at && 'rt-progress-now', i < at && 'rt-progress-done')} aria-current={i === at ? 'step' : undefined}>
          <span className="rt-progress-n">{i < at ? <Icon name="check" size={14} /> : i + 1}</span>
          <span>{s.key === 'pay' && free ? 'Confirm' : s.label}</span>
        </li>
      ))}
    </ol>
  );
}

const estimateLines = (c: CheckoutState, store: Storefront) => [
  ...c.chosen.map((t) => ({ name: t.name, quantity: c.qty[t.ticket_type]!, price: t.price })),
  ...store.add_ons.filter((a) => (c.addOns[a.add_on] ?? 0) > 0).map((a) => ({ name: a.name, quantity: c.addOns[a.add_on]!, price: a.price })),
];
const estimateExtra = (c: CheckoutState, store: Storefront): boolean => store.order_fees_passed_on || c.chosen.some((t) => t.fees_passed_on || t.taxed);
const estimateSum = (c: CheckoutState, store: Storefront): Money => ({ amount: estimateLines(c, store).reduce((n, l) => n + l.price.amount * l.quantity, 0), currency: store.event.currency });

/** What the picker adds up to before there is a hold. The real price comes from the hold; this says so. */
function Estimate({ c, store }: { c: CheckoutState; store: Storefront }) {
  const lines = estimateLines(c, store);
  const sum = estimateSum(c, store);
  const extra = estimateExtra(c, store);
  return (
    <aside className="rt-summary" aria-labelledby="rt-est-h">
      <h2 className="rt-h2" id="rt-est-h">
        Your order
      </h2>
      {lines.length === 0 ? (
        <p className="rt-row-sub">Nothing chosen yet.</p>
      ) : (
        <dl className="rt-lines">
          {lines.map((l) => (
            <div className="rt-line" key={l.name}>
              <dt>
                {l.quantity} &times; {l.name}
              </dt>
              <dd>{moneyOrFree({ amount: l.price.amount * l.quantity, currency: l.price.currency })}</dd>
            </div>
          ))}
          <div className="rt-line rt-line-total">
            <dt>Subtotal</dt>
            <dd>{moneyOrFree(sum)}</dd>
          </div>
        </dl>
      )}
      {lines.length && extra ? <p className="rt-hint">Fees and tax, if any, are added on the next step.</p> : null}
    </aside>
  );
}

/** Every ticket is on someone's hold: gone for now, and they may come back. Never "Sold out". */
export const HELD_WORDS = 'Every ticket is held right now. Try again in a few minutes.';

function Closed({ store, onLook }: { store: Storefront; onLook: () => void }) {
  const sold = store.event.status === 'on_sale' && store.ticket_types.length > 0 && store.ticket_types.every((t) => t.state === 'sold_out');
  if (sold && store.ticket_types.some((t) => t.held)) {
    return (
      <section className="rt-section">
        <NoticeBar tone="info" action={<Button kind="secondary" onClick={onLook}>Look again</Button>}>
          {HELD_WORDS}
        </NoticeBar>
      </section>
    );
  }
  const text =
    store.event.status === 'cancelled' ? 'This event was cancelled.' : store.event.status === 'ended' ? 'This event has ended.' : sold ? 'Sold out. Every ticket has been sold.' : store.event.status === 'paused' ? 'Ticket sales are paused for now. Please check back soon.' : store.event.status === 'draft' ? 'Tickets are not on sale yet.' : 'There are no tickets on sale right now.';
  return (
    <section className="rt-section">
      <NoticeBar tone="info">{text}</NoticeBar>
    </section>
  );
}

/**
 * The whole checkout, in the page: tickets, add-ons and a code, your details, payment, the confirmation. Everything it needs
 * comes from your own server (../server), so there is nothing to embed and no key in the browser.
 */
export function Checkout(props: CheckoutProps) {
  const c = useCheckout(props);
  const { store, step } = c;
  const bodyRef = useRef<HTMLDivElement>(null);
  const rootRef = useRef<HTMLDivElement>(null);
  const placing = useRef(false);
  const first = useRef(true);
  useEffect(() => {
    if (first.current) {
      first.current = false;
      return;
    }
    // Focus for a screen reader, then the scroll by hand: the browser would leave the heading under the floating clock if it thinks it can already see it.
    bodyRef.current?.focus({ preventScroll: true });
    bodyRef.current?.scrollIntoView({ block: 'start', behavior: 'instant' });
  }, [step, c.expired]);
  // What the keyboard lands on must not sit under the floating bar or the clock (a phone: the bar is fixed, the page scrolls behind it).
  useEffect(() => {
    const root = rootRef.current;
    if (!root) return;
    const onFocus = (e: FocusEvent) => {
      const el = e.target as HTMLElement;
      // A press moves focus between its down and its up: scrolling then would pull the target out from under the finger, and the press would miss.
      if (placing.current || pressing) return;
      if (!el.matches('input, select, textarea, button, a') || el.closest('.rt-actions, .rt-timebar')) return;
      const r = el.getBoundingClientRect();
      const bar = root.querySelector<HTMLElement>('.rt-actions');
      const clockEl = root.querySelector<HTMLElement>('.rt-timebar');
      const floor = bar && getComputedStyle(bar).position === 'fixed' ? bar.getBoundingClientRect().top : window.innerHeight;
      const ceiling = clockEl ? clockEl.getBoundingClientRect().bottom : 0;
      if (r.bottom > floor || r.top < ceiling) el.scrollIntoView({ block: 'center', behavior: 'instant' });
    };
    let pressing = false;
    const down = () => {
      pressing = true;
    };
    const up = () => {
      pressing = false;
    };
    root.addEventListener('pointerdown', down, true);
    window.addEventListener('pointerup', up, true);
    window.addEventListener('pointercancel', up, true);
    root.addEventListener('focusin', onFocus);
    return () => {
      root.removeEventListener('pointerdown', down, true);
      window.removeEventListener('pointerup', up, true);
      window.removeEventListener('pointercancel', up, true);
      root.removeEventListener('focusin', onFocus);
    };
  }, [!!store]); // eslint-disable-line react-hooks/exhaustive-deps
  useEffect(() => {
    const root = document.getElementById('rt-checkout');
    // Inside the sheet it is already in view, and scrolling would hide the Close button.
    if (c.deep.open && store && step === 'tickets' && !root?.closest('dialog')) root?.scrollIntoView({ block: 'start' });
    // once the store is here
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [!!store]);
  // The tab says where the buyer is: a screen reader's first word on a new step, and how they find it again. Put back as it was on the way out.
  const eventName = store?.event.name;
  useEffect(() => {
    if (!eventName) return;
    const before = document.title;
    document.title = `${c.step === 'done' ? 'Your tickets' : (STEPS.find((s) => s.key === c.step)?.label ?? '')} · ${eventName}`;
    return () => {
      document.title = before;
    };
  }, [c.step, eventName]);
  // Something the buyer must see just appeared, maybe far above the button they pressed: take them to it (a field first, else the notice).
  useEffect(() => {
    if (!c.attention) return;
    const root = rootRef.current;
    if (!root) return;
    const target = root.querySelector<HTMLElement>('.rt-field-error input, .rt-field-error select, .rt-field-error textarea, [aria-invalid="true"]') ?? root.querySelector<HTMLElement>('.rt-notice-error, .rt-notice-warn, .rt-notice, .rt-refused');
    if (!target) return;
    placing.current = true; // the scroll just below is the one that counts
    target.focus({ preventScroll: true });
    placing.current = false;
    const found = target.closest<HTMLElement>('.rt-field, .rt-fieldset, .rt-check, .rt-notice') ?? target;
    // A notice right under its heading brings the heading along, or the heading slides half under the clock.
    const above = found.previousElementSibling;
    const place = above instanceof HTMLElement && above.matches('.rt-h2') ? above : found;
    // The one-line summary too, when it and the field fit on the screen together; the field alone when they don't.
    const summary = root.querySelector<HTMLElement>('.rt-notice-error');
    const bar = root.querySelector<HTMLElement>('.rt-actions');
    const room = window.innerHeight - 76 - (bar && getComputedStyle(bar).position === 'fixed' ? bar.offsetHeight + 12 : 0);
    const together = summary ? place.getBoundingClientRect().bottom - summary.getBoundingClientRect().top : Infinity;
    // Instant: a site's `scroll-behavior: smooth` could still be running from the buyer's own scroll, and the two fight, leaving the field off screen (seen in Chromium).
    (summary && together >= 0 && together <= room ? summary : place).scrollIntoView({ block: 'start', behavior: 'instant' });
  }, [c.attention]);

  if (c.loadError && !store) {
    return (
      <div className={cx('rt-checkout', props.className)} id="rt-checkout" data-rt-scheme={props.scheme} style={props.style}>
        <NoticeBar tone="error" action={<Button kind="secondary" onClick={() => void c.reload()}>Try again</Button>}>
          {c.loadError}
        </NoticeBar>
      </div>
    );
  }
  if (!store) {
    return (
      <div className={cx('rt-checkout', props.className)} id="rt-checkout" data-rt-scheme={props.scheme} style={props.style} aria-busy="true">
        <div className="rt-skeleton" role="status" aria-label="Loading tickets" />
      </div>
    );
  }

  // Sold-out tickets don't close the page while parking can still be bought alone.
  const open = store.event.status === 'on_sale' && (store.ticket_types.some((t) => t.state !== 'sold_out') || store.add_ons.some((a) => goesAlone(a) && a.state !== 'sold_out'));
  const hold = c.hold;
  const noteBar = c.notice ? (
    <NoticeBar tone={c.notice.tone}>{c.notice.text}</NoticeBar>
  ) : null;

  const expiredPanel =
    c.expired && hold && step !== 'done' ? (
      <section className="rt-section" aria-labelledby="rt-exp-h">
        <h2 className="rt-h2" id="rt-exp-h">
          {c.released ? 'Your tickets were released' : 'Your time ran out'}
        </h2>
        <p className="rt-lead">We can try to hold them again.</p>
        <Button busy={c.holding} onClick={() => void c.holdAgain()}>
          Hold the same tickets again
        </Button>
      </section>
    ) : null;

  const refusedPanel = c.refusal ? (
    <section className="rt-section rt-refused" aria-labelledby="rt-ref-h" tabIndex={-1}>
      <h2 className="rt-h2" id="rt-ref-h">
        {c.refusal.title ?? 'We could not finish your order'}
      </h2>
      <p className="rt-lead">{c.refusal.text}</p>
      {c.refusal.action === 'again' ? (
        <Button busy={c.holding} onClick={() => void c.holdAgain()}>
          Hold the same tickets again
        </Button>
      ) : c.refusal.action === 'pay' ? (
        <Button onClick={c.tryAfterRefusal}>Try again</Button>
      ) : null}
    </section>
  ) : null;

  const unconfirmedPanel = c.unconfirmed ? (
    <section className="rt-section" aria-labelledby="rt-unc-h" role="alert">
      <h2 className="rt-h2" id="rt-unc-h">
        We can&rsquo;t confirm this payment yet
      </h2>
      <p className="rt-lead">It may still be finishing. You will not be charged twice.</p>
      <Button busy={c.checking} onClick={() => void c.recheck(true)}>
        Check again
      </Button>
      <p className="rt-hint" role="status">
        {`Last checked at ${new Date(c.lastChecked ?? Date.now()).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })}.${c.hold ? ` We will know by ${new Date(Date.parse(c.hold.expires_at)).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })}.` : ''}`}
      </p>
    </section>
  ) : null;

  const noRealMoney = !props.payment || !!props.payment.noRealMoney?.(store.mode);
  const special = refusedPanel ?? unconfirmedPanel ?? expiredPanel;
  const main = special ?? (
    <>
      {step === 'tickets' ? (
        open ? (
          <>
            {store.ticket_types.length > 0 && store.ticket_types.every((t) => t.state === 'sold_out' && t.held) ? <Closed store={store} onLook={() => void c.reload()} /> : null}
            {canBuyNow(store) ? null : <OpensIn store={store} now={c.serverNow} />}
            <TicketPicker store={store} qty={c.qty} onChange={c.setTicket} />
            <AddOns store={store} addOns={c.addOns} ticketCount={c.ticketCount} onChange={c.setAddOn} />
            <CodeField value={c.codeInput} onChange={c.setCodeInput} applied={c.hold?.code ?? c.appliedCode} busy={c.codeBusy} note={c.codeNote} onApply={() => void c.applyCode()} onRemove={() => void c.removeCode()} appliedWords={props.codeAppliedWords} appliedNote={props.codeAppliedNote} />
          </>
        ) : (
          <Closed store={store} onLook={() => void c.reload()} />
        )
      ) : null}
      {step === 'details' ? (
        <>
          {c.errorSummary ? <NoticeBar tone="error">{c.errorSummary}</NoticeBar> : null}
          {c.payError && c.errorSummary ? <NoticeBar tone={c.payError.tone}>{c.payError.text}</NoticeBar> : null}
          <BuyerForm c={c} store={store} />
        </>
      ) : null}
      {step === 'pay' && hold ? <PaymentStep hold={hold} mode={store.mode} slot={props.payment} busy={c.paying} error={c.payError} onSubmit={(p) => void c.pay(p)} onBack={() => c.setStep('details')} slowAfterMs={props.slowAfterMs} /> : null}
      {step === 'done' && c.order ? <Confirmation order={c.order} store={store} noRealMoney={noRealMoney} onBuyMore={c.buyMore} /> : null}
    </>
  );

  const freeNow = !!hold && hold.price.total.amount === 0;
  const showSide = step !== 'done' && !special && (step !== 'tickets' || open);
  const barNote = props.barNote && action0() ? props.barNote({ tickets: c.ticketCount, total: hold && step !== 'tickets' ? hold.price.total : estimateSum(c, store), extra: step === 'tickets' && estimateExtra(c, store) }) : null;
  function action0(): boolean {
    return (step === 'tickets' || step === 'details') && c.hasChoice;
  }
  const action =
    step === 'tickets' ? (
      <Button busy={c.holding} onClick={() => void c.toDetails()}>
        Continue
      </Button>
    ) : step === 'details' ? (
      <>
        <Button busy={c.checking} onClick={() => void c.toPay()}>
          {freeNow ? 'Continue' : 'Continue to payment'}
        </Button>
        <Button kind="quiet" onClick={c.backToTickets}>
          Change tickets
        </Button>
      </>
    ) : null;

  return (
    <div className={cx('rt-checkout', props.className)} id="rt-checkout" data-rt-scheme={props.scheme} style={props.style} data-rt-step={step} ref={rootRef}>
      <header className="rt-header">
        {props.eventHeading === false ? null : props.eventHeading === 'h2' ? <h2 className="rt-h1">{store.event.name}</h2> : <h1 className="rt-h1">{store.event.name}</h1>}
        <p className="rt-lead">
          {eventDates(store.event.days)}
          {store.event.venue.name ? ` at ${store.event.venue.name}` : ''}
        </p>
        {store.mode === 'test' ? <p className="rt-pill">{noRealMoney ? 'Test mode: no real money moves' : 'Test mode'}</p> : null}
        {props.intro}
      </header>
      <Progress step={c.unconfirmed ? 'pay' : step} free={freeNow} />
      {hold && (step === 'details' || step === 'pay') && !c.expired && !c.unconfirmed && !c.refusal ? (
        <div className="rt-timebar">
          <HoldTimer hold={hold} onExpire={c.onExpire} onExtend={hold.extended ? undefined : () => void c.extend()} />
        </div>
      ) : null}
      {noteBar}
      <div className="rt-layout">
        <div className="rt-body" ref={bodyRef} tabIndex={-1}>
          {main}
        </div>
        {showSide ? (
          <div className="rt-side">
            {hold && step !== 'tickets' ? <Summary hold={hold} onExpire={c.onExpire} showTimer={false} /> : <Estimate c={c} store={store} />}
            {action ? (
              <div className="rt-actions">
                {barNote ? <p className="rt-bar-note">{barNote}</p> : null}
                {action}
              </div>
            ) : null}
          </div>
        ) : null}
      </div>
      <p className="rt-powered">
        <Icon name="ticket" size={14} />
        <span>Powered by RCMS Tickets</span>
      </p>
    </div>
  );
}
````

### src/rcms-tickets/client/CheckoutSheet.tsx

````tsx
import { useEffect, useRef, useState } from 'react';
import { Checkout, type CheckoutProps } from './Checkout';
import { readDeepLink } from './deeplink';
import { Button } from './ui';

/** Escape must not throw away a payment on its way: while anything is busy the sheet stays. */
export function sheetMayClose(dialog: HTMLElement): boolean {
  return !dialog.querySelector('[aria-busy="true"]');
}

/**
 * The same checkout in a full-screen sheet, opened by a button on your page or by `?tickets=1`. It is a native <dialog>: the browser
 * traps the keyboard focus inside it, Escape closes it (not while a payment is on its way), and a screen reader is told it is a dialog.
 * The page behind doesn't scroll. Closing keeps the hold: its clock goes on, and opening again comes back to the same tickets.
 */
export function CheckoutSheet({ label = 'Get tickets', ...props }: CheckoutProps & { label?: string }) {
  const dialog = useRef<HTMLDialogElement>(null);
  const [mounted, setMounted] = useState(false);
  const show = () => {
    setMounted(true);
  };
  useEffect(() => {
    if (readDeepLink(props.search ?? window.location.search).open) setMounted(true);
  }, [props.search]);
  useEffect(() => {
    if (!mounted || !dialog.current) return;
    if (!dialog.current.open) dialog.current.showModal();
    const root = document.documentElement;
    const before = root.style.overflow;
    root.style.overflow = 'hidden';
    // First focus on what the sheet is about, not on Close. The heading arrives with the storefront.
    const el = dialog.current;
    const moved = new MutationObserver(focusHeading);
    function focusHeading() {
      const h = el.querySelector<HTMLElement>('.rt-h1');
      if (!h) return;
      h.tabIndex = -1;
      h.focus({ preventScroll: true });
      moved.disconnect();
    }
    moved.observe(el, { childList: true, subtree: true });
    focusHeading();
    return () => {
      moved.disconnect();
      root.style.overflow = before;
    };
  }, [mounted]);
  return (
    <>
      <Button onClick={show}>{label}</Button>
      {mounted ? (
        <dialog
          ref={dialog}
          className="rt-sheet"
          aria-label="Buy tickets"
          onClose={() => setMounted(false)}
          onCancel={(e) => {
            if (!sheetMayClose(e.currentTarget)) e.preventDefault();
          }}
        >
          <div className="rt-sheet-bar">
            <Button kind="quiet" onClick={() => dialog.current?.close()}>
              Close
            </Button>
          </div>
          <Checkout {...props} />
        </dialog>
      ) : null}
    </>
  );
}
````

### src/rcms-tickets/client/CodeField.tsx

````tsx
import { useState } from 'react';
import { Button, Field, NoticeBar } from './ui';
import type { Notice } from './useCheckout';

export interface CodeFieldProps {
  value: string;
  onChange: (v: string) => void;
  applied: string | null;
  busy: boolean;
  note: Notice | null;
  onApply: () => void;
  onRemove: () => void;
  /** The words for a code that is on the order. Default: "Code X is on your order." */
  appliedWords?: (code: string) => string;
  /** A line under them. Default: none. */
  appliedNote?: string | undefined;
}

/** "Have a code?": closed until asked for, so it never gets in the way of a buyer who has none. */
export function CodeField({ value, onChange, applied, busy, note, onApply, onRemove, appliedWords, appliedNote }: CodeFieldProps) {
  const [open, setOpen] = useState(!!value && !applied);
  if (applied) {
    return (
      <div className="rt-code-applied">
        <p>{appliedWords ? appliedWords(applied) : `Code ${applied} is on your order.`}</p>
        <Button kind="quiet" onClick={onRemove}>
          Remove code
        </Button>
        {appliedNote ? <p className="rt-code-note">{appliedNote}</p> : null}
      </div>
    );
  }
  if (!open) {
    return (
      <div className="rt-code">
        <Button kind="quiet" onClick={() => setOpen(true)} aria-expanded={false}>
          Have a code?
        </Button>
      </div>
    );
  }
  return (
    <form
      className="rt-code"
      onSubmit={(e) => {
        e.preventDefault();
        onApply();
      }}
    >
      <Field label="Your code" error={note?.tone === 'error' ? note.text : undefined}>
        {(p) => (
          <div className="rt-code-row">
            <input {...p} className="rt-input" type="text" name="code" value={value} onChange={(e) => onChange(e.target.value)} autoCapitalize="characters" autoComplete="off" spellCheck={false} />
            <Button type="submit" kind="secondary" busy={busy} disabled={!value.trim()}>
              Apply
            </Button>
          </div>
        )}
      </Field>
      {note && note.tone !== 'error' ? <NoticeBar tone={note.tone}>{note.text}</NoticeBar> : null}
    </form>
  );
}
````

### src/rcms-tickets/client/Confirmation.tsx

````tsx
import { formatMoney } from './money';
import { Button, Icon } from './ui';
import type { OrderView, Storefront } from './types';

/*
  The confirmation: the order, each ticket with its Wallet buttons, and the link to the private ticket page (where the QR
  code is). The tickets are made a moment after the payment, so for a second the list says so, and the checkout checks again.

  It says only what is true of the money. A PENDING order (the processor is still finishing the payment, so there are no tickets and
  nothing is counted as paid) says so and promises only an email. A CANCELLED one says what the API knows (`payment_end`): not charged only when
  that is proved, the opposite if the money turned out to be taken, and neither when nobody has confirmed it. "You are going" and "Paid" are for an order whose money is in.
  "Buy more tickets" is for someone who has tickets: a buyer who is waiting may otherwise pay twice, and one with a cancelled order has nothing to buy more of.
*/

export function Confirmation({ order, store, noRealMoney = true, onBuyMore }: { order: OrderView; store: Storefront | null; noRealMoney?: boolean; onBuyMore?: () => void }) {
  const waiting = order.status === 'pending';
  const ended = order.status === 'cancelled';
  const pending = order.tickets_status === 'pending';
  // Parking bought alone, with no pass of its own: there are no tickets to speak of, only what was bought.
  const extrasOnly = !pending && order.tickets.length === 0 && order.items.length > 0 && order.items.every((i) => i.kind === 'add_on');
  return (
    <section className="rt-section rt-done" aria-labelledby="rt-done-h">
      <div className="rt-done-mark">
        <Icon name={waiting ? 'clock' : ended ? 'alert' : 'check'} size={28} />
      </div>
      <h2 className="rt-h1" id="rt-done-h" tabIndex={-1}>
        {waiting ? 'Almost done' : ended ? 'This order was cancelled' : extrasOnly ? `You are all set${store ? ` for ${store.event.name}` : ''}` : `You are going${store ? ` to ${store.event.name}` : ''}`}
      </h2>
      <p className="rt-lead" role={waiting || ended ? 'status' : undefined}>
        {waiting ? (
          order.buyer.email ? (
            <>
              Your payment is being finished. We will email your tickets to <strong>{order.buyer.email}</strong> when it is.
            </>
          ) : (
            'Your payment is being finished. We will email your tickets when it is.'
          )
        ) : ended ? (
          order.payment_end === 'not_charged' ? (
            'Your card was not charged.'
          ) : order.payment_end === 'taken_after_end' ? (
            'Your payment went through. The organizer will refund you.'
          ) : (
            'If your card shows a charge, contact the organizer.'
          )
        ) : extrasOnly ? (
          'Your order is confirmed.'
        ) : order.mail_note === 'none' ? (
          'Your tickets are ready. We did not email them, so open them now.'
        ) : order.mail_note === 'later' ? (
          'Your tickets are ready. We will email them soon, so open them now.'
        ) : order.buyer.email ? (
          <>
            {order.mail_note === 'all_to_buyer' ? 'We sent all the tickets to ' : 'We sent your tickets to '}
            <strong>{order.buyer.email}</strong>.
          </>
        ) : (
          'Your tickets are ready.'
        )}
      </p>
      {order.mode === 'test' ? <p className="rt-hint">{noRealMoney ? 'This was a test order. No real money moved.' : 'This was a test order.'}</p> : null}
      <dl className="rt-facts">
        <div>
          <dt>Order number</dt>
          <dd className="rt-mono">{order.number}</dd>
        </div>
        {ended ? null : (
          <div>
            <dt>{order.total.amount === 0 || waiting ? 'Total' : 'Paid'}</dt>
            <dd>{order.total.amount === 0 ? 'Free' : formatMoney(order.total)}</dd>
          </div>
        )}
      </dl>

      {waiting || ended ? null : <h3 className="rt-h2">{extrasOnly ? 'Your order' : 'Your tickets'}</h3>}
      {waiting || ended ? null : extrasOnly ? (
        <ul className="rt-list">
          {order.items.map((i) => (
            <li className="rt-row" key={i.name}>
              <div className="rt-row-main">
                <h4 className="rt-row-title">{i.name}</h4>
                <p className="rt-row-sub">Quantity {i.quantity}</p>
              </div>
            </li>
          ))}
        </ul>
      ) : pending ? (
        <p className="rt-lead" role="status">
          Getting your tickets ready. This takes a moment.
        </p>
      ) : (
        <ul className="rt-list">
          {order.tickets.map((t) => (
            <li className="rt-row rt-ticket" key={t.id}>
              <div className="rt-row-main">
                <h4 className="rt-row-title">{t.name}</h4>
                <p className="rt-row-sub">{t.holder_name ? `For ${t.holder_name}` : 'Your ticket'}</p>
                <p className="rt-row-sub rt-mono">{t.short_code}</p>
              </div>
              <div className="rt-ticket-actions">
                {t.apple_wallet_url ? (
                  <a className="rt-button rt-button-wallet" href={t.apple_wallet_url}>
                    Add to Apple Wallet
                  </a>
                ) : null}
                {t.google_wallet_url ? (
                  <a className="rt-button rt-button-wallet" href={t.google_wallet_url}>
                    Save to Google Wallet
                  </a>
                ) : null}
              </div>
            </li>
          ))}
        </ul>
      )}
      {order.url && !ended ? (
        <a className="rt-button rt-button-primary" href={order.url}>
          <span>{waiting || extrasOnly ? 'See your order' : 'See your tickets'}</span>
        </a>
      ) : null}
      {store?.my_tickets_url && !ended && !waiting ? (
        <p className="rt-hint">
          Lost your email? Your tickets are always in <a href={store.my_tickets_url}>My tickets</a>.
        </p>
      ) : null}
      {store?.event.attendee_info && !ended && !waiting ? (
        <>
          <h3 className="rt-h2">Before you come</h3>
          <p className="rt-lead rt-pre">{store.event.attendee_info}</p>
        </>
      ) : null}
      {onBuyMore && !waiting && !ended ? (
        <Button kind="quiet" onClick={onBuyMore}>
          Buy more tickets
        </Button>
      ) : null}
    </section>
  );
}
````

### src/rcms-tickets/client/PaymentStep.tsx

````tsx
import { useEffect, useState, type ReactNode } from 'react';
import { formatMoney } from './money';
import { Button, Field, Icon, NoticeBar } from './ui';
import type { Hold, PaymentPayload, TestToken } from './types';
import type { Notice } from './useCheckout';

/*
  The payment step has one slot: a PaymentSlot is whatever collects the card and hands back a payload for your server.
  The kit ships the test provider's card form (test mode only) and a Square slot (square.tsx). To use another processor,
  write a slot that returns { provider: 'yours', ... } and handle it in ../server/payment.ts. The card itself never touches
  the kit's server: a processor's own script turns it into a token in the browser, and only the token is sent.
*/

export interface PaymentSlotContext {
  hold: Hold;
  mode: 'test' | 'live';
  busy: boolean;
  /** "Pay $390.00" */
  payLabel: string;
  /** Hand over what the buyer paid with. */
  submit: (payload: PaymentPayload) => void;
  /** Say why a card could not be read (the processor's own words). */
  fail: (message: string) => void;
}

export interface PaymentSlot {
  id: string;
  /** True only when this slot, in this mode, can never move real money. The page says "no real money moves" on nothing less. */
  noRealMoney?: (mode: 'test' | 'live') => boolean;
  render: (ctx: PaymentSlotContext) => ReactNode;
}

/** The test provider's cards (the API's TEST_TOKENS). The number maps to a token; only the token is sent. */
export const TEST_CARDS: Array<{ number: string; token: TestToken; label: string }> = [
  { number: '4242 4242 4242 4242', token: 'tok_success', label: 'Works' },
  { number: '4000 0000 0000 0002', token: 'tok_decline', label: 'Declined' },
  { number: '4000 0000 0000 9995', token: 'tok_insufficient', label: 'Not enough funds' },
  { number: '4000 0000 0000 0119', token: 'tok_error', label: 'Processor error' },
];

const digits = (s: string) => s.replace(/\D/g, '');
const group = (s: string) => digits(s).slice(0, 19).replace(/(.{4})/g, '$1 ').trim();

function TestCardForm({ ctx }: { ctx: PaymentSlotContext }) {
  const [number, setNumber] = useState('');
  const [exp, setExp] = useState('');
  const [cvc, setCvc] = useState('');
  const [problem, setProblem] = useState<string | null>(null);
  const known = TEST_CARDS.find((c) => digits(c.number) === digits(number));
  return (
    <form
      className="rt-form"
      noValidate
      onSubmit={(e) => {
        e.preventDefault();
        if (!known) {
          setProblem('That is not one of the test cards. Pick one below.');
          return;
        }
        setProblem(null);
        ctx.submit({ provider: 'test', token: known.token });
      }}
    >
      <NoticeBar tone="info">Test mode. No real card is charged. Pick a test card.</NoticeBar>
      <div className="rt-chips" role="group" aria-label="Test cards">
        {TEST_CARDS.map((c) => (
          <button
            type="button"
            key={c.token}
            className="rt-chip"
            aria-pressed={digits(number) === digits(c.number)}
            onClick={() => {
              setNumber(c.number);
              setExp('12 / 30');
              setCvc('123');
              setProblem(null);
            }}
          >
            {c.label}
          </button>
        ))}
      </div>
      <Field label="Card number" error={problem ?? undefined}>
        {(p) => <input {...p} className="rt-input" type="text" name="cardnumber" inputMode="numeric" autoComplete="cc-number" value={number} onChange={(e) => setNumber(group(e.target.value))} />}
      </Field>
      <div className="rt-two">
        <Field label="Expires">{(p) => <input {...p} className="rt-input" type="text" name="cc-exp" inputMode="numeric" autoComplete="cc-exp" placeholder="MM / YY" value={exp} onChange={(e) => setExp(e.target.value.slice(0, 7))} />}</Field>
        <Field label="Security code">{(p) => <input {...p} className="rt-input" type="text" name="cvc" inputMode="numeric" autoComplete="cc-csc" value={cvc} onChange={(e) => setCvc(digits(e.target.value).slice(0, 4))} />}</Field>
      </div>
      <Button type="submit" busy={ctx.busy}>
        {ctx.payLabel}
      </Button>
    </form>
  );
}

/** The test provider's card form. Shown only in test mode: a live checkout must never offer fake cards. */
export const testCardSlot: PaymentSlot = {
  id: 'test',
  noRealMoney: (mode) => mode === 'test',
  render: (ctx) => (ctx.mode === 'test' ? <TestCardForm ctx={ctx} /> : <NoticeBar tone="error">The test card form is only for test mode. Add a payment slot for your processor.</NoticeBar>),
};

export interface PaymentStepProps {
  hold: Hold;
  mode: 'test' | 'live';
  slot?: PaymentSlot;
  busy: boolean;
  error: Notice | null;
  onSubmit: (p: PaymentPayload) => void;
  onBack: () => void;
  /** After this long with no answer, the buyer is told it is still going, in ms. Default 6000. */
  slowAfterMs?: number;
}

export function PaymentStep({ hold, mode, slot = testCardSlot, busy, error, onSubmit, onBack, slowAfterMs = 6000 }: PaymentStepProps) {
  const [slotError, setSlotError] = useState<string | null>(null);
  const [slow, setSlow] = useState(false);
  useEffect(() => {
    if (!busy) return setSlow(false);
    const t = setTimeout(() => setSlow(true), slowAfterMs);
    return () => clearTimeout(t);
  }, [busy, slowAfterMs]);
  const shown = slotError ?? error?.text ?? null;
  const free = hold.price.total.amount === 0;
  return (
    <section className="rt-section" aria-labelledby="rt-pay-h">
      <h2 className="rt-h2" id="rt-pay-h">
        {free ? 'Your free tickets' : 'Payment'}
      </h2>
      {shown ? <NoticeBar tone={slotError ? 'error' : (error?.tone ?? 'error')}>{shown}</NoticeBar> : null}
      {free ? (
        <Button busy={busy} onClick={() => onSubmit({ provider: 'free' })}>
          Get my free tickets
        </Button>
      ) : (
        slot.render({ hold, mode, busy, payLabel: `Pay ${formatMoney(hold.price.total)}`, submit: (p) => (setSlotError(null), onSubmit(p)), fail: setSlotError })
      )}
      {slow ? (
        <p className="rt-lead rt-slow" role="status">
          Still working. Please keep this page open and do not press anything.
        </p>
      ) : null}
      {free ? null : (
        <div className="rt-secure">
          <Icon name="lock" size={16} />
          <span>You are only charged when you press Pay.</span>
        </div>
      )}
      <Button kind="quiet" onClick={onBack} disabled={busy}>
        Back to details
      </Button>
    </section>
  );
}
````

### src/rcms-tickets/client/Summary.tsx

````tsx
import { useEffect, useRef, useState } from 'react';
import { formatMoney, formatOff, moneyOrFree } from './money';
import { Button, Icon } from './ui';
import type { Hold } from './types';

/** Milliseconds left on a hold, by the kit server's clock (never the buyer's, which may be minutes off). */
export function msLeft(hold: Pick<Hold, 'expires_at' | 'server_time'>, startedAt: number, now: number): number {
  return Date.parse(hold.expires_at) - Date.parse(hold.server_time) - (now - startedAt);
}

export const clock = (ms: number): string => {
  const s = Math.max(0, Math.ceil(ms / 1000));
  return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
};

const SPOKEN = [120_000, 60_000, 30_000];

/** The countdown. It does not read out every second: a screen reader hears at 2 minutes, 1 minute and 30 seconds. */
export function HoldTimer({ hold, onExpire, onExtend }: { hold: Hold; onExpire: () => void; onExtend?: () => void }) {
  const started = useRef(Date.now());
  const [now, setNow] = useState(Date.now());
  const [spoken, setSpoken] = useState('');
  const fired = useRef(false);
  useEffect(() => {
    started.current = Date.now();
    setNow(Date.now());
    fired.current = false;
  }, [hold.id, hold.expires_at, hold.server_time]);
  useEffect(() => {
    const t = setInterval(() => setNow(Date.now()), 500);
    return () => clearInterval(t);
  }, []);
  const left = msLeft(hold, started.current, now);
  useEffect(() => {
    if (left <= 0 && !fired.current) {
      fired.current = true;
      onExpire();
    }
    for (const mark of SPOKEN) if (left <= mark && left > mark - 1500) setSpoken(`${mark >= 60_000 ? `${mark / 60_000} minute${mark > 60_000 ? 's' : ''}` : `${mark / 1000} seconds`} left to pay.`);
  }, [left, onExpire]);
  const low = left <= 120_000;
  return (
    <div className="rt-timer-wrap">
      <p className={`rt-timer ${low ? 'rt-timer-low' : ''}`} role="timer" aria-label="Time left to pay">
        <Icon name="clock" size={18} />
        <span>
          Held for <strong>{clock(left)}</strong>
        </span>
      </p>
      <p className="rt-sr" role="status" aria-live="polite">
        {spoken}
      </p>
      {low && !hold.extended && onExtend ? (
        <Button kind="quiet" onClick={onExtend}>
          Need more time?
        </Button>
      ) : null}
    </div>
  );
}

/** The hold's price, exactly as the server made it. */
export function Summary({ hold, onExpire, onExtend, showTimer = true }: { hold: Hold; onExpire: () => void; onExtend?: () => void; showTimer?: boolean }) {
  const p = hold.price;
  const feeNames = [...p.order_fees, ...p.lines.flatMap((l) => l.fees)].filter((f) => f.passed_on).map((f) => f.name);
  const uniqueFees = [...new Set(feeNames)];
  return (
    <aside className="rt-summary" aria-labelledby="rt-summary-h">
      <h2 className="rt-h2" id="rt-summary-h">
        Your order
      </h2>
      {showTimer ? <HoldTimer hold={hold} onExpire={onExpire} onExtend={onExtend} /> : null}
      <dl className="rt-lines">
        {p.lines.map((l, i) => (
          <div className="rt-line" key={`${l.name}-${i}`}>
            <dt>
              {l.quantity} &times; {l.name}
              {l.tickets_per_unit ? <span className="rt-note"> ({l.quantity * l.tickets_per_unit} tickets)</span> : null}
            </dt>
            <dd>{moneyOrFree(l.amount)}</dd>
          </div>
        ))}
        {p.discount.amount > 0 ? (
          <div className="rt-line rt-line-discount">
            <dt>{p.code ? `Code ${p.code.code}` : 'Discount'}</dt>
            <dd>{formatOff(p.discount)}</dd>
          </div>
        ) : null}
        {p.fees.amount > 0 ? (
          <div className="rt-line">
            <dt>
              Fees
              {uniqueFees.length ? <span className="rt-note"> ({uniqueFees.join(', ')})</span> : null}
            </dt>
            <dd>{formatMoney(p.fees)}</dd>
          </div>
        ) : null}
        {p.tax.amount > 0 ? (
          <div className="rt-line">
            <dt>Tax</dt>
            <dd>{formatMoney(p.tax)}</dd>
          </div>
        ) : null}
        <div className="rt-line rt-line-total">
          <dt>Total</dt>
          <dd>{moneyOrFree(p.total)}</dd>
        </div>
      </dl>
    </aside>
  );
}
````

### src/rcms-tickets/client/TicketPicker.tsx

````tsx
import { goodFor, whenText } from './dates';
import { maxUnits } from './useCheckout';
import { formatMoney, moneyOrFree } from './money';
import { cx, Icon, Stepper } from './ui';
import type { Money, Storefront, StorefrontAddOn, StorefrontTicketType } from './types';

export interface TicketPickerProps {
  store: Storefront;
  qty: Record<string, number>;
  onChange: (t: StorefrontTicketType, units: number) => void;
}

/**
 * Why a row cannot be bought, in words. null when it can. "On sale" against "ended" goes by the read the row came from (`store.as_of`), never by this device's clock: a read from before the start says
 * nothing about after it, and a phone running fast must not call a sale over before it opens.
 */
export function unavailableWhy(item: Pick<StorefrontTicketType | StorefrontAddOn, 'state' | 'on_sale' | 'sale_starts_at' | 'sale_ends_at'> & { held?: boolean }, store?: { as_of?: string; event?: { venue?: { timezone?: string } } }): string | null {
  if (item.state === 'sold_out') return item.held ? 'Held by other buyers. Try again in a few minutes.' : 'Sold out';
  if (!item.on_sale) {
    const read = store?.as_of ? Date.parse(store.as_of) : Date.now();
    if (item.sale_starts_at && Date.parse(item.sale_starts_at) > read) return `On sale ${whenText(item.sale_starts_at, undefined, store?.event?.venue?.timezone)}`;
    return 'Sales have ended';
  }
  return null;
}

/** What one ticket of a bundle costs: plain arithmetic on its own price. Null for a single ticket. Whether that is a saving is the site's to say. */
export function perTicket(t: Pick<StorefrontTicketType, 'tickets_per_unit' | 'price'>): Money | null {
  return t.tickets_per_unit < 2 ? null : { amount: Math.round(t.price.amount / t.tickets_per_unit), currency: t.price.currency };
}

export function TicketPicker({ store, qty, onChange }: TicketPickerProps) {
  if (!store.ticket_types.length) return null; // A page that sells only parking has no tickets to choose.
  const soldDays = new Set(store.days.filter((d) => d.state === 'sold_out').map((d) => d.day));
  // "All 3 days" on every row says nothing: it is said only when a ticket is good for fewer days than another.
  const allTheSame = store.ticket_types.every((t) => !t.valid_days.length || t.valid_days.length === store.event.days.length);
  return (
    <section className="rt-section" aria-labelledby="rt-tickets-h">
      <h2 className="rt-h2" id="rt-tickets-h">
        Choose your tickets
      </h2>
      <ul className="rt-list">
        {store.ticket_types.map((t) => {
          const why = unavailableWhy(t, store) ?? (t.valid_days.length && t.valid_days.every((d) => soldDays.has(d)) ? 'Sold out' : null);
          const n = qty[t.ticket_type] ?? 0;
          const max = why ? 0 : maxUnits(t);
          const note = t.fees_passed_on && t.taxed ? 'plus fees and tax' : t.fees_passed_on ? 'plus fees' : t.taxed ? 'plus tax' : '';
          const pack = t.tickets_per_unit > 1;
          const each = perTicket(t);
          const sub = pack ? (t.description ? null : `Pack of ${t.tickets_per_unit}. Each ticket has its own code to pass on.`) : allTheSame ? null : goodFor(t, store);
          return (
            <li key={t.ticket_type} className={cx('rt-row', n > 0 && 'rt-row-on', why && 'rt-row-off')}>
              <div className="rt-row-main">
                <h3 className="rt-row-title" id={`rt-t-${t.ticket_type}`}>
                  {t.name}
                </h3>
                {sub ? <p className="rt-row-sub">{sub}</p> : null}
                {t.description ? <p className="rt-row-sub">{t.description}</p> : null}
                <p className="rt-price">
                  {t.compare_at_price ? (
                    <s className="rt-was">
                      <span className="rt-sr">Was </span>
                      {formatMoney(t.compare_at_price)}
                    </s>
                  ) : null}
                  <strong>{moneyOrFree(t.price)}</strong>
                  {note ? <span className="rt-note"> {note}</span> : null}
                </p>
                {each ? <p className="rt-row-sub">{formatMoney(each)} a ticket.</p> : null}
                {why ? (
                  <p className="rt-badge rt-badge-off">
                    <Icon name="alert" size={16} /> {why}
                  </p>
                ) : t.state === 'low' && t.remaining !== null ? (
                  <p className="rt-badge rt-badge-low">
                    <Icon name="clock" size={16} /> {t.remaining === 1 ? 'Only 1 left' : `Only ${t.remaining} left`}
                  </p>
                ) : null}
                {t.min_age ? <p className="rt-row-sub">{t.min_age}+ only. Bring photo ID.</p> : null}
              </div>
              {why ? null : <Stepper label={t.name} value={n} max={max} min={0} onChange={(v) => onChange(t, v)} />}
            </li>
          );
        })}
      </ul>
    </section>
  );
}
````

### src/rcms-tickets/client/api.ts

````ts
import type { Answers, Attribution, CheckoutError, Hold, OrderView, PaymentPayload, ResumeView, Storefront } from './types';

/*
  The browser's side of the conversation with YOUR server (the handlers in ../server). The page never talks to RCMS Tickets
  directly and never holds a key: your server does, and answers in the shapes in types.ts.
*/

export class CheckoutApiError extends Error implements CheckoutError {
  readonly status: number;
  readonly type: string;
  readonly code: string;
  readonly param: string | null;
  readonly decline_code: string | null;
  /** Seconds, from a 429's Retry-After. */
  readonly retryAfter: number | null;
  /** The rest of the answer, when it carries more (a changed price carries the new hold). */
  readonly extra: Record<string, unknown>;
  constructor(status: number, body: { error?: Partial<CheckoutError> } & Record<string, unknown>, retryAfter: number | null = null) {
    const e = body.error ?? {};
    super(e.message ?? 'Something went wrong. Please try again.');
    this.name = 'CheckoutApiError';
    this.status = status;
    this.type = e.type ?? 'api_error';
    this.code = e.code ?? 'unknown';
    this.param = e.param ?? null;
    this.decline_code = e.decline_code ?? null;
    this.retryAfter = retryAfter;
    const { error: _e, ...rest } = body;
    this.extra = rest;
  }
}

export interface HoldRequest {
  items: Array<{ ticket_type: string; quantity: number } | { add_on: string; quantity: number; ticket_type?: string }>;
  code?: string;
  email?: string;
  attribution?: Attribution;
  event?: string;
  /** The hold this one takes the place of: the buyer changing their mind. Goes with its receipt, or it is no such thing. */
  replaces?: string;
}

export interface OrderRequest {
  hold: string;
  buyer: { name: string; email: string; phone?: string; marketing?: { email?: { granted: boolean; text_version?: string }; sms?: { granted: boolean; text_version?: string } } };
  answers?: Answers;
  attendees?: Array<{ ticket_type: string; name?: string; email?: string; answers?: Answers }>;
  payment: PaymentPayload;
  ad_consent?: 'granted' | 'denied' | 'unknown';
  /** What the buyer was shown, in minor units. Your server refuses the order, and takes no money, if the hold's total is different. */
  expected_total: number;
}

export interface CheckoutApi {
  /** `fresh`: past the server's few seconds of sharing, for after a refused hold. */
  storefront(o?: { code?: string; event?: string; fresh?: boolean }): Promise<Storefront>;
  createHold(input: HoldRequest, key: string, receipt?: string): Promise<Hold>;
  setHoldEmail(id: string, email: string | null, receipt?: string, marketingEmail?: { granted: boolean; text_version: string }): Promise<void>;
  extendHold(id: string, receipt?: string): Promise<Hold>;
  releaseHold(id: string, receipt?: string): Promise<void>;
  readHold(id: string, receipt?: string): Promise<Hold>;
  resume(id: string, key?: string | null): Promise<ResumeView>;
  /** Everything an order can be refused for, before the page asks for a card. */
  checkOrder(input: Omit<OrderRequest, 'payment' | 'expected_total'>, receipt?: string): Promise<void>;
  createOrder(input: OrderRequest, receipt?: string): Promise<OrderView>;
  readOrder(id: string, hold: string, receipt?: string): Promise<OrderView>;
}

/** How long the page waits for one call, in ms. An order waits longest: the server takes the payment and makes the tickets. */
export const DEFAULT_TIMEOUT_MS = 20_000;
export const ORDER_TIMEOUT_MS = 60_000;

export function createApi(endpoint = '/api/tickets', fetchImpl?: typeof fetch, timeoutMs?: number): CheckoutApi {
  const base = endpoint.replace(/\/+$/, '');
  const call = async <T>(method: string, path: string, body?: unknown, headers: Record<string, string> = {}, wait = timeoutMs ?? DEFAULT_TIMEOUT_MS): Promise<T> => {
    const f = fetchImpl ?? fetch;
    const abort = new AbortController();
    let timer: ReturnType<typeof setTimeout> | undefined;
    let res: Response;
    let text: string;
    try {
      ({ res, text } = await Promise.race([
        new Promise<never>((_, reject) => {
          timer = setTimeout(() => {
            abort.abort();
            reject(new Error('timed out'));
          }, wait);
        }),
        (async () => {
          const r = await f(`${base}${path}`, { method, signal: abort.signal, headers: { ...(body === undefined ? {} : { 'content-type': 'application/json' }), ...headers }, body: body === undefined ? undefined : JSON.stringify(body), credentials: 'same-origin' });
          return { res: r, text: await r.text() };
        })(),
      ]));
    } catch {
      throw new CheckoutApiError(0, { error: { type: 'connection_error', code: 'offline', message: 'We could not reach the server. Check your connection and try again.' } });
    } finally {
      if (timer) clearTimeout(timer);
    }
    let json: Record<string, unknown> = {};
    try {
      json = text ? (JSON.parse(text) as Record<string, unknown>) : {};
    } catch {
      /* not json */
    }
    if (!res.ok) {
      const after = Number(res.headers.get('retry-after'));
      throw new CheckoutApiError(res.status, json as { error?: Partial<CheckoutError> }, Number.isFinite(after) && after > 0 ? after : null);
    }
    return json as T;
  };
  const withReceipt = (receipt?: string): Record<string, string> => (receipt ? { 'x-rt-receipt': receipt } : {});
  const qs = (o: Record<string, string | undefined>) => {
    const p = new URLSearchParams();
    for (const [k, v] of Object.entries(o)) if (v) p.set(k, v);
    const s = p.toString();
    return s ? `?${s}` : '';
  };
  return {
    storefront: (o = {}) => call('GET', `/storefront${qs({ code: o.code, event: o.event, fresh: o.fresh ? '1' : undefined })}`),
    createHold: (input, key, receipt) => call('POST', '/holds', input, { 'idempotency-key': key, ...(receipt ? { 'x-rt-receipt': receipt } : {}) }),
    setHoldEmail: async (id, email, receipt, marketingEmail) => void (await call('PATCH', `/holds/${encodeURIComponent(id)}`, { email, ...(marketingEmail ? { marketing_email: marketingEmail } : {}) }, withReceipt(receipt))),
    extendHold: (id, receipt) => call('POST', `/holds/${encodeURIComponent(id)}/extend`, {}, withReceipt(receipt)),
    releaseHold: async (id, receipt) => void (await call('DELETE', `/holds/${encodeURIComponent(id)}`, undefined, withReceipt(receipt))),
    readHold: (id, receipt) => call('GET', `/holds/${encodeURIComponent(id)}`, undefined, withReceipt(receipt)),
    resume: (id, key) => call('GET', `/holds/${encodeURIComponent(id)}/resume`, undefined, key ? { 'x-rt-resume': key } : undefined),
    checkOrder: async (input, receipt) => void (await call('POST', '/orders/check', input, withReceipt(receipt))),
    createOrder: (input, receipt) => call('POST', '/orders', input, withReceipt(receipt), timeoutMs ?? ORDER_TIMEOUT_MS),
    readOrder: (id, hold, receipt) => call('GET', `/orders/${encodeURIComponent(id)}${qs({ hold })}`, undefined, withReceipt(receipt)),
  };
}

/** A fresh key for one attempt to hold: the same key on a retry gives the same hold, never two. */
export function newKey(): string {
  const c = globalThis.crypto as Crypto | undefined;
  if (c?.randomUUID) return c.randomUUID();
  return `k${Date.now().toString(36)}${Math.random().toString(36).slice(2, 12)}`;
}
````

### src/rcms-tickets/client/attribution.ts

````ts
import { readJson, removeKey, writeJson } from './storage';
import type { Attribution } from './types';

/*
  Where the buyer came from, ported from Christmas at the Tail's cattAttrib() with its lessons built in.
  The campaign tags exist only on the landing page view, so they are kept in first-party storage for 90 days and sent
  with the hold, which makes the order say which ad it came from. Call `captureAttribution()` once in your site's root
  (every page, not just the checkout: the visitor usually lands somewhere else first).
  - A fresh tagged click is the LAST touch and replaces the one before it. The FIRST touch is kept separately and never replaced.
  - fbclid, gclid and ttclid are kept apart (CATT folded gclid into fbclid and lost which ad network sent the click).
  - Never tagged: the referring site is the only signal there is, and it is recorded as both touches.
  - Nothing is kept that the buyer did not already send us in the URL, and nothing leaves first-party storage except with a hold.
  - An ad consent of "denied" keeps nothing, clears what was kept, and sends no tags and no ad cookies.
  - It never throws: a bad cookie or a corrupt store must not stop a sale (a lost sale is worse than a lost tag).
*/

export const ATTRIBUTION_KEY = 'rcmst_attr';
export const ATTRIBUTION_TTL_MS = 90 * 24 * 60 * 60 * 1000;

type Touch = NonNullable<Attribution['first_touch']> & { at: string; tracking_link?: string };
interface Stored {
  v: 1;
  first: Touch;
  last: Touch;
}

const UTM = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'] as const;
const CLICK_IDS = ['fbclid', 'gclid', 'ttclid'] as const;

const clip = (v: string | null | undefined, max: number): string => (v ?? '').trim().slice(0, max);

/** The URL without its query or fragment: a landing page or referrer is a place, not a trail of tags. */
const placeOf = (url: string): string => {
  try {
    const u = new URL(url);
    return /^https?:$/.test(u.protocol) ? `${u.origin}${u.pathname}`.slice(0, 2048) : '';
  } catch {
    return '';
  }
};

export interface CaptureOptions {
  /** For tests. */
  now?: () => number;
  location?: Pick<Location, 'href' | 'hostname'>;
  referrer?: string;
  /** What your cookie banner says about ad tracking. Denied: nothing is kept, and what was kept is cleared. */
  adConsent?: 'granted' | 'denied' | 'unknown';
}

function touchFromUrl(o: CaptureOptions): { touch: Touch; tagged: boolean } | null {
  const loc = o.location ?? window.location;
  const now = (o.now ?? Date.now)();
  const q = new URL(loc.href).searchParams;
  const touch: Touch = { at: new Date(now).toISOString() };
  let tagged = false;
  for (const k of UTM) {
    const v = clip(q.get(k), 200);
    if (v) (touch[k] = v), (tagged = true);
  }
  for (const k of CLICK_IDS) {
    const v = clip(q.get(k), 500);
    if (v) (touch[k] = v), (tagged = true);
  }
  // A tracking link's id (`rtl`, on the links the dashboard makes): which link this visit came through. Anything else in it is dropped.
  const link = clip(q.get('rtl'), 45);
  if (link.length >= 7 && link.length <= 44 && /^lnk_[A-Za-z0-9]+(?:_[A-Za-z0-9]+)*$/.test(link)) (touch.tracking_link = link), (tagged = true);
  const ref = o.referrer ?? (typeof document === 'undefined' ? '' : document.referrer);
  let refPlace = '';
  try {
    if (ref && new URL(ref).hostname !== loc.hostname) refPlace = placeOf(ref);
  } catch {
    refPlace = '';
  }
  if (refPlace) touch.referrer = refPlace;
  const landing = placeOf(loc.href);
  if (landing) touch.landing_page = landing;
  if (tagged) return { touch, tagged };
  // Never tagged: only an outside referrer is a signal.
  return refPlace ? { touch, tagged } : null;
}

let pending: { touch: Touch; tagged: boolean } | null = null;

/** Reads the visit and updates what is kept. Safe to call on every page and more than once. */
export function captureAttribution(o: CaptureOptions = {}): void {
  if (o.adConsent === 'denied') {
    // Nothing kept: but the tags exist only on this page view, so they wait in memory in case the buyer agrees later on this page.
    try {
      pending = touchFromUrl(o) ?? pending;
    } catch {
      /* no tags, then */
    }
    return removeKey(ATTRIBUTION_KEY);
  }
  try {
    capture(o);
  } catch {
    /* a corrupt store is an empty one */
    removeKey(ATTRIBUTION_KEY);
  }
}

function capture(o: CaptureOptions): void {
  const now = (o.now ?? Date.now)();
  const seen = touchFromUrl(o) ?? pending;
  pending = null;
  if (!seen) return;
  const stored = readJson<Stored>(ATTRIBUTION_KEY);
  const alive = (t: Touch | undefined): t is Touch => !!t && now - Date.parse(t.at) < ATTRIBUTION_TTL_MS;
  const first = stored && alive(stored.first) ? stored.first : seen.touch;
  if (seen.tagged) {
    writeJson(ATTRIBUTION_KEY, { v: 1, first, last: seen.touch } satisfies Stored);
    return;
  }
  // An untagged visit with an outside referrer only fills an empty store: it never replaces a tagged click.
  if (!stored || !alive(stored.last)) writeJson(ATTRIBUTION_KEY, { v: 1, first: seen.touch, last: seen.touch } satisfies Stored);
}

/** A malformed cookie is no cookie. */
const decoded = (v: string): string => {
  try {
    return decodeURIComponent(v);
  } catch {
    return '';
  }
};

function cookie(name: string): string {
  if (typeof document === 'undefined') return '';
  for (const part of document.cookie.split(';')) {
    const i = part.indexOf('=');
    if (i > 0 && part.slice(0, i).trim() === name) return decoded(part.slice(i + 1).trim());
  }
  return '';
}

/** "GA1.1.1234567890.1700000000" to "1234567890.1700000000". */
export function gaClientId(value: string): string | null {
  const m = /^GA\d+\.\d+\.(\d{1,20}\.\d{1,20})$/.exec(value.trim());
  return m ? m[1]! : null;
}

/** The session id out of a `_ga_<id>` cookie, in either of Google's two layouts (GS1.1.<id>.… and GS2.1.s<id>$…). */
export function gaSessionId(value: string): string | null {
  const m = /^GS1\.\d+\.(\d{1,20})\./.exec(value.trim()) ?? /^GS2\.\d+\.s(\d{1,20})(?:\$|$)/.exec(value.trim());
  return m ? m[1]! : null;
}

function gaSession(): string | null {
  if (typeof document === 'undefined') return null;
  for (const part of document.cookie.split(';')) {
    const i = part.indexOf('=');
    const name = part.slice(0, i).trim();
    if (i > 0 && /^_ga_[A-Za-z0-9]+$/.test(name)) {
      const id = gaSessionId(decoded(part.slice(i + 1)));
      if (id) return id;
    }
  }
  return null;
}

export interface ReadOptions extends CaptureOptions {
  /** What your cookie banner says about ad tracking. Default "unknown". */
  adConsent?: 'granted' | 'denied' | 'unknown';
}

/** What goes with a hold: last touch flat, the first touch beside it, and the ad cookies. Empty fields are left out. */
export function readAttribution(o: ReadOptions = {}): Attribution {
  if (o.adConsent === 'denied') return { ad_consent: 'denied' };
  try {
    return read(o);
  } catch {
    return { ad_consent: o.adConsent ?? 'unknown' };
  }
}

function read(o: ReadOptions): Attribution {
  const now = (o.now ?? Date.now)();
  const loc = o.location ?? window.location;
  const stored = readJson<Stored>(ATTRIBUTION_KEY);
  const out: Attribution = { ad_consent: o.adConsent ?? 'unknown', page_url: placeOf(loc.href) || undefined };
  if (stored && now - Date.parse(stored.last.at) < ATTRIBUTION_TTL_MS) {
    Object.assign(out, stored.last);
    if (now - Date.parse(stored.first.at) < ATTRIBUTION_TTL_MS) out.first_touch = stored.first;
  }
  const fbp = cookie('_fbp');
  if (fbp) out.fbp = fbp.slice(0, 500);
  const fbc = cookie('_fbc') || (out.fbclid ? `fb.1.${Date.parse(out.at ?? '') || now}.${out.fbclid}` : '');
  if (fbc) out.fbc = fbc.slice(0, 500);
  const gid = gaClientId(cookie('_ga'));
  if (gid) out.ga_client_id = gid;
  const gs = gaSession();
  if (gs) out.ga_session_id = gs;
  for (const k of Object.keys(out) as Array<keyof Attribution>) if (out[k] === undefined || out[k] === '') delete out[k];
  return out;
}
````

### src/rcms-tickets/client/cart.ts

````ts
import { readJson, removeKey, writeJson } from './storage';

/*
  What survives a reload: which hold the buyer has and what is in it. Never a name, an email or a card. It lasts as long
  as a hold can (30 minutes at most), so a refresh in the middle of paying puts the buyer back where they were.
*/

export const CART_KEY = 'rcmst_cart';
const MAX_AGE_MS = 35 * 60 * 1000;

export interface SavedCart {
  /** The order was pending when it was shown: the Purchase and onComplete are still owed when it becomes paid, even after a reload. */
  owed?: boolean;
  event: string;
  hold: string | null;
  items: Array<{ ticket_type: string | null; add_on: string | null; quantity: number }>;
  code: string | null;
  /** Proof this browser made the hold: what opens its order. A hash, never a person. */
  receipt?: string;
  /** A payment was started on this hold and no answer was seen. After a reload, the page must look before offering Pay. */
  attempted?: boolean;
  /** The order was made and shown: a reload shows it again, and says nothing twice to the pixels. */
  done?: boolean;
  at: number;
}

export function saveCart(c: Omit<SavedCart, 'at'>): void {
  writeJson(CART_KEY, { ...c, at: Date.now() }, 'session');
}

export function loadCart(event: string, now = Date.now()): SavedCart | null {
  const c = readJson<SavedCart>(CART_KEY, 'session');
  if (!c || c.event !== event || now - c.at > MAX_AGE_MS) return null;
  return c;
}

export function readSaved(): Omit<SavedCart, 'at'> | null {
  return readJson<SavedCart>(CART_KEY, 'session');
}

export function clearCart(): void {
  removeKey(CART_KEY, 'session');
}
````

### src/rcms-tickets/client/checkout.css

````css
/*
  The kit's look: Apple Wallet, the way a ticket page should feel. A soft canvas, raised surfaces with a very soft neutral
  lift (never a glow, never a card inside a card), spacing in place of lines, big calm type, a glass bar for the one
  action that floats. It follows the buyer's phone (light or dark).

  BRAND IN ONE PLACE: override the variables in the first block (from your own CSS, below this file), or call
  brandStyle('#yourcolour') from theme.ts. Nothing else in this file needs to change to re-theme the kit.
*/

.rt-checkout {
  /* ---- the handful a site changes ---- */
  --rt-accent: light-dark(#0b0b0d, #f5f5f7); /* the buttons */
  --rt-on-accent: light-dark(#ffffff, #0b0b0d); /* the words on the buttons */
  --rt-accent-ink: light-dark(#0a58ca, #409cff); /* links, the selected ring, the focus ring */
  --rt-radius: 20px; /* raised surfaces; fields and buttons follow it */
  --rt-font: -apple-system, BlinkMacSystemFont, 'SF Pro Text', 'Inter', 'Segoe UI', Roboto, system-ui, sans-serif;
  --rt-canvas: light-dark(#f2f2f7, #000000); /* the page behind; set to transparent to sit on your own background */
  --rt-surface: light-dark(#ffffff, #1c1c1e); /* raised rows, the summary */

  /* ---- derived: leave alone unless you mean to ---- */
  --rt-fg: light-dark(#0b0b0d, #f5f5f7);
  --rt-fg-2: light-dark(#2c2c31, #d1d1d6);
  --rt-fg-3: light-dark(#55555c, #aeaeb4);
  --rt-fill: light-dark(#ebebf0, #2c2c2e);
  --rt-border-input: light-dark(#85858d, #7c7c84);
  --rt-lift-ring: light-dark(rgb(0 0 0 / 0.04), rgb(255 255 255 / 0.08));
  --rt-lift: 0 0 0 1px var(--rt-lift-ring), 0 1px 2px light-dark(rgb(0 0 0 / 0.05), rgb(0 0 0 / 0)), 0 14px 32px -14px light-dark(rgb(0 0 0 / 0.16), rgb(0 0 0 / 0));
  --rt-glass: light-dark(rgb(250 250 252 / 0.76), rgb(30 30 32 / 0.74));
  --rt-glass-rim: light-dark(rgb(0 0 0 / 0.1), rgb(255 255 255 / 0.16));
  --rt-info-bg: light-dark(#eaf0ff, #14233f);
  --rt-info-fg: light-dark(#1f3a8a, #c7d8ff);
  --rt-warn-bg: light-dark(#fcf1d9, #3a2a08);
  --rt-warn-fg: light-dark(#6f4500, #ffdf9f);
  --rt-bad-bg: light-dark(#fdeceb, #3b1512);
  --rt-bad-fg: light-dark(#a3211a, #ffb4ad);
  --rt-bad: light-dark(#b0241d, #ff8a80);

  color-scheme: light dark;
  box-sizing: border-box;
  background: var(--rt-canvas);
  color: var(--rt-fg);
  font: 400 17px/24px var(--rt-font); /* 17px: the iOS body size */
  padding: 20px 16px 140px;
  -webkit-text-size-adjust: 100%;
  overflow-wrap: anywhere; /* a long word or a pasted link never pushes the page sideways */
  text-align: start; /* a site's own centred #root (the Vite template has one) must not centre the rows */
}
.rt-checkout[data-rt-scheme='light'] {
  color-scheme: light;
}
.rt-checkout[data-rt-scheme='dark'] {
  color-scheme: dark;
}

/* Safari before 17.5 has no light-dark(): those phones get the light look, never an unstyled page. */
@supports not (color: light-dark(#000000, #ffffff)) {
  .rt-checkout {
    --rt-accent: #0b0b0d;
    --rt-on-accent: #ffffff;
    --rt-accent-ink: #0a58ca;
    --rt-canvas: #f2f2f7;
    --rt-surface: #ffffff;
    --rt-fg: #0b0b0d;
    --rt-fg-2: #2c2c31;
    --rt-fg-3: #55555c;
    --rt-fill: #ebebf0;
    --rt-border-input: #85858d;
    --rt-lift-ring: rgb(0 0 0 / 0.04);
    --rt-lift: 0 0 0 1px var(--rt-lift-ring), 0 1px 2px rgb(0 0 0 / 0.05), 0 14px 32px -14px rgb(0 0 0 / 0.16);
    --rt-glass: rgb(250 250 252 / 0.76);
    --rt-glass-rim: rgb(0 0 0 / 0.1);
    --rt-info-bg: #eaf0ff;
    --rt-info-fg: #1f3a8a;
    --rt-warn-bg: #fcf1d9;
    --rt-warn-fg: #6f4500;
    --rt-bad-bg: #fdeceb;
    --rt-bad-fg: #a3211a;
    --rt-bad: #b0241d;
  }
}

.rt-checkout *,
.rt-checkout *::before,
.rt-checkout *::after {
  box-sizing: border-box;
}
.rt-checkout :focus-visible {
  outline: 3px solid var(--rt-accent-ink);
  outline-offset: 2px;
}
.rt-body:focus {
  outline: none;
}
.rt-sr {
  position: absolute;
  width: 1px;
  height: 1px;
  margin: -1px;
  padding: 0;
  overflow: hidden;
  clip: rect(0 0 0 0);
  white-space: nowrap;
  border: 0;
}
.rt-mono {
  font-family: ui-monospace, 'SF Mono', Menlo, monospace;
  letter-spacing: 0.04em;
}

/* ---- type ---- */
.rt-h1 {
  margin: 0;
  font-size: 30px;
  line-height: 36px;
  font-weight: 700;
  letter-spacing: -0.02em;
  text-wrap: balance;
}
.rt-h2 {
  margin: 0 0 12px;
  font-size: 22px;
  line-height: 28px;
  font-weight: 700;
  letter-spacing: -0.01em;
}
.rt-h3 {
  margin: 0 0 8px;
  font-size: 17px;
  font-weight: 600;
}
.rt-lead {
  margin: 6px 0 0;
  color: var(--rt-fg-2);
}
.rt-pre {
  white-space: pre-line;
}
.rt-hint,
.rt-note {
  color: var(--rt-fg-3);
  font-size: 15px;
  line-height: 22px;
}
.rt-hint {
  margin: 6px 0 0;
}
.rt-pill {
  display: inline-block;
  margin: 12px 0 0;
  padding: 4px 12px;
  border-radius: 999px;
  background: var(--rt-warn-bg);
  color: var(--rt-warn-fg);
  font-size: 15px;
  font-weight: 600;
}

/* ---- layout ---- */
.rt-header {
  max-width: 1040px;
  margin: 0 auto 20px;
}
.rt-layout {
  max-width: 1040px;
  margin: 0 auto;
  display: grid;
  grid-template-columns: minmax(0, 1fr);
  gap: 24px;
}
/* What focus or a scroll lands on stays clear of the floating clock above and the action bar below. */
.rt-body {
  scroll-margin-top: 76px;
}
.rt-h2,
.rt-notice,
.rt-field,
.rt-fieldset,
.rt-check,
.rt-refused {
  scroll-margin-top: 76px;
  scroll-margin-bottom: 168px;
}
.rt-input,
.rt-check-row,
.rt-check-row input,
.rt-checkout button,
.rt-checkout a {
  scroll-margin-top: 76px;
  scroll-margin-bottom: 168px;
}
.rt-notice:focus,
.rt-refused:focus {
  outline: none;
}
.rt-body > .rt-section + .rt-section,
.rt-body > .rt-section + .rt-code,
.rt-body > .rt-section + .rt-code-applied {
  margin-top: 32px;
}
.rt-section {
  min-width: 0;
}
@media (min-width: 900px) {
  .rt-checkout {
    padding: 40px 32px 56px;
  }
  .rt-h1 {
    font-size: 40px;
    line-height: 46px;
  }
  .rt-layout {
    grid-template-columns: minmax(0, 1fr) 360px;
    gap: 40px;
    align-items: start;
  }
  .rt-side {
    position: sticky;
    top: 88px;
  }
}

/* ---- progress ---- */
.rt-progress {
  overflow-wrap: normal; /* never "Ticket/s" */
  flex-wrap: wrap;
  max-width: 1040px;
  margin: 0 auto 20px;
  padding: 0;
  list-style: none;
  display: flex;
  gap: 20px;
  color: var(--rt-fg-3);
  font-size: 15px;
  font-weight: 600;
}
.rt-progress li {
  display: flex;
  align-items: center;
  gap: 8px;
}
.rt-progress-n {
  display: inline-grid;
  place-items: center;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: var(--rt-fill);
  font-size: 13px;
}
.rt-progress-now {
  color: var(--rt-fg);
}
.rt-progress-now .rt-progress-n,
.rt-progress-done .rt-progress-n {
  background: var(--rt-accent);
  color: var(--rt-on-accent);
}

/* ---- rows: one raised tile per choice ---- */
.rt-list {
  margin: 0;
  padding: 0;
  list-style: none;
  display: grid;
  gap: 12px;
}
.rt-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  padding: 20px;
  background: var(--rt-surface);
  border-radius: var(--rt-radius);
  box-shadow: var(--rt-lift);
}
/* 320 px: a long name keeps the whole row, and the stepper drops under it (it was squeezed to a sliver of letters). */
@media (max-width: 359px) {
  .rt-row {
    flex-wrap: wrap;
    padding: 16px;
  }
  .rt-row-main {
    flex: 1 1 100%;
  }
}
.rt-row-on {
  box-shadow: var(--rt-lift), inset 0 0 0 2px var(--rt-accent-ink);
}
.rt-row-off {
  background: var(--rt-fill);
  box-shadow: none;
}
.rt-row-off .rt-row-title {
  color: var(--rt-fg-2);
}
.rt-row-main {
  min-width: 0;
  display: grid;
  gap: 2px;
}
.rt-row-title {
  margin: 0;
  font-size: 19px;
  line-height: 24px;
  font-weight: 650;
}
.rt-row-sub {
  margin: 0;
  color: var(--rt-fg-3);
  font-size: 15px;
  line-height: 22px;
}
.rt-price {
  margin: 4px 0 0;
  display: flex;
  flex-wrap: wrap;
  gap: 4px 8px;
  align-items: baseline;
}
.rt-price strong {
  font-size: 20px;
  font-weight: 700;
}
.rt-was {
  color: var(--rt-fg-3);
}
.rt-badge {
  margin: 6px 0 0;
  display: inline-flex;
  gap: 6px;
  align-items: center;
  width: fit-content;
  padding: 3px 10px 3px 8px;
  border-radius: 999px;
  font-size: 14px;
  font-weight: 600;
}
.rt-badge-low {
  background: var(--rt-warn-bg);
  color: var(--rt-warn-fg);
}
.rt-badge-off {
  background: var(--rt-fill);
  color: var(--rt-fg-2);
}
.rt-ticket {
  align-items: flex-start;
  flex-wrap: wrap;
}
.rt-ticket-actions {
  display: grid;
  gap: 8px;
}

/* ---- stepper: 48px targets ---- */
.rt-stepper {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  flex: none;
}
.rt-step-button {
  width: 48px;
  height: 48px;
  display: inline-grid;
  place-items: center;
  border: 0;
  border-radius: 50%;
  background: var(--rt-fill);
  color: var(--rt-fg);
  cursor: pointer;
}
.rt-step-button:disabled {
  opacity: 0.4;
  cursor: default;
}
.rt-step-value {
  min-width: 36px;
  text-align: center;
  font-size: 22px;
  font-weight: 700;
  font-variant-numeric: tabular-nums;
}

/* ---- buttons ---- */
.rt-button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  min-height: 52px;
  padding: 0 24px;
  border: 0;
  border-radius: 16px;
  font: 600 17px/24px var(--rt-font);
  text-decoration: none;
  cursor: pointer;
  width: 100%;
}
.rt-button:disabled {
  opacity: 0.5;
  cursor: default;
}
.rt-button-primary {
  background: var(--rt-accent);
  color: var(--rt-on-accent);
}
.rt-button-secondary {
  background: var(--rt-fill);
  color: var(--rt-fg);
  width: auto;
}
.rt-button-quiet {
  min-height: 48px;
  background: transparent;
  color: var(--rt-accent-ink);
  width: auto;
}
.rt-button-wallet {
  background: #000000;
  color: #ffffff;
  min-height: 48px;
  width: auto;
  white-space: nowrap;
}
@media (prefers-color-scheme: dark) {
  .rt-button-wallet {
    box-shadow: inset 0 0 0 1px rgb(255 255 255 / 0.24);
  }
}
.rt-spinner {
  width: 18px;
  height: 18px;
  border-radius: 50%;
  border: 2.5px solid currentColor;
  border-right-color: transparent;
  animation: rt-spin 0.8s linear infinite;
}
@keyframes rt-spin {
  to {
    transform: rotate(360deg);
  }
}
@media (prefers-reduced-motion: reduce) {
  .rt-spinner {
    animation-duration: 2.4s;
  }
}

/* ---- fields: on the canvas, no panel around them ---- */
.rt-form {
  display: grid;
  gap: 32px;
}
.rt-field,
.rt-fieldset,
.rt-check {
  margin: 0 0 16px;
  padding: 0;
  border: 0;
  min-width: 0;
}
.rt-section > .rt-field:last-child {
  margin-bottom: 0;
}
.rt-label {
  display: block;
  margin: 0 0 6px;
  padding: 0;
  font-size: 15px;
  font-weight: 600;
}
.rt-optional {
  color: var(--rt-fg-3);
  font-weight: 400;
}
.rt-input {
  display: block;
  width: 100%;
  min-height: 52px;
  padding: 0 16px;
  background: var(--rt-surface);
  color: var(--rt-fg);
  border: 1px solid var(--rt-border-input);
  border-radius: 12px;
  font: inherit;
  appearance: none;
}
select.rt-input {
  background-image: linear-gradient(45deg, transparent 50%, currentColor 50%), linear-gradient(135deg, currentColor 50%, transparent 50%);
  background-position: calc(100% - 22px) 50%, calc(100% - 16px) 50%;
  background-size: 6px 6px, 6px 6px;
  background-repeat: no-repeat;
  padding-right: 40px;
}
.rt-textarea {
  padding: 12px 16px;
  min-height: 96px;
}
.rt-field-error .rt-input {
  border-color: var(--rt-bad);
  border-width: 2px;
}
.rt-error {
  margin: 6px 0 0;
  color: var(--rt-bad);
  font-size: 15px;
  font-weight: 600;
}
.rt-two {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}
.rt-date {
  display: grid;
  grid-template-columns: 1.6fr 0.8fr 1fr;
  gap: 8px;
}
.rt-date-part {
  display: block;
}
.rt-check-row {
  display: flex;
  gap: 14px;
  align-items: flex-start;
  margin: 0 0 14px;
  cursor: pointer;
}
.rt-check-row input {
  flex: none;
  width: 26px;
  height: 26px;
  margin: 0;
  accent-color: var(--rt-accent);
}
.rt-code {
  margin-top: 20px;
}
.rt-code-row {
  display: flex;
  gap: 10px;
  align-items: stretch;
}
.rt-code-row .rt-button {
  min-height: 52px;
}
.rt-code-applied {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  flex-wrap: wrap;
}
.rt-code-applied p {
  margin: 0;
}
.rt-chips {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
.rt-chip {
  min-height: 44px;
  padding: 0 16px;
  border: 0;
  border-radius: 999px;
  background: var(--rt-fill);
  color: var(--rt-fg);
  font: 600 15px/1 var(--rt-font);
  cursor: pointer;
}
.rt-chip[aria-pressed='true'] {
  background: var(--rt-accent);
  color: var(--rt-on-accent);
}
.rt-square {
  min-height: 96px;
}
.rt-secure {
  display: flex;
  gap: 8px;
  align-items: flex-start;
  margin: 16px 0 8px;
  color: var(--rt-fg-3);
  font-size: 15px;
}
.rt-secure .rt-icon {
  flex: none;
  margin-top: 2px;
}

/* ---- notices ---- */
.rt-notice {
  max-width: 1040px;
  margin: 0 auto 16px;
  display: flex;
  gap: 12px;
  align-items: flex-start;
  padding: 14px 16px;
  border-radius: 14px;
}
.rt-section .rt-notice {
  margin: 0 0 16px;
}
.rt-notice p {
  margin: 0;
}
.rt-notice .rt-icon {
  flex: none;
  margin-top: 2px;
}
.rt-notice-body {
  display: grid;
  gap: 8px;
}
.rt-notice-info {
  background: var(--rt-info-bg);
  color: var(--rt-info-fg);
}
.rt-notice-warn {
  background: var(--rt-warn-bg);
  color: var(--rt-warn-fg);
}
.rt-notice-error {
  background: var(--rt-bad-bg);
  color: var(--rt-bad-fg);
  font-weight: 600;
}

/* ---- the summary and the clock ---- */
.rt-summary {
  padding: 24px;
  background: var(--rt-surface);
  border-radius: var(--rt-radius);
  box-shadow: var(--rt-lift);
}
.rt-lines {
  margin: 0;
  display: grid;
  gap: 12px;
}
.rt-line {
  display: flex;
  justify-content: space-between;
  gap: 16px;
}
.rt-line dt {
  min-width: 0;
}
.rt-line dd {
  margin: 0;
  font-variant-numeric: tabular-nums;
  white-space: nowrap;
}
.rt-line-discount dd {
  color: var(--rt-fg-2);
}
.rt-line-total {
  margin-top: 8px;
  font-size: 22px;
  line-height: 28px;
  font-weight: 700;
}
.rt-timebar {
  position: sticky;
  top: 8px;
  z-index: 5;
  max-width: 1040px;
  margin: 0 auto 16px;
}
.rt-timer-wrap {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  padding: 4px 8px 4px 16px;
  border-radius: 999px;
  background: var(--rt-glass);
  box-shadow: 0 0 0 1px var(--rt-glass-rim), 0 8px 24px -12px light-dark(rgb(0 0 0 / 0.24), rgb(0 0 0 / 0.6));
  -webkit-backdrop-filter: blur(20px) saturate(1.6);
  backdrop-filter: blur(20px) saturate(1.6);
}
@supports not (backdrop-filter: blur(1px)) {
  .rt-timer-wrap,
  .rt-actions {
    background: var(--rt-surface);
  }
}
@media (prefers-reduced-transparency: reduce) {
  .rt-timer-wrap,
  .rt-actions {
    background: var(--rt-surface);
    -webkit-backdrop-filter: none;
    backdrop-filter: none;
  }
}
.rt-timer {
  margin: 0;
  display: flex;
  gap: 8px;
  align-items: center;
  min-height: 40px;
  font-variant-numeric: tabular-nums;
}
.rt-timer-low {
  color: var(--rt-bad);
}

/* ---- the action: a glass bar on a phone, part of the side column from 900px ---- */
.rt-actions {
  position: fixed;
  z-index: 6;
  left: 12px;
  right: 12px;
  bottom: max(12px, env(safe-area-inset-bottom));
  display: grid;
  gap: 4px;
  padding: 12px;
  border-radius: 28px;
  background: var(--rt-glass);
  box-shadow: 0 0 0 1px var(--rt-glass-rim), 0 12px 32px -12px light-dark(rgb(0 0 0 / 0.28), rgb(0 0 0 / 0.7));
  -webkit-backdrop-filter: blur(24px) saturate(1.6);
  backdrop-filter: blur(24px) saturate(1.6);
}
.rt-actions .rt-button-quiet {
  min-height: 44px;
  width: 100%;
}
@media (min-width: 900px) {
  .rt-actions {
    position: static;
    margin-top: 16px;
    padding: 0;
    border-radius: 0;
    background: none;
    box-shadow: none;
    -webkit-backdrop-filter: none;
    backdrop-filter: none;
  }
  .rt-checkout {
    padding-bottom: 56px;
  }
}

/* ---- confirmation ---- */
.rt-done {
  display: grid;
  gap: 12px;
  justify-items: start;
}
.rt-done .rt-h2 {
  margin: 16px 0 0;
}
.rt-done .rt-list {
  width: 100%;
}
.rt-done-mark {
  display: grid;
  place-items: center;
  width: 56px;
  height: 56px;
  border-radius: 50%;
  background: var(--rt-accent);
  color: var(--rt-on-accent);
}
.rt-facts {
  margin: 12px 0 0;
  display: flex;
  gap: 32px;
  flex-wrap: wrap;
}
.rt-facts dt {
  color: var(--rt-fg-3);
  font-size: 15px;
}
.rt-facts dd {
  margin: 0;
  font-size: 20px;
  font-weight: 700;
}
.rt-powered {
  display: flex;
  align-items: center;
  gap: 6px;
  max-width: 1040px;
  margin: 40px auto 0;
  color: var(--rt-fg-3);
  font-size: 13px;
}
.rt-skeleton {
  height: 320px;
  border-radius: var(--rt-radius);
  background: var(--rt-fill);
}
.rt-icon {
  flex: none;
}

/* ---- the sheet ---- */
.rt-sheet {
  width: 100%;
  max-width: 100%;
  height: 100dvh;
  max-height: 100dvh;
  margin: 0;
  padding: 0;
  border: 0;
  color-scheme: light dark;
  background: light-dark(#f2f2f7, #000000);
  color: light-dark(#0b0b0d, #f5f5f7);
  overflow: auto;
}
.rt-sheet::backdrop {
  background: rgb(0 0 0 / 0.5);
}
.rt-sheet-bar {
  position: sticky;
  top: 0;
  z-index: 7;
  display: flex;
  justify-content: flex-end;
  padding: 8px 8px 0;
  background: light-dark(rgb(242 242 247 / 0.88), rgb(0 0 0 / 0.82));
  -webkit-backdrop-filter: blur(20px) saturate(1.6);
  backdrop-filter: blur(20px) saturate(1.6);
}
.rt-sheet .rt-checkout {
  padding-top: 0;
}
/* The clock sits under the Close bar, not behind it. */
.rt-sheet .rt-timebar {
  top: 64px;
}
.rt-sheet .rt-body,
.rt-sheet .rt-h2,
.rt-sheet .rt-notice,
.rt-sheet .rt-field,
.rt-sheet .rt-fieldset,
.rt-sheet .rt-check,
.rt-sheet .rt-refused {
  scroll-margin-top: 132px;
}
@media (min-width: 900px) {
  .rt-sheet {
    max-width: 1120px;
    height: auto;
    max-height: 92dvh;
    margin: auto;
    border-radius: 28px;
  }
}

/* a sentence followed by its one button: room between them */
.rt-lead + .rt-button {
  margin-top: 16px;
}

.rt-slow {
  margin-top: 12px;
}

/* A page opened before the sale: how long is left, said once. */
.rt-opens {
  display: flex;
  gap: 10px;
  align-items: flex-start;
}
.rt-opens-count {
  margin: 0;
  font-weight: 600;
  font-variant-numeric: tabular-nums;
}
.rt-opens .rt-hint {
  margin: 2px 0 0;
}
````

### src/rcms-tickets/client/dates.ts

````ts
import type { EventDay, Storefront, StorefrontTicketType } from './types';

/** A date-only value ("2027-07-16") as a local calendar day. Never hand the string to Date: that is UTC midnight and shows the day before. */
export function dayOf(date: string): Date {
  const [y, m, d] = date.split('-').map(Number);
  return new Date(y!, m! - 1, d!);
}

export const shortDay = (date: string, locale?: string): string => dayOf(date).toLocaleDateString(locale, { weekday: 'short', month: 'short', day: 'numeric' });

/** "July 16 to 18, 2027", "July 30 to August 1, 2027", or one day: "Fri, July 16, 2027". */
export function eventDates(days: EventDay[], locale?: string): string {
  if (!days.length) return '';
  const first = days[0]!.date;
  const last = days[days.length - 1]!.date;
  if (first === last) return dayOf(first).toLocaleDateString(locale, { weekday: 'short', month: 'long', day: 'numeric', year: 'numeric' });
  const a = dayOf(first);
  const b = dayOf(last);
  const whole = (d: Date) => d.toLocaleDateString(locale, { month: 'long', day: 'numeric', year: 'numeric' });
  if (a.getFullYear() !== b.getFullYear()) return `${whole(a)} to ${whole(b)}`;
  return a.getMonth() === b.getMonth() ? `${a.toLocaleDateString(locale, { month: 'long', day: 'numeric' })} to ${b.getDate()}, ${b.getFullYear()}` : `${a.toLocaleDateString(locale, { month: 'long', day: 'numeric' })} to ${whole(b)}`;
}

/** What a ticket is good for, in words a buyer reads: "All 3 days", "Friday", "Friday and Saturday". */
export function goodFor(t: Pick<StorefrontTicketType, 'valid_days'>, store: Pick<Storefront, 'event'>): string {
  const days = store.event.days;
  const mine = days.filter((d) => t.valid_days.includes(d.id));
  if (!mine.length || mine.length === days.length) return days.length > 1 ? `All ${days.length} days` : 'The whole event';
  const names = mine.map((d) => d.name ?? dayOf(d.date).toLocaleDateString(undefined, { weekday: 'long' }));
  return names.length === 1 ? names[0]! : `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`;
}

/** "Mar 1, 10:00 AM EST": the venue's time with its zone when it is given, so a buyer in Chicago reads the same 10:00 the poster says. Else the buyer's own time. */
export const whenText = (iso: string, locale?: string, timeZone?: string): string => {
  const parts = { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' } as const;
  try {
    return new Date(iso).toLocaleString(locale, timeZone ? { ...parts, timeZone, timeZoneName: 'short' } : parts);
  } catch {
    return new Date(iso).toLocaleString(locale, parts);
  }
};
````

### src/rcms-tickets/client/deeplink.ts

````ts
/*
  Links into the checkout.
    ?tickets=1                    open the picker (scroll to it and move focus there)
    ?type=tt_...&qty=2            preselect two of that ticket type (qty defaults to 1)
    ?code=EARLYBIRD               a code, applied when the picker loads
    ?resume=hold_...              the abandoned-checkout email's link: the same selection comes back
  Nothing about a person is ever in these links.
*/

export interface DeepLink {
  open: boolean;
  preselect: Array<{ ticket_type: string; quantity: number }>;
  code: string | null;
  resume: string | null;
  /** The signed link's proof: what brings the code back with the items. */
  resumeKey?: string;
}

const ID = /^[a-z]{2,4}_[A-Za-z0-9]{4,64}$/;

export function readDeepLink(search: string): DeepLink {
  const q = new URLSearchParams(search);
  const type = q.get('type');
  const qty = Number.parseInt(q.get('qty') ?? '1', 10);
  const resume = q.get('resume');
  const code = (q.get('code') ?? '').trim().slice(0, 40);
  return {
    open: q.get('tickets') === '1' || !!type || !!resume,
    preselect: type && ID.test(type) ? [{ ticket_type: type, quantity: Number.isInteger(qty) && qty >= 1 && qty <= 100 ? qty : 1 }] : [],
    code: code || null,
    resume: resume && ID.test(resume) ? resume : null,
    ...(q.get('resume_key') ? { resumeKey: q.get('resume_key')! } : {}),
  };
}
````

### src/rcms-tickets/client/index.ts

````ts
export { Checkout } from './Checkout';
export type { CheckoutProps } from './Checkout';
export { CheckoutSheet } from './CheckoutSheet';
export { TicketPicker } from './TicketPicker';
export { AddOns } from './AddOns';
export { CodeField } from './CodeField';
export { BuyerForm, QuestionField } from './BuyerForm';
export { Summary, HoldTimer } from './Summary';
export { PaymentStep, testCardSlot, TEST_CARDS } from './PaymentStep';
export type { PaymentSlot, PaymentSlotContext } from './PaymentStep';
export { squareSlot, squareEnvironmentProblem } from './square';
export type { SquareOptions } from './square';
export { Confirmation } from './Confirmation';
export { useCheckout, orderQuestions, maxUnits } from './useCheckout';
export type { CheckoutOptions, CheckoutState, Step } from './useCheckout';
export { createApi, CheckoutApiError } from './api';
export type { CheckoutApi } from './api';
export { captureAttribution, readAttribution } from './attribution';
export { createPixel, loadMetaPixel, loadGa4, noPixel } from './pixel';
export type { Pixel, PixelEvent, PixelOptions } from './pixel';
export { readDeepLink } from './deeplink';
export { brandStyle } from './theme';
export { formatMoney } from './money';
export { say } from './messages';
export { normalizePhone } from './phone';
export { KIT_VERSION } from './version';
export type * from './types';
````

### src/rcms-tickets/client/messages.ts

````ts
import type { CheckoutError } from './types';

/*
  The words a buyer reads when something goes wrong. Plain, short, and always saying what to do next (the API's own
  `message` is written for developers). Edit the wording here: nothing else in the kit holds copy for errors.
*/

export type Next = 'pick' | 'retry' | 'again' | 'fix' | 'none';
export interface Said {
  text: string;
  /** What the checkout offers: choose again, try again, hold the same tickets again, or fix a field. */
  next: Next;
}

/** After a charge attempt began and the answer is unknown. Never "you have not been charged": we do not know that. */
export const UNCONFIRMED = 'We can’t confirm this payment yet. Check your email for your tickets. You will not be charged twice.';

/** What a buyer is told at sale about a pass-through add-on (refund protection). Say what your provider's terms say. */
export const PROTECTION_WORDS = 'Not refundable unless the event is cancelled or postponed, or the organizer gives it back.';

const TEXT: Record<string, Said> = {
  sold_out: { text: 'That ticket just sold out. Please choose again.', next: 'pick' },
  quantity_unavailable: { text: 'There are not that many left. Please choose again.', next: 'pick' },
  event_not_on_sale: { text: 'Tickets are not on sale right now.', next: 'none' },
  sale_not_started: { text: 'This ticket is not on sale yet.', next: 'pick' },
  sale_ended: { text: 'Sales for this ticket have ended.', next: 'pick' },
  ticket_type_unavailable: { text: 'That ticket is no longer available. Please choose again.', next: 'pick' },
  order_minimum_not_met: { text: 'This ticket needs a few more in the order.', next: 'pick' },
  order_maximum_exceeded: { text: 'That is more tickets than one buyer can have for this event. Please lower the number.', next: 'pick' },
  too_many_tickets: { text: 'That is more tickets than one order can hold.', next: 'pick' },
  add_on_requires_ticket: { text: 'Add a ticket to go with that.', next: 'pick' },
  code_invalid: { text: 'We do not know that code. Check it and try again.', next: 'fix' },
  code_not_started: { text: 'That code does not work yet.', next: 'fix' },
  code_expired: { text: 'That code has expired.', next: 'fix' },
  code_exhausted: { text: 'That code has been used up.', next: 'fix' },
  code_not_applicable: { text: 'That code does not work with these tickets.', next: 'fix' },
  held_try_fewer: { text: 'We can’t hold that many right now. Please try fewer.', next: 'pick' },
  hold_expired: { text: 'Your time ran out and the tickets went back on sale.', next: 'again' },
  hold_released: { text: 'Your tickets were released.', next: 'again' },
  hold_consumed: { text: 'These tickets are already bought.', next: 'none' },
  hold_extension_used: { text: 'You have already added more time once.', next: 'none' },
  price_changed: { text: 'The price changed, so you have not been charged.', next: 'retry' },
  payment_declined: { text: 'Your card was declined. You have not been charged. Try another card.', next: 'retry' },
  payment_failed: { text: 'We could not take the payment. You have not been charged. Please try again.', next: 'retry' },
  payment_voided: { text: 'We could not finish your order, so your card was not charged.', next: 'again' },
  payment_refunded: { text: 'We could not finish your order, so your payment was refunded in full.', next: 'again' },
  payment_lost: { text: 'Your payment could not be taken.', next: 'again' },
  payment_taken_order_cancelled: { text: 'Your payment went through but this order was cancelled. The organizer will refund you.', next: 'none' },
  order_cancelled: { text: 'This order was cancelled. If your card shows a charge, contact the organizer.', next: 'none' },
  payment_unconfirmed: { text: UNCONFIRMED, next: 'retry' },
  order_pending: { text: UNCONFIRMED, next: 'retry' },
  not_ready: { text: 'We could not check your order just now. You have not been charged. Please try again.', next: 'retry' },
  refund_failed: { text: 'We could not finish your order and could not refund it ourselves. Please contact the organizer. You were charged.', next: 'none' },
  provider_unavailable: { text: 'The payment service is busy. You have not been charged. Please try again.', next: 'retry' },
  consent_requires_phone: { text: 'Add your mobile number to get texts.', next: 'fix' },
  offline: { text: 'We could not reach the server. Check your connection and try again.', next: 'retry' },
  checkout_not_configured: { text: 'Tickets are not set up on this site yet.', next: 'none' },
};

const DECLINE: Record<string, string> = {
  insufficient_funds: 'Your card has insufficient funds. You have not been charged. Try another card.',
  expired_card: 'Your card has expired. You have not been charged. Try another card.',
  incorrect_cvc: 'The security code did not match. You have not been charged. Check it and try again.',
  card_declined: 'Your card was declined. You have not been charged. Try another card.',
};

/** The API's codes for a field, when the answer names none we know. Each field has its own words in `fieldWords`. */
const GENERIC = 'Something went wrong. Please try again.';

/**
 * What to tell the buyer about an error from the server. `where` is 'pay' once a charge attempt has begun: an answer that is not a
 * clear one can no longer promise that nothing was charged. The API's own `message` is written for developers and is never shown.
 */
export function say(e: Pick<CheckoutError, 'code' | 'status' | 'decline_code' | 'message'> & { retryAfter?: number | null; param?: string | null }, where: 'pay' | 'other' = 'other'): Said {
  // The tickets are only on someone's hold, or this wifi holds its share: fewer may fit now, and more may come back. Never "sold out".
  if (e.code === 'rate_limited' && e.param?.startsWith('items[')) return TEXT.held_try_fewer!;
  if (e.code === 'rate_limited' && e.param === 'items') return { text: 'Those tickets are being held right now. Please try again in a minute.', next: 'pick' };
  // On their first try, maybe: it is the sale that is busy, not the buyer who did something wrong.
  if (e.code === 'rate_limited') return { text: `Tickets are very busy right now. Please try again${e.retryAfter ? (e.retryAfter >= 90 ? ` in about ${Math.round(e.retryAfter / 60)} minutes` : ` in about ${e.retryAfter} seconds`) : ' in a moment'}.`, next: 'retry' };
  if (e.code === 'payment_declined' && e.decline_code && DECLINE[e.decline_code]) return { text: DECLINE[e.decline_code]!, next: 'retry' };
  const known = TEXT[e.code];
  if (known) return known;
  if (e.status >= 500 || e.status === 0) {
    if (where === 'pay') return { text: UNCONFIRMED, next: 'retry' };
    return { text: e.status === 0 ? TEXT.offline!.text : 'Something went wrong on our side. Please try again.', next: 'retry' };
  }
  return { text: GENERIC, next: 'retry' };
}

/** The words for a field the server refused, by the kit's own field key (see `fieldOf` in useCheckout). */
export function fieldWords(field: string): string {
  if (field === 'buyer.phone') return 'Enter a mobile number with its area code. Outside the US and Canada, start with + and the country code.';
  if (field === 'buyer.email') return 'Enter an email address, like name@example.com.';
  if (field === 'buyer.name') return 'Enter your full name.';
  return 'Please check this answer.';
}
````

### src/rcms-tickets/client/money.ts

````ts
import type { Money } from './types';

const digitsOf = (currency: string, locale?: string): number => {
  try {
    return new Intl.NumberFormat(locale, { style: 'currency', currency }).resolvedOptions().maximumFractionDigits ?? 2;
  } catch {
    return 2;
  }
};

/** "$195.00": minor units are never a float until this moment, and only for display. */
export function formatMoney(m: Money, locale?: string): string {
  const digits = digitsOf(m.currency, locale);
  const major = m.amount / 10 ** digits;
  try {
    return new Intl.NumberFormat(locale, { style: 'currency', currency: m.currency, minimumFractionDigits: digits, maximumFractionDigits: digits }).format(major);
  } catch {
    return `${major.toFixed(digits)} ${m.currency.toUpperCase()}`;
  }
}

/** "Free" for nothing at all, else the money. */
export const moneyOrFree = (m: Money, locale?: string): string => (m.amount === 0 ? 'Free' : formatMoney(m, locale));

/** "-$19.50" for a discount line. */
export function formatOff(m: Money, locale?: string): string {
  return `−${formatMoney(m, locale)}`;
}

/** Sums quantities of a price in whole minor units. */
export function times(m: Money, quantity: number): Money {
  return { amount: m.amount * quantity, currency: m.currency };
}
````

### src/rcms-tickets/client/onSale.tsx

````tsx
import { useEffect, useState } from 'react';
import { Icon } from './ui';
import type { Storefront } from './types';

/*
  The on-sale moment, for a buyer waiting on the page. Nobody should have to reload: the page says how long is left, opens by itself on the server's clock, and then reads what is
  really there. The read is spread out over a few seconds (useCheckout), so a thousand open pages don't all ask in one second; the stepper doesn't wait for it, so that spread costs nobody a place.
*/

const asItems = (s: Storefront) => [...s.ticket_types, ...s.add_ons];

/** The next start this read found still ahead of it, or null. Only what the read itself saw waiting: a start already behind the read isn't coming, whatever is off about it. */
export function nextOpening(s: Storefront): number | null {
  if (s.event.status !== 'on_sale') return null;
  const read = Date.parse(s.as_of);
  let next: number | null = null;
  for (const item of asItems(s)) {
    if (item.on_sale || !item.sale_starts_at) continue;
    const at = Date.parse(item.sale_starts_at);
    if (at > read && (next === null || at < next)) next = at;
  }
  return next;
}

/** The page with everything whose start has come marked on sale. The hold is what checks: if the organizer changed the time, the read that follows puts it right. */
export function opened(s: Storefront, now: number): Storefront {
  const read = Date.parse(s.as_of);
  const open = <T extends Storefront['ticket_types'][number] | Storefront['add_ons'][number]>(item: T): T => {
    if (item.on_sale || !item.sale_starts_at) return item;
    const at = Date.parse(item.sale_starts_at);
    const over = item.sale_ends_at !== null && Date.parse(item.sale_ends_at) <= now;
    return at > read && at <= now && !over ? { ...item, on_sale: true } : item;
  };
  return { ...s, ticket_types: s.ticket_types.map(open), add_ons: s.add_ons.map(open) };
}

const unit = (n: number, word: string): string => `${n} ${word}${n === 1 ? '' : 's'}`;

/** "12 minutes 5 seconds": the two largest parts, in words. */
export function opensInWords(ms: number): string {
  const s = Math.ceil(ms / 1000);
  if (s <= 0) return 'Sales are opening now.';
  const [d, h, m, sec] = [Math.floor(s / 86400), Math.floor(s / 3600) % 24, Math.floor(s / 60) % 60, s % 60];
  const parts = d ? [unit(d, 'day'), h ? unit(h, 'hour') : ''] : h ? [unit(h, 'hour'), m ? unit(m, 'minute') : ''] : m ? [unit(m, 'minute'), sec ? unit(sec, 'second') : ''] : [unit(sec, 'second')];
  return `Sales open in ${parts.filter(Boolean).join(' ')}.`;
}

/** What a page with nothing to buy yet says, once, above the list (Checkout draws it only then: an early bird on sale must not read as "sales open in a month"). Each row says its own date. */
export function OpensIn({ store, now }: { store: Storefront; now: () => number }) {
  const at = nextOpening(store);
  const [, tick] = useState(0);
  useEffect(() => {
    if (at === null) return;
    let timer: ReturnType<typeof setTimeout>;
    const again = () => {
      tick((n) => n + 1);
      // Seconds matter in the last hour; before that a sleeping phone need not wake for it.
      timer = setTimeout(again, at - now() > 3_600_000 ? 30_000 : 1_000);
    };
    again();
    return () => clearTimeout(timer);
  }, [at, now]);
  if (at === null) return null;
  return (
    <div className="rt-notice rt-notice-info rt-opens" role="timer" aria-live="off">
      <Icon name="clock" size={18} />
      <div>
        <p className="rt-opens-count">{opensInWords(at - now())}</p>
        <p className="rt-hint">This page opens by itself. There is no need to reload.</p>
      </div>
    </div>
  );
}
````

### src/rcms-tickets/client/phone.ts

````ts
/*
  A phone number as people type it, made E.164 (`+13135550100`), which is what the API stores. The server has its own copy of this
  function (server/phone.ts) so each half stands alone. A bare 10-digit number is taken as the North American plan; anything else
  needs its country code. Null means "not a number we can use": ask again, never guess.
*/
const E164 = /^\+[1-9][0-9]{6,14}$/;

export function normalizePhone(raw: string): string | null {
  const t = raw.trim();
  if (/[^0-9+().\-\s]/.test(t)) return null;
  const digits = t.replace(/\D/g, '');
  const plus = t.startsWith('+');
  const out = plus ? `+${digits}` : digits.startsWith('00') ? `+${digits.slice(2)}` : digits.length === 10 ? `+1${digits}` : digits.length === 11 && digits.startsWith('1') ? `+${digits}` : '';
  return E164.test(out) ? out : null;
}
````

### src/rcms-tickets/client/pixel.ts

````ts
import type { Hold, Money, OrderView, Storefront } from './types';

/*
  One door for every browser event, ported from Christmas at the Tail's cattPixel(). A funnel step calls the helper;
  the helper calls whichever pixels are on the page (Meta, GA4, TikTok) and any sink you add. Nothing here loads a
  third party by itself unless you call loadMetaPixel / loadGa4, and an ad consent of "denied" stops everything, loaders included.
  The order's `tracking_event_id` is the event id of Purchase, which is how our server-side Purchase and the browser's
  count as one sale. A TEST-mode checkout never fires Purchase: a rehearsal must not be counted as revenue.
*/

export type PixelEventName = 'PageView' | 'ViewContent' | 'InitiateCheckout' | 'AddPaymentInfo' | 'Purchase';

export interface PixelEvent {
  name: PixelEventName;
  /** Meta's event parameters (value, currency, content_ids, num_items ...). */
  params: Record<string, unknown>;
  /** Shared with the server-side event so the two deduplicate. Only Purchase has one. */
  eventId?: string;
}

export interface PixelOptions {
  /** What your cookie banner says. A function, so it is asked at every event. Default "unknown": events fire. */
  consent?: () => 'granted' | 'denied' | 'unknown';
  /** Your own listeners (a data layer, a log). They get every allowed event. */
  sinks?: Array<(e: PixelEvent) => void>;
  /** Fire Purchase even in test mode. Only the kit's own proof turns this on. */
  firePurchaseInTestMode?: boolean;
}

type Win = Window & { fbq?: (...a: unknown[]) => void; gtag?: (...a: unknown[]) => void; ttq?: { track: (...a: unknown[]) => void; page?: () => void } };

const GA4_NAMES: Record<PixelEventName, string> = {
  PageView: 'page_view',
  ViewContent: 'view_item',
  InitiateCheckout: 'begin_checkout',
  AddPaymentInfo: 'add_payment_info',
  Purchase: 'purchase',
};

export interface Pixel {
  track(e: PixelEvent): void;
  pageView(): void;
  viewContent(store: Storefront): void;
  initiateCheckout(hold: Hold): void;
  addPaymentInfo(hold: Hold): void;
  purchase(order: OrderView): void;
}

const value = (m: Money): number => m.amount / 10 ** (m.currency.toLowerCase() === 'jpy' ? 0 : 2);
/** What was sold: refund protection is money held for someone else, not sales, so a pixel's value leaves it out. */
const sales = (total: Money, passThrough?: Money): number => value({ ...total, amount: total.amount - (passThrough?.amount ?? 0) });

export function createPixel(options: PixelOptions = {}): Pixel {
  const fire = (e: PixelEvent) => {
    if ((options.consent?.() ?? 'unknown') === 'denied') return;
    const w = window as Win;
    try {
      w.fbq?.('track', e.name, e.params, e.eventId ? { eventID: e.eventId } : undefined);
    } catch {
      /* a broken pixel never breaks a sale */
    }
    try {
      const p = e.params as { value?: number; currency?: string; content_ids?: string[]; content_name?: string };
      const ga = { value: p.value, currency: p.currency?.toUpperCase(), ...(e.eventId ? { transaction_id: e.eventId } : {}), items: (p.content_ids ?? []).map((id) => ({ item_id: id, item_name: p.content_name })) };
      w.gtag?.('event', GA4_NAMES[e.name], e.name === 'PageView' ? {} : ga);
    } catch {
      /* ignore */
    }
    try {
      w.ttq?.track(e.name, e.params, e.eventId ? { event_id: e.eventId } : undefined);
    } catch {
      /* ignore */
    }
    for (const s of options.sinks ?? []) {
      try {
        s(e);
      } catch {
        /* a sink may not break a sale either */
      }
    }
  };
  const ids = (hold: Hold): string[] => hold.items.map((i) => (i.ticket_type ?? i.add_on)!).filter(Boolean);
  const count = (hold: Hold): number => hold.items.reduce((n, i) => n + i.quantity * (i.tickets_per_unit ?? 1), 0);
  return {
    track: fire,
    pageView: () => fire({ name: 'PageView', params: {} }),
    viewContent: (s) => fire({ name: 'ViewContent', params: { content_type: 'product', content_ids: [s.event.id], content_name: s.event.name, currency: s.event.currency } }),
    initiateCheckout: (h) => fire({ name: 'InitiateCheckout', params: { value: sales(h.price.total, h.price.pass_through), currency: h.price.currency, content_ids: ids(h), num_items: count(h) } }),
    addPaymentInfo: (h) => fire({ name: 'AddPaymentInfo', params: { value: sales(h.price.total, h.price.pass_through), currency: h.price.currency, content_ids: ids(h) } }),
    purchase: (o) => {
      if (o.mode === 'test' && !options.firePurchaseInTestMode) return;
      fire({
        name: 'Purchase',
        eventId: o.tracking_event_id,
        params: { value: sales(o.total, o.pass_through), currency: o.currency, content_ids: o.items.map((i) => (i.ticket_type ?? i.add_on)!).filter(Boolean), num_items: o.items.reduce((n, i) => n + i.quantity * (i.tickets_per_unit ?? 1), 0) },
      });
    },
  };
}

/** A pixel that does nothing: what the checkout uses when you give it none. */
export const noPixel: Pixel = createPixel({ consent: () => 'denied' });

export interface LoadOptions {
  /** What your cookie banner says. Denied: nothing is loaded. Call the loader again when it changes. */
  consent?: () => 'granted' | 'denied' | 'unknown';
}

/** Meta's own snippet, as Christmas at the Tail ran it. Opt in: it loads a script from Meta onto YOUR page. */
export function loadMetaPixel(pixelId: string, o: LoadOptions = {}): void {
  const w = window as Win & { _fbq?: unknown };
  if (!pixelId || w.fbq || o.consent?.() === 'denied') return;
  const queue: unknown[][] = [];
  const fbq = ((...a: unknown[]) => {
    const f = fbq as unknown as { callMethod?: (...x: unknown[]) => void };
    if (f.callMethod) f.callMethod(...a);
    else queue.push(a);
  }) as unknown as Win['fbq'] & { queue: unknown[][]; loaded: boolean; version: string; push: unknown };
  fbq!.queue = queue;
  fbq!.loaded = true;
  fbq!.version = '2.0';
  fbq!.push = fbq;
  w.fbq = fbq;
  w._fbq = fbq;
  const s = document.createElement('script');
  s.async = true;
  s.src = 'https://connect.facebook.net/en_US/fbevents.js';
  document.head.appendChild(s);
  w.fbq!('init', pixelId);
}

/** Google's gtag, the same way. Opt in. */
export function loadGa4(measurementId: string, o: LoadOptions = {}): void {
  const w = window as Win & { dataLayer?: unknown[] };
  if (!measurementId || w.gtag || o.consent?.() === 'denied') return;
  w.dataLayer = w.dataLayer ?? [];
  w.gtag = function () {
    // eslint-disable-next-line prefer-rest-params
    w.dataLayer!.push(arguments);
  };
  const s = document.createElement('script');
  s.async = true;
  s.src = `https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(measurementId)}`;
  document.head.appendChild(s);
  w.gtag('js', new Date());
  w.gtag('config', measurementId);
}
````

### src/rcms-tickets/client/square.tsx

````tsx
import { useEffect, useRef, useState } from 'react';
import { Button, NoticeBar } from './ui';
import type { PaymentSlot, PaymentSlotContext } from './PaymentStep';

/*
  Square, the recipe's browser half. Square's Web Payments SDK draws the card fields (inside its own iframe, so the card
  never touches this page's code) and hands back a one-time token. Only that token goes to your server, which charges it.
  Needs your Square application id and location id. Sandbox ids use Square's sandbox script.
  Square's own page: https://developer.squareup.com/docs/web-payments/take-card-payment
*/

export interface SquareOptions {
  applicationId: string;
  locationId: string;
  /** Optional: the application id already says. If you pass it, it must agree. */
  sandbox?: boolean;
}

/** Square's application ids say which world they are in: `sandbox-sq0idb-...` and `sq0idp-...`. */
const envOf = (applicationId: string): 'sandbox' | 'production' | null => (applicationId.startsWith('sandbox-') ? 'sandbox' : applicationId.startsWith('sq0idp-') ? 'production' : null);

/**
 * Why this application id may not take a payment on this checkout, or null. A test checkout must never load Square's real form,
 * and a live one must never issue tickets from its sandbox.
 */
export function squareEnvironmentProblem(mode: 'test' | 'live', applicationId: string, sandbox?: boolean): string | null {
  const env = envOf(applicationId);
  const ok = mode === 'test' ? env === 'sandbox' : env === 'production';
  if (!ok || (sandbox !== undefined && sandbox !== (env === 'sandbox'))) return 'The card form is not set up for this site: the Square application id does not match this checkout’s mode. Please contact the organizer.';
  return null;
}

interface SquareCard {
  attach(selector: string | HTMLElement): Promise<void>;
  tokenize(): Promise<{ status: string; token?: string; errors?: Array<{ message: string }> }>;
  destroy?: () => Promise<void> | void;
}
interface SquareGlobal {
  payments(appId: string, locationId: string): Promise<{ card(): Promise<SquareCard> }> | { card(): Promise<SquareCard> };
}

const SCRIPT = { live: 'https://web.squarecdn.com/v1/square.js', sandbox: 'https://sandbox.web.squarecdn.com/v1/square.js' };

function loadSquare(sandbox: boolean): Promise<SquareGlobal> {
  const w = window as Window & { Square?: SquareGlobal };
  if (w.Square) return Promise.resolve(w.Square);
  return new Promise((resolve, reject) => {
    const s = document.createElement('script');
    s.src = sandbox ? SCRIPT.sandbox : SCRIPT.live;
    s.async = true;
    s.onload = () => (w.Square ? resolve(w.Square) : reject(new Error('Square did not load')));
    s.onerror = () => reject(new Error('Square did not load'));
    document.head.appendChild(s);
  });
}

function SquareForm({ ctx, o }: { ctx: PaymentSlotContext; o: SquareOptions }) {
  const sandbox = envOf(o.applicationId) === 'sandbox';
  const host = useRef<HTMLDivElement>(null);
  const card = useRef<SquareCard | null>(null);
  const [ready, setReady] = useState(false);
  const [loadError, setLoadError] = useState<string | null>(null);
  useEffect(() => {
    let live = true;
    (async () => {
      try {
        const sq = await loadSquare(sandbox);
        const payments = await sq.payments(o.applicationId, o.locationId);
        const c = await payments.card();
        if (!live) return void c.destroy?.();
        await c.attach(host.current!);
        card.current = c;
        setReady(true);
      } catch {
        if (live) setLoadError('The card form did not load. Check your connection and reload the page.');
      }
    })();
    return () => {
      live = false;
      void card.current?.destroy?.();
    };
  }, [o.applicationId, o.locationId, sandbox]);
  return (
    <form
      className="rt-form"
      noValidate
      onSubmit={async (e) => {
        e.preventDefault();
        if (!card.current) return;
        const r = await card.current.tokenize();
        if (r.status === 'OK' && r.token) ctx.submit({ provider: 'square', source_id: r.token });
        else ctx.fail(r.errors?.[0]?.message ?? 'We could not read that card. Check it and try again.');
      }}
    >
      {sandbox ? <NoticeBar tone="info">Test mode. Use one of Square&rsquo;s sandbox test cards. No real card is charged.</NoticeBar> : null}
      {loadError ? <NoticeBar tone="error">{loadError}</NoticeBar> : null}
      <div className="rt-square" ref={host} data-testid="square-card" />
      <Button type="submit" busy={ctx.busy} disabled={!ready}>
        {ctx.payLabel}
      </Button>
    </form>
  );
}

/** A payment slot for Square: `<Checkout payment={squareSlot({ applicationId, locationId })} />`. */
export function squareSlot(o: SquareOptions): PaymentSlot {
  return {
    id: 'square',
    noRealMoney: (mode) => mode === 'test' && !squareEnvironmentProblem(mode, o.applicationId, o.sandbox),
    render: (ctx) => {
      const problem = squareEnvironmentProblem(ctx.mode, o.applicationId, o.sandbox);
      return problem ? <NoticeBar tone="error">{problem}</NoticeBar> : <SquareForm ctx={ctx} o={o} />;
    },
  };
}
````

### src/rcms-tickets/client/storage.ts

````ts
/* First-party storage that never throws: a private window, a blocked site or a full disk all just mean "nothing kept". */

export function readJson<T>(key: string, store: 'local' | 'session' = 'local'): T | null {
  try {
    const s = store === 'local' ? window.localStorage : window.sessionStorage;
    const raw = s.getItem(key);
    return raw ? (JSON.parse(raw) as T) : null;
  } catch {
    return null;
  }
}

export function writeJson(key: string, value: unknown, store: 'local' | 'session' = 'local'): void {
  try {
    (store === 'local' ? window.localStorage : window.sessionStorage).setItem(key, JSON.stringify(value));
  } catch {
    /* nothing kept */
  }
}

export function removeKey(key: string, store: 'local' | 'session' = 'local'): void {
  try {
    (store === 'local' ? window.localStorage : window.sessionStorage).removeItem(key);
  } catch {
    /* nothing kept */
  }
}
````

### src/rcms-tickets/client/theme.ts

````ts
/*
  Brand in one place. Everything the kit paints comes from a handful of CSS variables (see theme.css); the helper
  below turns ONE brand colour into the variables that must agree with each other: the button colour, the words on
  it, and a version of the colour that is readable as text on the page in light and in dark.
  Use:  <Checkout style={brandStyle('#c8102e')} />   or put the same variables in your own CSS.
*/

const parse = (color: string): number[] | null => {
  const c = color.trim();
  const rgb = /^rgb\(\s*(\d{1,3})[\s,]+(\d{1,3})[\s,]+(\d{1,3})\s*\)$/i.exec(c);
  if (rgb) return rgb.slice(1, 4).map((v) => Math.min(255, Number(v)));
  const short = /^#?([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec(c);
  const m = short ? [c, `${short[1]}${short[1]}${short[2]}${short[2]}${short[3]}${short[3]}`] : /^#?([0-9a-f]{6})$/i.exec(c);
  if (!m) return null;
  const n = parseInt(m[1]!, 16);
  return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
};
const toHex = (c: number[]) => `#${c.map((v) => Math.round(Math.max(0, Math.min(255, v))).toString(16).padStart(2, '0')).join('')}`;
const lum = ([r, g, b]: number[]) => {
  const f = (v: number) => (v / 255 <= 0.03928 ? v / 255 / 12.92 : ((v / 255 + 0.055) / 1.055) ** 2.4);
  return 0.2126 * f(r!) + 0.7152 * f(g!) + 0.0722 * f(b!);
};
export const contrast = (a: string, b: string): number => {
  const ca = parse(a);
  const cb = parse(b);
  if (!ca || !cb) return 1;
  const [hi, lo] = [lum(ca), lum(cb)].sort((x, y) => y - x);
  return (hi! + 0.05) / (lo! + 0.05);
};
const mixWith = (c: number[], target: number, t: number) => c.map((v) => v + (target - v) * t);

/** Moves a colour toward black or white, a step at a time, until it reaches `floor` against `on`. */
function reach(color: string, on: string, floor: number, toward: 0 | 255): string {
  let c = parse(color)!;
  for (let i = 0; i < 40 && contrast(toHex(c), on) < floor; i++) c = mixWith(c, toward, 0.06);
  return toHex(c);
}

export interface Brand {
  '--rt-accent': string;
  '--rt-on-accent': string;
  '--rt-accent-ink': string;
}

/**
 * The accent exactly as given when it can carry words (4.5:1 for the button label, white or near-black), darkened only
 * as much as it takes when it cannot. The ink version is for links and the selected ring on the page's own background.
 */
export function brandStyle(accent: string): Brand & Record<string, string> {
  const base = parse(accent) ? toHex(parse(accent)!) : '#1c1c1e';
  const white = '#ffffff';
  const dark = '#0b0b0d';
  let button = base;
  let on = white;
  if (contrast(white, base) >= 4.5) on = white;
  else if (contrast(dark, base) >= 4.5) on = dark;
  else button = reach(base, white, 4.5, 0);
  // A button is a shape as well as words. A near-white brand on the light canvas, or a near-black one on the dark canvas, dissolves
  // into the page: it gets a version that shows there (3:1) and keeps its own colour on the other. A colour you can see (yellow) stays yours.
  const onCanvas = (canvas: string, toward: 0 | 255) => (contrast(button, canvas) >= 1.28 ? { fill: button, words: on } : (() => {
    const fill = reach(button, canvas, 3, toward);
    return { fill, words: contrast(white, fill) >= contrast(dark, fill) ? white : dark };
  })());
  const light = onCanvas('#f2f2f7', 0);
  const night = onCanvas('#000000', 255);
  const both = (a: string, b: string) => (a === b ? a : `light-dark(${a}, ${b})`);
  return {
    '--rt-accent': both(light.fill, night.fill),
    '--rt-on-accent': both(light.words, night.words),
    '--rt-accent-ink': `light-dark(${reach(base, '#f2f2f7', 4.5, 0)}, ${reach(base, '#000000', 4.5, 255)})`,
  };
}
````

### src/rcms-tickets/client/types.ts

````ts
/*
  The shapes the checkout reads. They are the API's own fields (the contract in packages/shared), trimmed to what a checkout
  uses, so the kit has no dependency on anything of ours: copy this folder and it stands alone. packages/checkout/test keeps
  these assignable from the contract's real types, so they can't drift.
*/

export interface Money {
  amount: number;
  currency: string;
}

export interface Question {
  key: string;
  label: string;
  kind: 'text' | 'long_text' | 'email' | 'phone' | 'date' | 'number' | 'select' | 'multi_select' | 'checkbox' | 'address';
  required: boolean;
  scope: 'order' | 'ticket';
  options: string[] | null;
  help: string | null;
  sensitive: boolean;
}

export type AvailabilityState = 'available' | 'low' | 'sold_out';
export type HolderDetails = 'none' | 'name' | 'name_and_email';

export interface StorefrontTicketType {
  /** None left, and some are only held right now: they may come back. Never "Sold out". */
  held?: boolean;
  ticket_type: string;
  name: string;
  description: string | null;
  state: AvailabilityState;
  remaining: number | null;
  on_sale: boolean;
  sale_starts_at: string | null;
  sale_ends_at: string | null;
  price: Money;
  compare_at_price: Money | null;
  fees_passed_on: boolean;
  taxed: boolean;
  valid_days: string[];
  tickets_per_unit: number;
  per_order_min: number;
  per_order_max: number;
  min_age: number | null;
  unlocked_by_code: boolean;
  holder_details: HolderDetails;
  questions: Question[];
}

export interface StorefrontAddOn {
  /** None left, and some are only held right now: they may come back. Never "Sold out". */
  held?: boolean;
  add_on: string;
  name: string;
  description: string | null;
  state: AvailabilityState;
  remaining: number | null;
  on_sale: boolean;
  sale_starts_at: string | null;
  sale_ends_at: string | null;
  price: Money;
  fees_passed_on: boolean;
  taxed: boolean;
  per: 'order' | 'ticket';
  per_order_max: number;
  unlocked_by_code: boolean;
  /** Refund protection, money held for someone else. */
  pass_through?: true;
}

export interface ConsentText {
  version: string;
  text: string;
}

export interface EventDay {
  id: string;
  date: string;
  name: string | null;
  doors_at: string;
  starts_at: string;
  ends_at: string;
}

export interface StorefrontEvent {
  id: string;
  name: string;
  status: 'draft' | 'on_sale' | 'paused' | 'ended' | 'cancelled';
  venue: { name: string; address?: { city: string | null; region: string | null } | null; timezone: string };
  days: EventDay[];
  currency: string;
  attendee_info: string | null;
  questions: Question[];
  consent_texts: { email: ConsentText | null; sms: ConsentText | null };
}

/** What `GET <endpoint>/storefront` answers: everything the picker, the questions and the consent boxes need, in one read. */
export interface Storefront {
  object: 'storefront';
  mode: 'test' | 'live';
  as_of: string;
  /** Where a buyer finds their tickets later (it asks for a code, not a link): link it from your site. */
  my_tickets_url?: string | null;
  event: StorefrontEvent;
  order_fees_passed_on: boolean;
  ticket_types: StorefrontTicketType[];
  add_ons: StorefrontAddOn[];
  days: Array<{ day: string; date: string; state: AvailabilityState; remaining: number | null }>;
  code: { code: string; valid: boolean; reason: string | null } | null;
}

export interface FeeAmount {
  name: string;
  amount: Money;
  passed_on: boolean;
  taxable: boolean;
}

export interface PriceLine {
  kind: 'ticket' | 'add_on';
  ticket_type: string | null;
  add_on: string | null;
  name: string;
  quantity: number;
  tickets_per_unit?: number;
  unit_price: Money;
  amount: Money;
  discount: Money;
  fees: FeeAmount[];
  tax: Money;
  total: Money;
}

export interface PriceBreakdown {
  currency: string;
  lines: PriceLine[];
  order_fees: FeeAmount[];
  subtotal: Money;
  discount: Money;
  fees: Money;
  tax: Money;
  total: Money;
  /** Refund protection inside the total: held for someone else, not sales. */
  pass_through?: Money;
  code: { code: string; applied: boolean; discount: Money } | null;
}

export interface HoldItem {
  kind: 'ticket' | 'add_on';
  ticket_type: string | null;
  add_on: string | null;
  name: string;
  quantity: number;
  tickets_per_unit?: number;
  for_ticket_type: string | null;
}

/** A hold as the browser sees it: no email, no attribution, nothing about the buyer. */
export interface Hold {
  /** Proof this browser made the hold: what opens its order later. Only the answer that made the hold carries it. */
  receipt?: string;
  id: string;
  mode: 'test' | 'live';
  event: string;
  status: 'active' | 'consumed' | 'released' | 'expired';
  items: HoldItem[];
  code: string | null;
  price: PriceBreakdown;
  expires_at: string;
  extended: boolean;
  order: string | null;
  /** The kit server's clock when it answered: the countdown is measured against it, never the buyer's clock. */
  server_time: string;
}

export interface OrderTicket {
  id: string;
  kind: 'admission' | 'add_on';
  name: string;
  holder_name: string | null;
  short_code: string;
  status: string;
  url: string | null;
  apple_wallet_url: string | null;
  google_wallet_url: string | null;
}

/** An order as the browser sees it. */
export interface OrderView {
  id: string;
  number: string;
  mode: 'test' | 'live';
  status: string;
  /** What is known of the money on a cancelled order. Only `not_charged` says the card was not charged. */
  payment_end?: 'not_charged' | 'not_confirmed' | 'taken_after_end';
  hold: string | null;
  tickets_status: 'pending' | 'issued' | 'none';
  /** What is true of this order's mail, when your server knows better than "we sent it". Left out: as usual. */
  mail_note?: 'none' | 'later' | 'all_to_buyer';
  /** The private page with all the tickets (the API's `url`). */
  url: string | null;
  /** Hand this to your pixels as the event id so the server-side Purchase deduplicates. */
  tracking_event_id: string;
  buyer: { name: string | null; email: string | null };
  items: HoldItem[];
  total: Money;
  /** Refund protection inside the total: held for someone else, not sales. */
  pass_through?: Money;
  currency: string;
  tickets: OrderTicket[];
}

export interface ResumeView {
  id: string;
  status: Hold['status'];
  event: string;
  items: Array<{ ticket_type: string | null; add_on: string | null; quantity: number }>;
  code: string | null;
}

/** The test provider's tokens, and the browser's payment payloads. */
export type TestToken = 'tok_success' | 'tok_decline' | 'tok_insufficient' | 'tok_error' | 'tok_dispute';
export type PaymentPayload = { provider: 'test'; token: TestToken } | { provider: 'square'; source_id: string } | { provider: 'free' } | { provider: string; [k: string]: unknown };

export interface Attribution {
  utm_source?: string;
  utm_medium?: string;
  utm_campaign?: string;
  utm_term?: string;
  utm_content?: string;
  referrer?: string;
  landing_page?: string;
  fbclid?: string;
  gclid?: string;
  ttclid?: string;
  at?: string;
  tracking_link?: string;
  first_touch?: Omit<Attribution, 'first_touch' | 'tracking_link' | 'fbp' | 'fbc' | 'ga_client_id' | 'ga_session_id' | 'ad_consent' | 'page_url'>;
  fbp?: string;
  fbc?: string;
  ga_client_id?: string;
  ga_session_id?: string;
  ad_consent?: 'granted' | 'denied' | 'unknown';
  page_url?: string;
}

export interface CheckoutError {
  status: number;
  type: string;
  code: string;
  message: string;
  param: string | null;
  decline_code: string | null;
}

export type Answers = Record<string, string | number | boolean | string[]>;
````

### src/rcms-tickets/client/ui.tsx

````tsx
import { useId, type ReactNode } from 'react';

/* The few pieces every step is built from. Plain elements and class names (rt-*): style them in checkout.css. */

export const cx = (...a: Array<string | false | null | undefined>): string => a.filter(Boolean).join(' ');

type IconName = 'check' | 'minus' | 'plus' | 'clock' | 'lock' | 'alert' | 'info' | 'ticket';
const PATHS: Record<IconName, string> = {
  check: 'M5 12.5l4.5 4.5L19 7.5',
  minus: 'M6 12h12',
  plus: 'M12 6v12M6 12h12',
  clock: 'M12 7v5l3 2M12 21a9 9 0 100-18 9 9 0 000 18z',
  lock: 'M7 11V8a5 5 0 0110 0v3M6 11h12v9H6z',
  alert: 'M12 8v5M12 16.5v.5M12 3l10 18H2z',
  info: 'M12 11v6M12 7.5v.5M12 21a9 9 0 100-18 9 9 0 000 18z',
  ticket: 'M4 8a2 2 0 012-2h12a2 2 0 012 2v2a2 2 0 000 4v2a2 2 0 01-2 2H6a2 2 0 01-2-2v-2a2 2 0 000-4z',
};

export function Icon({ name, size = 20 }: { name: IconName; size?: number }) {
  return (
    <svg className="rt-icon" width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" focusable="false">
      <path d={PATHS[name]} />
    </svg>
  );
}

export function Button({ kind = 'primary', busy, children, ...rest }: { kind?: 'primary' | 'secondary' | 'quiet'; busy?: boolean; children: ReactNode } & React.ButtonHTMLAttributes<HTMLButtonElement>) {
  return (
    <button {...rest} type={rest.type ?? 'button'} className={cx('rt-button', `rt-button-${kind}`, rest.className)} disabled={rest.disabled || busy} aria-busy={busy || undefined}>
      {busy ? <span className="rt-spinner" aria-hidden="true" /> : null}
      <span>{children}</span>
    </button>
  );
}

/** A labelled field. The label is always above and always visible (a placeholder is never the label). */
export function Field({ label, hint, error, optional, children }: { label: string; hint?: string; error?: string; optional?: boolean; children: (p: { id: string; 'aria-describedby'?: string; 'aria-invalid'?: boolean }) => ReactNode }) {
  const id = useId();
  const describedBy = [hint ? `${id}-hint` : '', error ? `${id}-error` : ''].filter(Boolean).join(' ') || undefined;
  return (
    <div className={cx('rt-field', error && 'rt-field-error')}>
      <label className="rt-label" htmlFor={id}>
        {label}
        {optional ? <span className="rt-optional"> (optional)</span> : null}
      </label>
      {children({ id, 'aria-describedby': describedBy, 'aria-invalid': error ? true : undefined })}
      {hint ? (
        <p className="rt-hint" id={`${id}-hint`}>
          {hint}
        </p>
      ) : null}
      {error ? (
        <p className="rt-error" id={`${id}-error`}>
          {error}
        </p>
      ) : null}
    </div>
  );
}

export function Stepper({ label, value, min = 0, max, onChange, disabled }: { label: string; value: number; min?: number; max: number; onChange: (n: number) => void; disabled?: boolean }) {
  return (
    <div className="rt-stepper" role="group" aria-label={label}>
      <button type="button" className="rt-step-button" aria-label={`Remove one ${label}`} disabled={disabled || value <= min} onClick={() => onChange(value - 1)}>
        <Icon name="minus" />
      </button>
      <output className="rt-step-value" aria-live="polite" aria-label={`${value} ${label}`}>
        {value}
      </output>
      <button type="button" className="rt-step-button" aria-label={`Add one ${label}`} disabled={disabled || value >= max} onClick={() => onChange(value + 1)}>
        <Icon name="plus" />
      </button>
    </div>
  );
}

export function NoticeBar({ tone, children, action }: { tone: 'info' | 'warn' | 'error'; children: ReactNode; action?: ReactNode }) {
  return (
    <div className={cx('rt-notice', `rt-notice-${tone}`)} role={tone === 'error' ? 'alert' : 'status'} tabIndex={-1}>
      <Icon name={tone === 'info' ? 'info' : 'alert'} />
      <div className="rt-notice-body">
        <p>{children}</p>
        {action}
      </div>
    </div>
  );
}
````

### src/rcms-tickets/client/useCheckout.ts

````ts
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { CheckoutApiError, createApi, newKey, type CheckoutApi, type HoldRequest, type OrderRequest } from './api';
import { captureAttribution, readAttribution } from './attribution';
import { clearCart, loadCart, readSaved, saveCart } from './cart';
import { readDeepLink } from './deeplink';
import { fieldWords, say, type Next } from './messages';
import { formatMoney } from './money';
import { nextOpening, opened } from './onSale';
import { normalizePhone } from './phone';
import { noPixel, type Pixel } from './pixel';
import type { Answers, Hold, OrderView, PaymentPayload, Question, Storefront, StorefrontAddOn, StorefrontTicketType } from './types';

/*
  The whole checkout as one hook: every step's state and every action. The components are only a face on this, so you can
  keep the hook and draw your own steps, or keep the steps and change what the hook does.
*/

export type Step = 'tickets' | 'details' | 'pay' | 'done';

export interface CheckoutOptions {
  /** Where your server's handlers are mounted. Default "/api/tickets". */
  endpoint?: string;
  fetch?: typeof fetch;
  /** The event, when your server sells more than one. */
  event?: string;
  pixel?: Pixel;
  /** What your cookie banner says about ad tracking; sent with the hold so server-side conversions respect it. */
  adConsent?: () => 'granted' | 'denied' | 'unknown';
  /** The page's query string. Default: the browser's. */
  search?: string;
  onComplete?: (order: OrderView) => void;
  /** Keeps what the buyer typed about themselves across a reload, if your page wants to: its own storage, its own rules. Default: not kept. */
  buyerMemory?: { load(): { name: string; email: string; phone: string } | null; save(b: { name: string; email: string; phone: string }): void };
  /** Time between checks while the tickets are being made, in ms. Default 1500. */
  pollMs?: number;
  /** How long the page waits for any one call, in ms. Default 20 seconds, 60 for an order. */
  timeoutMs?: number;
  /** After tickets go on sale, an open page reads them again within this many ms, at a random moment, so open pages don't all ask at once. The page opens at the start time either way. Default 20000. */
  openSpreadMs?: number;
}

export interface Notice {
  tone: 'info' | 'warn' | 'error';
  text: string;
  next?: Next;
}

export interface AttendeeData {
  name: string;
  email: string;
  answers: Answers;
}

/** The order could not be made and no money stays taken. `action` is what the buyer can do about it. */
export interface Refusal {
  /** The heading, if not the usual one. */
  title?: string;
  text: string;
  action: 'again' | 'pay' | 'none';
}

export const MAX_ORDER_UNITS = 100;
/** A setTimeout longer than this fires at once. */
const LONGEST_TIMER_MS = 2 ** 30;
const OPEN_SPREAD_MS = 20_000;
const LOOK_TRIES = 6;

/** The questions an order must answer: the event's and each chosen type's order-scope ones, once per key. */
export function orderQuestions(store: Storefront, chosen: StorefrontTicketType[]): Question[] {
  const seen = new Set<string>();
  const out: Question[] = [];
  for (const q of [...store.event.questions, ...chosen.flatMap((t) => t.questions)]) {
    if (q.scope !== 'order' || seen.has(q.key)) continue;
    seen.add(q.key);
    out.push(q);
  }
  return out;
}

/** The units a hold may take of one type: what is left, its per-order top and the ceiling. */
export function maxUnits(t: StorefrontTicketType): number {
  const left = t.remaining === null ? MAX_ORDER_UNITS : t.remaining;
  return t.state === 'sold_out' || !t.on_sale ? 0 : Math.max(0, Math.min(t.per_order_max, left, MAX_ORDER_UNITS));
}

/** Parking and the like: bought for the order, with a ticket, alone or later. Per-ticket extras go with a ticket, and so does refund protection, which has nothing to protect on its own. */
export const goesAlone = (a: Pick<StorefrontAddOn, 'per' | 'pass_through'>): boolean => a.per === 'order' && !a.pass_through;

/** Whether a buyer can buy something on this page right now: a ticket with a working stepper (a row whose every day is sold out has none), or an add-on that goes alone. An add-on that waits for a ticket doesn't count. */
export function canBuyNow(s: Pick<Storefront, 'ticket_types' | 'add_ons' | 'days'>): boolean {
  const soldDays = new Set(s.days.filter((d) => d.state === 'sold_out').map((d) => d.day));
  return s.ticket_types.some((t) => maxUnits(t) > 0 && !(t.valid_days.length && t.valid_days.every((d) => soldDays.has(d)))) || s.add_ons.some((a) => goesAlone(a) && a.on_sale && a.state !== 'sold_out');
}

/**
 * After a refused hold, on a fresh read: what stays chosen, and each change in plain words. What is gone comes out, what is short comes down to what is left, the rest is untouched.
 * A row with no stepper can't be changed by the buyer, so without this the same refusal answers every Continue (final audit round 9, B M2).
 */
export function afterRefusal(s: Storefront, before: Storefront | null, qty: Record<string, number>, addOns: Record<string, number>): { qty: Record<string, number>; addOns: Record<string, number>; said: string[] } {
  const said: string[] = [];
  const out = (name: string) => `so we took ${name} out of your order.`;
  const gone = (name: string, item: Pick<StorefrontTicketType | StorefrontAddOn, 'state' | 'on_sale' | 'sale_starts_at'> & { held?: boolean }): string => {
    if (item.state === 'sold_out') return item.held ? `Other buyers are holding ${name} right now, ${out('it')} Try again in a few minutes.` : `${name} sold out, ${out('it')}`;
    if (!item.on_sale && item.sale_starts_at && Date.parse(item.sale_starts_at) > Date.parse(s.as_of)) return `${name} is not on sale yet, ${out('it')}`;
    if (!item.on_sale) return `Sales for ${name} have ended, ${out('it')}`;
    return `${name} sold out, ${out('it')}`;
  };
  const soldDays = new Set(s.days.filter((d) => d.state === 'sold_out').map((d) => d.day));
  const nextQty: Record<string, number> = {};
  for (const [id, n] of Object.entries(qty)) {
    if (!n) continue;
    const t = s.ticket_types.find((x) => x.ticket_type === id);
    if (!t) {
      said.push(`${before?.ticket_types.find((x) => x.ticket_type === id)?.name ?? 'A ticket you chose'} is no longer available, ${out('it')}`);
      continue;
    }
    const max = t.valid_days.length && t.valid_days.every((d) => soldDays.has(d)) ? 0 : maxUnits(t);
    if (max >= n) nextQty[id] = n;
    else if (max >= t.per_order_min && max > 0) {
      nextQty[id] = max;
      said.push(`Only ${max} of ${t.name} ${max === 1 ? 'is' : 'are'} left, so your order now has ${max}.`);
    } else said.push(gone(t.name, t));
  }
  const tickets = s.ticket_types.reduce((sum, t) => sum + (nextQty[t.ticket_type] ?? 0) * t.tickets_per_unit, 0);
  const nextAddOns: Record<string, number> = {};
  for (const [id, n] of Object.entries(addOns)) {
    if (!n) continue;
    const a = s.add_ons.find((x) => x.add_on === id);
    if (!a) {
      said.push(`${before?.add_ons.find((x) => x.add_on === id)?.name ?? 'An add-on you chose'} is no longer available, ${out('it')}`);
      continue;
    }
    if (a.state === 'sold_out' || !a.on_sale) {
      said.push(gone(a.name, a));
      continue;
    }
    if (tickets === 0 && !goesAlone(a)) {
      said.push(`${a.name} needs a ticket, ${out('it')}`);
      continue;
    }
    const cap = a.per === 'ticket' ? Math.min(a.per_order_max, tickets) : a.per_order_max;
    const max = Math.min(cap, a.remaining ?? cap);
    if (max >= n) nextAddOns[id] = n;
    else if (max > 0) {
      nextAddOns[id] = max;
      said.push(`Only ${max} of ${a.name} ${max === 1 ? 'goes' : 'go'} with this order now, so it now has ${max}.`);
    } else said.push(gone(a.name, a));
  }
  return { qty: nextQty, addOns: nextAddOns, said };
}

const signature = (qty: Record<string, number>, addOns: Record<string, number>, code: string | null): string =>
  JSON.stringify([Object.entries(qty).filter(([, n]) => n > 0).sort(), Object.entries(addOns).filter(([, n]) => n > 0).sort(), code ?? '']);

/** YYYY-MM-DD that is a real day (not February 31st) and not in the future. */
function realDate(v: string): boolean {
  const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(v);
  if (!m) return false;
  const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])];
  const t = new Date(y, mo - 1, d);
  return y >= 1900 && t.getFullYear() === y && t.getMonth() === mo - 1 && t.getDate() === d && t.getTime() <= Date.now();
}

const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;

/** An answer as the API takes it: a phone in E.164; an address with every key. */
function cleanAnswer(q: Question, v: Answers[string]): Answers[string] {
  if (q.kind === 'phone' && typeof v === 'string') return normalizePhone(v) ?? v;
  if (q.kind === 'address' && v && typeof v === 'object' && !Array.isArray(v)) {
    const a = v as unknown as Record<string, string | null | undefined>;
    return { line1: a.line1 ?? '', line2: a.line2 || null, city: a.city ?? '', region: a.region || null, postal_code: a.postal_code || null, country: a.country || 'US' } as unknown as Answers[string];
  }
  return v;
}

const NO_ORDER = 'Your order was not made. If your card shows a pending charge, it drops off in a few days.';
const RELEASED = 'Your tickets were released';
const BOUGHT_ELSEWHERE = 'These tickets were bought. Please check your email for them.';

const CART_ITEMS = (h: Hold) => h.items.map((i) => ({ ticket_type: i.ticket_type, add_on: i.add_on, quantity: i.quantity }));

export function useCheckout(options: CheckoutOptions = {}) {
  const api: CheckoutApi = useMemo(() => createApi(options.endpoint, options.fetch, options.timeoutMs), [options.endpoint, options.fetch, options.timeoutMs]);
  const pixel = options.pixel ?? noPixel;
  const pixelRef = useRef(pixel);
  pixelRef.current = pixel;
  const optionsRef = useRef(options);
  optionsRef.current = options;
  const search = options.search ?? (typeof window === 'undefined' ? '' : window.location.search);
  const deep = useMemo(() => readDeepLink(search), [search]);

  const [store, setStore] = useState<Storefront | null>(null);
  const [loadError, setLoadError] = useState<string | null>(null);
  const [step, setStepRaw] = useState<Step>('tickets');
  const [qty, setQty] = useState<Record<string, number>>({});
  const [addOns, setAddOns] = useState<Record<string, number>>({});
  const [codeInput, setCodeInput] = useState(deep.code ?? '');
  const [appliedCode, setAppliedCode] = useState<string | null>(null);
  const [codeBusy, setCodeBusy] = useState(false);
  const [codeNote, setCodeNote] = useState<Notice | null>(null);
  const [hold, setHold] = useState<Hold | null>(null);
  const [holding, setHolding] = useState(false);
  const [buyer, setBuyer] = useState(() => options.buyerMemory?.load() ?? { name: '', email: '', phone: '' });
  const [consent, setConsent] = useState({ email: false, sms: false });
  const [answers, setAnswers] = useState<Answers>({});
  const [attendees, setAttendees] = useState<Record<string, AttendeeData>>({});
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [notice, setNotice] = useState<Notice | null>(null);
  const [expired, setExpired] = useState(false);
  /** The hold was let go (by the organizer, or another tab), not out of time. */
  const [released, setReleased] = useState(false);
  const [paying, setPaying] = useState(false);
  const [payError, setPayError] = useState<Notice | null>(null);
  const [order, setOrder] = useState<OrderView | null>(null);
  /** The sale is owed to the pixel and onComplete: the order was pending when it was shown. */
  const owed = useRef(false);
  /** A charge attempt began and its answer never came: the page must look before it offers Pay again. */
  const [unconfirmed, setUnconfirmed] = useState(false);
  const [checking, setChecking] = useState(false);
  const [refusal, setRefusal] = useState<Refusal | null>(null);
  const [lastChecked, setLastChecked] = useState<number | null>(null);
  /** Goes up when something the buyer must see just appeared: the page moves focus to it. */
  const [attention, setAttention] = useState(0);
  const look = useCallback(() => setAttention((n) => n + 1), []);
  const receipt = useRef<string | undefined>(undefined);
  /** The request of the last press, in memory only: sending the very same one again is the same payment and the same order. */
  const lastOrder = useRef<OrderRequest | null>(null);
  const refreshRef = useRef<(code?: string | null) => Promise<Storefront | null>>(async () => null);
  const payingRef = useRef(false);
  const holdKey = useRef<{ sig: string; key: string } | null>(null);
  const lastEmail = useRef<string>('');
  const savedEmail = useRef<{ hold: string; email: string; yes: boolean } | null>(null);
  const emailBusy = useRef(false);
  const emailAgain = useRef(false);
  const emailRetry = useRef<{ tries: number; timer?: ReturnType<typeof setTimeout> }>({ tries: 0 });
  const saveLatest = useRef<() => Promise<void>>(async () => undefined);
  const viewed = useRef(false);

  const setStep = useCallback((s: Step) => setStepRaw(s), []);
  useEffect(() => {
    optionsRef.current.buyerMemory?.save(buyer);
  }, [buyer]);

  /* ---- browser back and forward walk the steps, and never leave the checkout by surprise ---- */
  const stepNow = useRef(step);
  stepNow.current = step;
  const canShow = useRef<(s: Step) => Step>((s) => s);
  useEffect(() => {
    if (typeof window === 'undefined') return;
    // A router may keep its own state here (Next.js does, and reloads without it): keep whatever is there.
    const here = window.history.state as { rtStep?: Step; rtDepth?: number } | null;
    if (here?.rtStep === step) return;
    if (step === 'done') window.history.replaceState({ ...here, rtStep: step, rtDepth: here?.rtDepth ?? 0 }, '');
    else if (!here?.rtStep) window.history.replaceState({ ...here, rtStep: step, rtDepth: 0 }, '');
    else window.history.pushState({ ...here, rtStep: step, rtDepth: (here.rtDepth ?? 0) + 1 }, '');
  }, [step]);
  useEffect(() => {
    if (typeof window === 'undefined') return;
    const onPop = (e: PopStateEvent) => {
      const state = e.state as { rtStep?: Step; rtDepth?: number } | null;
      if (!state?.rtStep) return;
      // After the confirmation Back leaves the checkout, past its own steps: the buyer has what they came for.
      if (stepNow.current === 'done') return window.history.go(-((state.rtDepth ?? 0) + 1));
      setStepRaw(canShow.current(state.rtStep));
    };
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, []);

  /** The order is made: this is the one way to the confirmation, however we learned of it. */
  const finish = useCallback((o: OrderView, again = false) => {
    setOrder(o);
    setUnconfirmed(false);
    setRefusal(null);
    setStepRaw('done');
    lastOrder.current = null;
    // Kept, not cleared: a reload must show this confirmation, never an empty picker that invites a second purchase.
    const saved = readSaved();
    // A sale still owed from before a reload is remembered with the cart: the page that showed "Almost done" is gone. A page closed for good never fires it: the server's own Purchase, with the same event id, is the record of that sale.
    const wasOwed = !!saved?.owed;
    const owesNow = o.status === 'pending' && (!again || wasOwed);
    if (saved) saveCart({ ...saved, attempted: false, done: true, owed: owesNow });
    owed.current = owesNow;
    // An order whose payment is still being finished is not a sale yet: the pixel and onComplete wait until the poll below sees it paid. A cancelled one never was one.
    if (o.status === 'pending' || o.status === 'cancelled') return;
    if (again && !wasOwed) return;
    pixelRef.current.purchase(o);
    optionsRef.current.onComplete?.(o);
  }, []);

  /** After the confirmation: a clean checkout, for a buyer who wants more. */
  const buyMore = useCallback(() => {
    clearCart();
    setOrder(null);
    setHold(null);
    holdKey.current = null;
    setQty({});
    setAddOns({});
    setErrors({});
    setNotice(null);
    setPayError(null);
    setStepRaw('tickets');
    void refreshRef.current(null);
  }, []);

  /** How far the server's clock is ahead of this device's: an answer is never from the future, so the largest gap seen is the closest. */
  const clockGap = useRef<number | null>(null);
  const noteClock = useCallback((s: Storefront) => {
    const gap = Date.parse(s.as_of) - Date.now();
    if (Number.isFinite(gap) && (clockGap.current === null || gap > clockGap.current)) clockGap.current = gap;
  }, []);
  const serverNow = useCallback(() => Date.now() + (clockGap.current ?? 0), []);

  /** Reads the storefront (again, with a code, after a failed hold). */
  const refresh = useCallback(
    async (code?: string | null, fresh = false): Promise<Storefront | null> => {
      try {
        const s = await api.storefront({ code: code ?? undefined, event: options.event, ...(fresh ? { fresh } : {}) });
        noteClock(s);
        setStore(s);
        setLoadError(null);
        if (!viewed.current) {
          viewed.current = true;
          pixelRef.current.viewContent(s);
        }
        return s;
      } catch (e) {
        setLoadError(say(e as CheckoutApiError).text);
        return null;
      }
    },
    [api, options.event, noteClock],
  );

  refreshRef.current = refresh;

  /* ---- the on-sale moment (onSale.tsx): the page opens by itself, then reads what is really there ---- */
  const [wake, setWake] = useState(0);
  const codeNow = useRef<string | null>(null);
  codeNow.current = appliedCode;
  const lookTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
  const lookSoon = useCallback(
    (tries = 0) => {
      if (lookTimer.current) return;
      const spread = optionsRef.current.openSpreadMs ?? OPEN_SPREAD_MS;
      // A first look is spread out; one after a refusal backs off, and the page is open meanwhile, so a busy moment costs nobody anything.
      const wait = tries === 0 ? Math.random() * spread : Math.min(60_000, 5_000 * 2 ** tries) * (0.5 + Math.random() / 2);
      lookTimer.current = setTimeout(() => {
        lookTimer.current = undefined;
        api.storefront({ code: codeNow.current ?? undefined, event: optionsRef.current.event }).then(
          (s) => {
            noteClock(s);
            setStore(s);
          },
          () => {
            if (tries < LOOK_TRIES) lookSoon(tries + 1);
          },
        );
      }, wait);
    },
    [api, noteClock],
  );
  useEffect(() => () => void (lookTimer.current && clearTimeout(lookTimer.current)), []);
  useEffect(() => {
    if (!store) return;
    const next = nextOpening(store);
    if (next === null) return;
    const timer = setTimeout(
      () => {
        if (serverNow() < next) return setWake((n) => n + 1);
        setStore((s) => (s ? opened(s, serverNow()) : s));
        if (stepNow.current === 'tickets') setNotice({ tone: 'info', text: 'Tickets are on sale now.' });
        lookSoon();
      },
      Math.min(Math.max(0, next - serverNow()), LONGEST_TIMER_MS),
    );
    return () => clearTimeout(timer);
  }, [store, wake, serverNow, lookSoon]);
  // A phone that slept through the moment: its timer may not have run. Come back and it runs now.
  useEffect(() => {
    if (typeof document === 'undefined') return;
    const onShow = () => {
      if (document.visibilityState === 'visible') setWake((n) => n + 1);
    };
    document.addEventListener('visibilitychange', onShow);
    return () => document.removeEventListener('visibilitychange', onShow);
  }, []);

  /* ---- landing: attribution, the storefront, then a resume link, a saved hold or a deep link ---- */
  useEffect(() => {
    let live = true;
    captureAttribution({ adConsent: options.adConsent?.() });
    (async () => {
      const s = await refresh(deep.code);
      if (!s || !live) return;
      if (deep.code && s.code?.valid) setAppliedCode(s.code.code);
      const adopt = (items: Array<{ ticket_type: string | null; add_on: string | null; quantity: number }>) => {
        const q: Record<string, number> = {};
        const a: Record<string, number> = {};
        for (const it of items) {
          const t = it.ticket_type && !it.add_on ? s.ticket_types.find((x) => x.ticket_type === it.ticket_type) : null;
          if (t) q[t.ticket_type] = Math.min(it.quantity, maxUnits(t));
          const ao = it.add_on ? s.add_ons.find((x) => x.add_on === it.add_on) : null;
          if (ao && ao.state !== 'sold_out' && ao.on_sale) a[ao.add_on] = Math.min(it.quantity, ao.per_order_max);
        }
        for (const k of Object.keys(q)) if (!q[k]) delete q[k];
        setQty(q);
        setAddOns(a);
        return Object.keys(q).length + Object.keys(a).length;
      };
      // First what this browser already has: a hold it made may be an order by now, whatever the URL says.
      const saved = loadCart(s.event.id);
      if (saved?.hold) {
        receipt.current = saved.receipt;
        try {
          const h = await api.readHold(saved.hold, saved.receipt);
          if (!live) return;
          if (h.status === 'consumed' && h.order) {
            const o = await api.readOrder(h.order, h.id, saved.receipt);
            if (!live) return;
            setHold(h);
            finish(o, !!saved.done);
            return;
          }
          if (h.status === 'active') {
            adopt(h.items);
            if (h.code) setAppliedCode(h.code);
            setHold(h);
            setStepRaw('details');
            if (saved.attempted) setUnconfirmed(true);
            return;
          }
          // Bought, but this browser's proof no longer opens it (the site rolled its key). Never tell a paid buyer there was no order.
          if (h.status === 'consumed') setNotice({ tone: 'info', text: BOUGHT_ELSEWHERE });
          else if (h.status === 'released') setNotice({ tone: 'info', text: RELEASED });
          else if (saved.attempted) setNotice({ tone: 'warn', text: NO_ORDER });
        } catch (e) {
          const err = e as CheckoutApiError;
          if (err.status === 0 || err.status >= 500) {
            // We can't tell, and an empty picker would invite a second purchase. The cart stays for the next look.
            if (live) setNotice({ tone: 'warn', text: 'We could not check on your order. Please reload this page in a moment before you buy again.' });
            return;
          }
          /* gone: start fresh */
        }
        clearCart();
      }
      if (deep.resume) {
        try {
          const r = await api.resume(deep.resume, deep.resumeKey);
          if (!live) return;
          if (r.code) {
            const s2 = await refresh(r.code);
            if (s2?.code?.valid) {
              setAppliedCode(s2.code.code);
              setCodeInput(s2.code.code);
            }
          }
          const n = adopt(r.items);
          setNotice(n ? { tone: 'info', text: 'Welcome back. We saved your tickets. Check them and continue when you are ready.' } : { tone: 'warn', text: 'Those tickets are no longer available. Please choose again.' });
        } catch {
          setNotice({ tone: 'warn', text: 'We could not find your saved tickets. Please choose again.' });
        }
        return;
      }
      if (deep.preselect.length) adopt(deep.preselect.map((p) => ({ ticket_type: p.ticket_type, add_on: null, quantity: p.quantity })));
    })();
    return () => {
      live = false;
    };
    // once, on landing
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  /* ---- the picker ---- */
  const ticketTypes = store?.ticket_types ?? [];
  const chosen = ticketTypes.filter((t) => (qty[t.ticket_type] ?? 0) > 0);
  const ticketCount = chosen.reduce((n, t) => n + (qty[t.ticket_type] ?? 0) * t.tickets_per_unit, 0);
  /** Something to hold: a ticket, or an add-on that is bought alone. */
  const hasChoice = ticketCount > 0 || !!store?.add_ons.some((a) => goesAlone(a) && (addOns[a.add_on] ?? 0) > 0);

  const setTicket = useCallback(
    (t: StorefrontTicketType, n: number) => {
      let next = Math.max(0, Math.min(n, maxUnits(t)));
      if (next > 0 && next < t.per_order_min) next = n > (qty[t.ticket_type] ?? 0) ? Math.min(t.per_order_min, maxUnits(t)) : 0;
      const after = { ...qty, [t.ticket_type]: next };
      setQty(after);
      setNotice(null);
      // With no ticket left, what goes only with a ticket goes too. Parking can stay: it is bought alone as well.
      if (Object.values(after).every((v) => !v)) setAddOns((a) => Object.fromEntries(Object.entries(a).filter(([id]) => store?.add_ons.some((x) => x.add_on === id && goesAlone(x)))));
    },
    [qty, store],
  );
  const setAddOn = useCallback((id: string, n: number) => {
    setAddOns((a) => ({ ...a, [id]: Math.max(0, n) }));
    setNotice(null);
  }, []);

  const applyCode = useCallback(async () => {
    const code = codeInput.trim();
    if (!code) return;
    setCodeBusy(true);
    setCodeNote(null);
    const s = await refresh(code);
    setCodeBusy(false);
    if (!s) return;
    if (s.code?.valid) {
      setAppliedCode(s.code.code);
      setCodeNote({ tone: 'info', text: `Code ${s.code.code} added. Your discount shows in the summary.` });
    } else {
      setAppliedCode(null);
      setCodeNote({ tone: 'error', text: say({ code: s.code?.reason ?? 'code_invalid', status: 409, decline_code: null, message: '' }).text });
    }
  }, [codeInput, refresh]);

  const removeCode = useCallback(async () => {
    setAppliedCode(null);
    setCodeInput('');
    setCodeNote(null);
    await refresh(null);
  }, [refresh]);

  const holdRequest = useCallback((): HoldRequest => {
    const items: HoldRequest['items'] = [
      ...chosen.map((t) => ({ ticket_type: t.ticket_type, quantity: qty[t.ticket_type]! })),
      ...Object.entries(addOns)
        .filter(([, n]) => n > 0)
        .map(([add_on, quantity]) => ({ add_on, quantity })),
    ];
    return { items, ...(appliedCode ? { code: appliedCode } : {}), ...(buyer.email && EMAIL.test(buyer.email) ? { email: buyer.email } : {}), attribution: readAttribution({ adConsent: options.adConsent?.() }), ...(options.event ? { event: options.event } : {}) };
  }, [chosen, qty, addOns, appliedCode, buyer.email, options]);

  const sigNow = signature(qty, addOns, appliedCode);

  const explain = useCallback(
    async (e: unknown, where: 'hold' | 'pay'): Promise<Notice> => {
      const err = e instanceof CheckoutApiError ? e : new CheckoutApiError(0, {});
      const said = say(err);
      if (where === 'hold' && (said.next === 'pick' || err.code === 'event_not_on_sale' || err.code === 'ticket_type_unavailable' || (err.code === 'rate_limited' && err.param === 'items'))) {
        // Read what is really there now, take out what is gone, keep the rest, and say so: the buyer can't change a row that has no stepper.
        const was = store;
        const s = await refresh(appliedCode, true);
        if (s) {
          const left = afterRefusal(s, was, qty, addOns);
          if (left.said.length) {
            setQty(left.qty);
            setAddOns(left.addOns);
            const any = Object.keys(left.qty).length + Object.keys(left.addOns).length > 0;
            return { tone: 'warn', text: `${left.said.join(' ')} ${any ? 'Check your order and continue.' : 'Please choose again.'}`, next: 'pick' };
          }
        }
      }
      return { tone: 'error', text: said.text, next: said.next };
    },
    [refresh, appliedCode, store, qty, addOns],
  );

  /** Holds what is chosen and moves to the details. A hold that already matches is kept. */
  const toDetails = useCallback(async () => {
    if (holding) return;
    if (!hasChoice) {
      if (store && !canBuyNow(store)) setNotice({ tone: 'info', text: 'Nothing here can be bought right now.' });
      else setNotice({ tone: 'error', text: store?.add_ons.some(goesAlone) ? 'Choose a ticket or an add-on to continue.' : 'Choose at least one ticket to continue.' });
      look();
      return;
    }
    if (hold && hold.status === 'active' && holdKey.current?.sig === sigNow && !expired) {
      setStepRaw('details');
      return;
    }
    setHolding(true);
    setNotice(null);
    const previous = hold;
    try {
      const sameAttempt = holdKey.current?.sig === sigNow ? holdKey.current.key : newKey();
      holdKey.current = { sig: sigNow, key: sameAttempt };
      const mine = previous && previous.status === 'active' && !expired ? previous : null;
      const asked = holdRequest();
      let h: Hold;
      try {
        h = await api.createHold(mine ? { ...asked, replaces: mine.id } : asked, sameAttempt, mine ? receipt.current : undefined);
      } catch (e) {
        // Near the very end the only tickets left may be this buyer's own, and a hold can't take from a hold: let go, and ask once more. Told no again, the tickets are gone and they hear why.
        const own = e instanceof CheckoutApiError && (e.code === 'sold_out' || e.code === 'quantity_unavailable' || (e.code === 'rate_limited' && !!e.param));
        if (!mine || !own) throw e;
        await api.releaseHold(mine.id, receipt.current).catch(() => undefined);
        setHold(null);
        receipt.current = undefined;
        h = await api.createHold(asked, newKey());
      }
      if (previous) void api.releaseHold(previous.id, receipt.current).catch(() => undefined);
      setHold(h);
      setExpired(false);
      pixelRef.current.initiateCheckout(h);
      receipt.current = h.receipt;
      saveCart({ event: h.event, hold: h.id, items: CART_ITEMS(h), code: h.code, receipt: h.receipt });
      setStepRaw('details');
    } catch (e) {
      holdKey.current = null;
      setNotice(await explain(e, 'hold'));
      look();
    } finally {
      setHolding(false);
    }
  }, [holding, hasChoice, store, hold, sigNow, expired, api, holdRequest, explain, look]);

  /* ---- details ---- */
  const questionList = useMemo(() => (store ? orderQuestions(store, chosen) : []), [store, chosen]);

  /** One attendee slot per ticket of a type that asks for its holders: key `type:index`. */
  const attendeeSlots = useMemo(() => {
    const out: Array<{ key: string; type: StorefrontTicketType; index: number }> = [];
    for (const t of chosen) {
      const needs = t.tickets_per_unit === 1 && (t.holder_details !== 'none' || t.questions.some((q) => q.scope === 'ticket'));
      if (!needs) continue;
      for (let i = 0; i < (qty[t.ticket_type] ?? 0); i++) out.push({ key: `${t.ticket_type}:${i}`, type: t, index: i });
    }
    return out;
  }, [chosen, qty]);

  const setAttendee = useCallback((key: string, patch: Partial<AttendeeData>) => setAttendees((a) => ({ ...a, [key]: { ...({ name: '', email: '', answers: {} } as AttendeeData), ...a[key], ...patch } })), []);

  const emptyAnswer = (v: unknown): boolean => v === undefined || v === null || v === '' || v === false || (Array.isArray(v) && v.length === 0) || (typeof v === 'object' && !Array.isArray(v) && !(v as { line1?: string }).line1);

  const validate = useCallback((): Record<string, string> => {
    const e: Record<string, string> = {};
    if (buyer.name.trim().length < 2) e['buyer.name'] = 'Enter your full name.';
    if (!EMAIL.test(buyer.email.trim())) e['buyer.email'] = 'Enter an email address, like name@example.com.';
    const phone = buyer.phone.trim();
    if (phone && !normalizePhone(phone)) e['buyer.phone'] = fieldWords('buyer.phone');
    if (consent.sms && !phone) e['buyer.phone'] = 'Add your mobile number to get texts.';
    for (const q of questionList) {
      const v = answers[q.key];
      if (q.required && emptyAnswer(v) && q.kind !== 'checkbox') e[`q.${q.key}`] = 'Please answer this.';
      if (q.required && q.kind === 'checkbox' && v !== true) e[`q.${q.key}`] = 'Please tick this to continue.';
      if (q.kind === 'date' && typeof v === 'string' && v && !realDate(v)) e[`q.${q.key}`] = 'Enter the date as month, day and year.';
      if (q.kind === 'phone' && typeof v === 'string' && v && !normalizePhone(v)) e[`q.${q.key}`] = fieldWords('buyer.phone');
      if (q.kind === 'address' && v && !emptyAnswer(v) && !(v as unknown as { city?: string }).city?.trim()) e[`q.${q.key}`] = 'Enter the whole address, with the city.';
    }
    for (const s of attendeeSlots) {
      const a = attendees[s.key];
      if (s.type.holder_details !== 'none' && (a?.name ?? '').trim().length < 2) e[`a.${s.key}.name`] = 'Enter this ticket holder’s name.';
      if (s.type.holder_details === 'name_and_email' && !EMAIL.test((a?.email ?? '').trim())) e[`a.${s.key}.email`] = 'Enter this ticket holder’s email.';
      for (const q of s.type.questions.filter((x) => x.scope === 'ticket')) {
        const v = a?.answers?.[q.key];
        if (q.required && (q.kind === 'checkbox' ? v !== true : emptyAnswer(v))) e[`a.${s.key}.q.${q.key}`] = 'Please answer this.';
        else if (q.kind === 'phone' && typeof v === 'string' && v && !normalizePhone(v)) e[`a.${s.key}.q.${q.key}`] = fieldWords('buyer.phone');
      }
    }
    return e;
  }, [buyer, consent.sms, questionList, answers, attendeeSlots, attendees]);

  /**
   * Tells the server the email as soon as it is typed, and what the Email box says, one call at a time, so a yes and a no can never cross. A box that reads
   * unticked must end with no yes standing: the "no" goes for the address last saved on this hold, whatever the field holds now, and a failed one is sent again.
   * None of this ever stops a buyer.
   */
  const saveEmail = useCallback(async () => {
    if (!hold) return;
    const field = buyer.email.trim();
    const words = store?.event.consent_texts.email ?? null;
    const last = savedEmail.current?.hold === hold.id ? savedEmail.current : null;
    const email = EMAIL.test(field) ? field : last?.yes && !consent.email ? last.email : null;
    if (!email) return;
    const said = `${hold.id}|${email}|${consent.email}`;
    if (said === lastEmail.current) return;
    if (emailBusy.current) {
      emailAgain.current = true; // the one in flight looks again when it lands
      return;
    }
    emailBusy.current = true;
    lastEmail.current = said;
    if (emailRetry.current.timer) clearTimeout(emailRetry.current.timer);
    const mine = { hold: hold.id, email, yes: !!words && (consent.email || (last?.email === email && last.yes)) };
    savedEmail.current = mine;
    try {
      await api.setHoldEmail(hold.id, email, receipt.current, words ? { granted: consent.email, text_version: words.version } : undefined);
      if (!consent.email) mine.yes = false;
      emailRetry.current.tries = 0;
    } catch {
      lastEmail.current = '';
      if (mine.yes && !consent.email && emailRetry.current.tries < 5) {
        emailRetry.current.timer = setTimeout(() => void saveLatest.current(), 1000 * 2 ** emailRetry.current.tries);
        emailRetry.current.tries++;
      }
    } finally {
      emailBusy.current = false;
    }
    if (emailAgain.current) {
      emailAgain.current = false;
      void saveLatest.current();
    }
  }, [api, hold, buyer.email, consent.email, store]);
  saveLatest.current = saveEmail;
  // The Email box says yes or no as it is pressed, and again on a new hold: a buyer who ticks it after typing the address never leaves the field again.
  useEffect(() => {
    if (savedEmail.current) void saveEmail();
    // only the box and the hold: a half-typed address waits for the field's blur
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [consent.email, hold?.id]);
  useEffect(() => () => void (emailRetry.current.timer && clearTimeout(emailRetry.current.timer)), []);

  /** The buyer's half of the order, as the API takes it. */
  /** A consent platform that has failed must never cost a sale: no word, and the hold's stands. */
  const bannerWord = (ask: CheckoutOptions['adConsent']): { ad_consent: 'granted' | 'denied' | 'unknown' } | null => {
    try {
      return ask ? { ad_consent: ask() } : null;
    } catch {
      return null;
    }
  };

  const orderFields = useCallback((): Omit<OrderRequest, 'payment' | 'expected_total'> => {
    const consentOf = (c: { version: string } | null, granted: boolean) => (c ? { granted, text_version: c.version } : undefined);
    const marketing = { email: consentOf(store?.event.consent_texts.email ?? null, consent.email), sms: consentOf(store?.event.consent_texts.sms ?? null, consent.sms) };
    const attendeeList = attendeeSlots.map((s) => {
      const a = attendees[s.key];
      const asked = s.type.questions.filter((q) => q.scope === 'ticket');
      const cleaned: Answers = {};
      for (const q of asked) if (a && !emptyAnswer(a.answers[q.key])) cleaned[q.key] = cleanAnswer(q, a.answers[q.key]!);
      return { ticket_type: s.type.ticket_type, ...(a?.name.trim() ? { name: a.name.trim() } : {}), ...(a?.email.trim() ? { email: a.email.trim() } : {}), ...(Object.keys(cleaned).length ? { answers: cleaned } : {}) };
    });
    const cleanAnswers: Answers = {};
    for (const q of questionList) if (!emptyAnswer(answers[q.key])) cleanAnswers[q.key] = cleanAnswer(q, answers[q.key]!);
    const phone = normalizePhone(buyer.phone);
    return {
      hold: hold!.id,
      buyer: { name: buyer.name.trim(), email: buyer.email.trim(), ...(phone ? { phone } : {}), ...(marketing.email || marketing.sms ? { marketing: { ...(marketing.email ? { email: marketing.email } : {}), ...(marketing.sms ? { sms: marketing.sms } : {}) } } : {}) },
      ...(Object.keys(cleanAnswers).length ? { answers: cleanAnswers } : {}),
      ...(attendeeList.length ? { attendees: attendeeList } : {}),
      // What the banner says now: a "no" given since the hold still counts. The API only lets it narrow.
      ...(bannerWord(options.adConsent) ?? {}),
    };
  }, [store, consent, attendeeSlots, attendees, questionList, answers, hold, buyer, options]);

  /** The field a refusal is about, as this page names it, or null if no field on the page is it. */
  const fieldOf = useCallback(
    (param: string | null, code: string): string | null => {
      if (code === 'consent_requires_phone') return 'buyer.phone';
      if (!param) return null;
      if (param === 'buyer.name' || param === 'buyer.email' || param === 'buyer.phone') return param;
      const answer = /^answers\.(.+)$/.exec(param);
      if (answer) return questionList.some((q) => q.key === answer[1]) ? `q.${answer[1]}` : null;
      const person = /^attendees(?:\[(\d+)\])?(?:\.(.+))?$/.exec(param);
      if (!person || !attendeeSlots.length) return null;
      const slot = attendeeSlots[Number(person[1] ?? 0)] ?? attendeeSlots[0]!;
      const rest = person[2] ?? 'name';
      const q = /^answers\.(.+)$/.exec(rest);
      return `a.${slot.key}.${q ? `q.${q[1]}` : rest === 'email' ? 'email' : 'name'}`;
    },
    [questionList, attendeeSlots],
  );

  /** A refusal that names a field goes to that field, on the Details step, in plain words. */
  const toField = useCallback(
    (e: CheckoutApiError): boolean => {
      const field = fieldOf(e.param, e.code);
      if (!field) return false;
      setErrors({ [field]: fieldWords(field) });
      setStepRaw('details');
      look();
      return true;
    },
    [fieldOf, look],
  );

  const toPay = useCallback(async () => {
    const e = validate();
    setErrors(e);
    if (Object.keys(e).length) {
      look();
      return false;
    }
    if (hold) {
      setChecking(true);
      try {
        await api.checkOrder(orderFields(), receipt.current);
      } catch (x) {
        const err = x instanceof CheckoutApiError ? x : new CheckoutApiError(0, {});
        if (err.code === 'hold_expired' || err.code === 'hold_released') {
          setExpired(true);
          setReleased(err.code === 'hold_released');
          return false;
        }
        if (err.status >= 400 && err.status < 500) {
          if (!toField(err)) {
            setNotice({ tone: 'error', text: say(err).text });
            look();
          }
          return false;
        }
        // Our side is busy: nothing is lost by going on, because the server checks again before it takes any money.
      } finally {
        setChecking(false);
      }
    }
    await saveEmail();
    setNotice(null);
    setPayError(null);
    setStepRaw('pay');
    if (hold) pixelRef.current.addPaymentInfo(hold);
    return true;
  }, [validate, saveEmail, hold, api, orderFields, toField, look]);

  canShow.current = (to) => {
    if ((to === 'details' || to === 'pay') && !hold) return 'tickets';
    if (to === 'pay' && Object.keys(validate()).length) return 'details';
    return to === 'done' ? stepNow.current : to;
  };

  /* ---- paying ---- */
  const orderRequest = useCallback((payment: PaymentPayload): OrderRequest => ({ ...orderFields(), payment, expected_total: hold!.price.total.amount }), [orderFields, hold]);

  const remember = useCallback((h: Hold, attempted: boolean) => saveCart({ event: h.event, hold: h.id, items: CART_ITEMS(h), code: h.code, receipt: receipt.current, attempted }), []);

  /** The answer says plainly that nothing stays taken, so the next press is a new attempt. */
  const settled = useCallback(() => {
    lastOrder.current = null;
    setUnconfirmed(false);
    if (hold) remember(hold, false);
  }, [hold, remember]);

  /**
   * A charge attempt began and we do not know how it ended. Reads the hold: an order means show it. A dead hold means no order. A
   * live one means not yet, and only a press of "Check again" sends the very same request again, which is the same payment and the same order.
   */
  const recheck = useCallback(
    async (resend: boolean): Promise<void> => {
      if (!hold) return;
      setChecking(true);
      try {
        const h = await api.readHold(hold.id, receipt.current);
        if (h.status === 'consumed' && h.order) return finish(await api.readOrder(h.order, h.id, receipt.current));
        if (h.status === 'consumed') {
          setUnconfirmed(false);
          setRefusal({ text: BOUGHT_ELSEWHERE, action: 'none' });
          return;
        }
        if (h.status !== 'active') {
          // The hold says it plainly: no order, and now the buyer can start again.
          setUnconfirmed(false);
          lastOrder.current = null;
          setExpired(true);
          setReleased(h.status === 'released');
          setNotice({ tone: 'warn', text: NO_ORDER });
          look();
          return;
        }
        if (resend && lastOrder.current) {
          try {
            return finish(await api.createOrder(lastOrder.current, receipt.current));
          } catch (e) {
            const err = e instanceof CheckoutApiError ? e : new CheckoutApiError(0, {});
            if (err.status !== 0 && err.status < 500) return void settleRef.current(err);
          }
        }
        setUnconfirmed(true);
      } catch {
        setUnconfirmed(true);
      } finally {
        setLastChecked(Date.now());
        setChecking(false);
      }
    },
    [hold, api, finish, look],
  );

  /** A clear answer from the server, after a press of Pay. */
  const settleRef = useRef<(e: CheckoutApiError) => void>(() => undefined);
  settleRef.current = (e: CheckoutApiError) => {
    if (e.code === 'price_changed' && e.extra.hold) {
      const nh = e.extra.hold as Hold;
      settled();
      setHold(nh);
      setPayError({ tone: 'warn', text: `The total is now ${formatMoney(nh.price.total)}. You have not been charged. Check it and pay again.` });
      look();
    } else if (e.code === 'hold_expired' || e.code === 'hold_released') {
      settled();
      setExpired(true);
      setReleased(e.code === 'hold_released');
    } else if (e.code === 'refund_failed') {
      // Money was taken and could not go back. Nothing more can be done here, and a Pay button beside "you were charged" would be cruel.
      settled();
      setRefusal({ text: say(e, 'pay').text, action: 'none' });
      look();
    } else if (e.code === 'payment_taken_order_cancelled' || e.code === 'order_cancelled') {
      // The order ended and the money is not ours to speak for: say what is known, and offer nothing that could charge them again.
      settled();
      setRefusal({ title: 'This order was cancelled', text: e.code === 'order_cancelled' ? 'If your card shows a charge, contact the organizer.' : 'Your payment went through. The organizer will refund you.', action: 'none' });
      look();
    } else if (e.code === 'hold_consumed' || ((e.code === 'payment_voided' || e.code === 'payment_refunded') && e.extra.cause === 'hold_consumed')) {
      // Another tab got there first: its order is this buyer's. Show it.
      settled();
      void recheck(false);
    } else if (e.code === 'payment_voided' || e.code === 'payment_refunded') {
      settled();
      if (e.param && toField(e)) return setPayError({ tone: 'warn', text: 'Your card was not charged. Fix this and pay again.' });
      const cause = String(e.extra.cause ?? '');
      const refunded = e.code === 'payment_refunded';
      const why = say({ code: cause, status: 409, decline_code: null, message: '' });
      const money = refunded ? 'Your payment was refunded in full.' : 'You have not been charged.';
      const known = cause && say({ code: cause, status: 409, decline_code: null, message: '' }).text !== say({ code: '', status: 409, decline_code: null, message: '' }).text;
      setRefusal({ text: `${known && cause !== 'payment_lost' ? `${why.text} ` : ''}${money}`, action: why.next === 'none' ? 'none' : refunded || cause.startsWith('hold_') || why.next === 'again' || why.next === 'pick' ? 'again' : 'pay' });
      look();
    } else if (e.status >= 400 && e.status < 500 && e.code !== 'payment_declined' && e.code !== 'payment_failed' && e.code !== 'rate_limited' && toField(e)) {
      settled(); // refused before any money moved
    } else {
      settled();
      setPayError({ tone: 'error', text: say(e, 'pay').text, next: say(e, 'pay').next });
      look();
    }
  };

  const pay = useCallback(
    async (payment: PaymentPayload) => {
      if (!hold || payingRef.current) return;
      payingRef.current = true;
      setPaying(true);
      setPayError(null);
      const request = orderRequest(payment);
      lastOrder.current = request;
      remember(hold, true);
      try {
        finish(await api.createOrder(request, receipt.current));
      } catch (e) {
        const err = e instanceof CheckoutApiError ? e : new CheckoutApiError(0, {});
        // Only an answer we can read says what happened. Anything else may have charged: look, and say so.
        if (err.status === 0 || err.code === 'payment_unconfirmed' || (err.status >= 500 && err.code !== 'not_ready' && err.code !== 'provider_unavailable' && err.code !== 'refund_failed')) {
          await recheck(false);
          look();
        }
        else settleRef.current(err);
      } finally {
        payingRef.current = false;
        setPaying(false);
      }
    },
    [hold, api, orderRequest, finish, remember, recheck],
  );

  /* ---- the clock ---- */
  const onExpire = useCallback(() => {
    setExpired(true);
    setReleased(false);
  }, []);

  /** Holds the same tickets again after the time ran out. Says so when the price is not the one the buyer saw. */
  const holdAgain = useCallback(async () => {
    if (!hold || holding) return;
    setHolding(true);
    const before = hold.price.total;
    try {
      const sameAttempt = newKey();
      holdKey.current = { sig: sigNow, key: sameAttempt };
      const h = await api.createHold(holdRequest(), sameAttempt);
      setHold(h);
      setExpired(false);
      setReleased(false);
      setRefusal(null);
      setPayError(null);
      lastEmail.current = '';
      receipt.current = h.receipt;
      saveCart({ event: h.event, hold: h.id, items: CART_ITEMS(h), code: h.code, receipt: h.receipt });
      if (h.price.total.amount !== before.amount) setNotice({ tone: 'warn', text: `The price is now ${formatMoney(h.price.total)}. It was ${formatMoney(before)} when you started.` });
      else setNotice({ tone: 'info', text: 'Your tickets are held again.' });
      pixelRef.current.initiateCheckout(h);
    } catch (e) {
      clearCart();
      setHold(null);
      setExpired(false);
      setRefusal(null);
      setStepRaw('tickets');
      setNotice(await explain(e, 'hold'));
      look();
    } finally {
      setHolding(false);
    }
  }, [hold, holding, sigNow, api, holdRequest, explain, look]);

  const extend = useCallback(async () => {
    if (!hold) return;
    try {
      setHold(await api.extendHold(hold.id, receipt.current));
      setNotice({ tone: 'info', text: 'We added more time.' });
    } catch (e) {
      setNotice(await explain(e, 'pay'));
    }
  }, [hold, api, explain]);

  const backToTickets = useCallback(() => {
    setStepRaw('tickets');
    setPayError(null);
  }, []);

  /* ---- after paying: the payment may still be finishing (a pending order), and the tickets are made a moment later ---- */
  useEffect(() => {
    if (!order || (order.status !== 'pending' && order.tickets_status !== 'pending') || !order.hold) return;
    let live = true;
    let tries = 0;
    let timer: ReturnType<typeof setTimeout> | undefined;
    const fast = options.pollMs ?? 1500;
    const look = async () => {
      tries++;
      try {
        const o = await api.readOrder(order.id, order.hold!, receipt.current);
        if (!live) return;
        const settled = o.status !== 'pending' && o.tickets_status !== 'pending';
        if (settled || o.status !== order.status) {
          setOrder(o);
          // The sale counts once its money is in, not before: the pixel and onComplete wait for it.
          if (o.status === 'paid' && owed.current) {
            owed.current = false;
            const saved = readSaved();
            if (saved) saveCart({ ...saved, owed: false });
            pixelRef.current.purchase(o);
            optionsRef.current.onComplete?.(o);
          }
          if (o.status === 'cancelled') owed.current = false;
        }
        if (settled) return;
      } catch {
        /* try again */
      }
      // A moment apart while it is likely, then every 20 of those for as long as the page might still be open: a capture can land an hour later, and this page must not sit on "Almost done".
      if (tries < 260 && live) timer = setTimeout(() => void look(), tries < 20 ? fast : fast * 20);
    };
    timer = setTimeout(() => void look(), fast);
    return () => {
      live = false;
      if (timer) clearTimeout(timer);
    };
  }, [order, api, options.pollMs]);

  return {
    api,
    store,
    loadError,
    reload: () => refresh(appliedCode),
    serverNow,
    step,
    setStep,
    deep,
    qty,
    addOns,
    chosen,
    ticketCount,
    hasChoice,
    setTicket,
    setAddOn,
    codeInput,
    setCodeInput,
    appliedCode,
    codeBusy,
    codeNote,
    applyCode,
    removeCode,
    hold,
    holding,
    toDetails,
    buyer,
    setBuyer,
    consent,
    setConsent,
    answers,
    setAnswers,
    attendees,
    attendeeSlots,
    setAttendee,
    questionList,
    errors,
    setErrors,
    errorSummary: (() => {
      const all = Object.values(errors);
      return all.length ? `${all.length === 1 ? '1 thing' : `${all.length} things`} to fix: ${all[0]}` : null;
    })(),
    attention,
    checking,
    unconfirmed,
    recheck,
    lastChecked,
    buyMore,
    refusal,
    tryAfterRefusal: () => setRefusal(null),
    saveEmail,
    toPay,
    notice,
    setNotice,
    expired,
    released,
    onExpire,
    holdAgain,
    extend,
    paying,
    payError,
    pay,
    order,
    backToTickets,
    pixel,
  };
}

export type CheckoutState = ReturnType<typeof useCheckout>;
````

### src/rcms-tickets/client/version.ts

````ts
/* The kit's version: the same number as server/version.ts, so each half stands alone. Leave it: it says what code you started from. */
export const KIT_VERSION = '0.3.13';
````

### src/rcms-tickets/server/api.ts

````ts
/*
  A small client for the RCMS Tickets API: key, retries that reuse the idempotency key, and errors that keep the API's own
  shape. It runs on your server only. The secret key is in a closure, so it never shows in a log or an error.
*/

import { serverFetch } from './serverFetch';
import { KIT_VERSION } from './version';

export const DEFAULT_TEST_BASE_URL = 'https://rcms-tickets-test.web.app';

export interface ApiErrorBody {
  type: string;
  code: string;
  message: string;
  param: string | null;
  decline_code?: string | null;
  request_id?: string;
}

export class ApiFailure extends Error {
  readonly status: number;
  readonly error: ApiErrorBody;
  /** The API's Retry-After, passed on to the page. */
  readonly retryAfter: string | null;
  constructor(status: number, error: Partial<ApiErrorBody>, retryAfter: string | null = null) {
    super(error.message ?? `RCMS Tickets answered ${status}`);
    this.name = 'ApiFailure';
    this.status = status;
    this.retryAfter = retryAfter;
    this.error = { type: error.type ?? 'api_error', code: error.code ?? 'unknown', message: error.message ?? 'Something went wrong.', param: error.param ?? null, decline_code: error.decline_code ?? null, request_id: error.request_id };
  }
  is(...codes: string[]): boolean {
    return codes.includes(this.error.code);
  }
}

/** The longest Retry-After the kit's server waits out itself, in seconds. */
const RETRY_AFTER_KEPT_S = 5;

export interface ApiOptions {
  apiKey: string;
  baseUrl?: string;
  fetch?: typeof fetch;
  maxRetries?: number;
  sleep?: (ms: number) => Promise<void>;
  /** Each attempt gives up after this long, in ms. Default 15000. */
  timeoutMs?: number;
}

export interface Api {
  readonly mode: 'test' | 'live';
  get<T>(path: string, query?: Record<string, string | undefined>, headers?: Record<string, string>): Promise<T>;
  post<T>(path: string, body: unknown, o?: { idempotencyKey?: string }): Promise<T>;
  patch<T>(path: string, body: unknown, o?: { idempotencyKey?: string }): Promise<T>;
  del<T>(path: string, o?: { idempotencyKey?: string }): Promise<T>;
  /** Every item of a list, following its pages (at most `pages` of 100). */
  all<T extends { id?: string }>(path: string, query?: Record<string, string | undefined>, pages?: number): Promise<T[]>;
}

const KEY = /^rt_(test|live)_[A-Za-z0-9_]{8,}$/;
const wait = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));

export function createApi(o: ApiOptions): Api {
  const m = KEY.exec(o.apiKey ?? '');
  // Never echo what was passed: a wrong value may still be somebody's secret.
  if (!m) throw new TypeError('apiKey is not an RCMS Tickets secret key: it starts with rt_test_ or rt_live_. Is the environment variable set?');
  const mode = m[1] as 'test' | 'live';
  const base = (o.baseUrl ?? (mode === 'test' ? DEFAULT_TEST_BASE_URL : '')).replace(/\/+$/, '');
  if (!base) throw new TypeError('baseUrl is required for a live key: production has no default host yet');
  const local = /^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:|\/|$)/.test(base);
  if (!base.startsWith('https://') && !local) throw new TypeError('baseUrl must be https: a key is never sent in plain text (http is allowed for localhost only)');
  const f = o.fetch ?? serverFetch;
  const retries = o.maxRetries ?? 2;
  const sleep = o.sleep ?? wait;
  const key = o.apiKey;
  const timeoutMs = o.timeoutMs ?? 15_000;

  /** One attempt, whole body included, or a timeout: a call that never answers must not hold a serverless function until it dies. */
  const attemptOnce = async (url: string, init: RequestInit): Promise<{ res: Response; text: string }> => {
    const abort = new AbortController();
    let timer: ReturnType<typeof setTimeout> | undefined;
    try {
      return await Promise.race([
        new Promise<never>((_, reject) => {
          timer = setTimeout(() => {
            abort.abort();
            reject(new Error('timed out'));
          }, timeoutMs);
        }),
        (async () => {
          const res = await f(url, { ...init, signal: abort.signal });
          return { res, text: await res.text() };
        })(),
      ]);
    } finally {
      if (timer) clearTimeout(timer);
    }
  };

  async function send<T>(method: string, path: string, body?: unknown, idem?: string, query?: Record<string, string | undefined>, extra?: Record<string, string>): Promise<T> {
    const qs = new URLSearchParams();
    for (const [k, v] of Object.entries(query ?? {})) if (v !== undefined && v !== '') qs.set(k, v);
    const url = `${base}${path}${qs.size ? `?${qs}` : ''}`;
    const idempotencyKey = method === 'GET' ? undefined : (idem ?? globalThis.crypto.randomUUID());
    let last: unknown;
    let told: number | null = null;
    for (let attempt = 0; attempt <= retries; attempt++) {
      if (attempt > 0) await sleep(told ?? 150 * 2 ** (attempt - 1));
      told = null;
      let res: Response;
      let text: string;
      try {
        ({ res, text } = await attemptOnce(url, { method, headers: { ...extra, authorization: `Bearer ${key}`, 'rcms-tickets-kit': KIT_VERSION, ...(body === undefined ? {} : { 'content-type': 'application/json' }), ...(idempotencyKey ? { 'idempotency-key': idempotencyKey } : {}) }, body: body === undefined ? undefined : JSON.stringify(body) }));
      } catch (e) {
        last = new ApiFailure(0, { type: 'api_error', code: 'connection_error', message: 'Could not reach RCMS Tickets.' });
        void e;
        continue;
      }
      let json: unknown = null;
      try {
        json = text ? JSON.parse(text) : null;
      } catch {
        /* not json */
      }
      if (res.ok) return json as T;
      const failure = new ApiFailure(res.status, ((json as { error?: Partial<ApiErrorBody> } | null)?.error) ?? {}, res.headers.get('retry-after'));
      // A 429 that names a param is about what was asked (tickets on hold, a network's share), not about how fast: asking again in a moment says the same. The page tells the buyer.
      // One that doesn't says when: a short wait the server keeps (the API's in-flight limit says 1 s), a long one goes back to the page, because nobody should sit on a request for a minute.
      const after = res.status === 429 ? Number(failure.retryAfter) : NaN;
      if (res.status === 429 && Number.isFinite(after) && after > RETRY_AFTER_KEPT_S) throw failure;
      if ((res.status >= 500 || (res.status === 429 && !failure.error.param) || failure.is('idempotency_key_in_use', 'lock_timeout')) && attempt < retries) {
        if (res.status === 429 && Number.isFinite(after) && after > 0) told = after * 1000;
        last = failure;
        continue;
      }
      throw failure;
    }
    throw last;
  }

  return {
    mode,
    get: (path, query, headers) => send('GET', path, undefined, undefined, query, headers),
    post: (path, body, x) => send('POST', path, body, x?.idempotencyKey),
    patch: (path, body, x) => send('PATCH', path, body, x?.idempotencyKey),
    del: (path, x) => send('DELETE', path, undefined, x?.idempotencyKey),
    async all<T extends { id?: string }>(path: string, query: Record<string, string | undefined> = {}, pages = 5): Promise<T[]> {
      const out: T[] = [];
      let after: string | undefined;
      for (let i = 0; i < pages; i++) {
        const page = await send<{ data: T[]; has_more: boolean }>('GET', path, undefined, undefined, { ...query, limit: '100', starting_after: after });
        out.push(...page.data);
        const lastId = page.data[page.data.length - 1]?.id;
        if (!page.has_more || !lastId) break;
        after = lastId;
      }
      return out;
    },
  };
}
````

### src/rcms-tickets/server/attribution.ts

````ts
/*
  What the page may send as attribution, checked and trimmed to exactly what the API accepts (its schema is strict: one stray
  field would refuse the whole hold, and a lost sale is worse than a lost tag). The buyer's address and browser come from the
  request itself, never from the page.
*/

const clip = (v: unknown, max: number): string | undefined => (typeof v === 'string' && v.trim() ? v.trim().slice(0, max) : undefined);

const TOUCH: Array<[string, number]> = [
  ['utm_source', 200],
  ['utm_medium', 200],
  ['utm_campaign', 200],
  ['utm_term', 200],
  ['utm_content', 200],
  ['referrer', 2048],
  ['landing_page', 2048],
  ['fbclid', 500],
  ['gclid', 500],
  ['ttclid', 500],
];

/** A place is a web address: `javascript:` and `data:` are never kept, whatever a page sends. */
const webUrl = (s: string): boolean => {
  try {
    return /^https?:$/.test(new URL(s).protocol);
  } catch {
    return false;
  }
};

function touch(v: unknown, withAt = true): Record<string, string> {
  const o = (v && typeof v === 'object' ? v : {}) as Record<string, unknown>;
  const out: Record<string, string> = {};
  for (const [k, max] of TOUCH) {
    const s = clip(o[k], max);
    if (s && ((k !== 'referrer' && k !== 'landing_page') || webUrl(s))) out[k] = s;
  }
  const at = clip(o.at, 40);
  if (withAt && at && !Number.isNaN(Date.parse(at))) out.at = new Date(at).toISOString();
  return out;
}

export function sanitizeAttribution(v: unknown, server: { client_ip?: string; user_agent?: string }): Record<string, unknown> {
  const o = (v && typeof v === 'object' ? v : {}) as Record<string, unknown>;
  // The flat fields are the last touch and take no `at` (the API's strict schema refuses it there); only first_touch carries one.
  const out: Record<string, unknown> = { ...touch(o, false) };
  if (o.first_touch && typeof o.first_touch === 'object') {
    const first = touch(o.first_touch);
    if (Object.keys(first).length) out.first_touch = first;
  }
  const fbp = clip(o.fbp, 500);
  const fbc = clip(o.fbc, 500);
  if (fbp) out.fbp = fbp;
  if (fbc) out.fbc = fbc;
  if (typeof o.ga_client_id === 'string' && /^[0-9]{1,20}\.[0-9]{1,20}$/.test(o.ga_client_id)) out.ga_client_id = o.ga_client_id;
  if (typeof o.ga_session_id === 'string' && /^[0-9]{1,20}$/.test(o.ga_session_id)) out.ga_session_id = o.ga_session_id;
  if (o.ad_consent === 'granted' || o.ad_consent === 'denied' || o.ad_consent === 'unknown') out.ad_consent = o.ad_consent;
  // Exactly the API's id, because a stray one would refuse the whole hold. The API then checks it is this org's link.
  if (typeof o.tracking_link === 'string' && /^lnk_[A-Za-z0-9]+(?:_[A-Za-z0-9]+)*$/.test(o.tracking_link) && o.tracking_link.length >= 7 && o.tracking_link.length <= 44) out.tracking_link = o.tracking_link;
  const page = clip(o.page_url, 2048);
  if (page && webUrl(page)) out.page_url = page;
  // The address always goes: the API counts its per-network caps on open holds from it, and keeps none of it when the buyer said no
  // (a page's own word can't turn the caps off). The browser string stays out for them: nothing but ad conversions wants it.
  if (server.client_ip) out.client_ip = server.client_ip;
  if (server.user_agent && o.ad_consent !== 'denied') out.user_agent = server.user_agent;
  return out;
}
````

### src/rcms-tickets/server/core.ts

````ts
import { ApiFailure, createApi, type Api } from './api';
import { orderKey } from './orderKey';
import { testPayment } from './payment';
import { sanitizeAttribution } from './attribution';
import { ipNetwork } from './hostingIp';
import { normalizePhone } from './phone';
import { PaymentFailure, PaymentProblem, PaymentRefunded, RefundFailed, type ApiHold, type PaymentOutcome, type ServerPayment } from './types';
import { resumeLink as makeResumeLink, verifyWebhook, WebhookError, type WebhookEvent } from './webhook';

/*
  The server half of the kit: a few handlers that sit between your page and RCMS Tickets. The page never holds a key.
  Every handler takes a standard Request and answers a standard Response, so the same code runs in a Next.js route handler,
  Express, Firebase Functions, Cloudflare Workers or anything else that speaks fetch (see next.ts and express.ts).

    GET    /storefront            what the page sells: the event, its tickets, add-ons, questions and consent words
    POST   /holds                 hold the chosen items and answer the price (the attribution is added here)
    GET    /holds/:id             a hold, as the page may see it (to carry on after a reload)
    GET    /holds/:id/resume      what an abandoned-checkout email's link needs: the items and code
    PATCH  /holds/:id             the buyer's email, so an abandoned checkout can be followed up
    POST   /holds/:id/extend      more time, once
    DELETE /holds/:id             give the items back
    POST   /orders/check          everything an order can be refused for, before the page asks for a card
    POST   /orders                pay and make the order (price and fields checked first; a payment never outlives a failed order)
    GET    /orders/:id?hold=…     the order and its tickets (they are made a moment after the payment; needs the hold's receipt)
    POST   /webhook               RCMS Tickets' deliveries, verified (hold.expired starts your abandoned-checkout email)
    GET|POST /sweep               finishes payments a crash left half done (needs `sweepSecret`; run it on a schedule)
*/

export interface CheckoutConfig {
  /** Your secret key, rt_test_… or rt_live_…. From the environment, never from the code. */
  apiKey: string;
  /** The event (or events) this site sells. A page may only ask for these. */
  event: string | string[];
  /** Left out, a test key goes to the test host. A live key must say. */
  baseUrl?: string;
  fetch?: typeof fetch;
  sleep?: (ms: number) => Promise<void>;
  /** How the money is taken. Default: the test provider (test keys only). */
  payment?: ServerPayment;
  /** `whsec_…`, to verify webhook deliveries. */
  webhookSecret?: string | readonly string[];
  /** The page that holds your checkout, for the abandoned-checkout link. */
  siteUrl?: string;
  /** Called with a verified delivery. Make it safe to run twice: a delivery can arrive again (the entry's id is stable). */
  onWebhook?: (entry: WebhookEvent) => Promise<void> | void;
  /**
   * Called for a hold that expired with the buyer's email on it: send the email. `link` reopens the same selection.
   * Dedupe on `entry.id` (a delivery is retried until you answer 200). `api` is this checkout's own client: "has this address bought?" needs no second one.
   */
  onHoldExpired?: (x: { hold: ApiHold & { email: string }; link: string | null; entry: WebhookEvent; api: ReturnType<typeof createApi> }) => Promise<void> | void;
  /**
   * The buyer ticked or unticked the event's Email box while this hold was open: called each time, with the version of the words they saw.
   * The API hears about it only with the order, so an abandoned-checkout rule that needs the box (KIT.md, "Abandoned checkout") keeps it here. It is a yes from whoever typed
   * the address, not proof they own it: `ip` is the caller's address when `clientIp` knows it, so you can cap how many addresses one caller names.
   * Failing here costs no sale: `onError` hears 'email_choice'. A failed "no" also answers 503, so the page sends it again; a yes that stays standing would be a mail nobody wants.
   */
  onEmailChoice?: (x: { hold: string; email: string; granted: boolean; textVersion: string | null; ip: string | null }) => Promise<void> | void;
  /** Called with anything unexpected (never with a body, a card or a key). */
  onError?: (error: unknown, where: string) => void;
  /**
   * Where the buyer's real address is, on your hosting. A live key must say (or bring its own `beforeRequest`): the address is what stops one visitor holding a whole sale for free.
   * Left out on a test key, the address is unknown: nothing is limited by address, and no address goes on the hold. KIT.md, "The buyer's address", says which to use.
   *   'vercel'       Vercel's x-real-ip
   *   'cloudflare'   cf-connecting-ip (only if your server can't be reached except through Cloudflare)
   *   'rightmost:N'  the Nth X-Forwarded-For entry from the right; N is the proxies you run (Cloud Run, Render, Fly: 1; ALB behind CloudFront: 2)
   *   'peer'         the socket's address: nothing stands in front of your server
   *   (req) => string  your own
   */
  clientIp?: 'vercel' | 'cloudflare' | 'peer' | `rightmost:${number}` | ((req: Request) => string | null | undefined);
  /** The same as clientIp: 'rightmost:1'. Prefer clientIp. Off by default, because anyone can send that header. */
  trustProxy?: boolean;
  now?: () => number;
  /** Each call to the RCMS Tickets API gives up after this long, in ms. Default 15000. */
  timeoutMs?: number;
  /** How long one read of the storefront (with no code) is shared, in ms: an on-sale's page loads don't each spend the key's budget. Default 2000 on a live key, 0 on a test key. */
  storefrontCacheMs?: number;
  /** A long random string, 32 characters at least. Turns on GET|POST /sweep, sent as `Authorization: Bearer <it>`, for your scheduler. */
  sweepSecret?: string;
  /**
   * Runs before every page call but POST /orders: a buyer who holds tickets can always pay. Answer a Response to stop it (a 429, say).
   * Left out, `defaultLimiter()` limits each address in this instance's memory, and only when `clientIp` says the address is really
   * known. On serverless, where each instance counts alone, pass your own over a shared store. `null` turns it off, and a live key then must set `clientIp`.
   */
  beforeRequest?: BeforeRequest | null;
  /**
   * Whether to send this abandoned-checkout email. A hold can name any address, so this is your guard against mailing strangers.
   * Left out: once per address per 24 hours, in this instance's memory. On serverless, pass your own over a shared store.
   */
  abandonedGate?: (hold: ApiHold & { email: string }, x: { api: ReturnType<typeof createApi> }) => boolean | Promise<boolean>;
  /** Send the abandoned-checkout email for test-mode holds too. Default false. */
  abandonedInTestMode?: boolean;
}

export interface RequestFacts {
  request: Request;
  /** "POST /holds", "GET /storefront", "POST /orders", ... */
  route: string;
  /** The buyer's address, when it is known and public. */
  ip: string | null;
}
export type BeforeRequest = (facts: RequestFacts) => Response | void | undefined | Promise<Response | void | undefined>;

export interface SweepResult {
  captured: number;
  voided: number;
  kept: number;
  failed: number;
  /**
   * Held payments the processor can never take (it cancelled them): the order was cancelled through the API, once, and counted here once. Each also reaches onError.
   * For an order a kit before 0.2.0 made (paid, tickets out) the API can't cancel anything: it is reported, once per server start, and counted then.
   */
  lost: number;
  /** Money the processor took for an order that had already ended, found by this sweep and told to the API, once. Each also reaches onError ('captured_after_end'): refund it at your processor. */
  money_after_end: number;
}

export interface Checkout {
  /** One standard Request in, one Response out. `ip` is the socket's address, when an adapter knows it. */
  handle(req: Request, facts?: { ip?: string | undefined }): Promise<Response>;
  api: Api;
  resumeLink(holdId: string, campaign?: string): string;
  /** Finishes what a crash left half done: captures a payment whose order exists, voids one whose hold died. Safe to run any time. */
  sweep(): Promise<SweepResult>;
}

const MAX_BODY = 64 * 1024;
const ID = /^[a-z]{2,4}_[A-Za-z0-9]{4,64}$/;
const EMAIL = /^[^\s@]{1,64}@[^\s@]{1,255}\.[^\s@]{2,}$/;
const IDEM = /^[A-Za-z0-9_-]{8,100}$/;

class HttpError extends Error {
  readonly status: number;
  readonly code: string;
  readonly type: string;
  readonly param: string | null;
  readonly extra: Record<string, unknown>;
  constructor(status: number, code: string, message: string, type = 'invalid_request_error', param: string | null = null, extra: Record<string, unknown> = {}) {
    super(message);
    this.status = status;
    this.code = code;
    this.type = type;
    this.param = param;
    this.extra = extra;
  }
}

const json = (status: number, body: unknown, headers: Record<string, string> = {}): Response => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json', 'cache-control': 'no-store', ...headers } });

const bad = (message: string, param: string | null = null) => new HttpError(400, 'parameter_invalid', message, 'invalid_request_error', param);

async function body(req: Request): Promise<Record<string, unknown>> {
  const text = await req.text();
  if (text.length > MAX_BODY) throw new HttpError(413, 'parameter_invalid', 'The request is too large.');
  try {
    const v = text ? JSON.parse(text) : {};
    if (!v || typeof v !== 'object' || Array.isArray(v)) throw new Error('not an object');
    return v as Record<string, unknown>;
  } catch {
    throw bad('The body must be JSON.');
  }
}

const str = (v: unknown, max: number): string | undefined => (typeof v === 'string' && v.trim() ? v.trim().slice(0, max) : undefined);

const IPV4 = /^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$/;
const IPV6 = /^[0-9a-fA-F:]{2,45}$/;
const PROXY_HEADERS = ['cf-connecting-ip', 'x-vercel-id', 'fly-client-ip', 'x-forwarded-for', 'x-real-ip', 'cloudfront-viewer-address', 'forwarded'];

const validIp = (v: string | null | undefined): string | undefined => {
  const raw = (v ?? '').trim().replace(/^::ffff:/, '');
  return IPV4.test(raw) || (raw.includes(':') && IPV6.test(raw)) ? raw : undefined;
};

/** The buyer's address by the site's own statement of where it is, or nothing. */
function readAddress(req: Request, how: NonNullable<CheckoutConfig['clientIp']>, peer: string | undefined): string | undefined {
  if (typeof how === 'function') {
    try {
      return validIp(how(req));
    } catch {
      return undefined;
    }
  }
  if (how === 'peer') return validIp(peer);
  if (how === 'cloudflare') return validIp(req.headers.get('cf-connecting-ip'));
  if (how === 'vercel') return validIp(req.headers.get('x-real-ip') ?? (req.headers.get('x-forwarded-for') ?? '').split(',')[0]);
  const n = Number(how.split(':')[1]);
  const list = (req.headers.get('x-forwarded-for') ?? '').split(',').map((x) => x.trim()).filter(Boolean);
  return Number.isInteger(n) && n >= 1 ? validIp(list[list.length - n]) : undefined;
}

/** An address that is never one buyer's: a proxy's hop, a gateway inside a private range. Limiting it would limit everyone. */
function isPublicIp(ip: string): boolean {
  if (ip.includes(':')) return !/^(::1?$|f[cd]|fe[89ab])/i.test(ip);
  const [a = 0, b = 0] = ip.split('.').map(Number);
  return !(a === 10 || a === 127 || a === 0 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 169 && b === 254) || (a === 100 && b >= 64 && b <= 127));
}

const rateLimited = (seconds: number): Response => json(429, { error: { type: 'rate_limit_error', code: 'rate_limited', message: 'Too many requests. Please wait and try again.', param: null } }, { 'retry-after': String(seconds) });

/** The tickets a hold's body asks for, as sent. A bundle is one here (the kit doesn't know its size): the API counts it in full. A body past the kit's limit, or an ask the handler refuses, counts nothing: it never reaches the API. */
async function ticketsAsked(request: Request): Promise<number> {
  try {
    if (Number(request.headers.get('content-length') ?? 0) > MAX_BODY) return 0;
    const text = await request.clone().text();
    if (text.length > MAX_BODY) return 0;
    const b = JSON.parse(text) as { items?: Array<{ quantity?: unknown; add_on?: unknown }> };
    return (b.items ?? []).reduce((n, i) => n + (Number.isInteger(i?.quantity) && (i.quantity as number) >= 1 && (i.quantity as number) <= 100 && !i.add_on ? (i.quantity as number) : 0), 0);
  } catch {
    return 0;
  }
}

/** An IPv6 address's /64 and /48, as the API counts them; IPv4 is itself. */
function subscriberOf(ip: string): { one: string; block: string | null } {
  const n = ipNetwork(ip);
  const six = n ? /^([0-9a-f]+:[0-9a-f]+:[0-9a-f]+):[0-9a-f]+::\/64$/.exec(n) : null;
  return six ? { one: n!, block: `${six[1]}::/48` } : { one: n ?? ip, block: null };
}

/**
 * The default throttle: a sliding minute per address and kind of call, in this instance's memory, and only for an address the site says it really knows. It slows one address down;
 * the API's cap (half of what is left of each pool, per network per event) is what bounds what an address can hold, and it holds on every instance.
 * An address is an IPv4 address or an IPv6 /64 (one subscriber, who can rotate inside it for free). Holds: 30 a minute and 120 tickets a minute. A real buyer makes a hold or two a minute, so 30 is one every two seconds without a
 * pause from one address, and 120 tickets is 30 families of 4 every minute: a carrier's NAT or a venue's Wi-Fi, many real buyers on one address, does not meet it. (A whole YRD-sized on-sale runs at about 5 holds a second, from thousands of addresses.)
 * An IPv6 /48 is what the API calls one network, and it is free too, so it has a count of its own: four times an address (BLOCK_SHARE), since a carrier's /48 is many subscribers: 120 holds and 480 tickets a minute, per instance.
 * Order checks 120, code tries 60, reads 600, per address. Over it, a 429 with Retry-After: "try again in N seconds", never a block. POST /orders is not here at all: a buyer who holds tickets can always pay.
 */
export function defaultLimiter(limits: { holdsPerMinute?: number; ticketsPerMinute?: number; ordersPerMinute?: number; codesPerMinute?: number; readsPerMinute?: number } = {}): BeforeRequest {
  const seen = new Map<string, number[]>();
  const WINDOW = 60_000;
  const BLOCK_SHARE = 4;
  /** What is in the minute under a key: [when, how many, when, how many, ...], and its first moment. */
  const inMinute = (key: string, at: number): { kept: number[]; sum: number; first: number } => {
    const was = seen.get(key) ?? [];
    const kept: number[] = [];
    let sum = 0;
    for (let i = 0; i + 1 < was.length; i += 2) {
      if (at - was[i]! < WINDOW) {
        kept.push(was[i]!, was[i + 1]!);
        sum += was[i + 1]!;
      }
    }
    return { kept, sum, first: kept[0] ?? at };
  };
  const wait = (first: number, at: number): number => Math.max(1, Math.ceil((WINDOW - (at - first)) / 1000));
  const put = (key: string, kept: number[], at: number, n: number): void => {
    kept.push(at, n);
    seen.delete(key);
    seen.set(key, kept);
    if (seen.size > 20_000) for (const k of [...seen.keys()].slice(0, 5_000)) seen.delete(k);
  };
  return async ({ route, ip, request }) => {
    if (!ip) return undefined;
    const { one, block } = subscriberOf(ip);
    const at = Date.now();
    if (route === 'POST /holds') {
      const maxHolds = limits.holdsPerMinute ?? 30;
      const maxTickets = limits.ticketsPerMinute ?? 120;
      const holds = [{ key: `hold|${one}`, max: maxHolds }, ...(block ? [{ key: `hold|${block}`, max: maxHolds * BLOCK_SHARE }] : [])].map((c) => ({ ...c, ...inMinute(c.key, at) }));
      // Over its holds already: the body isn't read at all.
      for (const c of holds) if (c.sum >= c.max) return rateLimited(wait(c.first, at));
      const asked = await ticketsAsked(request);
      const tickets = [{ key: `tickets|${one}`, max: limits.ticketsPerMinute ?? 120 }, ...(block ? [{ key: `tickets|${block}`, max: maxTickets * BLOCK_SHARE }] : [])].map((c) => ({ ...c, ...inMinute(c.key, at) }));
      for (const c of tickets) if (c.sum > 0 && c.sum + asked > c.max) return rateLimited(wait(c.first, at));
      for (const c of holds) put(c.key, c.kept, at, 1);
      for (const c of tickets) put(c.key, c.kept, at, asked);
      return undefined;
    }
    const coded = route === 'GET /storefront' && new URL(request.url).searchParams.has('code');
    const [kind, max] = route === 'POST /orders/check' ? (['order', limits.ordersPerMinute ?? 120] as const) : coded ? (['code', limits.codesPerMinute ?? 60] as const) : (['read', limits.readsPerMinute ?? 600] as const);
    const key = `${kind}|${one}`;
    const c = inMinute(key, at);
    if (c.sum >= max) return rateLimited(wait(c.first, at));
    put(key, c.kept, at, 1);
    return undefined;
  };
}

/** `order` only for whoever made the hold (see `receipt`): the order's id opens a buyer's name and tickets. */
export function holdView(h: ApiHold, serverTime: Date, o: { receipt?: string; showOrder?: boolean } = {}): Record<string, unknown> {
  return { id: h.id, mode: h.mode, event: h.event, status: h.status, items: h.items, code: h.code, price: h.price, expires_at: h.expires_at, extended: h.extended, order: o.showOrder ? h.order : null, server_time: serverTime.toISOString(), ...(o.receipt ? { receipt: o.receipt } : {}) };
}

interface ApiOrder {
  id: string;
  number: string;
  mode: 'test' | 'live';
  status: string;
  hold: string | null;
  tickets_status: string;
  url: string | null;
  tracking_event_id: string;
  buyer: { name: string | null; email: string | null };
  items: unknown[];
  price: { total: { amount: number; currency: string }; currency: string; pass_through?: { amount: number; currency: string } };
  tickets: Array<{ id: string; kind: string; name: string; short_code: string; status: string; url: string | null; holder?: { name?: string | null }; wallet?: { apple_url: string | null; google_url: string | null } }>;
  payments?: Array<{ provider?: string; reference?: string | null; status?: string }>;
  amount_refunded?: { amount: number };
  cancelled_at?: string | null;
  payment_end?: 'not_charged' | 'not_confirmed' | 'taken_after_end';
}

/** What POST /v1/orders/{id}/external_payment answers. */
interface ExternalPaymentResult {
  order: ApiOrder;
  outcome: 'paid' | 'cancelled' | 'capture' | 'void_me';
  void_why?: 'event_cancelled' | 'bought_again' | 'order_ended';
  changed: boolean;
  money_after_end: boolean;
}

export function orderView(o: ApiOrder): Record<string, unknown> {
  return {
    id: o.id,
    number: o.number,
    mode: o.mode,
    status: o.status,
    // What is known of the money on a cancelled order: it is what lets the page say "not charged" only when that was proved.
    ...(o.payment_end ? { payment_end: o.payment_end } : {}),
    hold: o.hold,
    tickets_status: o.tickets_status,
    url: o.url,
    tracking_event_id: o.tracking_event_id,
    buyer: { name: o.buyer.name, email: o.buyer.email },
    items: o.items,
    total: o.price.total,
    // Refund protection inside the total: not sales, so a pixel on the page can leave it out.
    ...(o.price.pass_through ? { pass_through: o.price.pass_through } : {}),
    currency: o.price.currency,
    tickets: (o.tickets ?? []).map((t) => ({ id: t.id, kind: t.kind, name: t.name, holder_name: t.holder?.name ?? null, short_code: t.short_code, status: t.status, url: t.url, apple_wallet_url: t.wallet?.apple_url ?? null, google_wallet_url: t.wallet?.google_url ?? null })),
  };
}

/** An order that did not answer for good: it may yet have been made. Never undo a payment on one of these. */
const OUTCOME_UNKNOWN = new Set(['idempotency_key_in_use', 'outcome_unknown', 'request_timeout']);

/** Longer than Square's longest hold (the recipe's list reads as far back), so money taken for a cancelled order is found while anyone can still act on it. */
const SWEEP_DAYS = 8;
/** 100 orders a page. Past this a sweep says so (`sweep_capped`), and goes on with what it has. Pending ones leave the list as they are finished, so the next sweep reaches the rest. */
const SWEEP_PAGES = 50;

export function createCheckout(config: CheckoutConfig): Checkout {
  const page = globalThis as { window?: unknown; document?: unknown };
  if (page.window !== undefined && page.document !== undefined) throw new TypeError('createCheckout runs on your server only: it holds your secret key, and this looks like a browser.');
  const api = createApi({ apiKey: config.apiKey, baseUrl: config.baseUrl, fetch: config.fetch, sleep: config.sleep, timeoutMs: config.timeoutMs });
  const events = (Array.isArray(config.event) ? config.event : [config.event]).filter(Boolean);
  if (!events.length) throw new TypeError('event is required: the id of the event this site sells (evt_…)');
  const payment = config.payment ?? testPayment();
  // Test money and real money never cross: a test key must not charge a card, and a live key must not issue tickets for no money.
  if (api.mode === 'test' && payment.environment === 'production') throw new TypeError(`A test key (rt_test_) cannot take payments through ${payment.name}'s production host: real cards would be charged for test orders. Use its sandbox.`);
  if (api.mode === 'live' && payment.environment === 'sandbox') throw new TypeError(`A live key (rt_live_) cannot take payments through ${payment.name}'s sandbox: real tickets would be issued for no money. Use its production host.`);
  if (api.mode === 'live' && payment.environment === 'test') throw new TypeError('A live key (rt_live_) cannot use the test provider: real tickets would be issued for no money. Set a real payment.');
  if (config.sweepSecret !== undefined && config.sweepSecret !== '' && config.sweepSecret.length < 32) throw new TypeError('sweepSecret must be 32 characters at least: anyone who guesses it can make your server call your processor.');
  if (api.mode === 'live' && payment.environment !== 'test' && !payment.open) throw new TypeError(`${payment.name} has no way to finish a payment a crash left half done: the buyer could be charged with no order and nobody told. Give externalPayment \`open\` (list, capture, void), or \`chargeFirstAcknowledged: true\` with a \`store\` (KIT.md, "Payment").`);
  if (api.mode === 'live' && payment.open) {
    // A webhook alone can miss: a secret with no endpoint registered looks the same from here. The sweep is the one that always finishes the job.
    if (!config.sweepSecret) throw new TypeError(`${payment.name} on a live key needs sweepSecret, and a scheduler calling /sweep: it finishes payments a crash left half done (KIT.md, "Going live").`);
    if (!config.onError) throw new TypeError(`${payment.name} on a live key needs onError: where 'capture_lost' or 'charged_no_order' means money needs a person, and someone has to hear it (KIT.md, "Going live").`);
  }
  // Not a refusal: a charge-first slot has no capture to lose. But without `state` the sweep can't see money already taken: a slot of your own should say.
  if (payment.authorizeFirst && payment.open && !payment.open.state) {
    try {
      config.onError?.(new Error(`${payment.name} has no open.state, so the sweep can't find money taken whose word to RCMS Tickets was lost, or taken for an order a person cancelled. Add it (KIT.md, "Another processor").`), 'no_state');
    } catch {
      /* a reporter may not break a start */
    }
  }
  const addressHow = config.clientIp ?? (config.trustProxy ? 'rightmost:1' : undefined);
  // The address is what stops one visitor holding a whole sale for free, with no card and no account (KIT.md, "The buyer's address"). A guess would be worse, so a live key has to say.
  if (api.mode === 'live' && !addressHow && typeof config.beforeRequest !== 'function') throw new TypeError('A live key (rt_live_) needs clientIp, or your own beforeRequest: without the buyer\'s address nothing stops one visitor holding every ticket for free, and the API counts every hold as one network. KIT.md, "The buyer\'s address", says what to set for your hosting.');
  if (api.mode === 'live' && !addressHow) {
    try {
      config.onError?.(new Error('This live key has its own beforeRequest and no clientIp, so holds name no buyer\'s address: the API counts them all as one network, at most half of what is left. Set clientIp, unless an owner has marked the key as selling from one address (KIT.md, "The buyer\'s address").'), 'no_client_ip');
    } catch {
      /* a reporter may not break a start */
    }
  }
  const clock = () => new Date(config.now ? config.now() : Date.now());
  const limiter: BeforeRequest | null = config.beforeRequest === undefined ? defaultLimiter() : config.beforeRequest;
  let toldUnknown = false;
  let toldNothing = false;
  /** The buyer's address if the site has said where it is. A guess here would limit a whole CDN edge as one buyer, so without that: none. */
  const addressOf = (req: Request, peer: string | undefined): string | undefined => {
    if (addressHow) return readAddress(req, addressHow, peer);
    const seen = PROXY_HEADERS.find((h) => req.headers.has(h));
    if (seen && !toldUnknown) {
      toldUnknown = true;
      report(new Error(`This request came through a proxy (${seen}), and clientIp is not set, so the buyer's address is unknown: nothing is limited by address, and a live key would not start. Set clientIp for your hosting (KIT.md, "The buyer's address").`), 'client_ip_unknown');
    }
    return undefined;
  };
  const report = (e: unknown, where: string) => {
    try {
      config.onError?.(e, where);
    } catch {
      /* a reporter may not break a sale */
    }
  };

  /** A proof that this page made this hold: what opens the order. A hold's id alone travels too far (a link, a log). Derived, so no store is needed; rolling the key ends old ones. */
  const receiptKey = globalThis.crypto.subtle.importKey('raw', new TextEncoder().encode(`rcms-tickets-kit-receipt:${config.apiKey}`), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
  const receiptOf = async (holdId: string): Promise<string> => btoa(String.fromCharCode(...new Uint8Array(await globalThis.crypto.subtle.sign('HMAC', await receiptKey, new TextEncoder().encode(holdId))))).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
  /** What an abandoned-checkout link carries to bring its code back: not a receipt, so a forwarded mail opens nothing else of the hold. */
  const resumeKeyOf = (holdId: string): Promise<string> => receiptOf(`resume\n${holdId}`);
  /** Nothing is done to a hold on its id alone: the plain "no such hold" a stranger would get anyway. */
  const needReceipt = async (req: Request, holdId: string): Promise<void> => {
    if (!(await hasReceipt(req, holdId))) throw new HttpError(404, 'resource_missing', 'No such hold.', 'invalid_request_error', 'hold');
  };
  const hasReceipt = async (req: Request, holdId: string): Promise<boolean> => {
    const given = req.headers.get('x-rt-receipt') ?? '';
    const want = await receiptOf(holdId);
    if (given.length !== want.length) return false;
    let diff = 0;
    for (let i = 0; i < want.length; i++) diff |= given.charCodeAt(i) ^ want.charCodeAt(i);
    return diff === 0;
  };

  // Once per address per 24 hours, unless the site brings its own gate.
  const mailed = new Map<string, number>();
  const mayMail = async (hold: ApiHold & { email: string }): Promise<boolean> => {
    if (hold.mode === 'test' && !config.abandonedInTestMode) return false;
    if (config.abandonedGate) return config.abandonedGate(hold, { api });
    const key = hold.email.trim().toLowerCase();
    const now = clock().getTime();
    const last = mailed.get(key);
    if (last !== undefined && now - last < 86_400_000) return false;
    if (mailed.size > 50_000) mailed.clear();
    mailed.set(key, now);
    return true;
  };

  const pickEvent = (asked: unknown): string => {
    const e = typeof asked === 'string' && asked ? asked : events[0]!;
    if (!events.includes(e)) throw new HttpError(404, 'resource_missing', 'No such event.', 'invalid_request_error', 'event');
    return e;
  };
  const idOf = (v: unknown, name: string): string => {
    if (typeof v !== 'string' || !ID.test(v)) throw bad(`${name} is not an id.`, name);
    return v;
  };
  /** A hold of this site's event, or a plain "no such hold": a page may not touch another event's holds. */
  const holdOf = async (id: string): Promise<ApiHold> => {
    const h = await api.get<ApiHold>(`/v1/holds/${id}`);
    if (!events.includes(h.event)) throw new HttpError(404, 'resource_missing', 'No such hold.', 'invalid_request_error', 'hold');
    return h;
  };

  /* ---- storefront ---- */
  const storefrontCacheMs = config.storefrontCacheMs ?? (api.mode === 'live' ? 2000 : 0);
  const storeCache = new Map<string, { at: number; body: Promise<unknown> }>();
  async function storefront(url: URL): Promise<Response> {
    const event = pickEvent(url.searchParams.get('event'));
    const code = str(url.searchParams.get('code'), 40);
    // Shared for a moment, and only with no code. The hold is what checks stock and price, so a page two seconds old costs nobody a ticket.
    if (storefrontCacheMs > 0 && !code && !url.searchParams.has('fresh')) {
      const now = clock().getTime();
      let hit = storeCache.get(event);
      if (!hit || now - hit.at >= storefrontCacheMs) {
        hit = { at: now, body: readStorefront(event, undefined) };
        storeCache.set(event, hit);
        hit.body.catch(() => storeCache.delete(event));
      }
      return json(200, await hit.body);
    }
    return json(200, await readStorefront(event, code));
  }

  async function readStorefront(event: string, typed: string | undefined): Promise<unknown> {
    // A code is plain letters, digits, - and _, so a phone's smart dash or an emoji can't be one, and no header can carry it (`new Headers` throws): the page says "invalid", as for any wrong code, and the API isn't asked.
    const sendable = !typed || /^[\x20-\x7E]+$/.test(typed);
    const code = sendable ? typed : undefined;
    const [ev, avail, types, addOns] = await Promise.all([
      api.get<Record<string, any>>(`/v1/events/${event}`), // eslint-disable-line @typescript-eslint/no-explicit-any
      // The code goes in a header: a URL lands in the platform's request log (the API's own rule).
      api.get<Record<string, any>>(`/v1/events/${event}/availability`, undefined, code ? { 'tickets-code': code } : undefined), // eslint-disable-line @typescript-eslint/no-explicit-any
      api.all<Record<string, any>>('/v1/ticket_types', { event, archived: 'false' }), // eslint-disable-line @typescript-eslint/no-explicit-any
      api.all<Record<string, any>>('/v1/add_ons', { event, archived: 'false' }), // eslint-disable-line @typescript-eslint/no-explicit-any
    ]);
    const typeById = new Map(types.map((t) => [t.id as string, t]));
    const addById = new Map(addOns.map((a) => [a.id as string, a]));
    return {
      object: 'storefront',
      mode: api.mode,
      as_of: avail.as_of,
      my_tickets_url: ev.my_tickets_url ?? null,
      event: {
        id: ev.id,
        name: ev.name,
        status: ev.status,
        venue: ev.venue,
        days: ev.days,
        currency: ev.currency,
        attendee_info: ev.attendee_info ?? null,
        questions: ev.questions ?? [],
        consent_texts: ev.consent_texts ?? { email: null, sms: null },
      },
      order_fees_passed_on: !!avail.order_fees_passed_on,
      ticket_types: (avail.ticket_types as Array<Record<string, any>>).map((a) => { // eslint-disable-line @typescript-eslint/no-explicit-any
        const t = typeById.get(a.ticket_type) ?? {};
        return { ...a, description: t.description ?? null, holder_details: t.holder_details ?? 'none', questions: t.questions ?? [], tickets_per_unit: a.tickets_per_unit ?? 1 };
      }),
      add_ons: (avail.add_ons as Array<Record<string, any>>).map((a) => ({ ...a, description: addById.get(a.add_on)?.description ?? null })), // eslint-disable-line @typescript-eslint/no-explicit-any
      days: avail.days,
      code: sendable ? (avail.code ?? null) : { code: typed, valid: false, reason: 'code_invalid' },
    };
  }

  /* ---- holds ---- */
  function cleanItems(v: unknown): Array<Record<string, unknown>> {
    if (!Array.isArray(v) || v.length < 1 || v.length > 20) throw bad('Choose between 1 and 20 items.', 'items');
    return v.map((raw, i) => {
      const it = (raw ?? {}) as Record<string, unknown>;
      const quantity = it.quantity;
      if (typeof quantity !== 'number' || !Number.isInteger(quantity) || quantity < 1 || quantity > 100) throw bad('Each quantity is a whole number from 1 to 100.', `items[${i}].quantity`);
      if (typeof it.ticket_type === 'string' && it.add_on === undefined) return { ticket_type: idOf(it.ticket_type, 'ticket_type'), quantity };
      if (typeof it.add_on === 'string') return { add_on: idOf(it.add_on, 'add_on'), quantity, ...(typeof it.ticket_type === 'string' ? { ticket_type: idOf(it.ticket_type, 'ticket_type') } : {}) };
      throw bad('Each item is a ticket_type or an add_on.', `items[${i}]`);
    });
  }

  async function createHold(req: Request, ip: string | undefined): Promise<Response> {
    const b = await body(req);
    const event = pickEvent(b.event);
    const email = str(b.email, 320);
    const key = req.headers.get('idempotency-key');
    const attribution = sanitizeAttribution(b.attribution, { client_ip: ip, user_agent: str(req.headers.get('user-agent'), 1000) });
    // A hold the page shows its receipt for: the buyer changing their mind. Without it, no such thing: a hold's id travels too far to change what another buyer holds.
    const replaces = typeof b.replaces === 'string' && ID.test(b.replaces) && (await hasReceipt(req, b.replaces)) ? b.replaces : undefined;
    const hold = await api.post<ApiHold>(
      '/v1/holds',
      { event, items: cleanItems(b.items), ...(str(b.code, 40) ? { code: str(b.code, 40) } : {}), ...(email && EMAIL.test(email) ? { email } : {}), ...(replaces ? { replaces } : {}), attribution },
      { idempotencyKey: key && IDEM.test(key) ? key : undefined },
    );
    return json(201, holdView(hold, clock(), { receipt: await receiptOf(hold.id), showOrder: true }));
  }

  async function holdRoute(req: Request, id: string, action: string | undefined, ip: string | undefined): Promise<Response> {
    if (action === 'resume' && req.method === 'GET') {
      const h = await holdOf(id);
      // The items are the link's to bring back. The code's text only to the link this kit signed: a hold's id travels too far (a log, a shared tab) to open an access code.
      const signed = (req.headers.get('x-rt-resume') ?? '') === (await resumeKeyOf(id));
      return json(200, { id: h.id, status: h.status, event: h.event, items: h.items.map((i) => ({ ticket_type: i.ticket_type, add_on: i.add_on, quantity: i.quantity })), code: signed ? h.code : null });
    }
    if (action === 'extend' && req.method === 'POST') {
      await needReceipt(req, id);
      return json(200, holdView(await api.post<ApiHold>(`/v1/holds/${id}/extend`, { minutes: 10 }), clock()));
    }
    if (!action && req.method === 'GET') return json(200, holdView(await holdOf(id), clock(), { showOrder: await hasReceipt(req, id) }));
    if (!action && req.method === 'PATCH') {
      const b = await body(req);
      const email = b.email === null ? null : str(b.email, 320);
      if (email !== null && !(email && EMAIL.test(email))) throw bad('That is not an email address.', 'email');
      await needReceipt(req, id);
      await api.patch(`/v1/holds/${id}`, { email });
      const word = b.marketing_email as { granted?: unknown; text_version?: unknown } | null | undefined;
      if (config.onEmailChoice && email && word && typeof word === 'object' && typeof word.granted === 'boolean') {
        try {
          await config.onEmailChoice({ hold: id, email, granted: word.granted, textVersion: str(word.text_version, 64) || null, ip: ip ?? null });
        } catch (e) {
          report(e, 'email_choice');
          if (!word.granted) throw new HttpError(503, 'email_choice_failed', 'That did not save. Please try again.', 'api_error');
        }
      }
      return json(200, { ok: true });
    }
    if (!action && req.method === 'DELETE') {
      await needReceipt(req, id);
      try {
        await api.del(`/v1/holds/${id}`);
      } catch (e) {
        if (!(e instanceof ApiFailure && e.is('hold_consumed', 'hold_expired'))) throw e;
      }
      return json(200, { ok: true });
    }
    throw new HttpError(405, 'method_not_allowed', 'That method is not allowed here.');
  }

  /* ---- orders ---- */
  /** The buyer's half of an order, checked and trimmed. A field that is wrong throws with its name, before anything else happens. */
  function orderFields(b: Record<string, unknown>, ip: string | undefined) {
    const buyerIn = (b.buyer ?? {}) as Record<string, unknown>;
    const name = str(buyerIn.name, 200);
    const email = str(buyerIn.email, 320);
    if (!name) throw bad('Enter your name.', 'buyer.name');
    if (!email || !EMAIL.test(email)) throw bad('Enter a valid email address.', 'buyer.email');
    const typed = str(buyerIn.phone, 40);
    const phone = typed ? normalizePhone(typed) : null;
    if (typed && !phone) throw bad('Enter a mobile number with its area code.', 'buyer.phone');
    const marketing = (buyerIn.marketing ?? {}) as Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any
    // A consent given is evidenced with the address of the request it came in on, whatever the buyer said about ad tracking: they are separate purposes. A "no" keeps none.
    const consent = (c: any) => (c && typeof c.granted === 'boolean' ? { granted: c.granted, ...(typeof c.text_version === 'string' ? { text_version: c.text_version.slice(0, 40) } : {}), ...(c.granted === true && ip ? { ip } : {}) } : undefined); // eslint-disable-line @typescript-eslint/no-explicit-any
    return {
      name,
      email,
      fields: {
        buyer: {
          name,
          email,
          ...(phone ? { phone } : {}),
          ...(consent(marketing.email) || consent(marketing.sms) ? { marketing: { ...(consent(marketing.email) ? { email: consent(marketing.email) } : {}), ...(consent(marketing.sms) ? { sms: consent(marketing.sms) } : {}) } } : {}),
        },
        ...(b.answers && typeof b.answers === 'object' && !Array.isArray(b.answers) ? { answers: b.answers } : {}),
        ...(Array.isArray(b.attendees) && b.attendees.length ? { attendees: b.attendees } : {}),
        ...(b.ad_consent === 'granted' || b.ad_consent === 'denied' || b.ad_consent === 'unknown' ? { ad_consent: b.ad_consent } : {}),
      },
    };
  }

  /** The API's check: everything an order can be refused for, while no money has moved. */
  const dryRun = (holdId: string, fields: Record<string, unknown>) => orOlderApi({ hold: holdId, ...fields }, (b) => api.post('/v1/orders/check', b));

  /** An API from before `ad_consent` refuses the word as an unknown field. A sale never stops for it: the word comes off, once, and the hold's stands. */
  async function orOlderApi<B extends Record<string, unknown>, T>(body: B, call: (b: B) => Promise<T>): Promise<T> {
    try {
      return await call(body);
    } catch (e) {
      if (!(e instanceof ApiFailure) || e.error.code !== 'parameter_unknown' || e.error.param !== 'ad_consent' || !('ad_consent' in body)) throw e;
      const { ad_consent: _gone, ...rest } = body;
      return call(rest as B);
    }
  }

  /** The answer for a page that asked for an order to be checked. */
  async function checkOrder(req: Request, ip: string | undefined): Promise<Response> {
    const b = await body(req);
    const holdId = idOf(b.hold, 'hold');
    await needReceipt(req, holdId);
    const { fields } = orderFields(b, ip);
    await dryRun(holdId, fields);
    return json(200, { ok: true });
  }

  const paidInFull = (o: ApiOrder): boolean => o.status === 'paid' && (o.amount_refunded?.amount ?? 0) === 0;
  /** The order is waiting on this payment: made with an authorization (`held`), money not counted until the capture is told to the API. */
  const waitingOn = (o: ApiOrder, reference: string): boolean => o.status === 'pending' && (o.payments ?? []).some((p) => p.provider === 'external' && p.reference === reference && p.status === 'pending');
  /** Does the order still stand on this payment: paid in full, or waiting for it. */
  const standsOn = (o: ApiOrder, reference: string): boolean => (o.payments ?? []).some((p) => p.reference === reference) && (paidInFull(o) || waitingOn(o, reference));

  /** Said to the API, then forgotten: the answer decides what the kit reports, and the API's own state is the memory. Nothing here is kept in this server's memory, because on serverless the instance that sweeps is rarely the one that took the buyer's request. */
  const tell = (o: ApiOrder, reference: string, outcome: 'captured' | 'lost', why?: 'event_cancelled' | 'bought_again'): Promise<ExternalPaymentResult> => api.post<ExternalPaymentResult>(`/v1/orders/${o.id}/external_payment`, { reference, outcome, ...(why ? { why } : {}) });

  /** The processor took the money: the order becomes paid. A failure leaves it pending, and the webhook or the sweep says it again. Never throws, unless `strict`. */
  async function confirm(o: ApiOrder, reference: string, strict = false): Promise<ApiOrder> {
    try {
      const r = await tell(o, reference, 'captured');
      if (r.money_after_end) report(new PaymentProblem(`Order ${o.id} had ended when its payment was taken. The money is taken at your processor and no order keeps it: refund it there.`, { order: o.id, hold: o.hold ?? undefined, reference }), 'captured_after_end');
      return r.order;
    } catch (e) {
      if (strict) throw e;
      report(e, 'capture_unconfirmed');
      return o;
    }
  }

  /** The processor can never take the money: the order is cancelled (it has no tickets), and a person hears it. `newly` is true when this call is the one that did it. */
  async function lose(o: ApiOrder, reference: string, why: string): Promise<{ order: ApiOrder; newly: boolean }> {
    const told = (order: ApiOrder) => report(new PaymentProblem(`Order ${order.id} was cancelled: its payment can never be taken (${why}). No tickets were issued and the card was not charged.`, { order: order.id, hold: order.hold ?? undefined, reference }), 'capture_lost');
    try {
      const r = await tell(o, reference, 'lost');
      if (r.changed) told(r.order);
      return { order: r.order, newly: r.changed };
    } catch (e) {
      // Tickets are out already (an order an older kit made, or the money did land): nothing was cancelled, and a person looks. Said once per server start.
      if (e instanceof ApiFailure && e.is('invalid_state_transition')) {
        if (o.status === 'refunded') return { order: o, newly: false }; // Its money went back and its tickets are void: nothing is out, and nobody needs telling.
        const legacy = !toldLost.has(reference);
        if (legacy) {
          if (toldLost.size > 10_000) toldLost.clear();
          toldLost.add(reference);
          report(new PaymentProblem(`Order ${o.id} stands with its tickets out, but its payment can never be taken (${why}): tickets are out with no money. Cancel or refund it from the order.`, { order: o.id, hold: o.hold ?? undefined, reference }), 'capture_lost');
        }
        return { order: o, newly: legacy };
      }
      // The answer was lost, and the word may still have landed: the order says. Seen ended on this word, it counts now, because the next look will find nothing left to do.
      const now = await api.get<ApiOrder>(`/v1/orders/${o.id}`).catch(() => null);
      if (now?.status === 'cancelled' && now.payment_end === 'not_charged') {
        told(now);
        return { order: now, newly: true };
      }
      report(e, 'capture_lost_unrecorded');
      return { order: now ?? o, newly: false };
    }
  }
  const toldLost = new Set<string>();

  /** Money a refund took back before the order was ever told: never tickets. The order waits, and its 2-hour mail goes to the owners from the API. Reported once per server start. */
  const toldRefunded = new Set<string>();
  function reportRefunded(o: ApiOrder, reference: string): void {
    if (toldRefunded.has(reference)) return;
    if (toldRefunded.size > 10_000) toldRefunded.clear();
    toldRefunded.add(reference);
    report(new PaymentProblem(`Order ${o.id} waits on a payment that was refunded at your processor, so it was not confirmed and no tickets were issued. Cancel the order if that was meant.`, { order: o.id, hold: o.hold ?? undefined, reference }), 'capture_refunded');
  }

  /**
   * Before taking the money of an order that has waited: what the processor holds now, and whether the API still wants it taken. A void costs the buyer nothing, and a capture on a cancelled
   * event, or on the earlier try of a buyer who bought again, charges them for nothing. Money already taken is real and is never voided here: it goes on to `confirm`, and the API says what it finds.
   */
  async function beforeTaking(o: ApiOrder, reference: string): Promise<{ go: 'capture' | 'confirm' | 'refunded' | 'dropped' } | { go: 'void'; why: 'event_cancelled' | 'bought_again' | 'order_ended' }> {
    const state = payment.open?.state;
    if (state) {
      const held = await state(reference);
      if (held === 'refunded') return { go: 'refunded' };
      if (held === 'taken') return { go: 'confirm' };
      if (held === 'dropped') return { go: 'dropped' };
      // A read that doesn't answer is never a yes and never a no. Nothing is taken or said on it.
      if (held !== 'open') throw new Error('The processor could not say what became of this payment, so nothing was done to it.');
    }
    const a = await api.post<ExternalPaymentResult>(`/v1/orders/${o.id}/external_payment`, { reference, outcome: 'may_capture' });
    if (a.outcome === 'void_me') return { go: 'void', why: a.void_why ?? 'order_ended' };
    if (a.outcome === 'capture') return { go: 'capture' };
    throw new Error('The API did not say whether to take this payment, so nothing was done to it.');
  }

  /** The API said not to take it. Voided first, then said, so "not charged" is only ever said of money that is gone from the card; if the void found it taken after all, that is what is told. */
  async function voidHeld(o: ApiOrder, reference: string, why: 'event_cancelled' | 'bought_again' | 'order_ended'): Promise<ApiOrder> {
    const open = payment.open!;
    const hold = await holdOf(o.hold ?? '');
    await open.void(reference, { api, hold });
    // "Not charged" is said only of a payment the processor says is gone (or a slot that can't be asked, whose void is its word). Anything else stays as it is, and the next look asks again.
    if (open.state) {
      const held = await open.state(reference);
      if (held === 'taken') return confirm(o, reference, true);
      if (held === 'refunded') {
        reportRefunded(o, reference);
        return o;
      }
      if (held !== 'dropped') throw new Error('The processor could not say the payment was voided, so nothing was said of it.');
    }
    if (why === 'order_ended') return api.get<ApiOrder>(`/v1/orders/${o.id}`);
    return (await tell(o, reference, 'lost', why)).order;
  }

  /**
   * The one road a capture takes, from the order's own request, a retry, the webhook and the sweep: take the money, then tell the API (which makes the order paid and issues
   * the tickets). A payment the processor can never take ends the order. A transient failure leaves it pending for the next look. Safe to run twice. In the buyer's request it never throws
   * (the buyer has an order); with `strict` (the webhook and the sweep) a transient failure is thrown, so a delivery answers 5xx and is tried again. `fresh` is the buyer's own first press, a
   * moment after the order was made: nothing can have changed, so it takes no extra calls.
   */
  async function takeHeld(o: ApiOrder, reference: string, capture: () => Promise<void>, o2: { strict?: boolean; fresh?: boolean } = {}): Promise<{ order: ApiOrder; lost: boolean; voided: boolean }> {
    const strict = !!o2.strict;
    if (o.status === 'pending' && !o2.fresh && payment.open) {
      try {
        const next = await beforeTaking(o, reference);
        if (next.go === 'refunded') {
          reportRefunded(o, reference);
          return { order: o, lost: false, voided: false };
        }
        if (next.go === 'dropped') {
          const r = await lose(o, reference, 'the processor cancelled it');
          return { order: r.order, lost: r.newly, voided: false };
        }
        if (next.go === 'confirm') return { order: await confirm(o, reference, strict), lost: false, voided: false };
        if (next.go === 'void') return { order: await voidHeld(o, reference, next.why), lost: false, voided: true };
      } catch (e) {
        if (strict) throw e;
        report(e, 'capture');
        return { order: o, lost: false, voided: false };
      }
    }
    try {
      await capture();
    } catch (e) {
      if (e instanceof PaymentRefunded) {
        reportRefunded(o, reference);
        return { order: o, lost: false, voided: false };
      }
      if (e instanceof PaymentFailure) {
        const r = await lose(o, reference, e.message);
        return { order: r.order, lost: r.newly, voided: false };
      }
      if (strict) throw e;
      report(e, 'capture');
      return { order: o, lost: false, voided: false };
    }
    // Taken. An order already paid (an older API, charge-first) has nothing to be told.
    if (o.status !== 'pending') return { order: o, lost: false, voided: false };
    return { order: await confirm(o, reference, strict), lost: false, voided: false };
  }

  /**
   * A payment to finish, given the hold it was for. The order's own is captured, but only if the order still stands on it (paid with nothing refunded, or waiting for it).
   * Any other is dropped, and one still in its time is left. Safe to run twice, from anywhere.
   */
  async function settle(reference: string, holdId: string): Promise<'captured' | 'voided' | 'kept' | 'lost'> {
    const open = payment.open;
    if (!open) return 'kept';
    const h = await holdOf(holdId).catch((e: unknown) => {
      if (e instanceof HttpError || (e instanceof ApiFailure && e.status === 404)) return null;
      throw e;
    });
    if (!h || h.status === 'active') return 'kept';
    if (h.status === 'consumed' && h.order) {
      const o = await api.get<ApiOrder>(`/v1/orders/${h.order}`);
      if ((o.payments ?? []).some((p) => p.reference === reference)) {
        if (standsOn(o, reference)) {
          const r = await takeHeld(o, reference, () => open.capture(reference), { strict: true });
          return r.lost ? 'lost' : r.voided ? 'voided' : r.order.status === 'pending' ? 'kept' : 'captured';
        }
        // Before saying the money was not taken: was it? An order can end while the money is already gone, and then the truth is the opposite, and it needs a refund.
        if (open.state) {
          const held = await open.state(reference);
          if (held === 'taken') {
            await confirm(o, reference, true);
            return 'kept';
          }
          // Square can't say right now. Saying nothing beats saying the wrong thing: a delivery comes again, and the sweep looks again.
          if (held === 'unknown') throw new Error('The processor could not say what became of a payment on an order that has ended.');
          // Taken, then given back, on an order that has ended: nothing is left to do or to say.
          if (held === 'refunded') return 'kept';
        }
        report(new PaymentProblem(`Order ${o.id} is ${o.status}${o.status === 'cancelled' ? '' : ' with money refunded'}, so the kit did not capture its payment.`, { order: o.id, hold: holdId, reference }), 'capture_refused');
      }
    }
    await open.void(reference, { api, hold: h });
    return 'voided';
  }

  /** The order's own payment, taken if it is not yet (a retry). Answers the order as it stands after. */
  async function captureOrderPayments(o: ApiOrder): Promise<ApiOrder> {
    if (!payment.open) return o;
    let now = o;
    for (const p of o.payments ?? []) {
      if (p.provider !== 'external' || !p.reference || !standsOn(now, p.reference)) continue;
      now = (await takeHeld(now, p.reference, () => payment.open!.capture(p.reference!))).order;
    }
    return now;
  }

  /** A payment the processor dropped by itself. Its order, if it still waits on it, is cancelled through the API (counted once); an order an older kit made, paid with tickets out, is only reported. */
  async function checkDropped(reference: string, holdId: string): Promise<boolean> {
    const h = await holdOf(holdId).catch(() => null);
    if (!h || h.status !== 'consumed' || !h.order) return false;
    const o = await api.get<ApiOrder>(`/v1/orders/${h.order}`);
    if (!standsOn(o, reference)) return false;
    return (await lose(o, reference, 'the processor cancelled it')).newly;
  }

  /** Every page of a list, up to SWEEP_PAGES; one past that is said, never quietly left. Pending orders are read oldest first, because those are nearest the processor's own cancel. */
  async function listAll(where: Record<string, string>, what: string): Promise<ApiOrder[]> {
    const rows = await api.all<ApiOrder>('/v1/orders', where, SWEEP_PAGES);
    if (rows.length >= SWEEP_PAGES * 100) report(new Error(`More than ${SWEEP_PAGES * 100} ${what} orders on one event: this sweep looked at the first ${rows.length}, and the next looks again.`), 'sweep_capped');
    return rows;
  }

  async function sweep(): Promise<SweepResult> {
    const out: SweepResult = { captured: 0, voided: 0, kept: 0, failed: 0, lost: 0, money_after_end: 0 };
    if (!payment.open) return out;
    for (const p of await payment.open.list({ fresh: true })) {
      try {
        if (p.status === 'dropped') {
          if (await checkDropped(p.reference, p.hold)) out.lost++;
        } else {
          const r = await settle(p.reference, p.hold);
          if (r === 'lost') out.lost++;
          else out[r]++;
        }
      } catch (e) {
        out.failed++;
        report(e, 'sweep');
      }
    }
    // The list above holds only open and dropped payments, so it can't see money the processor already took. The orders are asked about instead, and nothing needs remembering.
    const state = payment.open.state;
    if (state) {
      try {
        // Waiting on a payment: a crash or an API outage between the capture and the word to the API, or a payment that fell out of the list.
        const waiting: ApiOrder[] = [];
        for (const e of events) waiting.push(...(await listAll({ status: 'pending', event: e, sort: 'created_at' }, 'pending')));
        for (const o of waiting) {
          for (const p of o.payments ?? []) {
            if (p.provider !== 'external' || !p.reference || p.status !== 'pending') continue;
            try {
              const held = await state(p.reference);
              if (!waitingOn(o, p.reference)) continue;
              if (held === 'dropped') {
                if ((await lose(o, p.reference, 'the processor cancelled it')).newly) out.lost++;
              } else if (held === 'refunded') {
                reportRefunded(o, p.reference);
              } else if (held === 'taken') {
                const now = await confirm(o, p.reference);
                if (now.status === 'paid') out.captured++;
              }
            } catch (e) {
              out.failed++;
              report(e, 'sweep');
            }
          }
        }
        // Ended, while the money was on its way: the word never reached the API, or a person cancelled first. The API's own `late_money` mark makes this once only, across every instance.
        const since = clock().getTime() - SWEEP_DAYS * 86_400_000;
        const ended: ApiOrder[] = [];
        // Created in the last two windows: money can't be taken long after the order was made (Square's own delay is far shorter), and an old event's cancelled orders are not read every 15 minutes.
        for (const e of events) ended.push(...(await listAll({ status: 'cancelled', event: e, created_gte: new Date(since - SWEEP_DAYS * 86_400_000).toISOString() }, 'cancelled')));
        for (const o of ended) {
          if (o.payment_end === 'taken_after_end' || (o.cancelled_at && Date.parse(o.cancelled_at) < since)) continue;
          // Not charged, an hour on: Square's CANCELED is final, so this order costs no more reads for the rest of its 8 days.
          if (o.payment_end === 'not_charged' && o.cancelled_at && clock().getTime() - Date.parse(o.cancelled_at) > 3_600_000) continue;
          for (const p of o.payments ?? []) {
            if (p.provider !== 'external' || !p.reference || p.status !== 'failed') continue;
            try {
              const held = await state(p.reference);
              if (held === 'taken') {
                const r = await confirm(o, p.reference, true);
                if (r.payment_end === 'taken_after_end') out.money_after_end++;
              } else if (held === 'dropped' && o.payment_end === 'not_confirmed') {
                // A person cancelled it and nobody could say where the money was. Now somebody can.
                await tell(o, p.reference, 'lost');
              }
            } catch (e) {
              out.failed++;
              report(e, 'sweep');
            }
          }
        }
      } catch (e) {
        out.failed++;
        report(e, 'sweep');
      }
    }
    return out;
  }

  /** A payment open far longer than any hold can last means nothing is sweeping. Evidence, so a serverless instance can see it too. */
  let toldStaleAt = 0;
  const warnIfStale = (open: Array<{ status?: string; created_at?: string }>) => {
    const now = clock().getTime();
    if (now - toldStaleAt < 3_600_000) return;
    if (open.some((p) => p.status !== 'dropped' && p.created_at && now - Date.parse(p.created_at) > 2 * 3_600_000)) {
      toldStaleAt = now;
      report(new Error('A payment has been open for more than two hours. Nothing seems to be calling /sweep: buyers may have pending amounts on their cards.'), 'sweep_stale');
    }
  };

  /** The order exists: take the money and tell the API. If that fails now, the webhook or the sweep finishes it. Answers the order as it stands: pending (not taken yet), paid, or cancelled (lost). Never throws. */
  async function captureAfterOrder(outcome: PaymentOutcome, order: ApiOrder): Promise<ApiOrder> {
    const reference = outcome.payment.provider === 'external' ? outcome.payment.reference : null;
    // Only an order that stands on this payment (paid, or waiting for it) takes its money: one a person cancelled meanwhile never does, and the sweep voids the authorization.
    if (!outcome.capture || !reference || !standsOn(order, reference)) return order;
    return (await takeHeld(order, reference, outcome.capture, { fresh: order.status === 'pending' })).order;
  }

  /**
   * The order as the buyer is answered. A cancelled one says only what is known of the money: "not charged" when the processor can never take it (and they may hold the tickets again),
   * the opposite when the money turned out to be taken, and neither when nobody has confirmed it.
   */
  /**
   * The Wallet links. An order's tickets never carry them (the API keeps them off every answer and log row about an order), so they are read
   * from the tickets, once the tickets exist. Only for a ticket still on its first version: a later one may have been sent to someone else, and
   * this answer goes to whoever holds the buyer's receipt. Their ticket page has the buttons from then on. A read that fails costs the buttons,
   * never the confirmation.
   */
  async function withWallets(o: ApiOrder): Promise<ApiOrder> {
    if (o.status === 'cancelled' || !o.tickets?.length) return o;
    try {
      const rows = await api.all<{ id: string; status?: string; version?: number; wallet?: { apple_url: string | null; google_url: string | null } }>('/v1/tickets', { order: o.id });
      const read = new Map(rows.map((r) => [r.id, r]));
      return {
        ...o,
        tickets: o.tickets.map((t) => {
          const r = read.get(t.id);
          return r?.status === 'valid' && r.version === 1 && r.wallet ? { ...t, wallet: r.wallet } : t;
        }),
      };
    } catch (e) {
      report(e, 'wallet_links');
      return o;
    }
  }

  async function answerOrder(status: 200 | 201, o: ApiOrder): Promise<Response> {
    if (o.status === 'cancelled') {
      if (o.payment_end === 'not_charged') throw new HttpError(409, 'payment_voided', 'The payment could not be taken, so nothing was charged.', 'state_error', null, { cause: 'payment_lost' });
      if (o.payment_end === 'taken_after_end') throw new HttpError(409, 'payment_taken_order_cancelled', 'Your payment went through but this order was cancelled. The organizer will refund you.', 'state_error');
      throw new HttpError(409, 'order_cancelled', 'This order was cancelled. If your card shows a charge, contact the organizer.', 'state_error');
    }
    return json(status, orderView(await withWallets(o)));
  }

  async function createOrder(req: Request, ip: string | undefined): Promise<Response> {
    const b = await body(req);
    const holdId = idOf(b.hold, 'hold');
    await needReceipt(req, holdId);
    const { name, email, fields } = orderFields(b, ip);
    const expected = b.expected_total;
    if (typeof expected !== 'number' || !Number.isInteger(expected) || expected < 0) throw bad('expected_total is the total the buyer was shown, in minor units.', 'expected_total');
    const payIn = (b.payment ?? {}) as Record<string, unknown>;

    const hold = await holdOf(holdId);
    if (hold.status === 'consumed' && hold.order) {
      // A retry after the order was made (a timeout, a double tap): the same order, to the same buyer only.
      const existing = await api.get<ApiOrder>(`/v1/orders/${hold.order}`);
      if ((existing.buyer.email ?? '').toLowerCase() === email.toLowerCase()) {
        const now = await captureOrderPayments(existing).catch((e: unknown) => (report(e, 'capture'), existing));
        return await answerOrder(200, now);
      }
      // A cancelled order bought nothing: these tickets are free to hold again. The other buyer's money is not this buyer's to hear about.
      if (existing.status === 'cancelled') throw new HttpError(410, 'hold_released', 'The hold is no longer active. Hold the tickets again.', 'state_error', 'hold');
      throw new HttpError(409, 'hold_consumed', 'These tickets are already bought.', 'state_error', 'hold');
    }
    if (hold.status !== 'active') throw new HttpError(410, hold.status === 'released' ? 'hold_released' : 'hold_expired', 'The hold is no longer active. Hold the tickets again.', 'state_error', 'hold');
    if (expected !== hold.price.total.amount) throw new HttpError(409, 'price_changed', 'The total is not the one the buyer saw.', 'state_error', 'expected_total', { hold: holdView(hold, clock()) });

    // A free order goes to no processor, whatever the page sent. The word "free" gets nothing else through.
    const free = hold.price.total.amount === 0;
    if (!free && payIn.provider === 'free') throw new PaymentFailure('payment_failed', 'This order is not free.');

    // Every field an order can be refused for, while no money has moved. A refusal here names its field, and nothing was charged.
    // The API's own test provider and a free order take nothing before the order, whose first step is this same check.
    if (!free && payment.environment !== 'test') try {
      await dryRun(holdId, fields);
    } catch (e) {
      if (e instanceof ApiFailure && (e.status >= 500 || e.status === 0)) throw new HttpError(503, 'not_ready', 'We could not check your order just now. Nothing was charged. Please try again.', 'api_error');
      throw e;
    }

    const outcome: PaymentOutcome = free ? { payment: { provider: 'external', reference: `free_${hold.id}`.slice(0, 200), amount: 0, method: 'other' } } : await payment.prepare({ api, hold, payment: payIn, buyer: { name, email } });
    const orderBody = { hold: holdId, ...fields, payment: outcome.payment };
    const reference = outcome.payment.provider === 'external' ? outcome.payment.reference : null;

    /** The order may have been made after all (a lost answer, a twin request): if this payment is on it, this is success. */
    const orderWithThisPayment = async (): Promise<ApiOrder | null> => {
      if (!reference) return null;
      const h = await holdOf(holdId);
      if (h.status !== 'consumed' || !h.order) return null;
      const o = await api.get<ApiOrder>(`/v1/orders/${h.order}`);
      return (o.payments ?? []).some((p) => p.reference === reference) ? o : null;
    };

    let made: ApiOrder;
    let status: 200 | 201 = 201;
    try {
      made = await orOlderApi<Record<string, unknown>, ApiOrder>(orderBody, async (b) => api.post<ApiOrder>('/v1/orders', b, { idempotencyKey: await orderKey(holdId, b) }));
    } catch (e) {
      if (!outcome.undo && !outcome.refund && !outcome.capture) throw e; // nothing was taken here (the API's test provider, a free order): its answer stands
      const unknown = !(e instanceof ApiFailure) || e.status === 0 || e.status >= 500 || OUTCOME_UNKNOWN.has(e.error.code);
      const found = await orderWithThisPayment().catch(() => null);
      if (found) {
        made = found;
        status = 200;
        return await answerOrder(status, await captureAfterOrder(outcome, made));
      }
      if (unknown) {
        // We cannot say. An authorization stays uncaptured unless an order names it, and the sweep or the webhook settles it. A charge-first
        // processor is another thing: the money is gone. A person must hear about it, with the reference.
        if (outcome.charged && reference) report(new PaymentProblem(`The buyer was charged (${reference}) and the order could not be confirmed. If no order appears for hold ${holdId}, refund it.`, { hold: holdId, reference }), 'charged_no_order');
        else report(e, 'order');
        throw new HttpError(503, 'payment_unconfirmed', 'We could not confirm the order yet.', 'api_error');
      }
      const refused = e as ApiFailure;
      const why = `order refused: ${refused.error.code}`;
      let how: 'voided' | 'refunded' = 'voided';
      try {
        if (outcome.undo) how = await outcome.undo(why);
        else if (outcome.refund) {
          await outcome.refund(why);
          how = 'refunded';
        }
      } catch (re) {
        report(re, 'refund');
        // An authorization not voided yet is never captured: the sweep or the processor's own delay ends it. Money actually taken is another thing.
        if (!outcome.undo || re instanceof RefundFailed) throw new HttpError(500, 'refund_failed', 'We could not finish your order and could not refund it automatically. Please contact the organizer: you were charged.', 'api_error');
      }
      if (how === 'refunded') {
        // A charge-first processor keys on the hold: a retry could reuse the refunded payment, so the hold is let go.
        await api.del(`/v1/holds/${holdId}`).catch(() => undefined);
      }
      throw new HttpError(409, how === 'refunded' ? 'payment_refunded' : 'payment_voided', how === 'refunded' ? 'The order could not be made, so the payment was refunded.' : 'The order could not be made, so nothing was charged.', 'state_error', refused.error.param, { cause: refused.error.code });
    }
    return await answerOrder(status, await captureAfterOrder(outcome, made));
  }

  async function readOrder(req: Request, url: URL, id: string): Promise<Response> {
    const hold = idOf(url.searchParams.get('hold'), 'hold');
    // The same plain "no such order" for a missing receipt: this answer holds a person and their tickets.
    if (!(await hasReceipt(req, hold))) throw new HttpError(404, 'resource_missing', 'No such order.', 'invalid_request_error', 'order');
    const o = await api.get<ApiOrder>(`/v1/orders/${id}`);
    if (o.hold !== hold) throw new HttpError(404, 'resource_missing', 'No such order.', 'invalid_request_error', 'order');
    return json(200, orderView(await withWallets(o)));
  }

  /* ---- webhook ---- */
  async function webhook(req: Request): Promise<Response> {
    if (!config.webhookSecret || (Array.isArray(config.webhookSecret) && !config.webhookSecret.length)) throw new HttpError(503, 'webhook_not_configured', 'No webhook secret is set on this server.', 'api_error');
    const raw = new Uint8Array(await req.arrayBuffer());
    let entry: WebhookEvent;
    try {
      entry = await verifyWebhook({ payload: raw, headers: req.headers, secret: config.webhookSecret });
    } catch (e) {
      if (e instanceof WebhookError) throw new HttpError(400, 'signature_invalid', 'The signature is not valid.', 'invalid_request_error');
      throw e;
    }
    await config.onWebhook?.(entry);
    if (entry.type === 'order.paid' || entry.type === 'order.created') {
      // The gap between the order and the capture. A failure here answers 5xx, so the delivery is tried again.
      const o = entry.data.object as unknown as ApiOrder;
      if (o.hold) {
        for (const p of o.payments ?? []) if (p.provider === 'external' && p.reference) await settle(p.reference, o.hold);
        // A losing authorization (a second press, a second tab) should not sit on the buyer's card until the delay runs out.
        if (payment.open) {
          const mine = new Set((o.payments ?? []).map((p) => p.reference));
          for (const p of await payment.open.list()) if (p.hold === o.hold && p.status !== 'dropped' && !mine.has(p.reference)) await settle(p.reference, p.hold);
        }
      }
    }
    if (entry.type === 'hold.expired') {
      const hold = entry.data.object as unknown as ApiHold;
      // Another event of the org goes to its own site: a link from here could not work.
      if (events.includes(hold.event)) {
        // Whatever happens to the processor's list, the email still goes.
        if (payment.open) {
          try {
            const open = await payment.open.list();
            warnIfStale(open);
            for (const p of open) if (p.hold === hold.id && p.status !== 'dropped') await settle(p.reference, p.hold);
          } catch (e) {
            report(e, 'sweep');
          }
        }
        // A hold made on a hosted link was never this site's: only that link can finish it, so a resume link from here could not work.
        if (config.onHoldExpired && hold.status === 'expired' && !hold.checkout_link && typeof hold.email === 'string' && hold.email && (await mayMail(hold as ApiHold & { email: string }))) {
          await config.onHoldExpired({ hold: hold as ApiHold & { email: string }, link: config.siteUrl ? `${makeResumeLink(config.siteUrl, hold.id)}&resume_key=${await resumeKeyOf(hold.id)}` : null, entry, api });
        }
      }
    }
    return json(200, { received: true });
  }

  let wrong = 0;
  let wrongAt = 0;
  async function sweepRoute(req: Request): Promise<Response> {
    if (!config.sweepSecret) throw new HttpError(404, 'route_not_found', 'No such route.');
    const given = req.headers.get('authorization') ?? '';
    const want = `Bearer ${config.sweepSecret}`;
    let diff = given.length ^ want.length;
    for (let i = 0; i < want.length; i++) diff |= (given.charCodeAt(i) || 0) ^ want.charCodeAt(i);
    if (diff !== 0) {
      const now = clock().getTime();
      if (now - wrongAt > 60_000) {
        wrongAt = now;
        wrong = 0;
      }
      if (++wrong > 10) return json(429, { error: { type: 'rate_limit_error', code: 'rate_limited', message: 'Too many tries.', param: null } }, { 'retry-after': '60' });
      throw new HttpError(401, 'unauthorized', 'That is not the sweep secret.');
    }
    return json(200, await sweep());
  }

  async function handle(req: Request, facts: { ip?: string | undefined } = {}): Promise<Response> {
    try {
      const url = new URL(req.url);
      const path = url.pathname.replace(/\/+$/, '');
      const m = /(?:^|\/)(storefront|webhook|sweep)$/.exec(path) ?? /(?:^|\/)(orders)\/(check)$/.exec(path) ?? /(?:^|\/)(holds|orders)(?:\/([A-Za-z0-9_]+)(?:\/(extend|resume))?)?$/.exec(path);
      if (!m) throw new HttpError(404, 'route_not_found', 'No such route.');
      const [, what, id, action] = m;
      if (what === 'webhook') return req.method === 'POST' ? await webhook(req) : json(405, { error: { type: 'invalid_request_error', code: 'method_not_allowed', message: 'Use POST.', param: null } });
      if (what === 'sweep') return req.method === 'POST' || req.method === 'GET' ? await sweepRoute(req) : json(405, { error: { type: 'invalid_request_error', code: 'method_not_allowed', message: 'Use POST.', param: null } });

      const ip = addressOf(req, facts.ip);
      const route = `${req.method} /${what}${id === 'check' ? '/check' : id ? '/:id' : ''}${action ? `/${action}` : ''}`;
      // On any key: a clientIp that finds nothing on this hosting is silent until a live on-sale, where every hold then counts as one network.
      if (route === 'POST /holds' && addressHow && !(ip && isPublicIp(ip)) && !toldNothing) {
        toldNothing = true;
        report(new Error('clientIp is set, but it found no public address on this request: holds name no buyer\'s address. On a live key they would all count as one network, at most half of what is left. Check what your hosting really sends (KIT.md, "The buyer\'s address").'), 'client_ip_none');
      }
      if (limiter && route !== 'POST /orders') {
        const stop = await limiter({ request: req, route, ip: ip && isPublicIp(ip) ? ip : null });
        if (stop) return stop;
      }

      if (what === 'storefront') return req.method === 'GET' ? await storefront(url) : json(405, { error: { type: 'invalid_request_error', code: 'method_not_allowed', message: 'Use GET.', param: null } });
      if (what === 'holds') {
        if (!id) {
          if (req.method !== 'POST') throw new HttpError(405, 'method_not_allowed', 'Use POST.');
          return await createHold(req, ip);
        }
        return await holdRoute(req, idOf(id, 'hold'), action, ip);
      }
      if (id === 'check') {
        if (req.method !== 'POST') throw new HttpError(405, 'method_not_allowed', 'Use POST.');
        return await checkOrder(req, ip);
      }
      if (!id) {
        if (req.method !== 'POST') throw new HttpError(405, 'method_not_allowed', 'Use POST.');
        return await createOrder(req, ip);
      }
      if (req.method !== 'GET') throw new HttpError(405, 'method_not_allowed', 'Use GET.');
      return await readOrder(req, url, idOf(id, 'order'));
    } catch (e) {
      if (e instanceof HttpError) return json(e.status, { error: { type: e.type, code: e.code, message: e.message, param: e.param }, ...e.extra });
      if (e instanceof PaymentFailure) return json(e.code === 'payment_unconfirmed' ? 503 : 402, { error: { type: 'payment_error', code: e.code, message: e.message, param: null, decline_code: e.decline_code } });
      if (e instanceof ApiFailure) return json(e.status >= 400 && e.status < 600 ? e.status : 502, { error: { type: e.error.type, code: e.error.code, message: e.error.message, param: e.error.param, decline_code: e.error.decline_code ?? null } }, e.retryAfter ? { 'retry-after': e.retryAfter } : {});
      report(e, 'handle');
      return json(500, { error: { type: 'api_error', code: 'server_error', message: 'Something went wrong on our side. Please try again.', param: null } });
    }
  }

  return { handle, api, sweep, resumeLink: (holdId, campaign) => (config.siteUrl ? makeResumeLink(config.siteUrl, holdId, campaign) : (() => { throw new TypeError('siteUrl is required to make a resume link'); })()) };
}

/**
 * The same checkout, built on its first request. Use this in a route file: `next build` and Docker builds import your routes with
 * no secrets in the environment, and `createCheckout` refuses a missing key. A config that is still wrong at a real request answers
 * a clean 503; the key is never in the answer.
 */
export function lazyCheckout(make: () => CheckoutConfig): Checkout {
  let built: Checkout | null = null;
  const get = (): Checkout => (built ??= createCheckout(make()));
  return {
    async handle(req, facts) {
      let c: Checkout;
      try {
        c = get();
      } catch {
        return json(503, { error: { type: 'api_error', code: 'checkout_not_configured', message: 'Tickets are not set up on this site yet.', param: null } });
      }
      return c.handle(req, facts);
    },
    get api() {
      return get().api;
    },
    resumeLink: (holdId, campaign) => get().resumeLink(holdId, campaign),
    sweep: () => get().sweep(),
  };
}
````

### src/rcms-tickets/server/express.ts

````ts
import type { Checkout } from './core';

/*
  Adapters from your framework's request to the kit's standard Request/Response.
    Express:   app.use('/api/tickets', expressHandler(checkout));      (mount it BEFORE express.json())
    Firebase:  export const tickets = onRequest(expressHandler(checkout));
  The adapter reads the request's raw bytes itself, which a webhook's signature needs. If a JSON body parser ran first it
  has already used the stream: then the parsed body is written back as JSON (fine for the page's calls, not for a webhook).
*/

interface NodeReq {
  method?: string;
  originalUrl?: string;
  url?: string;
  ip?: string;
  socket?: { remoteAddress?: string };
  headers: Record<string, string | string[] | undefined>;
  rawBody?: Uint8Array | string;
  body?: unknown;
  readableEnded?: boolean;
  on(event: string, cb: (...a: any[]) => void): unknown; // eslint-disable-line @typescript-eslint/no-explicit-any
}
interface NodeRes {
  statusCode: number;
  headersSent?: boolean;
  setHeader(name: string, value: string): unknown;
  end(chunk?: Uint8Array | string): unknown;
}

// Named from Request itself, not from the DOM's BodyInit: a server project (Node types, no DOM lib) has no BodyInit.
type Body = NonNullable<ConstructorParameters<typeof Request>[1]>['body'];
const MAX_BODY = 1024 * 1024;
class TooLarge extends Error {}

function readStream(req: NodeReq): Promise<Uint8Array> {
  return new Promise((resolve, reject) => {
    const parts: Uint8Array[] = [];
    let size = 0;
    let over = false;
    req.on('data', (c: Uint8Array) => {
      size += c.length;
      // Keep reading what is sent without keeping it, so the answer can still reach the client.
      if (size > MAX_BODY) {
        over = true;
        parts.length = 0;
      } else parts.push(c);
    });
    req.on('end', () => {
      if (over) return reject(new TooLarge());
      const out = new Uint8Array(size);
      let at = 0;
      for (const p of parts) (out.set(p, at), (at += p.length));
      resolve(out);
    });
    req.on('error', reject);
  });
}

const answer = (res: NodeRes, status: number, code: string, message: string): void => {
  if (res.headersSent) return void res.end();
  res.statusCode = status;
  res.setHeader('content-type', 'application/json');
  res.setHeader('cache-control', 'no-store');
  res.end(JSON.stringify({ error: { type: status >= 500 ? 'api_error' : 'invalid_request_error', code, message, param: null } }));
};

/**
 * The adapter never throws: on Express 4 a rejected handler is an unhandled rejection that ends the process, and on Express 5 it is a
 * 500 with a stack. Only the path is routed, so the Host header, which anyone can set, is never read.
 */
export function expressHandler(checkout: Checkout) {
  return async (req: NodeReq, res: NodeRes): Promise<void> => {
    try {
      let request: Request;
      try {
        const u = new URL(req.originalUrl ?? req.url ?? '/', 'http://localhost');
        const headers = new Headers();
        for (const [k, v] of Object.entries(req.headers)) {
          if (v === undefined) continue;
          try {
            headers.set(k, Array.isArray(v) ? v.join(', ') : v);
          } catch {
            /* a header a Request cannot carry: nothing here needs it */
          }
        }
        const method = req.method ?? 'GET';
        let body: Body | undefined;
        if (method !== 'GET' && method !== 'HEAD') {
          if (req.rawBody !== undefined) {
            if (req.rawBody.length > MAX_BODY) throw new TooLarge();
            body = req.rawBody as Body;
          } else if (req.readableEnded) body = typeof req.body === 'string' ? req.body : req.body instanceof Uint8Array ? (req.body as Body) : JSON.stringify(req.body ?? {});
          else body = (await readStream(req)) as Body;
        }
        request = new Request(`http://localhost${u.pathname}${u.search}`, { method, headers, body });
      } catch (e) {
        if (e instanceof TooLarge) return answer(res, 413, 'body_too_large', 'The request is too large.');
        return answer(res, 400, 'bad_request', 'That request could not be read.');
      }
      const out = await checkout.handle(request, { ip: req.ip ?? req.socket?.remoteAddress });
      const bytes = new Uint8Array(await out.arrayBuffer());
      res.statusCode = out.status;
      out.headers.forEach((v, k) => res.setHeader(k, v));
      res.end(bytes);
    } catch {
      try {
        answer(res, 500, 'server_error', 'Something went wrong on our side. Please try again.');
      } catch {
        /* the connection is gone */
      }
    }
  };
}

/** Firebase Functions (v2 `onRequest` gives an Express request with `rawBody`). */
export const firebaseHandler = expressHandler;
````

### src/rcms-tickets/server/hostingIp.ts

````ts
/*
  The buyer's address behind Firebase Hosting and a Cloud Function: `clientIp: hostingClientIp`.

  Measured by RCMS Tickets on its own service (the same Hosting and Cloud Functions front end):
  - Through Hosting, Hosting replaces any X-Forwarded-For the caller sent: the function sees "<caller>, <Google front end>".
  - Straight to the function's own address, the caller's header is kept and Google appends the real peer: "<anything the caller wrote>, <caller>".
  So the last entry is the only one nobody but Google writes. When it is a Google front end, the request came through Hosting and the caller is the
  entry before it; otherwise the last entry is the caller. `rightmost:2` is wrong here: on a direct call it reads what the caller wrote.

  What is left: someone calling the function's address directly FROM Google's own ranges (Apps Script, say) can still choose the entry before the
  last. Restricting the function's ingress to Hosting closes that.
*/

/** Google's front-end ranges that Firebase Hosting reaches a function from. */
const GOOGLE_V4: ReadonlyArray<readonly [string, number]> = [
  ['64.233.160.0', 19],
  ['66.102.0.0', 20],
  ['66.249.64.0', 19],
  ['72.14.192.0', 18],
  ['74.125.0.0', 16],
  ['108.177.0.0', 17],
  ['142.250.0.0', 15],
  ['172.217.0.0', 16],
  ['172.253.0.0', 16],
  ['173.194.0.0', 16],
  ['192.178.0.0', 15],
  ['209.85.128.0', 17],
  ['216.58.192.0', 19],
  ['216.239.32.0', 19],
];
const GOOGLE_V6 = ['2001:4860:', '2404:6800:', '2607:f8b0:', '2800:3f0:', '2a00:1450:', '2c0f:fb50:'];

function v4ToInt(ip: string): number | null {
  const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(ip);
  if (!m) return null;
  const parts = m.slice(1).map(Number) as [number, number, number, number];
  if (parts.some((p) => p > 255)) return null;
  return ((parts[0] << 24) >>> 0) + (parts[1] << 16) + (parts[2] << 8) + parts[3];
}

function isGoogleFrontEnd(ip: string): boolean {
  const n = v4ToInt(ip);
  if (n !== null) {
    return GOOGLE_V4.some(([base, bits]) => {
      const mask = (~0 << (32 - bits)) >>> 0;
      return ((n & mask) >>> 0) === ((v4ToInt(base)! & mask) >>> 0);
    });
  }
  const lower = ip.toLowerCase();
  return GOOGLE_V6.some((p) => lower.startsWith(p));
}

const HOUR = 3_600_000;
let toldUnlistedAt = -HOUR;

/**
 * Pass as `clientIp` in `createCheckout`. No header, no address: the kit then limits nothing by address, the safe side.
 * `onUnlisted`, if you wrap it, hears a Hosting request whose last hop is on no list: Google has a new range, and until it is added here every visitor counts as one address.
 */
export function hostingClientIp(req: Request, onUnlisted?: (lastHop: string) => void): string | null {
  const hops = (req.headers.get('x-forwarded-for') ?? '')
    .split(',')
    .map((s) => s.trim())
    .filter(Boolean);
  const last = hops[hops.length - 1];
  if (!last) return null;
  const google = isGoogleFrontEnd(last);
  // Anyone can send that header straight to the function, so at most once an hour in an instance: it can't fill a log.
  if (!google && hops.length >= 2 && req.headers.has('x-fh-requested-host') && Date.now() - toldUnlistedAt >= HOUR) {
    toldUnlistedAt = Date.now();
    onUnlisted?.(last.slice(0, 64));
  }
  return (google && hops.length >= 2 ? hops[hops.length - 2]! : last).slice(0, 64);
}

/**
 * The network to count a caller by: an IPv4 address as it is, an IPv6 address by its /64, since one home line is handed a whole /64 and counting full addresses
 * would give one caller 2^64 fresh counts. An IPv4-mapped address is its IPv4 address; anything unreadable is kept as it is. Null for none.
 */
export function ipNetwork(ip: string | null | undefined): string | null {
  if (!ip) return null;
  const s = ip.trim().slice(0, 64).replace(/^\[/, '').replace(/\]$/, '').replace(/%.*$/, '').toLowerCase();
  const mapped = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/.exec(s);
  if (mapped) return mapped[1]!;
  if (v4ToInt(s) !== null || !s.includes(':') || !/^[0-9a-f:]{2,39}$/.test(s)) return s;
  const halves = s.split('::');
  if (halves.length > 2) return s;
  const head = halves[0] ? halves[0].split(':') : [];
  const tail = halves.length === 2 && halves[1] ? halves[1].split(':') : [];
  if (halves.length === 1 ? head.length !== 8 : head.length + tail.length > 7) return s;
  if ([...head, ...tail].some((g) => !/^[0-9a-f]{1,4}$/.test(g))) return s;
  const groups = [...head, ...Array<string>(8 - head.length - tail.length).fill('0'), ...tail];
  return `${groups
    .slice(0, 4)
    .map((g) => parseInt(g, 16).toString(16))
    .join(':')}::/64`;
}
````

### src/rcms-tickets/server/index.ts

````ts
export { createCheckout, lazyCheckout, holdView, orderView, defaultLimiter } from './core';
export type { Checkout, CheckoutConfig, BeforeRequest, RequestFacts, SweepResult } from './core';
export { KIT_VERSION } from './version';
export { normalizePhone } from './phone';
export { hostingClientIp, ipNetwork } from './hostingIp';
export { ApiFailure, createApi } from './api';
export { http1Fetch, serverFetch } from './serverFetch';
export { testPayment, externalPayment } from './payment';
export { squarePayment, squareKey } from './square';
export type { SquareConfig } from './square';
export { PaymentFailure, PaymentProblem, RefundFailed } from './types';
export type { ServerPayment, ChargeContext, PaymentOutcome, OpenPayments, OpenPayment, ChargeStore, ApiHold } from './types';
export { verifyWebhook, WebhookError, resumeLink } from './webhook';
export type { WebhookEvent } from './webhook';
export { orderKey } from './orderKey';
export { expressHandler, firebaseHandler } from './express';
export { nextHandlers } from './next';
````

### src/rcms-tickets/server/next.ts

````ts
import type { Checkout } from './core';

/*
  Next.js (App Router): a catch-all route at app/api/tickets/[...path]/route.ts that exports GET, POST, PATCH and DELETE
  from nextHandlers(checkout), where `checkout` is made once in server/checkout.ts (see the Next recipe in manifest.json).
  A route handler already gets a standard Request, so there is nothing to convert. Nothing here needs Node, so the edge runtime works too.
*/

export function nextHandlers(checkout: Checkout) {
  const h = (req: Request) => checkout.handle(req);
  return { GET: h, POST: h, PATCH: h, DELETE: h };
}
````

### src/rcms-tickets/server/orderKey.ts

````ts
/*
  The Idempotency-Key of an order: the hold and a SHA-256 of the whole order body. The same order asked twice (a double tap, a
  retry after a timeout) is the same key and makes one order; anything corrected (another card, another answer) is a new key
  on purpose, because the API keeps a 4xx answer under its key for 24 hours. Hashed, so a buyer's details never sit in a header.
*/

export function canonicalJson(value: unknown): string {
  return JSON.stringify(value, (_k, v: unknown) => (v && typeof v === 'object' && !Array.isArray(v) ? Object.fromEntries(Object.entries(v as Record<string, unknown>).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) : v));
}

export async function orderKey(holdId: string, body: unknown): Promise<string> {
  const digest = await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(canonicalJson(body)));
  return `order-${holdId}-${[...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('')}`;
}
````

### src/rcms-tickets/server/payment.ts

````ts
import { PaymentFailure, RefundFailed, type ChargeContext, type ChargeStore, type OpenPayments, type PaymentOutcome, type ServerPayment } from './types';

const TEST_TOKENS = ['tok_success', 'tok_decline', 'tok_insufficient', 'tok_error', 'tok_dispute'];

/** The API's own test provider: a test key only. The "card" is a token the API's fake processor understands. */
export function testPayment(): ServerPayment {
  return {
    name: 'test',
    environment: 'test',
    async prepare(c: ChargeContext): Promise<PaymentOutcome> {
      if (c.api.mode !== 'test') throw new PaymentFailure('payment_failed', 'The test provider only works with a test key.');
      const token = c.payment.token;
      if (c.payment.provider !== 'test' || typeof token !== 'string' || !TEST_TOKENS.includes(token)) throw new PaymentFailure('payment_failed', 'That is not a test card.');
      return { payment: { provider: 'test', token } };
    },
  };
}

/**
 * Your own processor. Two ways, and on a live key it must be one of them.
 *
 * Better, if your processor can: authorize in `charge`, take the money in `capture` (called once the order exists), drop it in `void`,
 * and pass `open` so the sweep can finish a crash. Then a refused order costs no fee and needs no refund. See server/square.ts.
 * An authorize-first slot (one with `capture`) sends its payment `held`: the order is pending, with no tickets and no money counted, until the
 * capture lands and the kit tells the API. A capture that throws `PaymentFailure` can never land: the order is cancelled.
 *
 * Charge-first (the money is gone when `charge` returns): a crash or a lost answer after the charge is money with no order, and only you
 * can give it back. Say so with `chargeFirstAcknowledged: true`, and give a `store` you own: the kit writes each charge there, and the
 * sweep refunds any whose hold died with no order. `onError` hears `where: 'charged_no_order'` with the reference.
 *
 * Either way `charge` uses an idempotency key from the hold's id and the card's token, so a retry after a lost answer finds the same
 * payment. `refund` is required: an order can be refused after `charge`, and the money must never stay with nobody.
 */
export function externalPayment(o: {
  name?: string;
  environment?: ServerPayment['environment'];
  charge: (c: ChargeContext) => Promise<{ reference: string; method?: 'card' | 'cash' | 'card_reader' | 'bank_transfer' | 'other' }>;
  refund: (reference: string, why: string, c: Pick<ChargeContext, 'api' | 'hold'>) => Promise<void>;
  capture?: (reference: string, c: ChargeContext) => Promise<void>;
  void?: (reference: string, why: string, c: ChargeContext) => Promise<'voided' | 'refunded'>;
  open?: OpenPayments;
  chargeFirstAcknowledged?: boolean;
  store?: ChargeStore;
}): ServerPayment {
  if (typeof o.refund !== 'function') throw new TypeError('externalPayment needs refund: an order can be refused after the charge, and the money must go back.');
  if (o.chargeFirstAcknowledged && !o.store) throw new TypeError('chargeFirstAcknowledged needs a store: somewhere of yours that outlives a crash, or a charge with no order is forgotten.');
  const store = o.store;
  const refundFrom = async (reference: string, why: string, c: Pick<ChargeContext, 'api' | 'hold'>) => {
    try {
      await o.refund(reference, why, c);
    } catch (e) {
      throw new RefundFailed(e instanceof Error ? e.message : 'The refund failed.');
    }
    await store?.remove(reference);
  };
  const open: OpenPayments | undefined =
    o.open ??
    (store
      ? {
          list: async () => (await store.list()).map((r) => ({ reference: r.reference, hold: r.hold, status: 'open' as const })),
          // The money was taken at the charge: nothing left to do but stop watching it.
          capture: (reference) => store.remove(reference),
          void: (reference, c) => refundFrom(reference, 'No order was made for this charge', c),
        }
      : undefined);
  return {
    name: o.name ?? 'external',
    environment: o.environment,
    open,
    authorizeFirst: !!o.capture,
    async prepare(c) {
      const r = await o.charge(c);
      if (store) await store.put({ reference: r.reference, hold: c.hold.id });
      const chargeFirst = !o.capture;
      return {
        // Authorize-first (it has a `capture`): the money is only held until the order exists, so the order says so and waits for the kit's word that the capture landed.
        payment: { provider: 'external', reference: r.reference, amount: c.hold.price.total.amount, ...(r.method ? { method: r.method } : {}), ...(o.capture ? { held: true } : {}) },
        charged: chargeFirst,
        refund: (why: string) => o.refund(r.reference, why, c),
        ...(o.capture ? { capture: () => o.capture!(r.reference, c) } : store ? { capture: () => store.remove(r.reference) } : {}),
        ...(o.void ? { undo: (why: string) => o.void!(r.reference, why, c) } : store ? { undo: async (why: string) => (await refundFrom(r.reference, why, c), 'refunded' as const) } : {}),
      };
    },
  };
}
````

### src/rcms-tickets/server/phone.ts

````ts
/*
  A phone number as people type it, made E.164 (`+13135550100`), which is what the API stores. The browser has its own copy of
  this function (client/phone.ts) so each half stands alone. A bare 10-digit number is taken as the North American plan; anything
  else needs its country code. Null means "not a number we can use": ask again, never guess.
*/
const E164 = /^\+[1-9][0-9]{6,14}$/;

export function normalizePhone(raw: string): string | null {
  const t = raw.trim();
  if (/[^0-9+().\-\s]/.test(t)) return null;
  const digits = t.replace(/\D/g, '');
  const plus = t.startsWith('+');
  const out = plus ? `+${digits}` : digits.startsWith('00') ? `+${digits.slice(2)}` : digits.length === 10 ? `+1${digits}` : digits.length === 11 && digits.startsWith('1') ? `+${digits}` : '';
  return E164.test(out) ? out : null;
}
````

### src/rcms-tickets/server/serverFetch.ts

````ts
/*
  How a server calls an API over the internet, without one buyer's write waiting for another's (C-24).

  Node's built-in fetch is undici. From undici 8 (Node 26) it offers HTTP/2 by default, and Google's front end takes it, so on a warm connection
  every call to one origin shares that one connection. On it undici sends a request with a body only when nothing else is in flight: fetch always
  hands it the body as an async iterable, and undici's HTTP/2 `busy()` holds those back ("Request with stream or iterator body can error while
  other requests are inflight"). So per origin, on a warm connection, requests with a body run ONE AT A TIME, whatever their method, and anything
  sent behind one waits its turn. Requests with no body run together when none with a body is waiting. A cold burst opens many connections and
  does not stall. Measured, same API and same load, four buyers a second: 140 s a buyer with that fetch, 2.4 s with HTTP/1.1, and the API saw one
  request in flight the whole time. A site's on-sale would queue behind one connection, with no error and nothing in the API's logs.

  So where that fetch would do it, this speaks HTTP/1.1 through Node's own https module and a pool of kept-alive connections. Everywhere else it
  IS the platform's fetch: older Node (no HTTP/2 from fetch), Workers, Deno, Bun, a plain http:// address (no HTTP/2 without TLS).
  `process.getBuiltinModule` is the way in because it needs no import: a bundler and a runtime with no Node never see `node:https`. No dependency;
  no Node types, so it compiles in a project without them.

  Only the platform's own fetch is gone round: Node's (its source names `internal/deps/undici/undici`) or Next's patch of it (`__nextPatched`, whenever
  Next makes it: it patches inside the route's first run when it starts with no preload, as minimal mode does). Anything else on the global, a test's
  stub or a tracing wrapper, is called as given, in any order, so the worst a wrong guess can do is a stall with a warning, never a write to the real
  host. To keep a wrapper and lose the stall, wrap `http1Fetch` and pass that as the `fetch` option.

  Next's fetch cache: on the transport these calls never reach it. On the platform's road they say `cache: 'no-store'` unless the caller said how, or
  the page says `only-cache`, which would throw on it. KIT.md has which setting does what.

  Someone's network setup is honoured. NODE_USE_ENV_PROXY or --use-env-proxy: the pool goes through the proxy (`proxyEnv`). A global dispatcher that
  is not Node's plain default, in class, in options or behind a Proxy (ProxyAgent, MockAgent, `.compose()`, an Agent with a CA or a lookup), or
  `dispatcher` on a call: the platform's fetch, and with it the stall on Node 26.

  Only what the callers here send: a URL as a string, and a string or bytes as the body. Anything else goes to the platform's fetch.

  A write is never sent twice by this: a redirect answered to anything but GET or HEAD is a rejection that names it, and nothing more goes out. A
  connection that fails is an error, as with fetch, never a quiet resend (a stale kept-alive connection included): the callers retry with the same
  Idempotency-Key.

  packages/sdk/src/serverFetch.ts and packages/checkout/kit/server/serverFetch.ts are the same file (the kit depends on nothing of ours), and a test holds them equal.
*/

type NodeHeaders = Record<string, string>;

interface NodeAnswer {
  statusCode?: number;
  statusMessage?: string;
  rawHeaders: string[];
  complete: boolean;
  on(event: 'data', listener: (chunk: Uint8Array) => void): NodeAnswer;
  on(event: 'end' | 'close', listener: () => void): NodeAnswer;
  on(event: 'error', listener: (error: unknown) => void): NodeAnswer;
  resume(): unknown;
}

interface NodeSocket {
  connecting: boolean;
  encrypted?: boolean;
  once(event: 'connect' | 'secureConnect', listener: () => void): unknown;
}

interface NodeRequest {
  on(event: 'error', listener: (error: unknown) => void): NodeRequest;
  on(event: 'close', listener: () => void): NodeRequest;
  on(event: 'socket', listener: (socket: NodeSocket) => void): NodeRequest;
  end(body?: Uint8Array): unknown;
  destroy(error?: Error): unknown;
}

export interface NodeHttps {
  Agent: new (options: Record<string, unknown>) => unknown;
  request(url: URL, options: { method: string; headers: NodeHeaders; agent: unknown }, onAnswer: (answer: NodeAnswer) => void): NodeRequest;
}

interface NodeProcess {
  versions?: { undici?: string };
  env?: Record<string, string | undefined>;
  execArgv?: string[];
  getBuiltinModule?: (id: string) => unknown;
}

interface NodeTimersPromises {
  setImmediate(): Promise<unknown>;
}

const theProcess = (): NodeProcess | undefined => (globalThis as { process?: NodeProcess }).process;

/** The first undici whose fetch offers HTTP/2 by default (its `allowH2`). */
export const FIRST_UNDICI_WITH_H2 = 8;

/** Node's https, when this process's fetch would send writes one at a time. */
export function httpsWhereFetchQueues(proc: NodeProcess | undefined = theProcess()): NodeHttps | null {
  const major = Number(proc?.versions?.undici?.split('.')[0]);
  if (!(major >= FIRST_UNDICI_WITH_H2) || typeof proc?.getBuiltinModule !== 'function') return null;
  return (proc.getBuiltinModule('node:https') as NodeHttps | undefined) ?? null;
}

/** The switch Node reads for its own proxy support. */
function envProxyOn(proc: NodeProcess | undefined = theProcess()): boolean {
  return proc?.env?.NODE_USE_ENV_PROXY === '1' || Boolean(proc?.execArgv?.includes('--use-env-proxy')) || Boolean(proc?.env?.NODE_OPTIONS?.includes('--use-env-proxy'));
}

type Dispatcher = { constructor?: { name?: string } } & Record<symbol, unknown>;

/** Node's own default: an Agent by name, not behind a Proxy (`.compose()` is one), holding no option beyond the default. Anything else was set for a reason. */
function isPlainDefault(dispatcher: Dispatcher): boolean {
  const util = theProcess()?.getBuiltinModule?.('node:util') as { types?: { isProxy?: (v: unknown) => boolean } } | undefined;
  if (util?.types?.isProxy?.(dispatcher) !== false || dispatcher.constructor?.name !== 'Agent') return false;
  const held = Object.getOwnPropertySymbols(dispatcher).find((s) => s.description === 'options');
  const options = held ? (dispatcher[held] as Record<string, unknown> | undefined) : undefined;
  return Object.entries(options ?? {}).every(([name, value]) => name === 'maxOrigins' || value === undefined);
}

/**
  What is on undici's global, under any `undici.globalDispatcher.*` symbol: 'env' is Node's own for its proxy switch, 'own' is anything set for a reason, and
  'plain' is what Node makes. `Dispatcher1Wrapper` is undici's stand-in under an older symbol for the one under the newer. A bundled undici with another
  class name reads as 'own', the side that honours the site.
*/
export function globalDispatcherIs(): 'plain' | 'env' | 'own' {
  const global = globalThis as unknown as Record<symbol, Dispatcher | undefined>;
  const symbols = Object.getOwnPropertySymbols(globalThis).filter((s) => s.description?.startsWith('undici.globalDispatcher.'));
  let found: 'plain' | 'env' | 'own' = 'plain';
  for (const symbol of symbols) {
    const dispatcher = global[symbol];
    if (!dispatcher) continue;
    const name = dispatcher.constructor?.name;
    if (name === 'Dispatcher1Wrapper' || isPlainDefault(dispatcher)) continue;
    if (name !== 'EnvHttpProxyAgent' || !envProxyOn()) return 'own';
    found = 'env';
  }
  return found;
}

/** Statuses a Response may not carry a body with. fetch answers these with none. */
const NO_BODY_STATUS = new Set([204, 205, 304]);
const REDIRECT_STATUS = new Set([301, 302, 303, 307, 308]);
const MAX_REDIRECTS = 20;
const CUT_SHORT = 'the connection closed before the whole answer arrived';

/** What fetch gives a connection (10 s) and a silent server (300 s). A caller's signal usually ends a call long before either. */
export const DEFAULT_LIMITS = { connectMs: 10_000, idleMs: 300_000 };

/**
  How long an unused connection stays in the pool: undici's own default, and under the 5 s many servers close at. A server closing sooner with no
  hint can still lose the race now and then (docs/plan/lanes/C-24.md has the numbers), and the call fails plainly, never resent. A `Keep-Alive:
  timeout=` hint shortens it by itself (Node's Agent). The cost is a new connection after a quiet 4 s, which a busy on-sale never has.
*/
const IDLE_SOCKET_MS = 4_000;

function concat(chunks: readonly Uint8Array[]): Uint8Array {
  const out = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));
  let at = 0;
  for (const c of chunks) {
    out.set(c, at);
    at += c.length;
  }
  return out;
}

const agents = new WeakMap<object, { direct?: unknown; proxied?: unknown }>();

/**
  One pool per process: about 256 calls at once, kept open for the next call. Idle connections do not keep the process alive. Through a proxy, Node
  takes the wait for the proxy's CONNECT from the same `timeout`, so that pool has the connect limit and keeps an idle connection that long too.
*/
function agentOf(https: NodeHttps): unknown {
  const env = theProcess()?.env;
  const proxied = envProxyOn();
  const held = agents.get(https) ?? {};
  agents.set(https, held);
  const which = proxied ? 'proxied' : 'direct';
  return (held[which] ??= new https.Agent({ keepAlive: true, maxSockets: 256, maxFreeSockets: 64, scheduling: 'lifo', ...(proxied ? { timeout: DEFAULT_LIMITS.connectMs, proxyEnv: env } : { timeout: IDLE_SOCKET_MS }) }));
}

type Unzip = (bytes: Uint8Array, options: { maxOutputLength: number }, done: (error: unknown, out: Uint8Array) => void) => void;
/** No API answer here comes near this. It stops an answer built to unpack into all the memory there is. */
const MAX_DECODED_BYTES = 64 * 1024 * 1024;
/** fetch refuses a sixth. */
const MAX_CODINGS = 5;
const DECODERS: Record<string, string> = { gzip: 'gunzip', 'x-gzip': 'gunzip', br: 'brotliDecompress', deflate: 'inflate' };

/** We ask for no compression, and a server may send it anyway or the caller may have asked. A coding nobody knows stays as it is, as with fetch. */
async function decoded(bytes: Uint8Array, encoding: string | null): Promise<Uint8Array> {
  if (!encoding || !bytes.length) return bytes;
  const codings = encoding.toLowerCase().split(',').map((c) => c.trim()).filter((c) => c && c !== 'identity').reverse();
  if (!codings.length || !codings.every((c) => DECODERS[c])) return bytes;
  if (codings.length > MAX_CODINGS) throw new TypeError('too many content codings on the answer');
  const zlib = theProcess()?.getBuiltinModule?.('node:zlib') as Record<string, Unzip> | undefined;
  let out = bytes;
  for (const coding of codings) {
    const unzip = zlib?.[DECODERS[coding]];
    if (!unzip) throw new Error('this runtime cannot decompress the answer');
    out = await new Promise<Uint8Array>((resolve, reject) => unzip(out, { maxOutputLength: MAX_DECODED_BYTES }, (error, plain) => (error ? reject(error) : resolve(plain))));
  }
  return out;
}

/** A Response as fetch makes one. Its constructor refuses statuses outside 200 to 599 and fetch answers them, so those carry the status beside it. */
function answerOf(status: number, statusText: string, bytes: Uint8Array | null, headers: Headers, url: string, redirected: boolean): Response {
  const inRange = status >= 200 && status <= 599;
  const response = new Response(bytes as unknown as ConstructorParameters<typeof Response>[0], { status: inRange ? status : 200, statusText, headers });
  Object.defineProperties(response, {
    url: { value: url.split('#')[0] },
    redirected: { value: redirected },
    type: { value: 'basic' },
    ...(inRange ? {} : { status: { value: status }, ok: { value: false } }),
  });
  return response;
}

function abortReason(signal: AbortSignal): unknown {
  return signal.reason ?? new DOMException('This operation was aborted', 'AbortError');
}

function headersFor(init: RequestInit, body: Uint8Array | undefined): NodeHeaders {
  const headers: NodeHeaders = {};
  new Headers(init.headers).forEach((value, name) => {
    headers[name] = value;
  });
  // What fetch sends when nobody says: the API's request log files a caller under user-agent.
  headers['user-agent'] ??= 'node';
  headers.accept ??= '*/*';
  headers['accept-encoding'] ??= 'identity';
  if (typeof init.body === 'string') headers['content-type'] ??= 'text/plain;charset=UTF-8';
  if (body) headers['content-length'] = String(body.length);
  return headers;
}

/** The headers a redirect may take to another origin: never a key, as fetch. */
function withoutSecrets(init: RequestInit): RequestInit['headers'] {
  const kept = new Headers(init.headers);
  for (const name of ['authorization', 'proxy-authorization', 'cookie', 'host']) kept.delete(name);
  return kept;
}

/** One call over HTTP/1.1, answered as fetch answers: a Response, or a rejection when there is no whole answer. It always settles, and nothing it does can throw on the socket. */
export function fetchOverHttp1(https: NodeHttps, url: string, init: RequestInit, limits: typeof DEFAULT_LIMITS = DEFAULT_LIMITS): Promise<Response> {
  // A turn of the event loop first, as fetch takes one: a connection the far end closed while this process was stopped has its close waiting to be read,
  // and this call would otherwise pick it and fail. Through node:timers/promises, not the global, which a test's fake timers hold back for ever.
  const timers = theProcess()?.getBuiltinModule?.('node:timers/promises') as NodeTimersPromises | undefined;
  return (timers ? timers.setImmediate() : Promise.resolve()).then(() => call(https, new URL(url), init, limits, 0));
}

function call(https: NodeHttps, target: URL, init: RequestInit, limits: typeof DEFAULT_LIMITS, hops: number): Promise<Response> {
  return new Promise<Response>((resolve, reject) => {
    const signal = init.signal ?? undefined;
    if (signal?.aborted) return reject(abortReason(signal));
    const method = (init.method ?? 'GET').toUpperCase();
    const readOnly = method === 'GET' || method === 'HEAD';
    const body = typeof init.body === 'string' ? new TextEncoder().encode(init.body) : (init.body as Uint8Array | null | undefined) ?? undefined;
    if (readOnly && body) return reject(new TypeError('Request with GET/HEAD method cannot have body.'));

    let settled = false;
    let timer: ReturnType<typeof setTimeout> | undefined;
    const finish = () => {
      settled = true;
      if (timer !== undefined) clearTimeout(timer);
      signal?.removeEventListener('abort', onAbort);
    };
    const fail = (error: unknown) => {
      if (settled) return;
      finish();
      reject(error);
    };
    /** Settled, and the socket let go: its later errors land on listeners that do nothing. */
    const giveUp = (error: unknown) => {
      fail(error);
      request.destroy();
    };
    const onAbort = () => giveUp(abortReason(signal as AbortSignal));
    /** No word from the far end for this long ends the call. It runs only while a call has a socket: waiting behind 256 others is not a silent server. */
    const quietLimit = (ms: number, what: string) => {
      if (timer !== undefined) clearTimeout(timer);
      if (settled) return;
      timer = setTimeout(() => giveUp(Object.assign(new Error(`${what} after ${ms} ms`), { code: 'ETIMEDOUT' })), ms);
      (timer as unknown as { unref?: () => void }).unref?.();
    };

    let answered = false;
    const request = https.request(target, { method, headers: headersFor(init, body), agent: agentOf(https) }, (answer) => {
      answered = true;
      const chunks: Uint8Array[] = [];
      let ended = false;
      answer.on('error', fail);
      answer.on('close', () => {
        if (!ended) fail(new Error(CUT_SHORT));
      });
      try {
        const status = answer.statusCode ?? 0;
        // fetch refuses these, and they could never be a Response: 099, a 101 nobody asked for.
        if (status < 200) throw new TypeError(`the server answered with status ${status}, which is not an answer`);
        const headers = new Headers();
        const raw = answer.rawHeaders;
        for (let i = 0; i + 1 < raw.length; i += 2) headers.append(raw[i], raw[i + 1]);

        const redirected = REDIRECT_STATUS.has(status) && init.redirect !== 'manual';
        // `fail` then let go of the socket: an answer that never ends must not keep it.
        if (redirected && init.redirect === 'error') {
          ended = true;
          return giveUp(new TypeError(`the server answered with a redirect (${status}), and this call says not to follow one`));
        }
        const location = redirected ? headers.get('location') : null;
        if (location !== null) {
          ended = true;
          // The write went out once. Sending it again is the caller's to decide, with its own key.
          if (!readOnly) return giveUp(new TypeError(`the server answered ${method} with a redirect (${status}). It was not sent on, so it went out once.`));
          if (hops >= MAX_REDIRECTS) return giveUp(new TypeError('too many redirects'));
          const next = new URL(location, target);
          const onward: RequestInit = next.origin === target.origin ? init : { ...init, headers: withoutSecrets(init) };
          if (next.protocol !== 'http:' && next.protocol !== 'https:') return giveUp(new TypeError(`a redirect to ${next.protocol} is not followed`));
          finish();
          request.destroy();
          resolve(next.protocol === target.protocol ? call(https, next, onward, limits, hops + 1) : globalThis.fetch(next.href, onward));
          return;
        }

        quietLimit(limits.idleMs, 'the answer stopped');
        answer.on('data', (chunk) => {
          chunks.push(chunk);
          quietLimit(limits.idleMs, 'the answer stopped');
        });
        answer.on('end', () => {
          ended = true;
          if (!answer.complete) return fail(new Error(CUT_SHORT));
          if (timer !== undefined) clearTimeout(timer);
          const none = NO_BODY_STATUS.has(status);
          decoded(none ? new Uint8Array() : concat(chunks), method === 'HEAD' ? null : headers.get('content-encoding'))
            .then((bytes) => answerOf(status, answer.statusMessage ?? '', none ? null : bytes, headers, target.href, hops > 0))
            .then((response) => {
              if (settled) return;
              finish();
              resolve(response);
            }, fail);
        });
      } catch (error) {
        ended = true;
        giveUp(error);
      }
    });
    request.on('error', fail);
    request.on('close', () => {
      if (!answered) fail(new Error(CUT_SHORT));
    });
    request.on('socket', (socket) => {
      if (settled) return;
      if (!socket.connecting) return quietLimit(limits.idleMs, 'the server said nothing');
      quietLimit(limits.connectMs, 'could not connect');
      socket.once(socket.encrypted ? 'secureConnect' : 'connect', () => quietLimit(limits.idleMs, 'the server said nothing'));
    });
    signal?.addEventListener('abort', onAbort, { once: true });
    request.end(body);
  });
}

/** Node's fetch, by its own source. A stub, a wrapper or `.bind()` doesn't say this. */
const isNodesOwn = (f: unknown): boolean => {
  try {
    return Function.prototype.toString.call(f).includes('internal/deps/undici/undici');
  } catch {
    return false;
  }
};

/** The transport for this call, when the call is one it takes and nobody's network setup says otherwise. */
function transportFor(input: Parameters<typeof fetch>[0], init: RequestInit | undefined): NodeHttps | null {
  const body = init?.body;
  if (typeof input !== 'string' || !input.startsWith('https://')) return null;
  if (body !== undefined && body !== null && typeof body !== 'string' && !(body instanceof Uint8Array)) return null;
  if ((init as { dispatcher?: unknown } | undefined)?.dispatcher || globalDispatcherIs() === 'own') return null;
  return httpsWhereFetchQueues();
}

/**
  The transport itself, whatever is on the global: wrap this to keep a tracing wrapper and lose the stall.
  `createCheckout({ fetch: (url, init) => traced(() => http1Fetch(url, init)) })`. Elsewhere it is the global's fetch.
*/
export const http1Fetch: typeof fetch = (input, init) => {
  const https = transportFor(input, init);
  return https ? fetchOverHttp1(https, input as string, init ?? {}) : globalThis.fetch(input, init);
};

let warned = false;

/** Next's cache is for pages. This is an API call: never kept, unless the caller said how, or the page's `only-cache`, which would throw on `no-store`. */
function notKeptByNext(current: typeof fetch, init: RequestInit | undefined): RequestInit | undefined {
  if ((init as { cache?: unknown; next?: unknown } | undefined)?.cache || (init as { next?: unknown } | undefined)?.next) return init;
  const store = (current as unknown as { __nextGetStaticStore?: () => { getStore?: () => { fetchCache?: string } | undefined } | undefined }).__nextGetStaticStore?.()?.getStore?.();
  return store?.fetchCache === 'only-cache' ? init : ({ ...init, cache: 'no-store' } as RequestInit);
}

/** Use it as `fetch`. See the top of this file for what it does and when. */
export const serverFetch: typeof fetch = (input, init) => {
  const current = globalThis.fetch;
  const next = (current as { __nextPatched?: unknown }).__nextPatched === true;
  if (next || isNodesOwn(current)) {
    const https = transportFor(input, init);
    if (https) return fetchOverHttp1(https, input as string, init ?? {});
    return next ? current(input, notKeptByNext(current, init)) : current(input, init);
  }
  if (!warned && transportFor(input, init)) {
    warned = true;
    console.warn('RCMS Tickets: globalThis.fetch is not Node\'s own, so it is called as given. On Node 26 that fetch sends requests with a body one at a time per origin, and a busy on-sale will queue. To keep your wrapper and lose the stall, wrap http1Fetch and pass it as the `fetch` option. See KIT.md, "Node 26 and your own fetch".');
  }
  return current(input, init);
};
````

### src/rcms-tickets/server/square.ts

````ts
import { externalPayment } from './payment';
import { serverFetch } from './serverFetch';
import { PaymentFailure, PaymentRefunded, RefundFailed, type OpenPayment, type ServerPayment } from './types';

/*
  Square, the recipe's server half (the browser half is client/square.tsx). REST, no SDK to install. It uses Square's delayed
  capture (https://developer.squareup.com/docs/payments-api/take-payments/card-payments/delayed-capture):

    1. Authorize: POST /v2/payments with autocomplete false, a delay_duration and delay_action CANCEL. The card is held, not charged.
    2. The order: the kit makes it, with an `external` payment whose reference is this payment's id, sent `held: true`: the order is PENDING
       (no tickets, no money counted) because the money is only authorized.
    3. Capture: POST /v2/payments/{id}/complete, only after the order exists. Then the kit tells the API (`external_payment`, captured) and the
       order becomes paid and its tickets issue.

  So a refused order or a crash before step 3 costs no fee and needs no refund: the authorization is voided, or Square drops it by
  itself when the delay runs out.

  What it guarantees:
   - the amount is the HOLD's total, read here from our API, never a number the browser sent;
   - the idempotency key is hold + card token, so a retry of the same press is the same payment, and a new card after a decline is
     a new attempt (Square refuses a key reused with a changed request);
   - only the payment named on the order is ever captured, and a hold makes one order, so two presses can never be two charges;
   - any answer other than a 2xx with the thing asked for throws: nothing is reported done that was not.

  THE GAP BETWEEN THE ORDER AND THE CAPTURE. A crash there leaves a PENDING order (nothing paid, no tickets) whose money is only
  authorized. Three things close it, each safe to repeat: the same request retried (a consumed hold captures its order's payment), the
  `order.paid` / `order.created` webhooks, and `checkout.sweep()` on a schedule. Live, createCheckout refuses to start without a sweep
  secret and an onError. The delay (3 days by default) is longer than the webhook's whole retry schedule, so a capture is not lost to a
  short outage. If Square ever cancels it while the order waits, the kit tells the API the payment is lost: the order is cancelled once
  (no ticket was ever out), the owners get a mail naming it, and onError hears 'capture_lost'. Before a capture of an order that has waited, the kit asks the API
  whether to (`may_capture`): a cancelled event or a buyer who bought again means a void, never a charge.

  Sandbox: baseUrl https://connect.squareupsandbox.com, with a sandbox access token and location id.
*/

export interface SquareConfig {
  accessToken: string;
  locationId: string;
  /** "https://connect.squareup.com" (default, real money) or "https://connect.squareupsandbox.com". */
  baseUrl?: string;
  /** Square-Version header. Pin the version you tested with. */
  version?: string;
  fetch?: typeof fetch;
  /** Each call to Square gives up after this long, in ms. Default 15000. */
  timeoutMs?: number;
  /** How long Square keeps an authorization before cancelling it, as Square writes it. Default "P3D". */
  delayDuration?: string;
  /** How long the list of open payments is shared between webhooks, in ms. Default 60000. The sweep always reads fresh. */
  listCacheMs?: number;
}

const SQUARE_BASE = 'https://connect.squareup.com';
const HOSTS: Record<string, 'production' | 'sandbox'> = { 'connect.squareup.com': 'production', 'connect.squareupsandbox.com': 'sandbox' };
const HOLD_ID = /^hold_[A-Za-z0-9_]{3,64}$/;
/** Longer than the delay, so the sweep sees everything still open. */
const SWEEP_DAYS = 8;

const base64url = (bytes: ArrayBuffer): string => btoa(String.fromCharCode(...new Uint8Array(bytes))).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
const hash = async (s: string): Promise<string> => base64url(await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(s)));

/** Square allows idempotency keys of at most 45 characters: the hold and the card's token, hashed. A new card is a new key. */
export async function squareKey(holdId: string, sourceId: string): Promise<string> {
  return `p-${await hash(`${holdId}|${sourceId}`)}`;
}

interface SquareError {
  category?: string;
  code?: string;
  detail?: string;
}

interface SquarePayment {
  id: string;
  status: string;
  amount_money?: { amount: number; currency: string };
  /** What has gone back. A refunded payment stays COMPLETED: this is the only place it shows (Square's docs; not yet proved on the sandbox). */
  refunded_money?: { amount: number; currency: string };
  reference_id?: string;
  created_at?: string;
}

interface SquareAnswer {
  ok: boolean;
  status: number;
  /** The answer was lost: a network failure or a timeout. The call may still have happened. */
  lost: boolean;
  json: { payment?: SquarePayment; payments?: SquarePayment[]; cursor?: string; refund?: { id: string; status: string }; errors?: SquareError[] };
}

/** Square's decline codes, as the API names its own (the browser has words for these). */
const DECLINE: Record<string, string> = {
  INSUFFICIENT_FUNDS: 'insufficient_funds',
  CARD_EXPIRED: 'expired_card',
  INVALID_EXPIRATION: 'expired_card',
  CVV_FAILURE: 'incorrect_cvc',
  CARD_DECLINED: 'card_declined',
  GENERIC_DECLINE: 'card_declined',
  TRANSACTION_LIMIT: 'card_declined',
  VERIFY_CVV_FAILURE: 'incorrect_cvc',
  ADDRESS_VERIFICATION_FAILURE: 'card_declined',
  PAN_FAILURE: 'card_declined',
};

export function squarePayment(c: SquareConfig): ServerPayment {
  const f = c.fetch ?? serverFetch;
  const base = (c.baseUrl ?? SQUARE_BASE).replace(/\/+$/, '');
  const environment = HOSTS[base.replace(/^https:\/\//, '')];
  if (!environment) throw new TypeError('baseUrl must be https://connect.squareup.com or https://connect.squareupsandbox.com');
  const timeoutMs = c.timeoutMs ?? 15_000;

  const call = async (method: 'GET' | 'POST', path: string, body?: unknown): Promise<SquareAnswer> => {
    const abort = new AbortController();
    let timer: ReturnType<typeof setTimeout> | undefined;
    const late = new Promise<never>((_, reject) => {
      timer = setTimeout(() => {
        abort.abort();
        reject(new Error('timed out'));
      }, timeoutMs);
    });
    try {
      return await Promise.race([
        late,
        (async (): Promise<SquareAnswer> => {
          const res = await f(`${base}${path}`, { method, signal: abort.signal, headers: { authorization: `Bearer ${c.accessToken}`, 'square-version': c.version ?? '2025-01-23', ...(body === undefined ? {} : { 'content-type': 'application/json' }) }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
          const text = await res.text();
          let json = {};
          try {
            json = text ? JSON.parse(text) : {};
          } catch {
            /* not json: `ok` below still says what the status says, and the fields are missing */
          }
          return { ok: res.ok, status: res.status, lost: false, json };
        })(),
      ]);
    } catch {
      return { ok: false, status: 0, lost: true, json: {} };
    } finally {
      if (timer) clearTimeout(timer);
    }
  };

  const read = async (id: string): Promise<SquarePayment> => {
    const r = await call('GET', `/v2/payments/${encodeURIComponent(id)}`);
    if (!r.ok || !r.json.payment) throw new Error(`Square did not answer for the payment (${r.status}).`);
    return r.json.payment;
  };

  const capture = async (id: string): Promise<void> => {
    let last = 0;
    for (let attempt = 0; attempt < 2; attempt++) {
      const r = await call('POST', `/v2/payments/${encodeURIComponent(id)}/complete`, {});
      if (r.ok && r.json.payment?.status === 'COMPLETED') return;
      last = r.status;
      // Not a clear yes (the answer was lost, or it was completed already): ask what happened. COMPLETED with money gone back is no yes: it must make no tickets.
      const now = await read(id).catch(() => null);
      if (now?.status === 'COMPLETED' && (now.refunded_money?.amount ?? 0) > 0) throw new PaymentRefunded('The payment was taken and refunded.');
      if (now?.status === 'COMPLETED') return;
      if (now?.status === 'CANCELED' || now?.status === 'FAILED') throw new PaymentFailure('payment_failed', `The payment is ${now.status} and can never be taken.`);
    }
    throw new Error(`Square did not capture the payment (${last}).`);
  };

  const refund = async (id: string, amount: { amount: number; currency: string }, why: string): Promise<void> => {
    const r = await call('POST', '/v2/refunds', { idempotency_key: `r-${await hash(id)}`, payment_id: id, amount_money: amount, reason: why.slice(0, 190) });
    if (!r.ok || !r.json.refund || r.json.refund.status === 'REJECTED' || r.json.refund.status === 'FAILED') throw new RefundFailed(`Square refused the refund (${r.status}).`);
  };

  const dropPayment = async (id: string, why: string, amount?: { amount: number; currency: string }): Promise<'voided' | 'refunded'> => {
    const now = await read(id);
    if (now.status === 'CANCELED' || now.status === 'FAILED') return 'voided';
    if (now.status === 'COMPLETED') {
      const money = amount ?? now.amount_money;
      if (!money) throw new Error('Square did not say what the payment was for.');
      await refund(id, money, why);
      return 'refunded';
    }
    const r = await call('POST', `/v2/payments/${encodeURIComponent(id)}/cancel`, {});
    if (r.ok && r.json.payment?.status === 'CANCELED') return 'voided';
    const after = await read(id);
    if (after.status === 'CANCELED') return 'voided';
    throw new Error(`Square did not cancel the payment (${r.status}).`);
  };

  let cache: { at: number; rows: OpenPayment[] } | null = null;
  const inner = externalPayment({
    name: 'square',
    environment,
    async charge({ hold, payment, buyer }) {
      const source = payment.source_id;
      if (payment.provider !== 'square' || typeof source !== 'string' || !source) throw new PaymentFailure('payment_failed', 'Card details are missing.');
      const money = { amount: hold.price.total.amount, currency: hold.price.total.currency.toUpperCase() };
      const key = await squareKey(hold.id, source);
      const r = await call('POST', '/v2/payments', {
        idempotency_key: key,
        source_id: source,
        location_id: c.locationId,
        amount_money: money,
        buyer_email_address: buyer.email,
        reference_id: hold.id.slice(0, 40),
        note: `Tickets ${hold.id}`.slice(0, 500),
        autocomplete: false,
        delay_duration: c.delayDuration ?? 'P3D',
        delay_action: 'CANCEL',
      });
      if (r.lost || r.status >= 500) {
        // We do not know if it went through. Square's answer to that is to cancel by the key, and only then may we say nothing was taken.
        const undone = await call('POST', '/v2/payments/cancel', { idempotency_key: key });
        if (undone.ok) throw new PaymentFailure('provider_unavailable', 'Square is not answering.');
        throw new PaymentFailure('payment_unconfirmed', 'Square did not answer and the attempt could not be cancelled yet.');
      }
      const p = r.json.payment;
      if (r.ok && p && (p.status === 'APPROVED' || p.status === 'COMPLETED')) {
        // Square answers with what it holds: anything but the hold's total is wrong, and nothing is made from it.
        if (p.amount_money?.amount !== money.amount || p.amount_money?.currency !== money.currency) {
          await dropPayment(p.id, 'Amount did not match the order').catch(() => undefined);
          throw new PaymentFailure('payment_unconfirmed', 'Square answered with a different amount.');
        }
        return { reference: p.id, method: 'card' };
      }
      const err = r.json.errors?.[0];
      if (err?.category === 'PAYMENT_METHOD_ERROR') throw new PaymentFailure('payment_declined', 'The card was declined.', DECLINE[err.code ?? ''] ?? 'card_declined');
      if (err?.category === 'API_ERROR' || err?.category === 'RATE_LIMIT_ERROR') throw new PaymentFailure('provider_unavailable', 'Square is not answering.');
      // A refusal, no payment made (a used token, a reused key, a bad request).
      throw new PaymentFailure('payment_failed', 'The payment could not be taken.');
    },
    capture: (reference) => capture(reference),
    void: (reference, why, { hold }) => dropPayment(reference, why, { amount: hold.price.total.amount, currency: hold.price.total.currency.toUpperCase() }),
    refund: (reference, why, { hold }) => refund(reference, { amount: hold.price.total.amount, currency: hold.price.total.currency.toUpperCase() }, why),
    open: {
      async list(o = {}) {
        const now = Date.now();
        if (!o.fresh && cache && now - cache.at < (c.listCacheMs ?? 60_000)) return cache.rows;
        const rows: OpenPayment[] = [];
        let cursor: string | undefined;
        // Oldest first: the ones nearest Square's own cancel are the ones that must not fall off the end at a busy location.
        const since = new Date(now - SWEEP_DAYS * 86_400_000).toISOString();
        for (let page = 0; page < 50; page++) {
          const q = new URLSearchParams({ begin_time: since, location_id: c.locationId, sort_order: 'ASC', limit: '100', ...(cursor ? { cursor } : {}) });
          const r = await call('GET', `/v2/payments?${q}`);
          if (!r.ok) throw new Error(`Square did not list the payments (${r.status}).`);
          for (const p of r.json.payments ?? []) {
            if (!p.reference_id || !HOLD_ID.test(p.reference_id)) continue;
            if (p.status === 'APPROVED') rows.push({ reference: p.id, hold: p.reference_id, status: 'open', created_at: p.created_at });
            else if (p.status === 'CANCELED' || p.status === 'FAILED') rows.push({ reference: p.id, hold: p.reference_id, status: 'dropped', created_at: p.created_at });
          }
          cursor = r.json.cursor;
          if (!cursor) break;
        }
        cache = { at: now, rows };
        return rows;
      },
      capture,
      state: async (reference) => {
        const p = await read(reference).catch(() => null);
        if (p?.status === 'COMPLETED' && (p.refunded_money?.amount ?? 0) > 0) return 'refunded';
        return p?.status === 'COMPLETED' ? 'taken' : p?.status === 'APPROVED' ? 'open' : p?.status === 'CANCELED' || p?.status === 'FAILED' ? 'dropped' : 'unknown';
      },
      // Never a refund from here: this runs on what a list and an order said. Money already captured is a person's call.
      void: async (reference) => {
        const now = await read(reference);
        if (now.status === 'APPROVED') await dropPayment(reference, 'The order was not made');
      },
    },
  });
  return inner;
}
````

### src/rcms-tickets/server/types.ts

````ts
import type { Api } from './api';

/** The parts of the API's objects the handlers read. The rest passes through untouched. */
export interface Money {
  amount: number;
  currency: string;
}

export interface ApiHold {
  id: string;
  mode: 'test' | 'live';
  event: string;
  status: 'active' | 'consumed' | 'released' | 'expired';
  items: Array<{ kind: string; ticket_type: string | null; add_on: string | null; name: string; quantity: number; tickets_per_unit?: number; for_ticket_type: string | null }>;
  code: string | null;
  price: { total: Money; currency: string; [k: string]: unknown };
  email: string | null;
  expires_at: string;
  extended: boolean;
  order: string | null;
  [k: string]: unknown;
}

export interface ChargeContext {
  api: Api;
  hold: ApiHold;
  /** What the browser sent as the payment: the slot's payload (a test token, a Square source id, ...). */
  payment: Record<string, unknown>;
  buyer: { name: string; email: string };
}

/** What a payment method hands the order: the API's `payment` input. */
export type OrderPayment =
  | { provider: 'test'; token: string }
  | {
      provider: 'external';
      reference: string;
      amount: number;
      method?: 'card' | 'cash' | 'card_reader' | 'bank_transfer' | 'other';
      /** The processor only HOLDS this money: the order is pending, with no tickets and no money counted, until the kit tells the API the capture landed (or was lost). */
      held?: boolean;
    };

export interface PaymentOutcome {
  payment: OrderPayment;
  /** The money is only authorized so far: take it. Called once the order exists. Throw PaymentFailure if it can never be taken. */
  capture?: () => Promise<void>;
  /** Drop what `prepare` did because the order was refused: voids an authorization (no fee), or refunds if the money was taken. Says which. */
  undo?: (why: string) => Promise<'voided' | 'refunded'>;
  /** Give the money back. */
  refund?: (why: string) => Promise<void>;
  /** The money is already taken (charge-first), so an order we can't confirm is money with no order. */
  charged?: boolean;
}

/** An authorization not yet captured or voided, as the processor lists it. */
export interface OpenPayment {
  reference: string;
  hold: string;
  /** 'dropped': the processor ended it by itself (cancelled, failed). Left out, it is still open. */
  status?: 'open' | 'dropped';
  created_at?: string;
}

/**
 * What lets the kit finish a payment that a crash left half done: list the open authorizations, capture one, void one. It is
 * what `checkout.sweep()` and the webhook use. A processor that authorizes first (Square here) has it.
 */
export interface OpenPayments {
  /** `fresh`: a list that may be a minute old will not do. */
  list(o?: { fresh?: boolean }): Promise<OpenPayment[]>;
  capture(reference: string): Promise<void>;
  /**
   * What the processor holds for this payment now: 'taken' (captured), 'refunded' (captured, and money went back: it must not make tickets), 'open' (an authorization), 'dropped' (cancelled or failed) or 'unknown'.
   * Optional, and a live slot should have it: the sweep uses it to finish an order whose money was taken and whose word to the API got lost, and to find money taken for an order a person cancelled.
   */
  state?(reference: string): Promise<'taken' | 'refunded' | 'open' | 'dropped' | 'unknown'>;
  /** Drop what was not captured. Never takes money back from a payment already captured for a live order: that is a person's call. */
  void(reference: string, c: { api: Api; hold: ApiHold }): Promise<void>;
}

/**
 * Where a charge-first processor keeps what it charged, until the order that goes with it is known. Yours, and durable: a table, a
 * key-value store. It is what lets the sweep refund a charge whose order never came.
 */
export interface ChargeStore {
  put(row: { reference: string; hold: string }): Promise<void>;
  list(): Promise<Array<{ reference: string; hold: string }>>;
  remove(reference: string): Promise<void>;
}

/** One way of taking money. `test` is built in; `square` is the recipe; write your own for another processor. */
export interface ServerPayment {
  name: string;
  /** Whose money it moves. `createCheckout` refuses a test key with production money and a live key with anything else. */
  environment?: 'test' | 'sandbox' | 'production';
  /** Authorizes or takes the money (or, for the test provider, just maps the token) and says how the order is paid. Throws a PaymentFailure for a decline. */
  prepare(c: ChargeContext): Promise<PaymentOutcome>;
  open?: OpenPayments;
  /** It authorizes, and takes the money after the order exists. Then `open.state` matters: createCheckout says so at startup if it is missing. */
  authorizeFirst?: boolean;
}

/**
 * A payment that was refused, in the shape the browser understands (a 402 with the API's own error codes).
 * `payment_declined`, `payment_failed` and `provider_unavailable` promise the buyer has not been charged, so throw them only when
 * that is true. `payment_unconfirmed` is the other case: a call that may have gone through and could not be undone (a 503).
 */
export class PaymentFailure extends Error {
  readonly code: 'payment_declined' | 'payment_failed' | 'provider_unavailable' | 'payment_unconfirmed';
  readonly decline_code: string | null;
  constructor(code: PaymentFailure['code'], message: string, decline_code: string | null = null) {
    super(message);
    this.name = 'PaymentFailure';
    this.code = code;
    this.decline_code = decline_code;
  }
}

/** Money was taken and could not be given back: a person must look. Throw it from a processor's refund. */
export class RefundFailed extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'RefundFailed';
  }
}

/** The processor took this money and some of it has gone back. Throw it from a capture that finds that: it is neither taken (no tickets) nor lost (the card was charged). */
export class PaymentRefunded extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'PaymentRefunded';
  }
}

/** Money that needs a person, as `onError` hears it (where 'charged_no_order', 'capture_lost', 'capture_refused'). */
export class PaymentProblem extends Error {
  readonly order?: string;
  readonly hold?: string;
  readonly reference?: string;
  constructor(message: string, o: { order?: string; hold?: string; reference?: string }) {
    super(message);
    this.name = 'PaymentProblem';
    this.order = o.order;
    this.hold = o.hold;
    this.reference = o.reference;
  }
}
````

### src/rcms-tickets/server/version.ts

````ts
/*
  The kit's version. It goes out as the `rcms-tickets-kit` header on every call to the RCMS Tickets API, which is how an org on a
  version with a known problem can be found and told, and `tools/kit.mjs` compares it when you update. Leave it as it is:
  it says what code you started from, even after you change the code.
*/
export const KIT_VERSION = '0.3.13';
````

### src/rcms-tickets/server/webhook.ts

````ts
/*
  Webhooks, the Standard Webhooks way: the body is signed as `<webhook-id>.<webhook-timestamp>.<raw body>` with HMAC-SHA256
  keyed by the endpoint secret's bytes (the base64 after `whsec_`), sent as `v1,<base64>`. Verify the RAW body, exactly as
  received: a parsed and re-written body no longer matches. Web Crypto only, so it runs on Node, edge runtimes and Workers.
*/

export interface WebhookEvent {
  object: 'event_log_entry';
  id: string;
  type: string;
  created_at: string;
  event: string | null;
  data: { object: Record<string, unknown> & { object: string; id: string }; previous_attributes: Record<string, unknown> | null };
}

export class WebhookError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'WebhookError';
  }
}

// Named from the crypto calls themselves, not from the DOM's CryptoKey and BufferSource: a server project (Node types, no DOM lib) has neither.
type Key = Awaited<ReturnType<typeof globalThis.crypto.subtle.importKey>>;
type Bytes = Parameters<typeof globalThis.crypto.subtle.verify>[2];
const enc = new TextEncoder();

function fromBase64(s: string): Uint8Array {
  const bin = atob(s);
  const out = new Uint8Array(bin.length);
  for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
  return out;
}

export interface VerifyOptions {
  payload: string | Uint8Array;
  headers: Headers | Record<string, string | string[] | undefined>;
  /** `whsec_…`. Pass the old and the new while a secret is being rolled. */
  secret: string | readonly string[];
  /** Seconds either side of now a delivery may be stamped. Default 300. */
  toleranceSeconds?: number;
  now?: () => number;
}

function header(h: VerifyOptions['headers'], name: string): string | null {
  if (typeof (h as Headers).get === 'function') return (h as Headers).get(name);
  for (const [k, v] of Object.entries(h as Record<string, string | string[] | undefined>)) if (k.toLowerCase() === name) return Array.isArray(v) ? (v[0] ?? null) : (v ?? null);
  return null;
}

export async function verifyWebhook(o: VerifyOptions): Promise<WebhookEvent> {
  if (typeof o.payload !== 'string' && !(o.payload instanceof Uint8Array)) throw new WebhookError('The webhook body must be the raw bytes. Mount the kit before any JSON body parser (express.json, for example).');
  const secrets = (typeof o.secret === 'string' ? [o.secret] : [...o.secret]).filter((s) => typeof s === 'string' && s !== '');
  if (!secrets.length) throw new WebhookError('No signing secret. Is RCMS_TICKETS_WEBHOOK_SECRET set?');
  const id = header(o.headers, 'webhook-id');
  const ts = header(o.headers, 'webhook-timestamp');
  const sigs = header(o.headers, 'webhook-signature');
  if (!id || !ts || !sigs) throw new WebhookError('Missing webhook headers');
  const stamp = Number(ts);
  if (!Number.isInteger(stamp)) throw new WebhookError('Bad webhook-timestamp');
  const nowS = o.now ? o.now() : Math.floor(Date.now() / 1000);
  if (Math.abs(nowS - stamp) > (o.toleranceSeconds ?? 300)) throw new WebhookError('Timestamp outside the tolerance');
  const body = typeof o.payload === 'string' ? enc.encode(o.payload) : o.payload;
  const head = enc.encode(`${id}.${ts}.`);
  const data = new Uint8Array(head.length + body.length);
  data.set(head, 0);
  data.set(body, head.length);
  let matched = false;
  for (const secret of secrets) {
    let key: Key;
    try {
      key = await globalThis.crypto.subtle.importKey('raw', fromBase64((secret.startsWith('whsec_') ? secret.slice(6) : secret).trim()) as Bytes, { name: 'HMAC', hash: 'SHA-256' }, false, ['verify']);
    } catch {
      continue;
    }
    for (const part of sigs.split(' ')) {
      const [version, value] = part.split(',');
      if (version !== 'v1' || !value) continue;
      try {
        if (await globalThis.crypto.subtle.verify('HMAC', key, fromBase64(value) as Bytes, data as Bytes)) matched = true;
      } catch {
        /* a malformed signature is not a match */
      }
    }
  }
  if (!matched) throw new WebhookError('No signature matches');
  try {
    return JSON.parse(new TextDecoder().decode(body)) as WebhookEvent;
  } catch {
    throw new WebhookError('The body is signed but is not JSON');
  }
}

/**
 * The link in an abandoned-checkout email: it reopens the same selection (`?resume=<hold>`), and the tags make the visit
 * count as the email's, not as a stranger's. `siteUrl` is the page that holds your checkout.
 */
export function resumeLink(siteUrl: string, holdId: string, campaign = 'abandoned-checkout'): string {
  const u = new URL(siteUrl);
  u.searchParams.set('resume', holdId);
  u.searchParams.set('utm_source', 'email');
  u.searchParams.set('utm_medium', 'abandon');
  u.searchParams.set('utm_campaign', campaign);
  return u.toString();
}
````

### src/rcms-tickets/tools/kit.mjs

````js
#!/usr/bin/env node
// The checkout kit's own tool: installs the files, keeps kit.lock, updates a copy that is already in your site. Node only, no
// dependencies, nothing leaves your machine but the requests for the kit's files.
//   node kit.mjs install --manifest <url> [--framework next|vite]   copy every file (signature and sha256 checked), write kit.lock, write the recipe's NEW files
//                        [--allow-downgrade]                        for a version older than the one you have, or than this tool
//   node kit.mjs verify                                             what you changed since the install
//   node kit.mjs update  --manifest <url> [--accept <path>]         replace untouched files; a file you changed is kept, its diff shown
//                        [--allow-downgrade] [--allow-removals]     for an older version, or a version that removes most of the kit
// Run it from your project's root. It never overwrites a file that is not the kit's untouched copy, and it writes nothing outside the
// folders below. Before anything is written, the manifest's signature is checked against the key in this file.
import { spawnSync } from 'node:child_process';
import { createHash, createPublicKey, verify as verifySignature } from 'node:crypto';
import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { dirname, join, posix, relative, resolve, sep } from 'node:path';

/** RCMS Tickets' public signing key. The build writes it here, so the copy you were served knows who may publish an update. */
const PUBLIC_KEY = 'MCowBQYDK2VwAyEAzTgUzBeQoEX1avmURvdojXsfIEop33llhOU1SYV3Rys=';
// The version this copy of the tool was served with. An older signed manifest is a real signature on old bugs: install and update both refuse it without --allow-downgrade.
const TOOL_VERSION = '0.3.13';

/** The only places a recipe may write. Everything else a site already owns. */
const RECIPE_PATHS = [/^src\/rcms-tickets\//, /^src\/app\/api\/tickets\//, /^src\/app\/tickets\//, /^server\/tickets\.ts$/];

const [command, ...rest] = process.argv.slice(2);
const arg = (name) => (rest.includes(name) ? rest[rest.indexOf(name) + 1] : undefined);
const sha = (b) => createHash('sha256').update(b).digest('hex');
const die = (m) => {
  console.error(`STOP ${m}`);
  process.exit(1);
};
const LOCK = 'kit.lock';
const ENV_FILE = '.env.local';

/** Where the kit lives in this project: src/rcms-tickets if the project has a src folder, else rcms-tickets. */
const srcPrefix = () => (existsSync('src') ? 'src/' : '');
const findLock = () => [`src/rcms-tickets/${LOCK}`, `rcms-tickets/${LOCK}`].find((p) => existsSync(p));

async function get(url) {
  let res;
  try {
    res = await fetch(url);
  } catch {
    die(`${url} could not be reached.`);
  }
  if (!res.ok) die(`${url} answered ${res.status}`);
  return Buffer.from(await res.arrayBuffer());
}

/** A kit path inside a folder, on any machine, or a refusal: resolved, so `..` and an absolute path can't get out. */
function inside(base, rel) {
  if (typeof rel !== 'string' || !rel || rel.includes('\\') || posix.isAbsolute(rel)) die(`${String(rel)} is not a path inside the kit.`);
  const root = resolve(base);
  const target = resolve(root, rel);
  if (!target.startsWith(root + sep)) die(`${rel} is outside the kit's folder. Nothing was changed.`);
  return target;
}

/** The manifest, checked: signed by RCMS Tickets, well formed, its files only from its own host and only inside the kit's folder. */
async function loadManifest(url) {
  if (!url) die('--manifest <url> is required');
  if (!/^[A-Za-z0-9+/=]{20,}$/.test(PUBLIC_KEY)) die('This copy of the tool has no signing key, so it can trust no manifest. Fetch the tool again from the address in the RCMS Tickets docs.');
  const body = await get(url);
  const sigRes = await fetch(`${url}.sig`).catch(() => null);
  const signature = sigRes?.ok ? Buffer.from((await sigRes.text()).trim(), 'base64') : null;
  let good = false;
  try {
    good = !!signature && verifySignature(null, body, createPublicKey({ key: Buffer.from(PUBLIC_KEY, 'base64'), format: 'der', type: 'spki' }), signature);
  } catch {
    good = false;
  }
  if (!good) die('This manifest is not signed by RCMS Tickets, so it may have been changed on its way here. Nothing was changed. Do not use it; tell RCMS Tickets where it came from.');
  let m;
  try {
    m = JSON.parse(body.toString('utf8'));
  } catch {
    die(`${url} is not a kit manifest (it is not JSON). Nothing was changed.`);
  }
  if (!m || !Array.isArray(m.files) || !m.files.length || typeof m.version !== 'string') die(`${url} is not a kit manifest (no version, or no files). Nothing was changed.`);
  const host = new URL(url).origin;
  for (const f of m.files) {
    let from;
    try {
      from = new URL(f.url).origin;
    } catch {
      die(`${f.path}: the manifest gives no address for it.`);
    }
    if (from !== host) die(`${f.path}: the manifest points at another host (${from})`);
    if (!/^[0-9a-f]{64}$/.test(f.sha256 ?? '')) die(`${f.path}: no sha256 in the manifest`);
    // posix on purpose: a manifest's paths use forward slashes on every machine, Windows too.
    if (posix.normalize(f.dest) !== f.dest || !f.dest.startsWith('src/rcms-tickets/') || f.dest.split('/').includes('..')) die(`${f.path}: the manifest would write outside the kit's folder (${f.dest})`);
    inside('kit', f.path);
    if (f.path === LOCK) die('The manifest would overwrite kit.lock.');
  }
  return m;
}

/** Every file, fetched and checked before anything is written: a wrong file stops it all. */
async function fetchAll(m) {
  const out = new Map();
  for (const f of m.files) {
    const body = await get(f.url);
    if (sha(body) !== f.sha256) die(`${f.path} does not match its sha256 in the manifest. Nothing was written.`);
    out.set(f.path, { body, sha256: f.sha256, dest: f.dest });
  }
  return out;
}

function writeFile(path, body) {
  mkdirSync(dirname(path), { recursive: true });
  writeFileSync(path, body);
}

const git = (...a) => spawnSync('git', a, { encoding: 'utf8' });

/** Checks, never assumes, that the file holding the secret key is ignored by git. */
function ensureIgnored() {
  if (git('rev-parse', '--is-inside-work-tree').status !== 0) return console.log(`NOTE this is not a git repository. If it becomes one, ignore ${ENV_FILE} first: it holds the secret key.`);
  if (git('ls-files', '--error-unmatch', ENV_FILE).status === 0) die(`${ENV_FILE} is tracked by git. Take it out (git rm --cached ${ENV_FILE}) and replace any key it held.`);
  if (git('check-ignore', '-q', ENV_FILE).status === 0) return console.log(`OK ${ENV_FILE} is ignored by git`);
  appendFileSync('.gitignore', `${existsSync('.gitignore') && !readFileSync('.gitignore', 'utf8').endsWith('\n') ? '\n' : ''}${ENV_FILE}\n`);
  if (git('check-ignore', '-q', ENV_FILE).status !== 0) die(`${ENV_FILE} is still not ignored after adding it to .gitignore. Do not write the key until it is.`);
  console.log(`ADDED ${ENV_FILE} to .gitignore (it was not ignored)`);
}

async function install() {
  const m = await loadManifest(arg('--manifest'));
  const had = existsSync(join(`${srcPrefix()}rcms-tickets`, LOCK)) ? JSON.parse(readFileSync(join(`${srcPrefix()}rcms-tickets`, LOCK), 'utf8')).version : null;
  const floor = [had, /^\d+\.\d+\.\d+$/.test(TOOL_VERSION) ? TOOL_VERSION : null].filter(Boolean);
  for (const v of floor) if (older(m.version, v) && !rest.includes('--allow-downgrade')) die(`The manifest is version ${m.version}, older than ${v}. That can bring old bugs back. Nothing was changed. If you mean it: --allow-downgrade.`);
  const name = arg('--framework');
  const recipe = name ? m.recipes?.[name] : undefined;
  if (name && !recipe) die(`no recipe called ${name}`);
  for (const f of recipe?.files ?? []) {
    const canonical = posix.normalize(String(f.dest));
    if (!RECIPE_PATHS.some((re) => re.test(canonical))) die(`The recipe would write ${f.dest}, which is not one of its own places. Nothing was changed.`);
  }
  const files = await fetchAll(m);
  const base = `${srcPrefix()}rcms-tickets`;
  for (const [p, f] of files) {
    const target = inside(base, p);
    if (existsSync(target) && sha(readFileSync(target)) !== f.sha256) {
      console.log(`EXISTS ${target}: it differs from the kit, so it was left as it is. Use update if the kit is already installed.`);
      continue;
    }
    writeFile(target, f.body);
  }
  const lockFile = join(base, LOCK);
  writeFile(lockFile, `${JSON.stringify({ kit: m.name, version: m.version, manifest: arg('--manifest'), files: Object.fromEntries([...files].map(([p, f]) => [p, { sha256: f.sha256, version: m.version }])) }, null, 2)}\n`);
  console.log(`INSTALLED ${files.size} files in ${base}, version ${m.version}, signature and sha256 checked. Keep ${lockFile} in git. If you ran a copy of this tool from elsewhere, delete it: the one to use from now on is ${base}/tools/kit.mjs.`);
  ensureIgnored();
  if (recipe) {
    for (const f of recipe.files) {
      const target = f.dest.replace(/^src\//, srcPrefix());
      if (existsSync(target)) {
        console.log(`EXISTS ${target}: left as it is. Merge the recipe's copy by hand, or choose another path.`);
        continue;
      }
      writeFile(target, f.content);
      console.log(`WROTE ${target}`);
    }
    for (const s of recipe.merge ?? []) console.log(`MERGE ${s.file.replace(/^src\//, srcPrefix())}: ${s.how}`);
  }
}

function readLock() {
  const file = findLock();
  if (!file) die(`no ${LOCK} here: run from your project's root, after install`);
  let lock;
  try {
    lock = JSON.parse(readFileSync(file, 'utf8'));
  } catch {
    die(`${file} is not readable as JSON. Restore it from git.`);
  }
  if (!lock?.files || typeof lock.files !== 'object') die(`${file} has no list of files. Restore it from git.`);
  const base = dirname(file);
  for (const p of Object.keys(lock.files)) inside(base, p);
  return { file, base, lock };
}

function verify() {
  const { base, lock } = readLock();
  let changed = 0;
  for (const [p, f] of Object.entries(lock.files)) {
    const target = inside(base, p);
    if (!existsSync(target)) {
      changed++;
      console.log(`MISSING ${p}`);
    } else if (sha(readFileSync(target)) !== f.sha256) {
      changed++;
      console.log(`CHANGED ${p}`);
    }
  }
  console.log(`version ${lock.version}: ${changed} of ${Object.keys(lock.files).length} files differ from what was installed`);
}

const parts = (v) => String(v).split(/[.-]/).slice(0, 3).map(Number);
function older(a, b) {
  const [x, y] = [parts(a), parts(b)];
  for (let i = 0; i < 3; i++) if ((x[i] || 0) !== (y[i] || 0)) return (x[i] || 0) < (y[i] || 0);
  return false;
}

function showDiff(mine, theirs) {
  const r = spawnSync('diff', ['-u', mine, theirs], { encoding: 'utf8' });
  console.log(r.stdout || `(compare ${mine} with ${theirs})`);
}

async function update() {
  const { file, base, lock } = readLock();
  const m = await loadManifest(arg('--manifest') ?? lock.manifest);
  if (older(m.version, lock.version) && !rest.includes('--allow-downgrade')) die(`The manifest is version ${m.version}, older than the ${lock.version} you have. That can bring old bugs back. Nothing was changed. If you mean it: --allow-downgrade.`);
  const accepted = new Set(rest.filter((a, i) => rest[i - 1] === '--accept'));
  const files = await fetchAll(m);
  const incoming = new Set(files.keys());
  const leaving = Object.keys(lock.files).filter((p) => !incoming.has(p));
  if (leaving.length > Object.keys(lock.files).length / 2 && !rest.includes('--allow-removals')) die(`This version would remove ${leaving.length} of your ${Object.keys(lock.files).length} kit files. That is not an update. Nothing was changed. If you mean it: --allow-removals.`);
  // An advisory stays until the file it is about has really moved: a kept file keeps its own version in the lock.
  const fileVersion = (p) => lock.files[p]?.version ?? lock.version;
  const heldBack = () => Object.keys(lock.files).map(fileVersion);
  for (const a of m.advisories ?? []) {
    const concerned = Array.isArray(a.files) && a.files.length ? a.files.filter((p) => lock.files[p]).map(fileVersion) : heldBack();
    if (concerned.some((v) => older(v, a.fixed_in)) && !(Array.isArray(a.files) && a.files.every((p) => accepted.has(p)))) console.log(`ADVISORY ${a.id} (${a.severity}), fixed in ${a.fixed_in}: ${a.summary}`);
  }
  const nextLock = {};
  const conflicts = [];
  for (const [p, f] of files) {
    const target = inside(base, p);
    const was = lock.files[p]?.sha256;
    const now = existsSync(target) ? sha(readFileSync(target)) : null;
    if (now === f.sha256) {
      nextLock[p] = { sha256: f.sha256, version: m.version };
    } else if (accepted.has(p)) {
      nextLock[p] = { sha256: f.sha256, version: m.version };
      console.log(`ACCEPTED ${p}: your merged copy now counts as changed from ${m.version}`);
      rmSync(inside(base, join('.kit-update', `${p}.new`)), { force: true });
    } else if (now === null || now === was) {
      writeFile(target, f.body);
      nextLock[p] = { sha256: f.sha256, version: m.version };
      console.log(`${now === null ? 'ADDED' : 'REPLACED'} ${p}`);
    } else if (was === f.sha256) {
      nextLock[p] = { sha256: f.sha256, version: m.version };
      console.log(`KEPT ${p}: you changed it and the kit's copy did not move`);
    } else {
      // Yours and ours both moved. Yours stays; ours is set beside it, with the diff, for you to merge.
      const beside = inside(base, join('.kit-update', `${p}.new`));
      writeFile(beside, f.body);
      nextLock[p] = { sha256: was ?? f.sha256, version: fileVersion(p) };
      conflicts.push(p);
      console.log(`CONFLICT ${p}: you changed it, and so did this version. Yours is untouched; the new one is at ${relative('.', beside)}.`);
      showDiff(target, beside);
    }
  }
  for (const p of leaving) {
    const target = inside(base, p);
    if (!existsSync(target)) continue;
    if (sha(readFileSync(target)) === lock.files[p].sha256) {
      rmSync(target);
      console.log(`REMOVED ${p}: it left the kit`);
    } else console.log(`LEFT ${p}: it left the kit, but you changed it. Nothing uses it now; delete it when you are ready.`);
  }
  writeFileSync(file, `${JSON.stringify({ ...lock, version: m.version, files: nextLock }, null, 2)}\n`);
  console.log(`version ${m.version}: ${conflicts.length} file(s) to merge by hand. Then: update --accept <path> for each, typecheck, build, buy a test ticket.`);
}

if (command === 'install') await install();
else if (command === 'verify') verify();
else if (command === 'update') await update();
else die('use: install, verify or update');
````

