@bowlos/reservations 0.12.0 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/HEADLESS.md +330 -0
- package/README.md +22 -7
- package/dist/{catalog-kdDjgvT1.d.cts → catalog-BgWUl6e3.d.cts} +1 -1
- package/dist/{catalog-kd07kri0.d.ts → catalog-CfNxiNZn.d.ts} +1 -1
- package/dist/{chunk-2X7MFQWY.js → chunk-ADHCZPTB.js} +18 -3
- package/dist/chunk-ADHCZPTB.js.map +1 -0
- package/dist/{chunk-FPUWLOW3.js → chunk-YA6PPZUS.js} +3 -3
- package/dist/{chunk-FPUWLOW3.js.map → chunk-YA6PPZUS.js.map} +1 -1
- package/dist/components.cjs +82 -4
- package/dist/components.cjs.map +1 -1
- package/dist/components.d.cts +8 -2
- package/dist/components.d.ts +8 -2
- package/dist/components.js +84 -6
- package/dist/components.js.map +1 -1
- package/dist/{data-lC-l-haz.d.cts → data-fFL06CrT.d.cts} +38 -1
- package/dist/{data-lC-l-haz.d.ts → data-fFL06CrT.d.ts} +38 -1
- package/dist/index.cjs +17 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +2 -2
- package/dist/payments.cjs.map +1 -1
- package/dist/payments.d.cts +5 -3
- package/dist/payments.d.ts +5 -3
- package/dist/payments.js.map +1 -1
- package/dist/{react-B3dlcklN.d.ts → react-CIkaMMxI.d.ts} +1 -1
- package/dist/{react-aZplAyHS.d.cts → react-CZld8wak.d.cts} +1 -1
- package/dist/react.cjs +129 -0
- package/dist/react.cjs.map +1 -1
- package/dist/react.d.cts +48 -5
- package/dist/react.d.ts +48 -5
- package/dist/react.js +119 -2
- package/dist/react.js.map +1 -1
- package/package.json +3 -2
- package/templates/center-site/package.json +1 -1
- package/dist/chunk-2X7MFQWY.js.map +0 -1
package/HEADLESS.md
ADDED
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
# Headless integration guide
|
|
2
|
+
|
|
3
|
+
**Center sites are headless-first.** The booking engine must match the center's
|
|
4
|
+
own design and never look like a themed plugin, so real sites build the funnel
|
|
5
|
+
from the SDK's **hooks** — not the drop-in `<BookingFlow>`. The drop-in
|
|
6
|
+
components (`@bowlos/reservations/components`) are a *reference implementation*:
|
|
7
|
+
this guide maps **every behavior they bake in to the hook + pattern** you use to
|
|
8
|
+
reproduce it inside your own UI.
|
|
9
|
+
|
|
10
|
+
> **Maintainers:** `<BookingFlow>` is the reference for this document. Any change
|
|
11
|
+
> to a component's booking behavior must be mirrored here in the same PR — the
|
|
12
|
+
> capability map below **and** a dated entry under [Adopting changes by
|
|
13
|
+
> version](#adopting-changes-by-version). A component feature with no headless
|
|
14
|
+
> instructions is incomplete (AGENTS.md → "SDK Headless Parity").
|
|
15
|
+
|
|
16
|
+
All hooks come from `@bowlos/reservations/react`; the framework-agnostic twins
|
|
17
|
+
(`listStartTimes`, `listAddons`, `bookingPreview`, …) come from
|
|
18
|
+
`@bowlos/reservations`. Mount one `<BowlosProvider>` at your app root so
|
|
19
|
+
`useAccount()` shares a single session everywhere.
|
|
20
|
+
|
|
21
|
+
---
|
|
22
|
+
|
|
23
|
+
## Capability map
|
|
24
|
+
|
|
25
|
+
### 1. Login gate — online booking requires login
|
|
26
|
+
|
|
27
|
+
Online booking **requires a signed-in customer** (anonymous is the walk-in /
|
|
28
|
+
staff path only). Do not render the booking form, fetch pricing, or collect a
|
|
29
|
+
name/email for an anonymous visitor — show your sign-in / create-account UI and
|
|
30
|
+
drive it from `useAccount()`.
|
|
31
|
+
|
|
32
|
+
```tsx
|
|
33
|
+
const account = useAccount();
|
|
34
|
+
const signedIn = account.status === "linked" && account.customer !== null;
|
|
35
|
+
|
|
36
|
+
if (!signedIn) {
|
|
37
|
+
// Your themed sign-in / create-account form, wired to:
|
|
38
|
+
// account.signIn(email, password) / account.signUp(email, password) / account.link({...})
|
|
39
|
+
return <YourAuthForm account={account} />;
|
|
40
|
+
}
|
|
41
|
+
const customer = account.customer!; // { fullName, email, ... }
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Gate **every** read below on `signedIn` (member rates + credit only resolve once
|
|
45
|
+
authenticated).
|
|
46
|
+
|
|
47
|
+
### 2. Date — default to today
|
|
48
|
+
|
|
49
|
+
Default the date to the visitor's local today, set in an effect (not initial
|
|
50
|
+
state) so SSR and the first client render agree.
|
|
51
|
+
|
|
52
|
+
```tsx
|
|
53
|
+
const [dateISO, setDateISO] = useState(defaultDateISO ?? "");
|
|
54
|
+
useEffect(() => {
|
|
55
|
+
if (!defaultDateISO && dateISO === "") {
|
|
56
|
+
const d = new Date();
|
|
57
|
+
setDateISO(`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`);
|
|
58
|
+
}
|
|
59
|
+
}, [defaultDateISO, dateISO]);
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
### 3. Quantity — mode-aware (never hardcode `units`)
|
|
63
|
+
|
|
64
|
+
The count is `units`, `persons`, or `games` depending on the product's
|
|
65
|
+
`pricingMode`. Sending `units` for a per-person product books **lanes instead of
|
|
66
|
+
bowlers** and misprices. Label it accordingly.
|
|
67
|
+
|
|
68
|
+
```tsx
|
|
69
|
+
const COUNT_LABEL = { per_unit_per_hour: "Lanes", per_person_per_hour: "Bowlers", per_game: "Games" };
|
|
70
|
+
const countField = (n: number) =>
|
|
71
|
+
pricingMode === "per_person_per_hour" ? { persons: n }
|
|
72
|
+
: pricingMode === "per_game" ? { games: n }
|
|
73
|
+
: { units: n };
|
|
74
|
+
// label: COUNT_LABEL[pricingMode]; spread countField(count) into preview + booking args.
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
`pricingMode` comes from the product (the catalog read exposes it) — pass it in,
|
|
78
|
+
don't assume bowling.
|
|
79
|
+
|
|
80
|
+
### 4. Live availability + price
|
|
81
|
+
|
|
82
|
+
```tsx
|
|
83
|
+
const endMinuteOfDay = startMinuteOfDay + durationMinutes;
|
|
84
|
+
const availability = useAvailability(
|
|
85
|
+
{ productId, dateISO, startMinuteOfDay, endMinuteOfDay },
|
|
86
|
+
{ enabled: dateISO !== "" && signedIn },
|
|
87
|
+
);
|
|
88
|
+
const preview = useBookingPreview(
|
|
89
|
+
{ centerId, productId, dateISO, startMinuteOfDay, endMinuteOfDay, mode: pricingMode, ...countField(count), addons: selectedAddons },
|
|
90
|
+
{ enabled: dateISO !== "" && signedIn },
|
|
91
|
+
);
|
|
92
|
+
const freeUnits = availability.data ? availableUnitCount(availability.data) : null;
|
|
93
|
+
const quoteCents = preview.data?.totalCentsPerPlan?.[0]?.totalCents ?? null; // includes add-ons + tax + credit
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
### 5. Start time — a dropdown of bookable slots (not a free-form clock)
|
|
97
|
+
|
|
98
|
+
`useStartTimes` returns the minute-of-day slots that are within open hours, clear
|
|
99
|
+
the booking buffer, **and** have a real price plan (decided by the same pricing
|
|
100
|
+
engine the quote uses). Render them as a `<select>`; never offer a free-form time
|
|
101
|
+
input.
|
|
102
|
+
|
|
103
|
+
```tsx
|
|
104
|
+
const startTimes = useStartTimes(
|
|
105
|
+
{ productId, dateISO, durationMinutes, mode: pricingMode },
|
|
106
|
+
{ enabled: dateISO !== "" && signedIn },
|
|
107
|
+
);
|
|
108
|
+
const slots = startTimes.data ?? [];
|
|
109
|
+
|
|
110
|
+
// Keep the selection valid as the list loads / the date changes:
|
|
111
|
+
useEffect(() => {
|
|
112
|
+
if (slots.length > 0 && !slots.includes(startMinuteOfDay)) setStartMinuteOfDay(slots[0]);
|
|
113
|
+
}, [startTimes.data]); // eslint-disable-line
|
|
114
|
+
|
|
115
|
+
// 12-hour label:
|
|
116
|
+
const label = (m: number) => {
|
|
117
|
+
const h = Math.floor(m / 60) % 24, min = m % 60;
|
|
118
|
+
return `${h % 12 === 0 ? 12 : h % 12}:${String(min).padStart(2, "0")} ${h < 12 ? "AM" : "PM"}`;
|
|
119
|
+
};
|
|
120
|
+
// startTimes.loading → "Finding times…"; slots.length === 0 → "No times available" + disable submit.
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
### 6. Add-ons (shoes, upgrades)
|
|
124
|
+
|
|
125
|
+
`useAddons` lists the product's add-ons; collect quantities and pass them as
|
|
126
|
+
`addons: [{ addonId, quantity }]` to **both** the preview and the booking. The
|
|
127
|
+
server re-validates and the quote total already reflects them.
|
|
128
|
+
|
|
129
|
+
```tsx
|
|
130
|
+
const addons = useAddons({ productId }, { enabled: signedIn });
|
|
131
|
+
const [qty, setQty] = useState<Record<string, number>>({}); // addonId → quantity
|
|
132
|
+
const selectedAddons = Object.entries(qty).filter(([, q]) => q > 0).map(([addonId, quantity]) => ({ addonId, quantity }));
|
|
133
|
+
|
|
134
|
+
// Each addon: { id, name, description, priceCents, rateMode: "per_person"|"per_unit"|"flat", defaultQuantityRule }
|
|
135
|
+
// Show priceCents with a rate suffix (/ person, / unit, flat) + a quantity stepper per addon.
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
### 7. Review step — an order summary before payment
|
|
139
|
+
|
|
140
|
+
Match the branded portal: selection → **review** → payment. After the customer
|
|
141
|
+
has picked everything and the quote has loaded, show a summary of the order and a
|
|
142
|
+
"Continue to payment" action — don't hold inventory or jump to the card until they
|
|
143
|
+
confirm. The button that opens this reads **"Review order"** (not "Book now"); the
|
|
144
|
+
hold + payment happen on **"Continue to payment"**.
|
|
145
|
+
|
|
146
|
+
```tsx
|
|
147
|
+
const [reviewing, setReviewing] = useState(false);
|
|
148
|
+
// Form's primary button → setReviewing(true) (enable it only once quoteCents is loaded).
|
|
149
|
+
// Render the summary from data you already have — no extra call:
|
|
150
|
+
const chosen = (addons.data ?? [])
|
|
151
|
+
.map((a) => ({ ...a, quantity: qty[a.id] ?? 0 }))
|
|
152
|
+
.filter((a) => a.quantity > 0);
|
|
153
|
+
const addonsSubtotal = chosen.reduce((s, a) => s + a.priceCents * a.quantity, 0);
|
|
154
|
+
// The reservation FEE is folded into the quote total — itemize it (don't let it
|
|
155
|
+
// vanish) and subtract it from the line below so it isn't double-counted:
|
|
156
|
+
const fee = preview.data?.reservationFee; // { amountCents, label } | null
|
|
157
|
+
const feeCents = (fee?.amountCents as number) ?? 0;
|
|
158
|
+
const reservationCents = quoteCents != null ? quoteCents - addonsSubtotal - feeCents : null; // base + tax
|
|
159
|
+
// Summary rows: the reservation ({count} {label} · {date} · {start–end}) + each add-on
|
|
160
|
+
// ({name} × {qty}) + a "{fee.label}" line (feeCents) when feeCents > 0 + Total = quoteCents.
|
|
161
|
+
// "Continue to payment" → flow.startHold(bookingArgs); "Edit order" → setReviewing(false).
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
The total shown **must** be the quote's `totalCents` — it already includes tax
|
|
165
|
+
**and** the reservation fee, so the review matches what the customer is charged.
|
|
166
|
+
Itemize `preview.data.reservationFee` as its own line so the fee is visible.
|
|
167
|
+
|
|
168
|
+
### 8. Hold → pay → confirm, and pay-to-confirm
|
|
169
|
+
|
|
170
|
+
`useBookingFlow` is the state machine. To mirror the component's **complete-sale-
|
|
171
|
+
only** default (no held-but-unpaid screen), advance straight to payment the
|
|
172
|
+
moment the hold lands.
|
|
173
|
+
|
|
174
|
+
```tsx
|
|
175
|
+
const flow = useBookingFlow();
|
|
176
|
+
// flow.status: "idle" | "holding" | "held" | "preparingPayment" | "awaitingPayment" | "confirmed"
|
|
177
|
+
flow.startHold(bookingArgs); // → "held"
|
|
178
|
+
useEffect(() => { // complete-sale-only
|
|
179
|
+
if (flow.status === "held") void flow.preparePayment(); // → "awaitingPayment" (+ flow.paymentIntent)
|
|
180
|
+
}, [flow.status]);
|
|
181
|
+
// after payment confirms on the client: flow.startPolling() → "confirmed" (flow.reservation)
|
|
182
|
+
// flow.abandon() releases the hold; flow.reset() starts over.
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
`bookingArgs` (a `CreateBookingArgs`) — always the signed-in customer:
|
|
186
|
+
|
|
187
|
+
```tsx
|
|
188
|
+
const bookingArgs = {
|
|
189
|
+
centerId, productId, dateISO, startMinuteOfDay, endMinuteOfDay,
|
|
190
|
+
mode: pricingMode, ...countField(count), addons: selectedAddons,
|
|
191
|
+
customer: { fullName: customer.fullName, email: customer.email, marketingOptIn: false },
|
|
192
|
+
};
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
### 9. Payment (Stripe Connect)
|
|
196
|
+
|
|
197
|
+
`preparePayment()` gives you `flow.paymentIntent` (a `PaymentIntentInfo` with
|
|
198
|
+
`clientSecret`, `connectedAccountId`, `customerSessionClientSecret`,
|
|
199
|
+
`amountCents`). The SDK core never loads Stripe.js. Two options:
|
|
200
|
+
|
|
201
|
+
- **Keep your own Stripe Elements** (full control of the Stripe `appearance` — the
|
|
202
|
+
headless choice). Initialize with your **platform** publishable key scoped to
|
|
203
|
+
the operator's connected account, and pass the **customer session** so saved
|
|
204
|
+
cards work:
|
|
205
|
+
|
|
206
|
+
```tsx
|
|
207
|
+
const stripe = useMemo(
|
|
208
|
+
() => loadStripe(PLATFORM_PK, { stripeAccount: flow.paymentIntent.connectedAccountId }),
|
|
209
|
+
[flow.paymentIntent.connectedAccountId],
|
|
210
|
+
);
|
|
211
|
+
<Elements stripe={stripe} options={{
|
|
212
|
+
clientSecret: flow.paymentIntent.clientSecret,
|
|
213
|
+
customerSessionClientSecret: flow.paymentIntent.customerSessionClientSecret, // saved cards / save-for-future
|
|
214
|
+
appearance: { /* your theme */ },
|
|
215
|
+
}}>
|
|
216
|
+
{/* <PaymentElement/> → stripe.confirmPayment({ elements, redirect: "if_required" }) → flow.startPolling() */}
|
|
217
|
+
</Elements>
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
- **Or drop in `<BowlosPaymentForm>`** from `@bowlos/reservations/payments` if you
|
|
221
|
+
don't need a custom Stripe appearance (`{...ctx} publishableKey={PLATFORM_PK}`).
|
|
222
|
+
|
|
223
|
+
Either way: it's the **platform** key scoped to `connectedAccountId`, and saved
|
|
224
|
+
cards require `customerSessionClientSecret`.
|
|
225
|
+
|
|
226
|
+
---
|
|
227
|
+
|
|
228
|
+
## Flow lifecycle, reset & error handling — required for a clean install
|
|
229
|
+
|
|
230
|
+
`useBookingFlow` is **in-memory** (no persistence, no resume). It starts at
|
|
231
|
+
`"idle"` and moves through statuses; **your UI is driven entirely by
|
|
232
|
+
`flow.status`.** Most "stuck booking" / "nothing happened on submit" / "no
|
|
233
|
+
confirmation" bugs come from skipping a status. Handle **all** of them — never let
|
|
234
|
+
an unhandled status fall through to your catalog/landing page.
|
|
235
|
+
|
|
236
|
+
```tsx
|
|
237
|
+
switch (flow.status) {
|
|
238
|
+
case "idle": return <Form/>; // (or your review panel once reviewing)
|
|
239
|
+
case "holding":
|
|
240
|
+
case "preparingPayment": return <Securing/>; // brief loading
|
|
241
|
+
case "held": /* completeSaleOnly effect calls preparePayment → awaitingPayment */ return <Securing/>;
|
|
242
|
+
case "awaitingPayment": return <YourStripeForm intent={flow.paymentIntent!}/>;
|
|
243
|
+
case "confirmed": return <Confirmation id={flow.reservation?.reservationDisplayId}/>; // REQUIRED
|
|
244
|
+
case "error":
|
|
245
|
+
case "failed": return <Problem msg={flow.error?.message} onRetry={flow.reset}/>; // do NOT bounce to catalog
|
|
246
|
+
case "expired":
|
|
247
|
+
case "abandoned": return <Expired onStartOver={flow.reset}/>;
|
|
248
|
+
}
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
**The confirmation is mandatory.** After the customer pays, `startPolling()` →
|
|
252
|
+
`"confirmed"` is the moment the reservation actually exists (the webhook
|
|
253
|
+
materializes it). **Render the confirmation from `flow.reservation`.** If you
|
|
254
|
+
navigate away on submit/pay instead, the customer sees no confirmation and may
|
|
255
|
+
think it failed — even though it booked. Conversely, if `startHold` errors and you
|
|
256
|
+
*don't* handle `"error"`, your page falls back to "what are you booking?" and the
|
|
257
|
+
booking silently never happens. **Both are the same bug: an unhandled status.**
|
|
258
|
+
|
|
259
|
+
**Reset when leaving or restarting a booking.** Because the state is in-memory and
|
|
260
|
+
the flow component often stays mounted across in-app navigation:
|
|
261
|
+
|
|
262
|
+
- **"Back" / "All offers" / pick a different product** → `flow.abandon()` (if a
|
|
263
|
+
hold is active) then `flow.reset()` *before* navigating, and clear the
|
|
264
|
+
`productId` from the route. A stale in-progress flow is what makes "Book" keep
|
|
265
|
+
reopening the previous reservation.
|
|
266
|
+
- **Sign out** → `flow.reset()` (the in-progress booking belongs to that session).
|
|
267
|
+
Wire this wherever you call `account.signOut()`.
|
|
268
|
+
- **Starting a fresh booking** must begin at `"idle"` — if you reuse a mounted
|
|
269
|
+
flow, call `reset()` first.
|
|
270
|
+
|
|
271
|
+
**Holds are server-side + TTL-bound.** `startHold` places a hold; if it errors
|
|
272
|
+
(slot taken, or a *prior* hold of yours still occupies the slot), surface
|
|
273
|
+
`flow.error` and offer "start over" (which should `abandon()` + `reset()`). Don't
|
|
274
|
+
hold during the review step — hold on "Continue to payment" only (§7).
|
|
275
|
+
|
|
276
|
+
---
|
|
277
|
+
|
|
278
|
+
## Buying a game pass (packages + memberships follow)
|
|
279
|
+
|
|
280
|
+
Game passes are a **direct purchase** — no inventory hold, no date/time. The buy
|
|
281
|
+
state machine is `usePurchase` (the per-type wrapper here is `useGameCardPurchase`),
|
|
282
|
+
which mirrors the booking lifecycle: mint a connected-account PaymentIntent → pay
|
|
283
|
+
with `<BowlosPaymentForm>` → poll to materialization. The charge lands on the
|
|
284
|
+
**operator's** connected account (same Connect rule as reservations).
|
|
285
|
+
|
|
286
|
+
```tsx
|
|
287
|
+
// List what's for sale (catalog read — anonymous):
|
|
288
|
+
const passes = useGameCards({ brandId }); // [{ id, name, priceCents, totalGames, … }]
|
|
289
|
+
|
|
290
|
+
// Buy one (requires a signed-in customer):
|
|
291
|
+
const buy = useGameCardPurchase();
|
|
292
|
+
// buy.start({ templateId }) → "awaitingPayment" (+ buy.paymentIntent)
|
|
293
|
+
// render the payment, then poll on success:
|
|
294
|
+
{buy.status === "awaitingPayment" && buy.paymentIntent && (
|
|
295
|
+
<BowlosPaymentForm
|
|
296
|
+
{...buy.paymentIntent} // { clientSecret, connectedAccountId, customerSessionClientSecret }
|
|
297
|
+
publishableKey={PLATFORM_PK}
|
|
298
|
+
amountCents={buy.paymentIntent.amountCents}
|
|
299
|
+
onPaid={() => buy.startPolling()} // → "confirmed", buy.resultId = the new game card
|
|
300
|
+
/>
|
|
301
|
+
)}
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
Drive the UI off `buy.status` exactly like the [Flow lifecycle](#flow-lifecycle-reset--error-handling)
|
|
305
|
+
section: show a **review** (item + price) before `start`, the payment on
|
|
306
|
+
`awaitingPayment`, a **confirmation** on `confirmed` (`buy.resultId`), and an
|
|
307
|
+
error + retry on `failed` / `expired` / `error`. Route the catalog's
|
|
308
|
+
`gamecard` pick to this flow **in-app** — not to the portal.
|
|
309
|
+
|
|
310
|
+
Headless function twins (non-React): `createGameCardOrder(client, { templateId })`
|
|
311
|
+
+ `getGameCardStatus(client, refToken)`.
|
|
312
|
+
|
|
313
|
+
## Adopting changes by version
|
|
314
|
+
|
|
315
|
+
What each SDK release changed in `<BookingFlow>` and the headless steps to match.
|
|
316
|
+
Headless sites do **not** get these from a version bump — apply them by hand.
|
|
317
|
+
|
|
318
|
+
| Version | Change | Headless adoption |
|
|
319
|
+
|---|---|---|
|
|
320
|
+
| **0.8.0** | Date defaults to today; primary button "Book Now"; count labels Lanes/Bowlers/Games and sends `units`/`persons`/`games` by mode | §2 (today default), §3 (mode-aware quantity). Stop hardcoding `mode: "per_unit_per_hour"` + `units`. |
|
|
321
|
+
| **0.9.0** | **Login required** — anonymous booking path removed | §1. Gate the funnel behind `useAccount()`; remove any anonymous name/email booking path; gate availability/preview on `signedIn`. |
|
|
322
|
+
| **0.10.0** | Add-ons UI | §6. Add `useAddons`; pass `addons` to preview + booking. |
|
|
323
|
+
| **0.11.0** | Start-time **dropdown** (new `availableStartTimes` endpoint) | §5. Replace any `<input type="time">` with a `<select>` from `useStartTimes`. |
|
|
324
|
+
| **0.12.0** | `<BowlosPaymentForm>` in a new `@bowlos/reservations/payments` entry | §9. Optional. Keep your custom Elements for a custom Stripe `appearance`; make sure you pass `customerSessionClientSecret` for saved cards. |
|
|
325
|
+
| **0.13.0** | **Review step** — selection now goes through an order summary before payment; primary button is "Review order" | §7. Insert a review summary between the form and the hold; relabel the submit "Review order"; only `startHold` on "Continue to payment". |
|
|
326
|
+
| **0.14.0** | Review **itemizes the reservation fee**; docs now spell out the full **flow lifecycle / reset / error handling** | §7 (show `reservationFee` as a line; total stays `totalCents`, which includes it) + the new **Flow lifecycle** section (handle every `flow.status`, render the confirmation, reset on navigation/sign-out). |
|
|
327
|
+
| **0.15.0** | **Headless game-pass purchase** — `useGameCardPurchase` (+ the `usePurchase` engine); `<BowlosPaymentForm>` accepts a minimal `ConnectedPaymentInput` | "Buying a game pass" section. Build the buy UI from `useGameCardPurchase` + `<BowlosPaymentForm>`; route the catalog's game-pass pick in-app instead of to the portal. (Game passes charge the operator's connected account.) |
|
|
328
|
+
|
|
329
|
+
When you add the next release here, add its row **and** any new capability-map
|
|
330
|
+
section in the same PR.
|
package/README.md
CHANGED
|
@@ -6,7 +6,11 @@ websites. Built for React/Next sites (including AI-agent-built ones) that book o
|
|
|
6
6
|
a BowlOS operator's behalf, with **Stripe Connect** payments landing on the
|
|
7
7
|
operator's own account.
|
|
8
8
|
|
|
9
|
-
- **Headless-first.** A typed client + hooks; you own the UI.
|
|
9
|
+
- **Headless-first.** A typed client + hooks; you own the UI. The booking engine
|
|
10
|
+
is meant to match your site's design, not look like a themed plugin — so the
|
|
11
|
+
primary path is the hooks. **→ [HEADLESS.md](./HEADLESS.md)** maps every
|
|
12
|
+
built-in booking behavior to its hook + pattern (and how to adopt each SDK
|
|
13
|
+
release). The drop-in components below are a *reference*, not the product.
|
|
10
14
|
- **Two entry points.** `@bowlos/reservations` (React-free core) and
|
|
11
15
|
`@bowlos/reservations/react` (provider + hooks). React is an optional peer.
|
|
12
16
|
- **Dual ESM + CJS**, fully typed.
|
|
@@ -130,8 +134,13 @@ non-React or server use.
|
|
|
130
134
|
|
|
131
135
|
## Drop-in components (`@bowlos/reservations/components`)
|
|
132
136
|
|
|
133
|
-
|
|
134
|
-
|
|
137
|
+
> These are a **reference / fast-start**, not the delivered product. Center sites
|
|
138
|
+
> are headless-first (your design, not a themed plugin) — build from the hooks per
|
|
139
|
+
> **[HEADLESS.md](./HEADLESS.md)**. Use these to prototype or to read how a
|
|
140
|
+
> behavior is wired.
|
|
141
|
+
|
|
142
|
+
Want a head start? A **themeable, white-label** component layer sits on top of
|
|
143
|
+
the hooks:
|
|
135
144
|
|
|
136
145
|
```tsx
|
|
137
146
|
import { BowlosProvider } from "@bowlos/reservations/react";
|
|
@@ -176,8 +185,8 @@ import { BookingCatalog } from "@bowlos/reservations/components";
|
|
|
176
185
|
|
|
177
186
|
The drop-in surfaces cover a center site end to end:
|
|
178
187
|
|
|
179
|
-
**`<BookingFlow>`** runs the whole funnel (availability + price →
|
|
180
|
-
confirm). **Online booking requires login** — there is **no anonymous path**.
|
|
188
|
+
**`<BookingFlow>`** runs the whole funnel (availability + price → **review** → pay
|
|
189
|
+
→ confirm). **Online booking requires login** — there is **no anonymous path**.
|
|
181
190
|
A signed-out visitor sees a sign-in / create-account form (the built-in
|
|
182
191
|
`<AuthForm>`); availability and pricing stay hidden until they authenticate,
|
|
183
192
|
then the flow books as them (member rates apply). Anonymous booking is the
|
|
@@ -199,8 +208,14 @@ itself from `pricingMode` — **Lanes** (`per_unit_per_hour`), **Bowlers**
|
|
|
199
208
|
(`per_person_per_hour`), **Games** (`per_game`) — and is sent to the API as the
|
|
200
209
|
matching field (`units` / `persons` / `games`), so a per-bowler product books
|
|
201
210
|
**bowlers, not lanes**. The page **auto-scrolls to the top** as the flow advances
|
|
202
|
-
past the form.
|
|
203
|
-
|
|
211
|
+
past the form.
|
|
212
|
+
|
|
213
|
+
The primary button reads **"Review order"** — submitting the form opens an
|
|
214
|
+
**order-summary review** (the reservation + each add-on + the authoritative total)
|
|
215
|
+
*before* anything is held or charged, matching the branded portal's select →
|
|
216
|
+
review → pay flow. **"Continue to payment"** then places the hold and advances to
|
|
217
|
+
payment; **"Edit order"** returns to the form. (Override copy via
|
|
218
|
+
`labels={{ reviewOrder, reviewHeading, orderTotal, editOrder, … }}`.)
|
|
204
219
|
|
|
205
220
|
**Add-ons** (shoe rental, upgrades) render automatically: any add-ons configured
|
|
206
221
|
on the product appear as a quantity-per-item list, each showing its unit price
|
|
@@ -298,6 +298,21 @@ function listStartTimes(client, args) {
|
|
|
298
298
|
function availableUnitCount(availability) {
|
|
299
299
|
return Math.max(0, availability.totalUnits - availability.busyUnitIds.length);
|
|
300
300
|
}
|
|
301
|
+
function createGameCardOrder(client, args) {
|
|
302
|
+
const idempotencyKey = args.idempotencyKey ?? generateIdempotencyKey();
|
|
303
|
+
return client.call(
|
|
304
|
+
"createGameCardPaymentIntent",
|
|
305
|
+
{ ...args, idempotencyKey },
|
|
306
|
+
{ auth: true }
|
|
307
|
+
);
|
|
308
|
+
}
|
|
309
|
+
function getGameCardStatus(client, refToken) {
|
|
310
|
+
return client.call(
|
|
311
|
+
"getGameCardCheckoutStatus",
|
|
312
|
+
{ refToken },
|
|
313
|
+
{ auth: true }
|
|
314
|
+
);
|
|
315
|
+
}
|
|
301
316
|
function generateIdempotencyKey() {
|
|
302
317
|
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
|
|
303
318
|
return crypto.randomUUID();
|
|
@@ -326,6 +341,6 @@ function abandonCheckout(client, refToken) {
|
|
|
326
341
|
return client.call("abandonCheckout", { refToken }, { auth: true });
|
|
327
342
|
}
|
|
328
343
|
|
|
329
|
-
export { BOWLOS_ERROR_CODES, BowlosApiError, BowlosClient, abandonCheckout, availableUnitCount, bookingPreview, checkAvailability, createBooking, createBowlosClient, createCheckoutPaymentIntent, generateIdempotencyKey, getCheckoutStatus, listAddons, listStartTimes, localStorageTokenStore };
|
|
330
|
-
//# sourceMappingURL=chunk-
|
|
331
|
-
//# sourceMappingURL=chunk-
|
|
344
|
+
export { BOWLOS_ERROR_CODES, BowlosApiError, BowlosClient, abandonCheckout, availableUnitCount, bookingPreview, checkAvailability, createBooking, createBowlosClient, createCheckoutPaymentIntent, createGameCardOrder, generateIdempotencyKey, getCheckoutStatus, getGameCardStatus, listAddons, listStartTimes, localStorageTokenStore };
|
|
345
|
+
//# sourceMappingURL=chunk-ADHCZPTB.js.map
|
|
346
|
+
//# sourceMappingURL=chunk-ADHCZPTB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/client.ts","../src/data.ts"],"names":[],"mappings":";AAaO,IAAM,kBAAA,GAAqB;AAAA;AAAA,EAEhC,eAAA,EAAiB,iBAAA;AAAA,EACjB,eAAA,EAAiB,iBAAA;AAAA,EACjB,kBAAA,EAAoB,oBAAA;AAAA,EACpB,YAAA,EAAc,cAAA;AAAA;AAAA,EAEd,mBAAA,EAAqB,qBAAA;AAAA,EACrB,aAAA,EAAe,eAAA;AAAA;AAAA,EAEf,iBAAA,EAAmB,mBAAA;AAAA,EACnB,iBAAA,EAAmB,mBAAA;AAAA,EACnB,aAAA,EAAe,eAAA;AAAA,EACf,SAAA,EAAW,WAAA;AAAA,EACX,gBAAA,EAAkB,kBAAA;AAAA,EAClB,sBAAA,EAAwB,wBAAA;AAAA,EACxB,sBAAA,EAAwB,wBAAA;AAAA,EACxB,0BAAA,EAA4B,4BAAA;AAAA,EAC5B,gBAAA,EAAkB,kBAAA;AAAA;AAAA,EAElB,aAAA,EAAe,eAAA;AAAA,EACf,OAAA,EAAS;AACX;AAWO,IAAM,cAAA,GAAN,MAAM,eAAA,SAAuB,KAAA,CAAM;AAAA;AAAA,EAE/B,IAAA;AAAA;AAAA,EAEA,MAAA;AAAA;AAAA,EAEA,iBAAA;AAAA,EAET,YACE,IAAA,EACA,OAAA,EACA,MAAA,EACA,OAAA,GAAiC,EAA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,EAAM,CAAA;AACrF","file":"chunk-ADHCZPTB.js","sourcesContent":["/**\n * Error model for the BowlOS Reservations SDK.\n *\n * Every failed gateway call surfaces as a single `BowlosApiError` carrying a\n * stable `code` (string), the HTTP `status`, and — for rate limits — a\n * `retryAfterSeconds`. The gateway normalizes the backend's two error\n * conventions (thrown ConvexError + `{ ok:false }` envelopes) into one JSON\n * shape; this class is the client-side mirror of that shape, so consumers\n * branch on `error.code`, never on message text.\n */\n\n/** Stable error codes the gateway / backend can return. Open set — treat\n * `code` as a string and match against these for known cases. */\nexport const BOWLOS_ERROR_CODES = {\n // Gateway front door\n API_KEY_MISSING: \"API_KEY_MISSING\",\n API_KEY_INVALID: \"API_KEY_INVALID\",\n ORIGIN_NOT_ALLOWED: \"ORIGIN_NOT_ALLOWED\",\n RATE_LIMITED: \"RATE_LIMITED\",\n // Auth\n INVALID_CREDENTIALS: \"INVALID_CREDENTIALS\",\n SIGNUP_FAILED: \"SIGNUP_FAILED\",\n // Shared backend codes\n VALIDATION_FAILED: \"VALIDATION_FAILED\",\n PERMISSION_DENIED: \"PERMISSION_DENIED\",\n SCOPE_REVOKED: \"SCOPE_REVOKED\",\n NOT_FOUND: \"NOT_FOUND\",\n VERSION_CONFLICT: \"VERSION_CONFLICT\",\n PRICING_SNAPSHOT_STALE: \"PRICING_SNAPSHOT_STALE\",\n PAYMENTS_NOT_CONNECTED: \"PAYMENTS_NOT_CONNECTED\",\n CONNECT_ACCOUNT_RESTRICTED: \"CONNECT_ACCOUNT_RESTRICTED\",\n CHECKOUT_EXPIRED: \"CHECKOUT_EXPIRED\",\n // Client-side\n NETWORK_ERROR: \"NETWORK_ERROR\",\n UNKNOWN: \"ERROR\",\n} as const;\n\nexport type BowlosErrorCode =\n | (typeof BOWLOS_ERROR_CODES)[keyof typeof BOWLOS_ERROR_CODES]\n | (string & {});\n\nexport interface BowlosApiErrorOptions {\n retryAfterSeconds?: number;\n cause?: unknown;\n}\n\nexport class BowlosApiError extends Error {\n /** Stable, machine-readable code. Branch on this, not on `message`. */\n readonly code: BowlosErrorCode;\n /** HTTP status (0 for a network failure before any response). */\n readonly status: number;\n /** Seconds to wait before retrying — present only on `RATE_LIMITED`. */\n readonly retryAfterSeconds?: number;\n\n constructor(\n code: BowlosErrorCode,\n message: string,\n status: number,\n options: BowlosApiErrorOptions = {},\n ) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause });\n this.name = \"BowlosApiError\";\n this.code = code;\n this.status = status;\n this.retryAfterSeconds = options.retryAfterSeconds;\n // Restore prototype chain for instanceof across transpile targets.\n Object.setPrototypeOf(this, BowlosApiError.prototype);\n }\n\n /** Too many requests — caller should back off `retryAfterSeconds`. */\n get isRateLimited(): boolean {\n return this.code === BOWLOS_ERROR_CODES.RATE_LIMITED;\n }\n\n /** Bad/expired login. The session could not be established or has lapsed. */\n get isAuthError(): boolean {\n return (\n this.code === BOWLOS_ERROR_CODES.INVALID_CREDENTIALS ||\n this.code === BOWLOS_ERROR_CODES.PERMISSION_DENIED ||\n this.code === BOWLOS_ERROR_CODES.SCOPE_REVOKED\n );\n }\n\n /** Wrong/missing API key or a disallowed origin — a site-config problem,\n * not something the end customer can fix. */\n get isConfigError(): boolean {\n return (\n this.code === BOWLOS_ERROR_CODES.API_KEY_MISSING ||\n this.code === BOWLOS_ERROR_CODES.API_KEY_INVALID ||\n this.code === BOWLOS_ERROR_CODES.ORIGIN_NOT_ALLOWED\n );\n }\n}\n","/**\n * BowlosClient — the framework-agnostic core of the Reservations SDK.\n *\n * It is a thin, typed client for the public API gateway (`/api/public/v1/*`):\n * - sends the brand API key (`X-BowlOS-Api-Key`) on every request,\n * - attaches the customer bearer token on authenticated calls,\n * - parses the `{ ok, data | error }` envelope and throws a typed\n * `BowlosApiError` on failure,\n * - owns the customer session: sign-in / sign-up / link / sign-out, plus\n * a transparent refresh-and-retry-once when a session has expired.\n *\n * The React layer (hooks + components) wraps this; nothing here imports React.\n */\n\nimport { BowlosApiError, BOWLOS_ERROR_CODES } from \"./errors\";\nimport type {\n AuthState,\n BowlosClientConfig,\n Customer,\n FetchLike,\n LinkProfile,\n PingResult,\n TokenStore,\n Tokens,\n} from \"./types\";\n\nclass MemoryTokenStore implements TokenStore {\n private tokens: Tokens | null = null;\n get(): Tokens | null {\n return this.tokens;\n }\n set(tokens: Tokens | null): void {\n this.tokens = tokens;\n }\n}\n\n/** A `TokenStore` backed by `localStorage` for browser apps. No-ops under SSR\n * / environments without `localStorage`. */\nexport function localStorageTokenStore(storageKey = \"bowlos.tokens\"): TokenStore {\n return {\n get(): Tokens | null {\n if (typeof localStorage === \"undefined\") return null;\n const raw = localStorage.getItem(storageKey);\n if (!raw) return null;\n try {\n const parsed = JSON.parse(raw) as Partial<Tokens>;\n return parsed.token && parsed.refreshToken\n ? { token: parsed.token, refreshToken: parsed.refreshToken }\n : null;\n } catch {\n return null;\n }\n },\n set(tokens: Tokens | null): void {\n if (typeof localStorage === \"undefined\") return;\n if (tokens) localStorage.setItem(storageKey, JSON.stringify(tokens));\n else localStorage.removeItem(storageKey);\n },\n };\n}\n\ninterface RawResponse {\n status: number;\n body: unknown;\n retryAfterSeconds?: number;\n}\n\ninterface Envelope {\n ok?: boolean;\n data?: unknown;\n error?: { code?: string; message?: string };\n}\n\n/** Codes that mean \"the API key / origin is wrong\" — refreshing the customer\n * token can't fix these, so never retry them. */\nfunction isConfigErrorCode(code: string): boolean {\n return (\n code === BOWLOS_ERROR_CODES.API_KEY_MISSING ||\n code === BOWLOS_ERROR_CODES.API_KEY_INVALID ||\n code === BOWLOS_ERROR_CODES.ORIGIN_NOT_ALLOWED ||\n code === BOWLOS_ERROR_CODES.RATE_LIMITED\n );\n}\n\n/** Heuristic for \"the customer session lapsed\" — worth one refresh + retry.\n * An expired bearer surfaces as 401, or as PERMISSION_DENIED/SCOPE_REVOKED\n * from the delegated function. Key/origin errors are excluded above. */\nfunction looksLikeExpiredSession(status: number, code: string): boolean {\n if (isConfigErrorCode(code)) return false;\n return (\n status === 401 ||\n code === BOWLOS_ERROR_CODES.PERMISSION_DENIED ||\n code === BOWLOS_ERROR_CODES.SCOPE_REVOKED\n );\n}\n\nexport class BowlosClient {\n private readonly apiKey: string;\n private readonly baseUrl: string;\n private readonly store: TokenStore;\n private readonly fetchFn: FetchLike;\n\n constructor(config: BowlosClientConfig) {\n this.apiKey = config.apiKey;\n this.baseUrl = config.baseUrl.replace(/\\/+$/, \"\");\n this.store = config.tokenStore ?? new MemoryTokenStore();\n this.fetchFn = config.fetch ?? defaultFetch;\n\n if (!this.apiKey) throw new Error(\"BowlosClient: `apiKey` is required.\");\n if (!this.baseUrl) throw new Error(\"BowlosClient: `baseUrl` is required.\");\n }\n\n /** Is there a stored session right now? (Does not validate it server-side.) */\n isAuthenticated(): boolean {\n return this.store.get() !== null;\n }\n\n /** The current token pair, if any (rarely needed directly). */\n getTokens(): Tokens | null {\n return this.store.get();\n }\n\n /**\n * Health + key-validity probe (`GET /ping`). Resolves with the gateway's\n * service info when the API key is accepted; throws a `BowlosApiError` whose\n * `.code` distinguishes the failure (`NETWORK_ERROR`, `API_KEY_INVALID`,\n * `ORIGIN_NOT_ALLOWED`, `RATE_LIMITED`, …). Cheap enough to call on boot, and\n * the basis for `runDoctor`.\n */\n async ping(): Promise<PingResult> {\n const { status, body, retryAfterSeconds } = await this.request(\n \"ping\",\n {},\n this.store.get()?.token,\n \"GET\",\n );\n const env = (body ?? {}) as Envelope;\n if (env.ok === true) return env.data as PingResult;\n\n const code =\n env.error?.code ??\n (status === 429\n ? BOWLOS_ERROR_CODES.RATE_LIMITED\n : status === 404\n ? BOWLOS_ERROR_CODES.NOT_FOUND\n : BOWLOS_ERROR_CODES.UNKNOWN);\n throw new BowlosApiError(\n code,\n env.error?.message ?? `Health ping failed (HTTP ${status}).`,\n status,\n { retryAfterSeconds: code === BOWLOS_ERROR_CODES.RATE_LIMITED ? retryAfterSeconds : undefined },\n );\n }\n\n // ── low-level transport ────────────────────────────────────────────────\n\n private async request(\n name: string,\n args: Record<string, unknown>,\n bearer?: string,\n method: \"GET\" | \"POST\" = \"POST\",\n ): Promise<RawResponse> {\n const headers: Record<string, string> = {\n \"X-BowlOS-Api-Key\": this.apiKey,\n };\n if (method !== \"GET\") headers[\"Content-Type\"] = \"application/json\";\n if (bearer) headers[\"Authorization\"] = `Bearer ${bearer}`;\n\n const init: RequestInit = { method, headers };\n if (method !== \"GET\") init.body = JSON.stringify(args);\n\n let res: Response;\n try {\n res = await this.fetchFn(`${this.baseUrl}/${name}`, init);\n } catch (cause) {\n throw new BowlosApiError(\n BOWLOS_ERROR_CODES.NETWORK_ERROR,\n `Network request to \"${name}\" failed.`,\n 0,\n { cause },\n );\n }\n\n const retryHeader = res.headers.get(\"Retry-After\");\n const retryAfterSeconds = retryHeader ? Number(retryHeader) || undefined : undefined;\n\n let body: unknown = null;\n const text = await res.text();\n if (text) {\n try {\n body = JSON.parse(text);\n } catch {\n // Non-JSON (e.g. the router's plain \"No matching routes found\" 404).\n body = { ok: false, error: { code: BOWLOS_ERROR_CODES.NOT_FOUND, message: text.slice(0, 200) } };\n }\n }\n return { status: res.status, body, retryAfterSeconds };\n }\n\n /**\n * Call a gateway route by name (`POST /api/public/v1/<name>`), returning the\n * unwrapped `data`. Set `{ auth: true }` to attach the bearer token and\n * enable refresh-and-retry on an expired session.\n */\n async call<T = unknown>(\n name: string,\n args: Record<string, unknown> = {},\n opts: { auth?: boolean; method?: \"GET\" | \"POST\" } = {},\n ): Promise<T> {\n return this.callInternal<T>(name, args, opts.auth ?? false, false, opts.method ?? \"POST\");\n }\n\n private async callInternal<T>(\n name: string,\n args: Record<string, unknown>,\n auth: boolean,\n retried: boolean,\n method: \"GET\" | \"POST\",\n ): Promise<T> {\n const bearer = auth ? this.store.get()?.token : undefined;\n const { status, body, retryAfterSeconds } = await this.request(name, args, bearer, method);\n const env = (body ?? {}) as Envelope;\n\n if (env.ok === true) {\n // The data-passthrough routes delegate to functions that return their\n // OWN `{ schema_version, ok, data }` envelope, so the gateway double-wraps\n // them. Detect that inner envelope (uniquely marked by `schema_version`)\n // and unwrap it — surfacing an inner `{ ok:false }` as a thrown error.\n // Auth relays + the raw payment-intent payload have no `schema_version`,\n // so they pass straight through. Forward-compatible if the gateway is ever\n // changed to single-wrap (no inner envelope → nothing to unwrap).\n const data: unknown = env.data;\n if (data !== null && typeof data === \"object\" && \"schema_version\" in data && \"ok\" in data) {\n const inner = data as {\n ok: boolean;\n data?: unknown;\n error?: { code?: string; message?: string };\n };\n if (inner.ok === false) {\n throw new BowlosApiError(\n inner.error?.code ?? BOWLOS_ERROR_CODES.UNKNOWN,\n inner.error?.message ?? `Request to \"${name}\" failed.`,\n status,\n );\n }\n return inner.data as T;\n }\n return data as T;\n }\n\n const code =\n env.error?.code ??\n (status === 429\n ? BOWLOS_ERROR_CODES.RATE_LIMITED\n : status === 404\n ? BOWLOS_ERROR_CODES.NOT_FOUND\n : BOWLOS_ERROR_CODES.UNKNOWN);\n const message = env.error?.message ?? `Request to \"${name}\" failed (HTTP ${status}).`;\n\n if (auth && !retried && this.store.get() && looksLikeExpiredSession(status, code)) {\n const refreshed = await this.tryRefresh();\n if (refreshed) return this.callInternal<T>(name, args, auth, true, method);\n }\n\n throw new BowlosApiError(code, message, status, {\n retryAfterSeconds: code === BOWLOS_ERROR_CODES.RATE_LIMITED ? retryAfterSeconds : undefined,\n });\n }\n\n /** Exchange the stored refresh token for a fresh pair. Clears the session if\n * the refresh token is itself invalid/expired. Returns success. */\n private async tryRefresh(): Promise<boolean> {\n const current = this.store.get();\n if (!current?.refreshToken) return false;\n const { status, body } = await this.request(\"auth/refresh\", {\n refreshToken: current.refreshToken,\n });\n const env = (body ?? {}) as Envelope & { data?: { tokens?: Tokens } };\n if (status >= 200 && status < 300 && env.ok === true && env.data?.tokens) {\n this.store.set(env.data.tokens);\n return true;\n }\n this.store.set(null);\n return false;\n }\n\n // ── auth lifecycle ───────────────────────────────────────────────────────\n\n /** Sign an existing customer in; stores the session on success. */\n async signIn(email: string, password: string): Promise<Tokens> {\n const { tokens } = await this.call<{ tokens: Tokens }>(\"auth/signin\", { email, password });\n this.store.set(tokens);\n return tokens;\n }\n\n /** Create a login (the auth half of sign-up); stores the session. Follow with\n * `link()` to attach the customer profile. */\n async signUp(email: string, password: string): Promise<Tokens> {\n const { tokens } = await this.call<{ tokens: Tokens }>(\"auth/signup\", { email, password });\n this.store.set(tokens);\n return tokens;\n }\n\n /** Link the signed-in auth user to a customer profile at the brand. */\n async link(profile: LinkProfile): Promise<unknown> {\n return this.call(\"auth/link\", { ...profile }, { auth: true });\n }\n\n /** End the session (best-effort server call; always clears locally). */\n async signOut(): Promise<void> {\n try {\n await this.call(\"auth/signout\", {}, { auth: true });\n } catch {\n // Even if the server call fails (expired token, network), drop locally.\n } finally {\n this.store.set(null);\n }\n }\n\n /** Session bootstrap: unauthenticated / authed-no-customer / linked.\n * GET — matches the gateway's `GET /auth/probe` route. */\n async probe(): Promise<AuthState> {\n const { state } = await this.call<{ state: AuthState }>(\n \"auth/probe\",\n {},\n { auth: true, method: \"GET\" },\n );\n return state;\n }\n\n /** The signed-in customer's profile, or null.\n * GET — matches the gateway's `GET /auth/me` route. */\n async me(): Promise<Customer | null> {\n const { customer } = await this.call<{ customer: Customer | null }>(\n \"auth/me\",\n {},\n { auth: true, method: \"GET\" },\n );\n return customer;\n }\n}\n\n/** Default transport: the global fetch, invoked on `globalThis` so browsers\n * don't throw \"Illegal invocation\". Fails only on first use if absent. */\nconst defaultFetch: FetchLike = (input, init) => {\n if (typeof globalThis.fetch !== \"function\") {\n throw new BowlosApiError(\n BOWLOS_ERROR_CODES.NETWORK_ERROR,\n \"No global fetch available. Pass `config.fetch`.\",\n 0,\n );\n }\n return globalThis.fetch(input, init);\n};\n\n/** Create a configured client. */\nexport function createBowlosClient(config: BowlosClientConfig): BowlosClient {\n return new BowlosClient(config);\n}\n","/**\n * Typed data surface for @bowlos/reservations — booking-funnel reads.\n *\n * Arg shapes mirror the gateway functions; result shapes type the headline\n * fields and pass the rest through (`[key: string]: unknown`), so the backend's\n * full breakdown can grow without an SDK release. Each read has a\n * framework-agnostic function here and a React hook in `hooks.tsx`, sharing\n * these types.\n *\n * This file is React-free, so it's exported from the core entry. The hooks\n * (React) live in `hooks.tsx` under the React entry.\n */\nimport type { BowlosClient } from \"./client\";\n\n/** Inputs for `checkAvailability`. Times are minutes-of-day in the Center's tz. */\nexport type AvailabilityArgs = {\n productId: string;\n dateISO: string;\n startMinuteOfDay: number;\n endMinuteOfDay: number;\n};\n\nexport interface AvailabilityResult {\n totalUnits: number;\n busyUnitIds: string[];\n}\n\nexport type PricingMode = \"per_unit_per_hour\" | \"per_person_per_hour\" | \"per_game\";\n\nexport type BookingAddonSelection = { addonId: string; quantity: number };\n\n/** A bookable add-on for a product (shoe rental, upgrades…). `rateMode` is how\n * it prices — `per_person` (× bowlers), `per_unit` (× lanes), or `flat` (once).\n * `defaultQuantityRule: \"one_per_guest\"` hints the natural quantity is the\n * party size; `\"manual\"` means the customer picks. */\nexport interface PublicAddon {\n id: string;\n displayId: string;\n name: string;\n description: string | null;\n priceCents: number;\n rateMode: \"per_person\" | \"per_unit\" | \"flat\";\n defaultQuantityRule: \"one_per_guest\" | \"manual\";\n}\n\n/** Inputs for `bookingPreview` (the authoritative price quote). */\nexport type BookingPreviewArgs = {\n centerId: string;\n productId: string;\n dateISO: string;\n startMinuteOfDay: number;\n endMinuteOfDay: number;\n mode: PricingMode;\n units?: number;\n persons?: number;\n games?: number;\n addons?: BookingAddonSelection[];\n shareToken?: string;\n subtypeId?: string;\n};\n\n/** The price quote. Headline fields are typed; the engine's full breakdown\n * (line items, discounts, tax, credit) is passed through. */\nexport interface BookingQuote {\n reservationFee: Record<string, unknown> | null;\n totalCentsPerPlan: Array<{ pricePlanId: string; totalCents: number }>;\n [key: string]: unknown;\n}\n\n/** Free units for a product/date/time window (anonymous). */\nexport function checkAvailability(\n client: BowlosClient,\n args: AvailabilityArgs,\n): Promise<AvailabilityResult> {\n return client.call<AvailabilityResult>(\"checkAvailability\", args);\n}\n\n/** Authoritative price quote for the chosen inputs (anonymous; a signed-in\n * session unlocks member rates + account credit). */\nexport function bookingPreview(\n client: BowlosClient,\n args: BookingPreviewArgs,\n): Promise<BookingQuote> {\n return client.call<BookingQuote>(\"bookingPreview\", args);\n}\n\n/** Add-ons available for a product (shoe rental, upgrades…). Anonymous-callable;\n * feed the customer's picks back as `addons` on the preview + the booking. */\nexport function listAddons(\n client: BowlosClient,\n args: { productId: string },\n): Promise<PublicAddon[]> {\n return client.call<PublicAddon[]>(\"listPublicAddons\", args);\n}\n\n/** Inputs for `availableStartTimes`. */\nexport type StartTimesArgs = {\n productId: string;\n dateISO: string;\n /** Booking length, to leave room before close. Default 60 on the server. */\n durationMinutes?: number;\n /** Grid step in minutes. Default 30 on the server. */\n stepMinutes?: number;\n mode?: PricingMode;\n};\n\n/** The bookable start times (minute-of-day, ascending) for a product on a date:\n * within operating hours, past the booking buffer, and backed by a real price\n * plan (same pricing engine the quote uses). Anonymous-callable. */\nexport function listStartTimes(\n client: BowlosClient,\n args: StartTimesArgs,\n): Promise<number[]> {\n return client.call<number[]>(\"availableStartTimes\", args);\n}\n\n/** Convenience: free units = total minus the busy set (never negative). */\nexport function availableUnitCount(availability: AvailabilityResult): number {\n return Math.max(0, availability.totalUnits - availability.busyUnitIds.length);\n}\n\n// ── booking flow (hold → pay → confirm) ──────────────────────────────────────\n\n/** Customer identity for a booking (collected in the booking form; the server\n * links/creates the customer per the booking-flow-only signup rule). */\nexport type BookingCustomer = {\n fullName: string;\n email: string;\n mobile?: string;\n marketingOptIn: boolean;\n};\n\n/** Inputs for `createAnonymousBooking` — places the inventory hold. */\nexport type CreateBookingArgs = {\n centerId: string;\n productId: string;\n dateISO: string;\n startMinuteOfDay: number;\n endMinuteOfDay: number;\n mode: PricingMode;\n units?: number;\n persons?: number;\n games?: number;\n addons?: BookingAddonSelection[];\n customer: BookingCustomer;\n /** Apply account credit (requires a signed-in customer). */\n applyCredit?: boolean;\n /** Idempotency key for the create. The SDK generates one if omitted. */\n idempotencyKey?: string;\n shareToken?: string;\n subtypeId?: string;\n};\n\n/** Result of placing a booking. The hold→pay path returns `checkoutRefToken`\n * with `requiresPayment: true`; a credit-covered / $0 booking returns the\n * materialized `reservationId` + `reservationDisplayId` with\n * `requiresPayment: false`. Headline fields typed; the rest passes through. */\nexport interface BookingHold {\n checkoutRefToken?: string;\n reservationId?: string | null;\n reservationDisplayId?: string | null;\n requiresPayment: boolean;\n finalCents: number;\n appliedCreditCents: number;\n paidCents?: number;\n holdExpiresAt?: number;\n replayed?: boolean;\n [key: string]: unknown;\n}\n\nexport type CheckoutStatus =\n | \"not_found\"\n | \"pending_payment\"\n | \"paid_materialized\"\n | \"expired\"\n | \"payment_failed_retryable\"\n | \"abandoned\";\n\nexport interface CheckoutStatusResult {\n status: CheckoutStatus;\n reservationDisplayId: string | null;\n reservationId: string | null;\n}\n\n/** Stripe (Connect) PaymentIntent data for the UI layer to render Elements.\n * The SDK does NOT load Stripe.js — initialize it with `connectedAccountId`\n * (the operator's connected account) + `clientSecret`. */\nexport interface PaymentIntentInfo {\n paymentIntentId: string;\n clientSecret: string;\n amountCents: number;\n customerId: string;\n ephemeralKey: string;\n customerSessionClientSecret: string;\n connectedAccountId: string;\n}\n\n/** The minimal shape `<BowlosPaymentForm>` needs to confirm a payment on the\n * operator's connected account. `PaymentIntentInfo` (booking) and the buy-flow\n * intents both satisfy it; a recurring membership passes the subscription's\n * first-invoice `clientSecret` here too. */\nexport interface ConnectedPaymentInput {\n clientSecret: string;\n connectedAccountId: string;\n customerSessionClientSecret?: string;\n}\n\n// ── headless purchases (game passes; packages + memberships follow) ──────────\n\n/** Inputs for a game-pass purchase. The SDK generates an idempotency key if omitted. */\nexport type GameCardPurchaseArgs = {\n templateId: string;\n idempotencyKey?: string;\n shareToken?: string;\n};\n\n/** The connected-account PaymentIntent for a game-pass purchase. Confirm it with\n * `<BowlosPaymentForm>` — it carries `connectedAccountId` + the customer session.\n * Poll `getGameCardStatus(refToken)` for materialization. */\nexport interface GameCardPurchaseIntent {\n paymentIntentId: string;\n clientSecret: string;\n amountCents: number;\n refToken: string | null;\n cardId: string;\n customerSessionClientSecret: string;\n connectedAccountId: string;\n}\n\n/** Buy a game pass — mints the connected-account PaymentIntent (requires a\n * signed-in customer; the charge lands on the operator's connected account). */\nexport function createGameCardOrder(\n client: BowlosClient,\n args: GameCardPurchaseArgs,\n): Promise<GameCardPurchaseIntent> {\n const idempotencyKey = args.idempotencyKey ?? generateIdempotencyKey();\n return client.call<GameCardPurchaseIntent>(\n \"createGameCardPaymentIntent\",\n { ...args, idempotencyKey },\n { auth: true },\n );\n}\n\nexport type GameCardCheckoutStatus =\n | \"not_found\"\n | \"pending_payment\"\n | \"paid_materialized\"\n | \"expired\"\n | \"payment_failed_retryable\"\n | \"abandoned\";\n\nexport interface GameCardStatusResult {\n status: GameCardCheckoutStatus;\n gameCardId: string | null;\n}\n\n/** Poll a game-pass purchase to materialization (by the create's `refToken`). */\nexport function getGameCardStatus(\n client: BowlosClient,\n refToken: string,\n): Promise<GameCardStatusResult> {\n return client.call<GameCardStatusResult>(\n \"getGameCardCheckoutStatus\",\n { refToken },\n { auth: true },\n );\n}\n\n/** Browser/Node-safe idempotency key for booking creates. */\nexport function generateIdempotencyKey(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n return `idem_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;\n}\n\n/** Place the inventory hold + open a checkout. Sends the session when present\n * (member rates + account credit); falls back to anonymous. */\nexport function createBooking(\n client: BowlosClient,\n args: CreateBookingArgs,\n): Promise<BookingHold> {\n const idempotencyKey = args.idempotencyKey ?? generateIdempotencyKey();\n return client.call<BookingHold>(\n \"createAnonymousBooking\",\n { ...args, idempotencyKey },\n { auth: true },\n );\n}\n\n/** Mint the Stripe Connect PaymentIntent for a held checkout (by refToken). */\nexport function createCheckoutPaymentIntent(\n client: BowlosClient,\n refToken: string,\n): Promise<PaymentIntentInfo> {\n return client.call<PaymentIntentInfo>(\n \"createCheckoutPaymentIntent\",\n { refToken },\n { auth: true },\n );\n}\n\n/** Poll the hold→pay→materialize state for a checkout (by refToken). */\nexport function getCheckoutStatus(\n client: BowlosClient,\n refToken: string,\n): Promise<CheckoutStatusResult> {\n return client.call<CheckoutStatusResult>(\"getCheckoutStatus\", { refToken }, { auth: true });\n}\n\n/** Release the hold + cancel the checkout (the \"Back\" button). */\nexport function abandonCheckout(\n client: BowlosClient,\n refToken: string,\n): Promise<{ ok: boolean }> {\n return client.call<{ ok: boolean }>(\"abandonCheckout\", { refToken }, { auth: true });\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createBowlosClient, BowlosApiError, BOWLOS_ERROR_CODES, createBooking, createCheckoutPaymentIntent, getCheckoutStatus, abandonCheckout } from './chunk-
|
|
1
|
+
import { createBowlosClient, BowlosApiError, BOWLOS_ERROR_CODES, createBooking, createCheckoutPaymentIntent, getCheckoutStatus, abandonCheckout } from './chunk-ADHCZPTB.js';
|
|
2
2
|
import { createContext, useRef, useContext, useState, useCallback, useEffect } from 'react';
|
|
3
3
|
import { jsx } from 'react/jsx-runtime';
|
|
4
4
|
|
|
@@ -327,5 +327,5 @@ function useBookingFlow() {
|
|
|
327
327
|
}
|
|
328
328
|
|
|
329
329
|
export { BowlosProvider, useAccount, useAddons, useAvailability, useBookingFlow, useBookingPreview, useBowlosClient, useBowlosQuery, useEvents, useFlashSale, useFlashSaleBookingOptions, useFlashSales, useGameCards, useMyCredits, useMyLoyalty, useMyMembershipDetail, useMyMemberships, useMyPasses, useMyReservationDetail, useMyReservations, usePackages, useProducts, usePublicMemberships, useStartTimes };
|
|
330
|
-
//# sourceMappingURL=chunk-
|
|
331
|
-
//# sourceMappingURL=chunk-
|
|
330
|
+
//# sourceMappingURL=chunk-YA6PPZUS.js.map
|
|
331
|
+
//# sourceMappingURL=chunk-YA6PPZUS.js.map
|