@openseat/booking
v0.1.0
Published
Seat status, selection rules, hold lifecycle and adapter contracts for OpenSeat. No payment processing; inventory truth stays on your backend.
Maintainers
Readme
@openseat/booking
Seat status types, selection rules, hold lifecycle and adapter contracts. Framework-independent.
This package does not reserve seats. A seat shown as available can be sold a moment later. Only your server's atomic hold reserves anything, and only your server verifies payment. See the concurrency guide in the docs.
Contracts
type SeatStatus = "available" | "held" | "booked" | "blocked";
interface SeatStatusRecord {
seatId: string;
status: SeatStatus;
categoryId?: string; // event-level category, overrides the layout's
priceLabel?: string; // display only; the SDK never computes prices
expiresAt?: string; // for held seats
version?: number; // older versions are ignored, so out-of-order updates cannot resurrect stale states
}
// Standing places, booths and whole tables, by inventory key.
interface AreaQuantity {
inventoryId: string;
quantity: number;
}
interface AreaStatusRecord {
inventoryId: string;
status: SeatStatus;
remaining: number;
capacity?: number;
version?: number;
}
interface InventoryAdapter {
getStatuses(
input: { eventId: string; seatIds?: string[] },
options?: { signal?: AbortSignal },
): Promise<SeatStatusRecord[]>;
// onSnapshot: a full re-read (after a reconnect, say); seats it does not list are available.
subscribe?(eventId: string, listener: (changes: SeatStatusRecord[]) => void, onError?, onSnapshot?): () => void;
getAreaStatuses?(input: { eventId: string; inventoryIds?: string[] }, options?): Promise<AreaStatusRecord[]>;
subscribeAreas?(eventId: string, listener: (changes: AreaStatusRecord[]) => void, onError?): () => void;
}
interface BookingAdapter extends InventoryAdapter {
holdSeats(input: { eventId; seatIds; areas?: AreaQuantity[]; idempotencyKey }): Promise<Hold>; // all or nothing
confirmHold(input: { holdId; paymentReference; idempotencyKey? }): Promise<Booking>;
releaseHold(holdId: string): Promise<void>;
getHold?(holdId: string): Promise<Hold>;
extendHold?(holdId: string, input?: { seconds?: number }): Promise<Hold>; // the server may clamp
}
// Hold and Booking carry `areas?: AreaQuantity[]` next to `seatIds`. Hold may also carry
// `status?: "active" | "expired" | "released" | "booked"`, `locked?: boolean` and `maxExpiresAt?: string`.Adapters throw BookingError with a code (SEATS_UNAVAILABLE with unavailableSeatIds, AREA_SOLD_OUT with unavailableAreaIds, LIMIT_EXCEEDED, HOLD_EXPIRED, PAYMENT_REJECTED, CONFLICT, UNAUTHORIZED, NETWORK, TIMEOUT, …) and a retryable flag, plus retryAfterMs when the server said how long to wait (a 429's Retry-After) and reason when it gave a finer reason (HOLD_LOCKED, EXTENSION_LIMIT, …). areas is optional everywhere, so adapters written before areas existed still work for seats.
Selection rules
import { toggleSeat, validateSelection } from "@openseat/booking";
const rules = { maxTickets: 8, minSeats: 2, allowMixedCategories: false, preventOrphans: true };
const result = toggleSeat(selection, "stalls:A:5", { layout, statuses }, rules);
if (!result.allowed && result.violation) show(result.violation.message); // "Seat 5 in row A is booked."
const check = validateSelection(selection, { layout, statuses }, rules, areas); // before holdingtoggleSeat refuses unavailable seats, disallowed categories, mixing categories and exceeding the maximum. maxTickets is one per-buyer limit across seats, standing places and booths (one each) and whole tables (their seats); countTickets(layout, seatIds, areas), ticketsLeft(layout, rules, seatIds, areas) and ticketLimitMessage(limit) ("You can buy up to 8 tickets.") use the same count. Without maxTickets, maxSeats applies. Hidden seats (hidden themselves or through a hidden row, table or section; SeatInfo.hidden) are unavailable whatever their status, are skipped by keyboard navigation and count as taken for the orphan rule. validateSelection adds the minimum, re-checks availability, and the orphan rule: a single free seat stranded between taken or selected seats, or between the selection and a row end or aisle. Aisles are detected from seat spacing, so a seat beside an aisle is not stranded by it.
Holds
import { createHoldController } from "@openseat/booking";
const holds = createHoldController({ adapter, eventId, maxTickets: 10, layout });
await holds.hold(selection, [{ inventoryId: "ga-fan-pit", quantity: 4 }]); // seats and places, all or nothing
holds.remainingMs();
await holds.confirm(paymentReference); // after your payment flow succeeds
holds.reset(); // optional: back to idle for the next booking
await holds.release();States: idle → holding → held → confirming → confirmed, with released, expired, completed and failed. Expiry follows the server's expiresAt, corrected for client clock skew using serverTime. Retrying a retryable failure reuses the same idempotency key, so a retried request cannot create a second hold. A request over maxTickets fails with LIMIT_EXCEEDED before anything is sent. After confirmed, hold() starts the next booking straight away; reset() returns to idle first (it throws CONFLICT while a request is in flight or a hold is active).
Extending, refreshing and completing
When your server takes the payment (and books the seats with its own API), the browser only watches the hold:
import { createHoldController } from "@openseat/booking";
const holds = createHoldController({ adapter, eventId, verifyExpiry: true });
await holds.hold(selection);
await holds.extend(300); // needs adapter.extendHold; the countdown follows the server's answer
await holds.refresh(); // re-reads the hold: a new expiry or lock, "booked" → completed, gone → expired
holds.complete(); // your server booked it: completed, timers stop, nothing is sentextend(seconds?)rejects withVALIDATIONwhen the adapter has noextendHold,CONFLICTwithout an active hold, and otherwise with the adapter's error (a hold the server no longer has becomesexpired).refresh()usesgetHold(a no-op without it). It works while held, after a failure that kept the hold, and after a local expiry, since your backend may have extended the hold.verifyExpiry: true(withgetHold): when the countdown ends, the server is asked first. A later expiry reschedules,"booked"completes, and only a hold that is gone (or an unanswered question) becomesexpired.hold()whileheldasks for a new hold with the new basket. Adapters that replace the customer's hold atomically swap it; with others,release()first. If the replacement fails, the state isfailedwith the earlier hold, which keeps counting down.resume(hold)takes a"booked"hold ascompletedand an"expired"or"released"one asexpired.
The controller never releases a hold on its own: not at expiry, not on an error, not on dispose(). Only release() does.
Carts and labels
import { buildCart, seatLabel } from "@openseat/booking";
const cart = buildCart({ layout, seatIds: selection, areas, priceOf: (categoryId) => prices[categoryId] });
// cart.lines: "Stalls, Row D, Seats 1–4", "4 × Fan pit", "Booth B8", "Table T3 (8 seats)", with unitPrice and amount
// cart.ticketCount, cart.total (null while any price is unknown)
seatLabel(layout, "stalls:A:10"); // "Row A, Seat 10"Labels are built from layout labels only and never contain seat or inventory IDs.
Also included
createInventoryStore(): merges snapshots and real-time updates, ignoring stale versions.findNeighbourSeat(layout, seatId, "right"),firstSeat(layout): keyboard navigation that works on curved and staggered rows.describeSeat(layout, seatId, statuses, selected): "Seat 5, row A, Stalls, VIP, ₹450, available, wheelchair space".toSeatVisualStates(statuses, selection): what the renderer should draw.getBookableAreas(layout),bookableAreaForObject(layout, objectId)andbookableAreaForSeat(layout, seatId): standing areas, booths andbookAsWholetables sold as one unit;bookableAreaForSeatmaps a seat ID to the table that owns it (for routing a click or key press on its seats), andwholeTableSeatIds(layout, inventoryId)lists a whole table's seats.createInMemoryBookingAdapter({ eventId, layout?, statuses?, areaCapacities?, initialBookings?, maxTicketsPerHold?, holdMs?, maxHoldMs?, onBooking? }): a complete adapter for demos and tests, with atomic holds of seats and areas, idempotency, expiry andextendHold(capped atmaxHoldMsfrom the hold's start, beyond which it fails with reasonEXTENSION_LIMIT). Holds reportstatus, andgetHoldanswers"booked"for a confirmed one. It also returnsgetAreaStatus,takeArea,getBookingsandsetStatus(a"blocked"record for an area key makes it not for sale). Not a backend.
Not for sale
Places organisers mark Not for sale are recorded in the layout's metadata. Hosts must report them as "blocked" and refuse holds on them: unsellableInventory(layout).inventoryIds from @openseat/core lists the keys (add wholeTableSeatIds for whole tables). See the inventory-adapter guide in the docs.
Documentation
Embedding the booking map (cart, zones, holds, accessible seating, prices in ₹), Inventory adapters (writing your own), Integrating end to end.
