@bowlos/reservations 0.22.0 → 0.22.1

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 CHANGED
@@ -135,6 +135,16 @@ const selectedAddons = Object.entries(qty).filter(([, q]) => q > 0).map(([addonI
135
135
  // Show priceCents with a rate suffix (/ person, / unit, flat) + a quantity stepper per addon.
136
136
  ```
137
137
 
138
+ **Included shoes are NOT a priced add-on.** The product read exposes
139
+ `shoeMode` + `defaultShoeAddonId` (also on `listProducts` rows), and a
140
+ reservation-mode event offer exposes `pricePlanShoeIncluded`. When
141
+ `product.shoeMode === "included"` — or, in an event funnel,
142
+ `offer.pricePlanShoeIncluded === true` — the engine charges $0 for the shoe
143
+ add-on no matter what quantity is sent. Do NOT render the shoe add-on
144
+ (`defaultShoeAddonId`) as a priced stepper in that case: show a static
145
+ "Shoe rental — included" note instead and send no quantity. Rendering a
146
+ priced stepper that doesn't change the total misleads the customer.
147
+
138
148
  ### 7. Review step — an order summary before payment
139
149
 
140
150
  Match the branded portal: selection → **review** → payment. After the customer
@@ -354,7 +364,10 @@ read the full offer with `useEventOffer({ slug })`.
354
364
  For `purchaseMode: "reservation"`, start the normal booking flow with the
355
365
  offer's `productId`, preselect `date`, `startMinuteOfDay`, and duration
356
366
  (`endMinuteOfDay - startMinuteOfDay`) when present, and preselect
357
- `includedAddons`. Pass `eventOfferSlug: offer.slug` into both
367
+ `includedAddons` — these are the offer's PRE-SELECTED add-ons, charged at
368
+ their normal add-on price on top of the event plan rate (they are not
369
+ free); initialize each add-on's quantity to the configured amount and let
370
+ the customer adjust. Pass `eventOfferSlug: offer.slug` into both
358
371
  `useBookingPreview` and the booking hold/create call (`useBookingFlow.startHold`
359
372
  or `createBooking`). The server uses that slug to bind the quote to the offer's
360
373
  event price plan, tax override, and Center fee override/inheritance. Then
@@ -711,6 +724,36 @@ Headless function twins (non-React):
711
724
  `createMembershipSubscriptionOrder(client, { templateId })`. (No status twin —
712
725
  subscriptions materialize via webhook; read `getMyMemberships(client, { brandId })`.)
713
726
 
727
+ ## Booking a flash-sale item at the sale price (headless)
728
+
729
+ A flash-sale reservation item books through a **purpose-built path** — never
730
+ the regular booking calendar (the sale price only exists on the sale's own
731
+ dates/blocks). All reads/creates are signed-in only.
732
+
733
+ 1. **List + landing**: `useFlashSales({ brandId })` for the index,
734
+ `useFlashSale({ slug })` for the sale page (anonymous gets the locked
735
+ view; members see prices).
736
+ 2. **Options**: `useFlashSaleBookingOptions({ slug, itemId })` (twin:
737
+ `getFlashSaleBookingOptions`) returns the bookable date/time-block
738
+ options **with the per-option sale price** for one reservation item
739
+ (`kind: "ok"` → `options[]`; handle `"signin_required"` /
740
+ `"unavailable"`). Render ONLY these options.
741
+ 3. **Book at the sale price** (v0.22.1): `createFlashSaleBooking(client,
742
+ { slug, itemId, dateISO, startMinuteOfDay, durationMinutes, units,
743
+ idempotencyKey })` — the flash analog of `eventOfferSlug`: the server
744
+ binds the item's SALE price, holds the inventory, and opens a checkout.
745
+ Returns `{ refToken, amountDueCents, holdExpiresAt, breakdown }` where
746
+ `breakdown` itemizes base (at the sale price) + tax + the Center fee —
747
+ render it as the static Review.
748
+ 4. **Pay + materialize** — the standard checkout pair:
749
+ `createCheckoutPaymentIntent(client, { refToken })` → confirm with your
750
+ Elements or `<BowlosPaymentForm>` → poll
751
+ `getCheckoutStatus(client, refToken)` to `"confirmed"` for the
752
+ reservation id. `abandonCheckout(client, refToken)` on back-out.
753
+
754
+ Never self-serve a flash booking through `bookingPreview`/`createBooking` —
755
+ those quote the REGULAR rate.
756
+
714
757
  ## The canonical catalog (visibility-aware) — `useCatalog`
715
758
 
716
759
  `<BookingCatalog>` assembles the catalog from five per-category reads
@@ -790,5 +833,7 @@ Headless sites do **not** get these from a version bump — apply them by hand.
790
833
 
791
834
  | **0.22.0** | **BREAKING: `<BookingCatalog>` is visibility-aware** — rebuilt on `useCatalog`/`listPublicCatalog`; `onSelect` hands off a `CatalogItem` (was the per-kind `CatalogOffer` union); section labels come from the backend (override via `sectionLabels`); new optional `surface` prop (default `"sdk_custom_site"`) | Headless sites need no change — `useCatalog` is unchanged. Sites using the drop-in update `onSelect` to route by `item.action.type` + `item.action.payload` (the routing table in "The canonical catalog"), and drop any `CatalogOffer` imports (`CatalogItem`/`CatalogSection`/`CatalogResult` are exported from `/components` too). Offers an admin hides for `sdk_custom_site` stop rendering in the drop-in — audit the admin Public Catalog page if something "disappears". |
792
835
 
836
+ | **0.22.1** | **Pay-button mount race fixed** (`<BowlosPaymentForm>` submit disabled until BOTH Stripe.js and the PaymentElement are mounted — a click during mount was a silent no-op) · **headless flash-sale checkout** — new `createFlashSaleBooking` (+ exported `CreateFlashSaleBookingArgs`/`FlashSaleBookingResult`) completing the options → book-at-sale-price → pay → poll path · docs: "Booking a flash-sale item" section; §6 included-shoes rule (`shoeMode`/`defaultShoeAddonId` + `offer.pricePlanShoeIncluded` — render "Included", never a priced stepper); event `includedAddons` are pre-selected AND charged | Custom payment UIs: mirror the disabled rule (`!stripe \|\| !elements \|\| submitting`). Flash funnels: adopt the new section (stop handing off / blocking). Event + bowling funnels: adopt the included-shoes rule in §6. |
837
+
793
838
  When you add the next release here, add its row **and** any new capability-map
794
839
  section in the same PR.
@@ -50,5 +50,41 @@ declare function getFlashSale<T = unknown>(client: BowlosClient, args: FlashSale
50
50
  /** The public flash-sale index for a Brand (live + upcoming; no prices). Public. */
51
51
  declare function getFlashSales<T = unknown>(client: BowlosClient, args: FlashSalesArgs): Promise<T>;
52
52
  declare function getFlashSaleBookingOptions<T = unknown>(client: BowlosClient, args: FlashBookingOptionsArgs): Promise<T>;
53
+ type CreateFlashSaleBookingArgs = {
54
+ slug: string;
55
+ itemId: string;
56
+ dateISO: string;
57
+ startMinuteOfDay: number;
58
+ durationMinutes: number;
59
+ units: number;
60
+ /** Per-attempt key; replays return the original checkout. */
61
+ idempotencyKey: string;
62
+ };
63
+ interface FlashSaleBookingResult {
64
+ /** Handle for the rest of the checkout: mint the PaymentIntent with
65
+ * `createCheckoutPaymentIntent(client, { refToken })`, then poll
66
+ * `getCheckoutStatus(client, refToken)` to materialization. */
67
+ refToken: string;
68
+ /** The SALE-priced total the PaymentIntent charges (base at the flash
69
+ * price + tax + the Center fee). */
70
+ amountDueCents: number;
71
+ holdExpiresAt: number;
72
+ breakdown: {
73
+ baseSubtotalCents: number;
74
+ reservationFeeCents: number;
75
+ reservationFeeLabel: string | null;
76
+ taxAddedCents: number;
77
+ taxIncludedCents: number;
78
+ totalCents: number;
79
+ };
80
+ }
81
+ /**
82
+ * v0.22.1 — book a flash-sale reservation item at its SALE price (the flash
83
+ * analog of `eventOfferSlug`: the server binds the item's sale price, holds
84
+ * the inventory, and opens a checkout). Signed-in customers only. Pick the
85
+ * date/time from `getFlashSaleBookingOptions` — the purpose-built option
86
+ * list — never the regular booking calendar.
87
+ */
88
+ declare function createFlashSaleBooking(client: BowlosClient, args: CreateFlashSaleBookingArgs): Promise<FlashSaleBookingResult>;
53
89
 
54
- export { type BrandScoped as B, type EventOrderDetailArgs as E, type FlashBookingOptionsArgs as F, type MembershipDetailArgs as M, type ReservationDetailArgs as R, type FlashSaleArgs as a, type FlashSalesArgs as b, getFlashSaleBookingOptions as c, getFlashSales as d, getMyCredits as e, getMyEventOrder as f, getFlashSale as g, getMyEventOrders as h, getMyLoyalty as i, getMyMembershipDetail as j, getMyMemberships as k, getMyPasses as l, getMyReservationDetail as m, getMyReservations as n };
90
+ export { type BrandScoped as B, type CreateFlashSaleBookingArgs as C, type EventOrderDetailArgs as E, type FlashBookingOptionsArgs as F, type MembershipDetailArgs as M, type ReservationDetailArgs as R, type FlashSaleArgs as a, type FlashSaleBookingResult as b, type FlashSalesArgs as c, createFlashSaleBooking as d, getFlashSaleBookingOptions as e, getFlashSales as f, getFlashSale as g, getMyCredits as h, getMyEventOrder as i, getMyEventOrders as j, getMyLoyalty as k, getMyMembershipDetail as l, getMyMemberships as m, getMyPasses as n, getMyReservationDetail as o, getMyReservations as p };
@@ -50,5 +50,41 @@ declare function getFlashSale<T = unknown>(client: BowlosClient, args: FlashSale
50
50
  /** The public flash-sale index for a Brand (live + upcoming; no prices). Public. */
51
51
  declare function getFlashSales<T = unknown>(client: BowlosClient, args: FlashSalesArgs): Promise<T>;
52
52
  declare function getFlashSaleBookingOptions<T = unknown>(client: BowlosClient, args: FlashBookingOptionsArgs): Promise<T>;
53
+ type CreateFlashSaleBookingArgs = {
54
+ slug: string;
55
+ itemId: string;
56
+ dateISO: string;
57
+ startMinuteOfDay: number;
58
+ durationMinutes: number;
59
+ units: number;
60
+ /** Per-attempt key; replays return the original checkout. */
61
+ idempotencyKey: string;
62
+ };
63
+ interface FlashSaleBookingResult {
64
+ /** Handle for the rest of the checkout: mint the PaymentIntent with
65
+ * `createCheckoutPaymentIntent(client, { refToken })`, then poll
66
+ * `getCheckoutStatus(client, refToken)` to materialization. */
67
+ refToken: string;
68
+ /** The SALE-priced total the PaymentIntent charges (base at the flash
69
+ * price + tax + the Center fee). */
70
+ amountDueCents: number;
71
+ holdExpiresAt: number;
72
+ breakdown: {
73
+ baseSubtotalCents: number;
74
+ reservationFeeCents: number;
75
+ reservationFeeLabel: string | null;
76
+ taxAddedCents: number;
77
+ taxIncludedCents: number;
78
+ totalCents: number;
79
+ };
80
+ }
81
+ /**
82
+ * v0.22.1 — book a flash-sale reservation item at its SALE price (the flash
83
+ * analog of `eventOfferSlug`: the server binds the item's sale price, holds
84
+ * the inventory, and opens a checkout). Signed-in customers only. Pick the
85
+ * date/time from `getFlashSaleBookingOptions` — the purpose-built option
86
+ * list — never the regular booking calendar.
87
+ */
88
+ declare function createFlashSaleBooking(client: BowlosClient, args: CreateFlashSaleBookingArgs): Promise<FlashSaleBookingResult>;
53
89
 
54
- export { type BrandScoped as B, type EventOrderDetailArgs as E, type FlashBookingOptionsArgs as F, type MembershipDetailArgs as M, type ReservationDetailArgs as R, type FlashSaleArgs as a, type FlashSalesArgs as b, getFlashSaleBookingOptions as c, getFlashSales as d, getMyCredits as e, getMyEventOrder as f, getFlashSale as g, getMyEventOrders as h, getMyLoyalty as i, getMyMembershipDetail as j, getMyMemberships as k, getMyPasses as l, getMyReservationDetail as m, getMyReservations as n };
90
+ export { type BrandScoped as B, type CreateFlashSaleBookingArgs as C, type EventOrderDetailArgs as E, type FlashBookingOptionsArgs as F, type MembershipDetailArgs as M, type ReservationDetailArgs as R, type FlashSaleArgs as a, type FlashSaleBookingResult as b, type FlashSalesArgs as c, createFlashSaleBooking as d, getFlashSaleBookingOptions as e, getFlashSales as f, getFlashSale as g, getMyCredits as h, getMyEventOrder as i, getMyEventOrders as j, getMyLoyalty as k, getMyMembershipDetail as l, getMyMemberships as m, getMyPasses as n, getMyReservationDetail as o, getMyReservations as p };
package/dist/index.cjs CHANGED
@@ -636,6 +636,11 @@ function getFlashSales(client, args) {
636
636
  function getFlashSaleBookingOptions(client, args) {
637
637
  return client.call("getFlashSaleBookingOptions", args, { auth: true });
638
638
  }
639
+ function createFlashSaleBooking(client, args) {
640
+ return client.call("createFlashSaleBooking", args, {
641
+ auth: true
642
+ });
643
+ }
639
644
 
640
645
  // src/catalog.ts
641
646
  function listCatalog(client, args) {
@@ -680,6 +685,7 @@ exports.createBooking = createBooking;
680
685
  exports.createBowlosClient = createBowlosClient;
681
686
  exports.createCheckoutPaymentIntent = createCheckoutPaymentIntent;
682
687
  exports.createEventTicketOrder = createEventTicketOrder;
688
+ exports.createFlashSaleBooking = createFlashSaleBooking;
683
689
  exports.createGameCardOrder = createGameCardOrder;
684
690
  exports.createMembershipOrder = createMembershipOrder;
685
691
  exports.createMembershipSubscriptionOrder = createMembershipSubscriptionOrder;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/client.ts","../src/doctor.ts","../src/data.ts","../src/account.ts","../src/catalog.ts"],"names":[],"mappings":";;;AAaO,IAAM,kBAAA,GAAqB;AAAA;AAAA,EAEhC,eAAA,EAAiB,iBAAA;AAAA,EACjB,eAAA,EAAiB,iBAAA;A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AAQ,qBAAA,EAAuB,IAAI,CAAA;AACnD;AAGO,SAAS,YAAA,CAA0B,QAAsB,IAAA,EAAoC;AAClG,EAAA,OAAO,MAAA,CAAO,IAAA,CAAQ,oBAAA,EAAsB,IAAI,CAAA;AAClD;AAKO,SAAS,UAAA,CAAwB,QAAsB,IAAA,EAAqC;AACjG,EAAA,OAAO,MAAA,CAAO,IAAA,CAAQ,kBAAA,EAAoB,IAAI,CAAA;AAChD;AAKO,SAAS,cAAA,CAA4B,QAAsB,IAAA,EAAmC;AACnG,EAAA,OAAO,MAAA,CAAO,IAAA,CAAQ,iCAAA,EAAmC,IAAI,CAAA;AAC/D;AAGO,SAAS,qBAAA,CACd,QACA,IAAA,EACY;AACZ,EAAA,OAAO,MAAA,CAAO,IAAA,CAAQ,uBAAA,EAAyB,IAAI,CAAA;AACrD;AAGO,SAAS,aAAA,CAA2B,QAAsB,IAAA,EAAoC;AACnG,EAAA,OAAO,MAAA,CAAO,IAAA,CAAQ,qBAAA,EAAuB,IAAI,CAAA;AACnD","file":"index.cjs","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 * `runDoctor` — a setup-readiness oracle for a site built on @bowlos/reservations.\n *\n * It runs a short sequence of checks against a configured gateway + API key and\n * returns a structured report (pass / warn / fail / skip), each with a one-line\n * fix when it isn't a pass. The point is to make per-site setup self-debuggable\n * — it walks the failure modes a new center site actually hits, in order:\n * config → gateway reachable → API key valid → origin allow-listed → data plane.\n *\n * Framework-agnostic and dependency-free: it builds a `BowlosClient`, leans on\n * `client.ping()` (one call covers reachability + key + origin + rate-limit),\n * and reports honestly — checks it can't run from the current environment are\n * `skip`ped with guidance rather than faked. The `bowlos doctor` CLI is a thin\n * wrapper that pretty-prints the report.\n */\nimport { createBowlosClient } from \"./client\";\nimport { BowlosApiError, BOWLOS_ERROR_CODES } from \"./errors\";\nimport type { FetchLike, PingResult } from \"./types\";\n\nexport type DoctorCheckStatus = \"pass\" | \"warn\" | \"fail\" | \"skip\";\n\nexport interface DoctorCheck {\n /** Stable id (`config` | `gateway` | `api-key` | `origin` | `rate-limit` | `data-read` | `payments`). */\n id: string;\n title: string;\n status: DoctorCheckStatus;\n detail: string;\n /** One-line remediation, present when `status` isn't `pass`. */\n fix?: string;\n}\n\nexport interface DoctorReport {\n /** True when no check failed (warnings and skips are tolerated). */\n ok: boolean;\n checks: DoctorCheck[];\n /** Echoed back so the CLI can show what it probed. */\n baseUrl: string;\n /** From a successful ping — the key's brand + mode. */\n brandId?: string;\n mode?: \"live\" | \"test\";\n}\n\nexport interface DoctorOptions {\n apiKey: string;\n baseUrl: string;\n /**\n * The deployed site origin. Origin allow-listing is enforced by the gateway\n * only for browser requests (Origin is a forbidden header from Node), so this\n * can be actively verified only in a browser; from Node it informs the\n * skip-guidance message.\n */\n origin?: string;\n /** Skip the (anonymous) data-plane read even when a brand is known. */\n skipDataRead?: boolean;\n /** Injectable transport (tests / SSR polyfills). */\n fetch?: FetchLike;\n}\n\nconst GATEWAY_SUFFIX = \"/api/public/v1\";\n\n/** Run the readiness checks and return a structured report. Never throws — every\n * failure mode is captured as a check. */\nexport async function runDoctor(options: DoctorOptions): Promise<DoctorReport> {\n const checks: DoctorCheck[] = [];\n const report: DoctorReport = { ok: true, checks, baseUrl: options.baseUrl };\n\n // 1) config — can we even build a client?\n const configIssues: string[] = [];\n if (!options.apiKey) configIssues.push(\"`apiKey` is empty\");\n let parsedUrl: URL | null = null;\n try {\n parsedUrl = new URL(options.baseUrl);\n } catch {\n configIssues.push(\"`baseUrl` is not a valid URL\");\n }\n if (configIssues.length > 0) {\n checks.push({\n id: \"config\",\n title: \"Client configuration\",\n status: \"fail\",\n detail: `${configIssues.join(\"; \")}.`,\n fix: \"Pass a brand API key and the gateway base URL, e.g. https://<deployment>.convex.site/api/public/v1\",\n });\n report.ok = false;\n return report; // can't probe without a valid client config\n }\n\n const urlMisaimed =\n parsedUrl !== null && !parsedUrl.pathname.replace(/\\/+$/, \"\").endsWith(GATEWAY_SUFFIX);\n checks.push({\n id: \"config\",\n title: \"Client configuration\",\n status: urlMisaimed ? \"warn\" : \"pass\",\n detail: urlMisaimed\n ? `baseUrl \"${options.baseUrl}\" doesn't end with ${GATEWAY_SUFFIX} — it should point at the gateway, not the site root.`\n : \"API key present; base URL well-formed.\",\n fix: urlMisaimed ? `Use the gateway URL, e.g. ${parsedUrl?.origin}${GATEWAY_SUFFIX}` : undefined,\n });\n\n const client = createBowlosClient({\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n fetch: options.fetch,\n });\n\n // 2) one ping covers: gateway reachable + key valid + (browser) origin + rate-limit.\n let ping: PingResult | null = null;\n try {\n ping = await client.ping();\n report.brandId = ping.brandId;\n report.mode = ping.mode;\n checks.push({\n id: \"gateway\",\n title: \"Gateway reachable\",\n status: \"pass\",\n detail: `Reached ${options.baseUrl} (service \"${ping.service}\", ${ping.version}).`,\n });\n checks.push({\n id: \"api-key\",\n title: \"API key accepted\",\n status: \"pass\",\n detail: `Key valid for brand ${ping.brandId} — mode: ${ping.mode}.`,\n });\n } catch (e) {\n const err = e instanceof BowlosApiError ? e : null;\n const code = err?.code ?? BOWLOS_ERROR_CODES.UNKNOWN;\n // A network error (status 0) or a router 404 means no real gateway answered;\n // any other coded envelope means the gateway responded (and judged the key).\n const reached =\n err !== null && err.status !== 0 && code !== BOWLOS_ERROR_CODES.NETWORK_ERROR && code !== BOWLOS_ERROR_CODES.NOT_FOUND;\n\n checks.push({\n id: \"gateway\",\n title: \"Gateway reachable\",\n status: reached ? \"pass\" : \"fail\",\n detail: reached\n ? `Reached ${options.baseUrl}.`\n : code === BOWLOS_ERROR_CODES.NETWORK_ERROR\n ? `Could not reach ${options.baseUrl} (network error).`\n : `No public-API gateway responded at ${options.baseUrl}.`,\n fix: reached\n ? undefined\n : \"Check the base URL, that the Convex deployment is live, and that the public-API routes are deployed.\",\n });\n\n if (code === BOWLOS_ERROR_CODES.RATE_LIMITED) {\n checks.push({\n id: \"api-key\",\n title: \"API key accepted\",\n status: \"pass\",\n detail: \"Key accepted (this probe was rate-limited).\",\n });\n checks.push({\n id: \"rate-limit\",\n title: \"Rate-limit headroom\",\n status: \"warn\",\n detail: `Currently rate-limited${err?.retryAfterSeconds ? ` — retry after ${err.retryAfterSeconds}s` : \"\"}.`,\n fix: \"Back off and retry; raise the key's per-minute limit if your real traffic is higher.\",\n });\n } else if (code === BOWLOS_ERROR_CODES.ORIGIN_NOT_ALLOWED) {\n checks.push({\n id: \"api-key\",\n title: \"API key accepted\",\n status: \"pass\",\n detail: \"Key accepted; the request was blocked on origin.\",\n });\n checks.push({\n id: \"origin\",\n title: \"Origin allow-listed\",\n status: \"fail\",\n detail: \"The request origin is not on the key's allow-list.\",\n fix: `Add your site origin${options.origin ? ` (${options.origin})` : \"\"} to the API key's allowed origins.`,\n });\n } else if (reached) {\n checks.push({\n id: \"api-key\",\n title: \"API key accepted\",\n status: \"fail\",\n detail:\n code === BOWLOS_ERROR_CODES.API_KEY_INVALID || code === BOWLOS_ERROR_CODES.API_KEY_MISSING\n ? \"The gateway rejected the API key.\"\n : `The gateway returned ${code}.`,\n fix: \"Mint or rotate a brand API key in the operator admin (Super-Admin → API keys) and use that value.\",\n });\n } else {\n checks.push({\n id: \"api-key\",\n title: \"API key accepted\",\n status: \"skip\",\n detail: \"Skipped — the gateway wasn't reachable.\",\n });\n }\n }\n\n // 3) origin — only actively verifiable in a browser (Origin is a forbidden\n // header from Node). A successful ping in a browser means the current\n // origin IS allow-listed; otherwise skip with guidance.\n if (!checks.some((c) => c.id === \"origin\")) {\n const browserOrigin =\n typeof window !== \"undefined\" && typeof window.location?.origin === \"string\"\n ? window.location.origin\n : null;\n if (ping !== null && browserOrigin !== null) {\n checks.push({\n id: \"origin\",\n title: \"Origin allow-listed\",\n status: \"pass\",\n detail: `This origin (${browserOrigin}) is allow-listed for the key.`,\n });\n } else {\n checks.push({\n id: \"origin\",\n title: \"Origin allow-listed\",\n status: \"skip\",\n detail: \"Origin allow-listing is enforced only for browser requests, so it can't be verified from a CLI.\",\n fix: `Ensure your deployed site origin${options.origin ? ` (${options.origin})` : \"\"} is on the key's allowed-origins list; load the site and watch for ORIGIN_NOT_ALLOWED.`,\n });\n }\n }\n\n // 4) data plane — a cheap anonymous read proves gateway → manifest → query → scope.\n if (ping !== null && options.skipDataRead !== true) {\n try {\n const data = await client.call<unknown>(\"listPublicCenters\", { brandId: ping.brandId });\n const innerError = typeof data === \"object\" && data !== null && (data as { ok?: boolean }).ok === false;\n checks.push({\n id: \"data-read\",\n title: \"Data passthrough\",\n status: innerError ? \"warn\" : \"pass\",\n detail: innerError\n ? \"Reached the data plane, but listPublicCenters returned an error envelope.\"\n : \"Anonymous read (listPublicCenters) succeeded — gateway → query passthrough works.\",\n fix: innerError ? \"Confirm the brand has at least one published center.\" : undefined,\n });\n } catch (e) {\n const err = e instanceof BowlosApiError ? e : null;\n checks.push({\n id: \"data-read\",\n title: \"Data passthrough\",\n status: \"warn\",\n detail: `An anonymous read failed${err ? ` (${err.code})` : \"\"}.`,\n fix: \"Key + gateway are fine; this read may need a published center or differ by brand. Safe to ignore if your booking reads work.\",\n });\n }\n } else if (ping === null) {\n checks.push({\n id: \"data-read\",\n title: \"Data passthrough\",\n status: \"skip\",\n detail: \"Skipped — needs a reachable gateway.\",\n });\n }\n\n // 5) payments — Stripe Connect status isn't exposed over the public API yet.\n // Honest skip (no faked pass) so the operator knows to verify it elsewhere.\n checks.push({\n id: \"payments\",\n title: \"Payments connected\",\n status: \"skip\",\n detail: \"Stripe Connect status isn't exposed over the public API yet, so the doctor can't verify it here.\",\n fix: \"Confirm the operator's Stripe account is connected + charges-enabled in the admin (Payments → Connect).\",\n });\n\n report.ok = !checks.some((c) => c.status === \"fail\");\n return report;\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 /** Reservation-mode event offer slug. Binds preview to that offer's event\n * price plan, tax override, and Center fee override/inheritance. */\n eventOfferSlug?: 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 taxLinesPerPlan?: Array<{\n pricePlanId: string;\n taxLines: Array<{\n rateId: string;\n label: string;\n rateBasisPoints: number;\n mode: \"added\" | \"included\";\n taxableBaseCents: number;\n taxCents: number;\n }>;\n taxTotalCents: number;\n }>;\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 /** Reservation-mode event offer slug. Must match the preview slug. */\n eventOfferSlug?: 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/** Inputs for an itemized game-pass quote. A pass has no config (no date/qty),\n * so it's just the template (+ an optional share token for a private pass).\n * The selling Center is resolved server-side from the customer's home Center. */\nexport type GameCardPreviewArgs = {\n templateId: string;\n shareToken?: string;\n};\n\n/** Server-computed itemized quote for a game-pass purchase — the base price,\n * tax lines, the selling Center's booking fee, and the authoritative grand\n * total. Drives the headless \"Review\" step. Computed by the SAME engine as the\n * PaymentIntent, so it never diverges from what the customer is charged. */\nexport interface GameCardPreviewResult {\n subtotalCents: number;\n taxLines: {\n rateId: string;\n label: string;\n rateBasisPoints: number;\n mode: \"added\" | \"included\";\n taxableBaseCents: number;\n taxCents: number;\n }[];\n taxTotalCents: number;\n reservationFeeCents: number | null;\n reservationFeeLabel: string | null;\n grandTotalCents: number;\n}\n\n/** Itemized quote for a game-pass purchase WITHOUT creating a PaymentIntent —\n * feeds the Review step. Requires a signed-in customer (so tax exemptions +\n * the resolved home Center match the eventual charge). */\nexport function previewGameCard(\n client: BowlosClient,\n args: GameCardPreviewArgs,\n): Promise<GameCardPreviewResult> {\n return client.call<GameCardPreviewResult>(\n \"previewGameCardOrder\",\n args,\n { auth: true },\n );\n}\n\nexport type EventTicketPreviewArgs = {\n eventOfferId: string;\n quantity: number;\n};\n\nexport interface EventTicketPreviewResult {\n eventName: string;\n eventDate: string;\n quantity: number;\n unitPriceCents: number;\n subtotalCents: number;\n taxLines: {\n rateId: string;\n label: string;\n rateBasisPoints: number;\n mode: \"added\" | \"included\";\n taxableBaseCents: number;\n taxCents: number;\n }[];\n taxTotalCents: number;\n reservationFeeCents: number | null;\n reservationFeeLabel: string | null;\n grandTotalCents: number;\n}\n\n/** Itemized quote for a ticket-mode event offer WITHOUT creating a\n * PaymentIntent. Requires a signed-in customer so tax exemptions match the\n * eventual charge. */\nexport function previewEventTicket(\n client: BowlosClient,\n args: EventTicketPreviewArgs,\n): Promise<EventTicketPreviewResult> {\n return client.call<EventTicketPreviewResult>(\n \"previewEventTicketOrder\",\n args,\n { auth: true },\n );\n}\n\nexport type EventTicketPurchaseArgs = {\n eventOfferId: string;\n quantity: number;\n idempotencyKey?: string;\n};\n\n/** The connected-account PaymentIntent for a ticket-mode event purchase.\n * Confirm it with `<BowlosPaymentForm>` — it carries `connectedAccountId` +\n * the customer session. After payment, read the receipt with `getMyEventOrder`. */\nexport interface EventTicketPurchaseIntent {\n paymentIntentId: string;\n clientSecret: string;\n amountCents: number;\n orderId: string;\n customerSessionClientSecret: string;\n connectedAccountId: string;\n}\n\n/** Buy tickets for a ticket-mode event offer — mints the connected-account\n * PaymentIntent. Requires a signed-in customer so taxes and account ownership\n * match the preview. */\nexport function createEventTicketOrder(\n client: BowlosClient,\n args: EventTicketPurchaseArgs,\n): Promise<EventTicketPurchaseIntent> {\n const idempotencyKey = args.idempotencyKey ?? generateIdempotencyKey();\n return client.call<EventTicketPurchaseIntent>(\n \"createEventTicketPaymentIntent\",\n { ...args, idempotencyKey },\n { auth: true },\n );\n}\n\nexport type EventTicketCheckoutStatus =\n | \"not_found\"\n | \"pending_payment\"\n | \"paid\"\n | \"cancelled\"\n | \"refunded\";\n\nexport interface EventTicketStatusResult {\n status: EventTicketCheckoutStatus;\n orderId: string | null;\n}\n\n/** Poll a ticket-mode event purchase by the order id returned from create. */\nexport function getEventTicketStatus(\n client: BowlosClient,\n orderId: string,\n): Promise<EventTicketStatusResult> {\n return client.call<EventTicketStatusResult>(\n \"getEventTicketCheckoutStatus\",\n { orderId },\n { auth: true },\n );\n}\n\n// ── headless purchases: packages ─────────────────────────────────────────────\n\n/** Inputs for a package purchase. The SDK generates an idempotency key if omitted.\n * `scheduledDate` is `YYYY-MM-DD` in the Center's timezone; `scheduledStartMinute`\n * is minutes-from-midnight (e.g. 1050 = 5:30 PM) and MUST be one of the package's\n * bookable start times — see HEADLESS.md → \"Buying a package\" for computing them. */\nexport type PackagePurchaseArgs = {\n packageId: string;\n centerId: string;\n quantity: number;\n optionalAddons?: { addonId: string; quantity: number }[];\n scheduledDate: string;\n scheduledStartMinute: number;\n idempotencyKey?: string;\n shareToken?: string;\n};\n\n/** The connected-account PaymentIntent for a package purchase. Confirm it with\n * `<BowlosPaymentForm>` — it carries `connectedAccountId` + the customer session.\n * Poll `getPackageStatus(orderId)` for materialization. */\nexport interface PackagePurchaseIntent {\n paymentIntentId: string;\n clientSecret: string;\n amountCents: number;\n orderId: string;\n customerSessionClientSecret: string;\n connectedAccountId: string;\n /** Group id for the inventory hold the order created — subscribe with\n * `getMyHoldGroup` to render the checkout countdown if you choose to. */\n inventoryHoldGroupId?: string;\n}\n\n/** Buy a package — mints the connected-account PaymentIntent (requires a\n * signed-in customer; the charge lands on the operator's connected account). */\nexport function createPackageOrder(\n client: BowlosClient,\n args: PackagePurchaseArgs,\n): Promise<PackagePurchaseIntent> {\n const idempotencyKey = args.idempotencyKey ?? generateIdempotencyKey();\n return client.call<PackagePurchaseIntent>(\n \"createPackagePaymentIntent\",\n { ...args, optionalAddons: args.optionalAddons ?? [], idempotencyKey },\n { auth: true },\n );\n}\n\nexport type PackageCheckoutStatus =\n | \"not_found\"\n | \"pending_payment\"\n | \"paid\"\n | \"cancelled\"\n | \"refunded\";\n\nexport interface PackageStatusResult {\n status: PackageCheckoutStatus;\n orderId: string | null;\n}\n\n/** Poll a package purchase to materialization (by the create's `orderId`). */\nexport function getPackageStatus(\n client: BowlosClient,\n orderId: string,\n): Promise<PackageStatusResult> {\n return client.call<PackageStatusResult>(\n \"getPackageCheckoutStatus\",\n { orderId },\n { auth: true },\n );\n}\n\n/** Inputs for an itemized package quote — the buy config minus the schedule\n * (price doesn't depend on date/time; the schedule only affects the eventual\n * create's slot validation). */\nexport type PackagePreviewArgs = {\n packageId: string;\n centerId: string;\n quantity: number;\n optionalAddons?: { addonId: string; quantity: number }[];\n shareToken?: string;\n};\n\n/** Server-computed itemized quote for a package order — base, optional add-ons,\n * tax lines, the selling Center's booking fee, and the authoritative grand\n * total. Drives the headless \"Review\" step. Computed by the SAME engine as the\n * PaymentIntent, so it never diverges from what the customer is charged. */\nexport interface PackagePreviewResult {\n baseTotalCents: number;\n addons: { addonId: string; name: string; quantity: number; lineCents: number }[];\n addonsTotalCents: number;\n taxLines: {\n rateId: string;\n label: string;\n rateBasisPoints: number;\n mode: \"added\" | \"included\";\n taxableBaseCents: number;\n taxCents: number;\n }[];\n taxTotalCents: number;\n reservationFeeCents: number | null;\n reservationFeeLabel: string | null;\n grandTotalCents: number;\n}\n\n/** Itemized quote for a package order WITHOUT creating a PaymentIntent — feeds\n * the Review step. Requires a signed-in customer (so tax exemptions match the\n * eventual charge). */\nexport function previewPackage(\n client: BowlosClient,\n args: PackagePreviewArgs,\n): Promise<PackagePreviewResult> {\n return client.call<PackagePreviewResult>(\n \"previewPackageOrder\",\n { ...args, optionalAddons: args.optionalAddons ?? [] },\n { auth: true },\n );\n}\n\n// ── headless purchases: memberships (one-time + recurring) ───────────────────\n\n/** Inputs for an itemized membership quote. A membership has no config (no\n * date/qty), so it's just the template (+ an optional share token for a private\n * membership). The selling Center is resolved server-side from the customer's\n * home Center. Shared by the one-time and recurring previews. */\nexport type MembershipPreviewArgs = {\n templateId: string;\n shareToken?: string;\n};\n\n/** Server-computed itemized quote for a one-time membership purchase — the dues,\n * the one-time setup (joining) fee, tax lines, the selling Center's booking fee,\n * and the authoritative grand total. Drives the headless \"Review\" step. Computed\n * by the SAME engine as the PaymentIntent, so it never diverges from what the\n * customer is charged. */\nexport interface MembershipPreviewResult {\n duesCents: number;\n setupFeeCents: number;\n subtotalCents: number;\n taxLines: {\n rateId: string;\n label: string;\n rateBasisPoints: number;\n mode: \"added\" | \"included\";\n taxableBaseCents: number;\n taxCents: number;\n }[];\n taxTotalCents: number;\n reservationFeeCents: number | null;\n reservationFeeLabel: string | null;\n grandTotalCents: number;\n}\n\n/** Itemized quote for a one-time membership purchase WITHOUT creating a\n * PaymentIntent — feeds the Review step. Requires a signed-in customer (so tax\n * exemptions + the resolved home Center match the eventual charge). */\nexport function previewMembership(\n client: BowlosClient,\n args: MembershipPreviewArgs,\n): Promise<MembershipPreviewResult> {\n return client.call<MembershipPreviewResult>(\n \"previewMembershipOrder\",\n args,\n { auth: true },\n );\n}\n\n/** Inputs for a one-time membership purchase. The SDK generates an idempotency\n * key if omitted. */\nexport type MembershipPurchaseArgs = {\n templateId: string;\n idempotencyKey?: string;\n shareToken?: string;\n};\n\n/** The connected-account PaymentIntent for a one-time membership purchase.\n * Confirm it with `<BowlosPaymentForm>` — it carries `connectedAccountId` + the\n * customer session. Poll `getMembershipStatus(refToken)` for materialization. */\nexport interface MembershipPurchaseIntent {\n paymentIntentId: string;\n clientSecret: string;\n amountCents: number;\n refToken: string | null;\n customerSessionClientSecret: string;\n connectedAccountId: string;\n}\n\n/** Buy a one-time membership — mints the connected-account PaymentIntent\n * (requires a signed-in customer; the charge lands on the operator's connected\n * account). */\nexport function createMembershipOrder(\n client: BowlosClient,\n args: MembershipPurchaseArgs,\n): Promise<MembershipPurchaseIntent> {\n const idempotencyKey = args.idempotencyKey ?? generateIdempotencyKey();\n return client.call<MembershipPurchaseIntent>(\n \"createMembershipPaymentIntent\",\n { ...args, idempotencyKey },\n { auth: true },\n );\n}\n\nexport type MembershipCheckoutStatus =\n | \"not_found\"\n | \"pending_payment\"\n | \"paid_materialized\"\n | \"expired\"\n | \"payment_failed_retryable\"\n | \"abandoned\";\n\nexport interface MembershipStatusResult {\n status: MembershipCheckoutStatus;\n membershipId: string | null;\n}\n\n/** Poll a one-time membership purchase to materialization (by the create's\n * `refToken`). */\nexport function getMembershipStatus(\n client: BowlosClient,\n refToken: string,\n): Promise<MembershipStatusResult> {\n return client.call<MembershipStatusResult>(\n \"getMembershipCheckoutStatus\",\n { refToken },\n { auth: true },\n );\n}\n\n/** Server-computed itemized quote for a RECURRING membership subscription — the\n * same fields as the one-time quote (what's charged today: dues + one-time setup\n * fee + tax + the selling Center's fee), PLUS `recurringTotalCents` (what each\n * renewal charges) and the `cadence`. Drives the recurring \"Review\" step's\n * \"Due today\" + \"Auto-renews at\" lines. Computed by the SAME engine as the\n * subscription's first invoice, so it never diverges. */\nexport interface MembershipSubscriptionPreviewResult extends MembershipPreviewResult {\n recurringTotalCents: number;\n cadence: \"monthly\" | \"annual\" | \"one_time\";\n}\n\n/** Itemized quote for a recurring membership subscription WITHOUT creating the\n * subscription — feeds the Review step. Requires a signed-in customer (so tax\n * exemptions + the resolved home Center match the eventual charge). */\nexport function previewMembershipSubscription(\n client: BowlosClient,\n args: MembershipPreviewArgs,\n): Promise<MembershipSubscriptionPreviewResult> {\n return client.call<MembershipSubscriptionPreviewResult>(\n \"previewMembershipSubscriptionOrder\",\n args,\n { auth: true },\n );\n}\n\n/** Inputs for a recurring membership subscription. (No idempotency key — the\n * subscription itself is the dedupe anchor; the buy is gated to one active\n * membership per customer.) */\nexport type MembershipSubscriptionArgs = {\n templateId: string;\n shareToken?: string;\n};\n\n/** The connected-account first-invoice payment for a recurring membership\n * subscription. Confirm `clientSecret` with `<BowlosPaymentForm>` — it carries\n * `connectedAccountId` + the customer session. There is NO refToken: the\n * subscription materializes via webhook, so re-query `useMyMemberships` after\n * payment rather than polling. */\nexport interface MembershipSubscriptionIntent {\n subscriptionId: string;\n clientSecret: string;\n amountCents: number;\n customerSessionClientSecret: string;\n connectedAccountId: string;\n}\n\n/** Start a recurring membership subscription — mints the subscription + its\n * first-invoice PaymentIntent on the operator's connected account (requires a\n * signed-in customer). Confirm the returned `clientSecret`; the subscription\n * materializes via webhook. */\nexport function createMembershipSubscriptionOrder(\n client: BowlosClient,\n args: MembershipSubscriptionArgs,\n): Promise<MembershipSubscriptionIntent> {\n return client.call<MembershipSubscriptionIntent>(\n \"createMembershipSubscription\",\n args,\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","/**\n * Typed account + flash reads for @bowlos/reservations.\n *\n * Session-scoped account reads (require a signed-in customer) and the\n * session-aware flash-sale reads. Args are typed precisely — every account read\n * is brand-scoped. Results are generic (`<T = unknown>`): parameterize with your\n * own shape, or read `unknown` and narrow. (The backend return shapes are rich\n * and evolving; the SDK doesn't pin them here.) Each read has a framework-agnostic\n * function here and a React hook in `hooks.tsx`.\n */\nimport type { BowlosClient } from \"./client\";\n\n/** Every account read is scoped to the customer's Brand. */\nexport type BrandScoped = { brandId: string };\nexport type ReservationDetailArgs = { brandId: string; displayId: string };\nexport type EventOrderDetailArgs = { brandId: string; orderId: string };\nexport type MembershipDetailArgs = { brandId: string; membershipId: string };\nexport type FlashSaleArgs = { slug: string };\nexport type FlashBookingOptionsArgs = { slug: string; itemId: string };\nexport type FlashSalesArgs = { brandId: string };\n\n// ── account (require a signed-in customer) ───────────────────────────────────\n\nexport function getMyReservations<T = unknown>(client: BowlosClient, args: BrandScoped): Promise<T> {\n return client.call<T>(\"listMyReservations\", args, { auth: true });\n}\n\nexport function getMyReservationDetail<T = unknown>(\n client: BowlosClient,\n args: ReservationDetailArgs,\n): Promise<T> {\n return client.call<T>(\"getMyReservationDetail\", args, { auth: true });\n}\n\nexport function getMyEventOrders<T = unknown>(client: BowlosClient, args: BrandScoped): Promise<T> {\n return client.call<T>(\"listMyEventOrders\", args, { auth: true });\n}\n\nexport function getMyEventOrder<T = unknown>(\n client: BowlosClient,\n args: EventOrderDetailArgs,\n): Promise<T> {\n return client.call<T>(\"getMyEventOrder\", args, { auth: true });\n}\n\nexport function getMyMemberships<T = unknown>(client: BowlosClient, args: BrandScoped): Promise<T> {\n return client.call<T>(\"listMyMemberships\", args, { auth: true });\n}\n\nexport function getMyMembershipDetail<T = unknown>(\n client: BowlosClient,\n args: MembershipDetailArgs,\n): Promise<T> {\n return client.call<T>(\"getMyMembershipDetail\", args, { auth: true });\n}\n\nexport function getMyLoyalty<T = unknown>(client: BowlosClient, args: BrandScoped): Promise<T> {\n return client.call<T>(\"getMyLoyalty\", args, { auth: true });\n}\n\nexport function getMyCredits<T = unknown>(client: BowlosClient, args: BrandScoped): Promise<T> {\n return client.call<T>(\"listMyCredits\", args, { auth: true });\n}\n\nexport function getMyPasses<T = unknown>(client: BowlosClient, args: BrandScoped): Promise<T> {\n return client.call<T>(\"listMyPasses\", args, { auth: true });\n}\n\n// ── flash sales (session-aware: members see prices) ──────────────────────────\n\nexport function getFlashSale<T = unknown>(client: BowlosClient, args: FlashSaleArgs): Promise<T> {\n return client.call<T>(\"getPublicFlashSaleBySlug\", args, { auth: true });\n}\n\n/** The public flash-sale index for a Brand (live + upcoming; no prices). Public. */\nexport function getFlashSales<T = unknown>(client: BowlosClient, args: FlashSalesArgs): Promise<T> {\n return client.call<T>(\"listPublicFlashSales\", args);\n}\n\nexport function getFlashSaleBookingOptions<T = unknown>(\n client: BowlosClient,\n args: FlashBookingOptionsArgs,\n): Promise<T> {\n return client.call<T>(\"getFlashSaleBookingOptions\", args, { auth: true });\n}\n","/**\n * Public catalog reads for @bowlos/reservations — the \"what can I book/buy here\"\n * surface that powers `<BookingCatalog>`. All anonymous (no customer login).\n * Products + events + memberships are Center-scoped; packages + game cards are\n * Brand-scoped (with an optional Center filter). Results are generic (`<T>`);\n * the component types the display fields it needs.\n */\nimport type { BowlosClient } from \"./client\";\n\nexport type CenterScoped = { centerId: string };\nexport type BrandCatalogArgs = { brandId: string; centerId?: string };\n\n// ── canonical catalog (listPublicCatalog) ─────────────────────────────────────\n// The one read that returns every category grouped + per-surface visibility\n// already applied. Prefer this over the per-category lists below when you want\n// the full, admin-controlled catalog for a surface. Types mirror the backend\n// wire shape (`@bowlos/shared` public-catalog).\n\n/** Which public surface is asking — the backend applies that surface's\n * per-category + per-offer visibility before returning. */\nexport type PublicSurface = \"sdk_custom_site\" | \"white_label_web\" | \"mobile_app\";\n\nexport type CatalogCategory =\n | \"bowling\"\n | \"other_attractions\"\n | \"events\"\n | \"packages\"\n | \"memberships\"\n | \"game_passes\";\n\nexport type CatalogActionType =\n | \"book_reservation\"\n | \"view_event\"\n | \"buy_ticket\"\n | \"buy_package\"\n | \"buy_membership\"\n | \"buy_game_pass\";\n\nexport type CatalogSourceTable =\n | \"products\"\n | \"event_offers\"\n | \"packages\"\n | \"membership_templates\"\n | \"game_card_templates\";\n\n/** A normalized, surface-agnostic catalog item. Route by `action.type`, using\n * the IDs in `action.payload` (e.g. `productId`, `slug`, `packageId`,\n * `templateId`). `priceLabel` is an indicative \"from $X\" only (null for\n * products — show \"See times & pricing\"); the binding price comes from the\n * per-category preview after login. */\nexport interface CatalogItem {\n id: string;\n category: CatalogCategory;\n sourceTable: CatalogSourceTable;\n sourceId: string;\n title: string;\n subtitle?: string | null;\n description?: string | null;\n priceLabel?: string | null;\n imageUrl?: string | null;\n badgeLabel?: string | null;\n action: { type: CatalogActionType; payload: Record<string, string> };\n}\n\nexport interface CatalogSection {\n key: CatalogCategory;\n label: string;\n items: CatalogItem[];\n}\n\nexport interface CatalogResult {\n sections: CatalogSection[];\n}\n\n/** Args for the canonical catalog read. `surface` selects which visibility\n * rules the backend applies. */\nexport type CatalogArgs = {\n brandId: string;\n centerId: string;\n surface: PublicSurface;\n};\n\n/**\n * The canonical public catalog for a surface — every active, public,\n * bookable/sellable item grouped into the six first-class categories, with the\n * Center admin's per-surface category + offer visibility already applied.\n * Anonymous. This is the recommended way to list \"everything bookable here\":\n * one call, all categories, visibility-aware, consistent with the white-label\n * web + mobile surfaces.\n */\nexport function listCatalog<T = CatalogResult>(\n client: BowlosClient,\n args: CatalogArgs,\n): Promise<T> {\n return client.call<T>(\"listPublicCatalog\", args);\n}\n/** One package's full detail. `shareToken` reveals a hidden/unlisted package. */\nexport type PackageDetailArgs = { packageId: string; shareToken?: string };\n/** Args for a Center's operating-hours window on a date, across attraction types. */\nexport type CenterHoursArgs = { centerId: string; attractionTypeKeys: string[]; dateISO: string };\n\n/** Bookable products at a Center (each carries its attraction + `attractionTypeKey`). */\nexport function listProducts<T = unknown>(client: BowlosClient, args: CenterScoped): Promise<T> {\n return client.call<T>(\"listPublicProducts\", args);\n}\n\n/** Upcoming pricing events (NYE Bash, tournaments…) at a Center. */\nexport function listEvents<T = unknown>(client: BowlosClient, args: CenterScoped): Promise<T> {\n return client.call<T>(\"listPublicEvents\", args);\n}\n\n/** Sellable event offers at a Center. These are the public lineup + event\n * landing-page records; use this instead of `listEvents` when routing a\n * customer to an event purchase flow. */\nexport function listEventOffers<T = unknown>(\n client: BowlosClient,\n args: CenterScoped,\n): Promise<T> {\n return client.call<T>(\"listPublicEventOffers\", args);\n}\n\n/** One sellable event offer by landing-page slug. */\nexport function getEventOffer<T = unknown>(\n client: BowlosClient,\n args: { slug: string },\n): Promise<T> {\n return client.call<T>(\"getPublicEventOffer\", args);\n}\n\n/** Purchasable packages at a Brand. */\nexport function listPackages<T = unknown>(client: BowlosClient, args: BrandCatalogArgs): Promise<T> {\n return client.call<T>(\"listPublicPackages\", args);\n}\n\n/** Full detail for one package — components, optional add-ons, allowed start\n * times, duration, and quantity bounds. Drives the headless package config UI\n * (see HEADLESS.md → \"Buying a package\"). */\nexport function getPackage<T = unknown>(client: BowlosClient, args: PackageDetailArgs): Promise<T> {\n return client.call<T>(\"getPublicPackage\", args);\n}\n\n/** A Center's combined open/close window (minutes-from-midnight) for the given\n * attraction types on a date — the intersection across types; `null` if closed.\n * Bound a package's start times with its component attraction-type keys. */\nexport function getCenterHours<T = unknown>(client: BowlosClient, args: CenterHoursArgs): Promise<T> {\n return client.call<T>(\"getCenterOperatingHoursForTypes\", args);\n}\n\n/** Purchasable memberships at a Center. */\nexport function listPublicMemberships<T = unknown>(\n client: BowlosClient,\n args: CenterScoped,\n): Promise<T> {\n return client.call<T>(\"listPublicMemberships\", args);\n}\n\n/** Purchasable game cards / passes at a Brand. */\nexport function listGameCards<T = unknown>(client: BowlosClient, args: BrandCatalogArgs): Promise<T> {\n return client.call<T>(\"listPublicGameCards\", args);\n}\n"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/client.ts","../src/doctor.ts","../src/data.ts","../src/account.ts","../src/catalog.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,EAAC,EAClC;AACA,IAAA,KAAA,CAAM,OAAA,EAAS,QAAQ,KAAA,KAAU,MAAA,GAAY,SAAY,EAAE,KAAA,EAAO,OAAA,CAAQ,KA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cjs","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 * `runDoctor` — a setup-readiness oracle for a site built on @bowlos/reservations.\n *\n * It runs a short sequence of checks against a configured gateway + API key and\n * returns a structured report (pass / warn / fail / skip), each with a one-line\n * fix when it isn't a pass. The point is to make per-site setup self-debuggable\n * — it walks the failure modes a new center site actually hits, in order:\n * config → gateway reachable → API key valid → origin allow-listed → data plane.\n *\n * Framework-agnostic and dependency-free: it builds a `BowlosClient`, leans on\n * `client.ping()` (one call covers reachability + key + origin + rate-limit),\n * and reports honestly — checks it can't run from the current environment are\n * `skip`ped with guidance rather than faked. The `bowlos doctor` CLI is a thin\n * wrapper that pretty-prints the report.\n */\nimport { createBowlosClient } from \"./client\";\nimport { BowlosApiError, BOWLOS_ERROR_CODES } from \"./errors\";\nimport type { FetchLike, PingResult } from \"./types\";\n\nexport type DoctorCheckStatus = \"pass\" | \"warn\" | \"fail\" | \"skip\";\n\nexport interface DoctorCheck {\n /** Stable id (`config` | `gateway` | `api-key` | `origin` | `rate-limit` | `data-read` | `payments`). */\n id: string;\n title: string;\n status: DoctorCheckStatus;\n detail: string;\n /** One-line remediation, present when `status` isn't `pass`. */\n fix?: string;\n}\n\nexport interface DoctorReport {\n /** True when no check failed (warnings and skips are tolerated). */\n ok: boolean;\n checks: DoctorCheck[];\n /** Echoed back so the CLI can show what it probed. */\n baseUrl: string;\n /** From a successful ping — the key's brand + mode. */\n brandId?: string;\n mode?: \"live\" | \"test\";\n}\n\nexport interface DoctorOptions {\n apiKey: string;\n baseUrl: string;\n /**\n * The deployed site origin. Origin allow-listing is enforced by the gateway\n * only for browser requests (Origin is a forbidden header from Node), so this\n * can be actively verified only in a browser; from Node it informs the\n * skip-guidance message.\n */\n origin?: string;\n /** Skip the (anonymous) data-plane read even when a brand is known. */\n skipDataRead?: boolean;\n /** Injectable transport (tests / SSR polyfills). */\n fetch?: FetchLike;\n}\n\nconst GATEWAY_SUFFIX = \"/api/public/v1\";\n\n/** Run the readiness checks and return a structured report. Never throws — every\n * failure mode is captured as a check. */\nexport async function runDoctor(options: DoctorOptions): Promise<DoctorReport> {\n const checks: DoctorCheck[] = [];\n const report: DoctorReport = { ok: true, checks, baseUrl: options.baseUrl };\n\n // 1) config — can we even build a client?\n const configIssues: string[] = [];\n if (!options.apiKey) configIssues.push(\"`apiKey` is empty\");\n let parsedUrl: URL | null = null;\n try {\n parsedUrl = new URL(options.baseUrl);\n } catch {\n configIssues.push(\"`baseUrl` is not a valid URL\");\n }\n if (configIssues.length > 0) {\n checks.push({\n id: \"config\",\n title: \"Client configuration\",\n status: \"fail\",\n detail: `${configIssues.join(\"; \")}.`,\n fix: \"Pass a brand API key and the gateway base URL, e.g. https://<deployment>.convex.site/api/public/v1\",\n });\n report.ok = false;\n return report; // can't probe without a valid client config\n }\n\n const urlMisaimed =\n parsedUrl !== null && !parsedUrl.pathname.replace(/\\/+$/, \"\").endsWith(GATEWAY_SUFFIX);\n checks.push({\n id: \"config\",\n title: \"Client configuration\",\n status: urlMisaimed ? \"warn\" : \"pass\",\n detail: urlMisaimed\n ? `baseUrl \"${options.baseUrl}\" doesn't end with ${GATEWAY_SUFFIX} — it should point at the gateway, not the site root.`\n : \"API key present; base URL well-formed.\",\n fix: urlMisaimed ? `Use the gateway URL, e.g. ${parsedUrl?.origin}${GATEWAY_SUFFIX}` : undefined,\n });\n\n const client = createBowlosClient({\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n fetch: options.fetch,\n });\n\n // 2) one ping covers: gateway reachable + key valid + (browser) origin + rate-limit.\n let ping: PingResult | null = null;\n try {\n ping = await client.ping();\n report.brandId = ping.brandId;\n report.mode = ping.mode;\n checks.push({\n id: \"gateway\",\n title: \"Gateway reachable\",\n status: \"pass\",\n detail: `Reached ${options.baseUrl} (service \"${ping.service}\", ${ping.version}).`,\n });\n checks.push({\n id: \"api-key\",\n title: \"API key accepted\",\n status: \"pass\",\n detail: `Key valid for brand ${ping.brandId} — mode: ${ping.mode}.`,\n });\n } catch (e) {\n const err = e instanceof BowlosApiError ? e : null;\n const code = err?.code ?? BOWLOS_ERROR_CODES.UNKNOWN;\n // A network error (status 0) or a router 404 means no real gateway answered;\n // any other coded envelope means the gateway responded (and judged the key).\n const reached =\n err !== null && err.status !== 0 && code !== BOWLOS_ERROR_CODES.NETWORK_ERROR && code !== BOWLOS_ERROR_CODES.NOT_FOUND;\n\n checks.push({\n id: \"gateway\",\n title: \"Gateway reachable\",\n status: reached ? \"pass\" : \"fail\",\n detail: reached\n ? `Reached ${options.baseUrl}.`\n : code === BOWLOS_ERROR_CODES.NETWORK_ERROR\n ? `Could not reach ${options.baseUrl} (network error).`\n : `No public-API gateway responded at ${options.baseUrl}.`,\n fix: reached\n ? undefined\n : \"Check the base URL, that the Convex deployment is live, and that the public-API routes are deployed.\",\n });\n\n if (code === BOWLOS_ERROR_CODES.RATE_LIMITED) {\n checks.push({\n id: \"api-key\",\n title: \"API key accepted\",\n status: \"pass\",\n detail: \"Key accepted (this probe was rate-limited).\",\n });\n checks.push({\n id: \"rate-limit\",\n title: \"Rate-limit headroom\",\n status: \"warn\",\n detail: `Currently rate-limited${err?.retryAfterSeconds ? ` — retry after ${err.retryAfterSeconds}s` : \"\"}.`,\n fix: \"Back off and retry; raise the key's per-minute limit if your real traffic is higher.\",\n });\n } else if (code === BOWLOS_ERROR_CODES.ORIGIN_NOT_ALLOWED) {\n checks.push({\n id: \"api-key\",\n title: \"API key accepted\",\n status: \"pass\",\n detail: \"Key accepted; the request was blocked on origin.\",\n });\n checks.push({\n id: \"origin\",\n title: \"Origin allow-listed\",\n status: \"fail\",\n detail: \"The request origin is not on the key's allow-list.\",\n fix: `Add your site origin${options.origin ? ` (${options.origin})` : \"\"} to the API key's allowed origins.`,\n });\n } else if (reached) {\n checks.push({\n id: \"api-key\",\n title: \"API key accepted\",\n status: \"fail\",\n detail:\n code === BOWLOS_ERROR_CODES.API_KEY_INVALID || code === BOWLOS_ERROR_CODES.API_KEY_MISSING\n ? \"The gateway rejected the API key.\"\n : `The gateway returned ${code}.`,\n fix: \"Mint or rotate a brand API key in the operator admin (Super-Admin → API keys) and use that value.\",\n });\n } else {\n checks.push({\n id: \"api-key\",\n title: \"API key accepted\",\n status: \"skip\",\n detail: \"Skipped — the gateway wasn't reachable.\",\n });\n }\n }\n\n // 3) origin — only actively verifiable in a browser (Origin is a forbidden\n // header from Node). A successful ping in a browser means the current\n // origin IS allow-listed; otherwise skip with guidance.\n if (!checks.some((c) => c.id === \"origin\")) {\n const browserOrigin =\n typeof window !== \"undefined\" && typeof window.location?.origin === \"string\"\n ? window.location.origin\n : null;\n if (ping !== null && browserOrigin !== null) {\n checks.push({\n id: \"origin\",\n title: \"Origin allow-listed\",\n status: \"pass\",\n detail: `This origin (${browserOrigin}) is allow-listed for the key.`,\n });\n } else {\n checks.push({\n id: \"origin\",\n title: \"Origin allow-listed\",\n status: \"skip\",\n detail: \"Origin allow-listing is enforced only for browser requests, so it can't be verified from a CLI.\",\n fix: `Ensure your deployed site origin${options.origin ? ` (${options.origin})` : \"\"} is on the key's allowed-origins list; load the site and watch for ORIGIN_NOT_ALLOWED.`,\n });\n }\n }\n\n // 4) data plane — a cheap anonymous read proves gateway → manifest → query → scope.\n if (ping !== null && options.skipDataRead !== true) {\n try {\n const data = await client.call<unknown>(\"listPublicCenters\", { brandId: ping.brandId });\n const innerError = typeof data === \"object\" && data !== null && (data as { ok?: boolean }).ok === false;\n checks.push({\n id: \"data-read\",\n title: \"Data passthrough\",\n status: innerError ? \"warn\" : \"pass\",\n detail: innerError\n ? \"Reached the data plane, but listPublicCenters returned an error envelope.\"\n : \"Anonymous read (listPublicCenters) succeeded — gateway → query passthrough works.\",\n fix: innerError ? \"Confirm the brand has at least one published center.\" : undefined,\n });\n } catch (e) {\n const err = e instanceof BowlosApiError ? e : null;\n checks.push({\n id: \"data-read\",\n title: \"Data passthrough\",\n status: \"warn\",\n detail: `An anonymous read failed${err ? ` (${err.code})` : \"\"}.`,\n fix: \"Key + gateway are fine; this read may need a published center or differ by brand. Safe to ignore if your booking reads work.\",\n });\n }\n } else if (ping === null) {\n checks.push({\n id: \"data-read\",\n title: \"Data passthrough\",\n status: \"skip\",\n detail: \"Skipped — needs a reachable gateway.\",\n });\n }\n\n // 5) payments — Stripe Connect status isn't exposed over the public API yet.\n // Honest skip (no faked pass) so the operator knows to verify it elsewhere.\n checks.push({\n id: \"payments\",\n title: \"Payments connected\",\n status: \"skip\",\n detail: \"Stripe Connect status isn't exposed over the public API yet, so the doctor can't verify it here.\",\n fix: \"Confirm the operator's Stripe account is connected + charges-enabled in the admin (Payments → Connect).\",\n });\n\n report.ok = !checks.some((c) => c.status === \"fail\");\n return report;\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 /** Reservation-mode event offer slug. Binds preview to that offer's event\n * price plan, tax override, and Center fee override/inheritance. */\n eventOfferSlug?: 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 taxLinesPerPlan?: Array<{\n pricePlanId: string;\n taxLines: Array<{\n rateId: string;\n label: string;\n rateBasisPoints: number;\n mode: \"added\" | \"included\";\n taxableBaseCents: number;\n taxCents: number;\n }>;\n taxTotalCents: number;\n }>;\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 /** Reservation-mode event offer slug. Must match the preview slug. */\n eventOfferSlug?: 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/** Inputs for an itemized game-pass quote. A pass has no config (no date/qty),\n * so it's just the template (+ an optional share token for a private pass).\n * The selling Center is resolved server-side from the customer's home Center. */\nexport type GameCardPreviewArgs = {\n templateId: string;\n shareToken?: string;\n};\n\n/** Server-computed itemized quote for a game-pass purchase — the base price,\n * tax lines, the selling Center's booking fee, and the authoritative grand\n * total. Drives the headless \"Review\" step. Computed by the SAME engine as the\n * PaymentIntent, so it never diverges from what the customer is charged. */\nexport interface GameCardPreviewResult {\n subtotalCents: number;\n taxLines: {\n rateId: string;\n label: string;\n rateBasisPoints: number;\n mode: \"added\" | \"included\";\n taxableBaseCents: number;\n taxCents: number;\n }[];\n taxTotalCents: number;\n reservationFeeCents: number | null;\n reservationFeeLabel: string | null;\n grandTotalCents: number;\n}\n\n/** Itemized quote for a game-pass purchase WITHOUT creating a PaymentIntent —\n * feeds the Review step. Requires a signed-in customer (so tax exemptions +\n * the resolved home Center match the eventual charge). */\nexport function previewGameCard(\n client: BowlosClient,\n args: GameCardPreviewArgs,\n): Promise<GameCardPreviewResult> {\n return client.call<GameCardPreviewResult>(\n \"previewGameCardOrder\",\n args,\n { auth: true },\n );\n}\n\nexport type EventTicketPreviewArgs = {\n eventOfferId: string;\n quantity: number;\n};\n\nexport interface EventTicketPreviewResult {\n eventName: string;\n eventDate: string;\n quantity: number;\n unitPriceCents: number;\n subtotalCents: number;\n taxLines: {\n rateId: string;\n label: string;\n rateBasisPoints: number;\n mode: \"added\" | \"included\";\n taxableBaseCents: number;\n taxCents: number;\n }[];\n taxTotalCents: number;\n reservationFeeCents: number | null;\n reservationFeeLabel: string | null;\n grandTotalCents: number;\n}\n\n/** Itemized quote for a ticket-mode event offer WITHOUT creating a\n * PaymentIntent. Requires a signed-in customer so tax exemptions match the\n * eventual charge. */\nexport function previewEventTicket(\n client: BowlosClient,\n args: EventTicketPreviewArgs,\n): Promise<EventTicketPreviewResult> {\n return client.call<EventTicketPreviewResult>(\n \"previewEventTicketOrder\",\n args,\n { auth: true },\n );\n}\n\nexport type EventTicketPurchaseArgs = {\n eventOfferId: string;\n quantity: number;\n idempotencyKey?: string;\n};\n\n/** The connected-account PaymentIntent for a ticket-mode event purchase.\n * Confirm it with `<BowlosPaymentForm>` — it carries `connectedAccountId` +\n * the customer session. After payment, read the receipt with `getMyEventOrder`. */\nexport interface EventTicketPurchaseIntent {\n paymentIntentId: string;\n clientSecret: string;\n amountCents: number;\n orderId: string;\n customerSessionClientSecret: string;\n connectedAccountId: string;\n}\n\n/** Buy tickets for a ticket-mode event offer — mints the connected-account\n * PaymentIntent. Requires a signed-in customer so taxes and account ownership\n * match the preview. */\nexport function createEventTicketOrder(\n client: BowlosClient,\n args: EventTicketPurchaseArgs,\n): Promise<EventTicketPurchaseIntent> {\n const idempotencyKey = args.idempotencyKey ?? generateIdempotencyKey();\n return client.call<EventTicketPurchaseIntent>(\n \"createEventTicketPaymentIntent\",\n { ...args, idempotencyKey },\n { auth: true },\n );\n}\n\nexport type EventTicketCheckoutStatus =\n | \"not_found\"\n | \"pending_payment\"\n | \"paid\"\n | \"cancelled\"\n | \"refunded\";\n\nexport interface EventTicketStatusResult {\n status: EventTicketCheckoutStatus;\n orderId: string | null;\n}\n\n/** Poll a ticket-mode event purchase by the order id returned from create. */\nexport function getEventTicketStatus(\n client: BowlosClient,\n orderId: string,\n): Promise<EventTicketStatusResult> {\n return client.call<EventTicketStatusResult>(\n \"getEventTicketCheckoutStatus\",\n { orderId },\n { auth: true },\n );\n}\n\n// ── headless purchases: packages ─────────────────────────────────────────────\n\n/** Inputs for a package purchase. The SDK generates an idempotency key if omitted.\n * `scheduledDate` is `YYYY-MM-DD` in the Center's timezone; `scheduledStartMinute`\n * is minutes-from-midnight (e.g. 1050 = 5:30 PM) and MUST be one of the package's\n * bookable start times — see HEADLESS.md → \"Buying a package\" for computing them. */\nexport type PackagePurchaseArgs = {\n packageId: string;\n centerId: string;\n quantity: number;\n optionalAddons?: { addonId: string; quantity: number }[];\n scheduledDate: string;\n scheduledStartMinute: number;\n idempotencyKey?: string;\n shareToken?: string;\n};\n\n/** The connected-account PaymentIntent for a package purchase. Confirm it with\n * `<BowlosPaymentForm>` — it carries `connectedAccountId` + the customer session.\n * Poll `getPackageStatus(orderId)` for materialization. */\nexport interface PackagePurchaseIntent {\n paymentIntentId: string;\n clientSecret: string;\n amountCents: number;\n orderId: string;\n customerSessionClientSecret: string;\n connectedAccountId: string;\n /** Group id for the inventory hold the order created — subscribe with\n * `getMyHoldGroup` to render the checkout countdown if you choose to. */\n inventoryHoldGroupId?: string;\n}\n\n/** Buy a package — mints the connected-account PaymentIntent (requires a\n * signed-in customer; the charge lands on the operator's connected account). */\nexport function createPackageOrder(\n client: BowlosClient,\n args: PackagePurchaseArgs,\n): Promise<PackagePurchaseIntent> {\n const idempotencyKey = args.idempotencyKey ?? generateIdempotencyKey();\n return client.call<PackagePurchaseIntent>(\n \"createPackagePaymentIntent\",\n { ...args, optionalAddons: args.optionalAddons ?? [], idempotencyKey },\n { auth: true },\n );\n}\n\nexport type PackageCheckoutStatus =\n | \"not_found\"\n | \"pending_payment\"\n | \"paid\"\n | \"cancelled\"\n | \"refunded\";\n\nexport interface PackageStatusResult {\n status: PackageCheckoutStatus;\n orderId: string | null;\n}\n\n/** Poll a package purchase to materialization (by the create's `orderId`). */\nexport function getPackageStatus(\n client: BowlosClient,\n orderId: string,\n): Promise<PackageStatusResult> {\n return client.call<PackageStatusResult>(\n \"getPackageCheckoutStatus\",\n { orderId },\n { auth: true },\n );\n}\n\n/** Inputs for an itemized package quote — the buy config minus the schedule\n * (price doesn't depend on date/time; the schedule only affects the eventual\n * create's slot validation). */\nexport type PackagePreviewArgs = {\n packageId: string;\n centerId: string;\n quantity: number;\n optionalAddons?: { addonId: string; quantity: number }[];\n shareToken?: string;\n};\n\n/** Server-computed itemized quote for a package order — base, optional add-ons,\n * tax lines, the selling Center's booking fee, and the authoritative grand\n * total. Drives the headless \"Review\" step. Computed by the SAME engine as the\n * PaymentIntent, so it never diverges from what the customer is charged. */\nexport interface PackagePreviewResult {\n baseTotalCents: number;\n addons: { addonId: string; name: string; quantity: number; lineCents: number }[];\n addonsTotalCents: number;\n taxLines: {\n rateId: string;\n label: string;\n rateBasisPoints: number;\n mode: \"added\" | \"included\";\n taxableBaseCents: number;\n taxCents: number;\n }[];\n taxTotalCents: number;\n reservationFeeCents: number | null;\n reservationFeeLabel: string | null;\n grandTotalCents: number;\n}\n\n/** Itemized quote for a package order WITHOUT creating a PaymentIntent — feeds\n * the Review step. Requires a signed-in customer (so tax exemptions match the\n * eventual charge). */\nexport function previewPackage(\n client: BowlosClient,\n args: PackagePreviewArgs,\n): Promise<PackagePreviewResult> {\n return client.call<PackagePreviewResult>(\n \"previewPackageOrder\",\n { ...args, optionalAddons: args.optionalAddons ?? [] },\n { auth: true },\n );\n}\n\n// ── headless purchases: memberships (one-time + recurring) ───────────────────\n\n/** Inputs for an itemized membership quote. A membership has no config (no\n * date/qty), so it's just the template (+ an optional share token for a private\n * membership). The selling Center is resolved server-side from the customer's\n * home Center. Shared by the one-time and recurring previews. */\nexport type MembershipPreviewArgs = {\n templateId: string;\n shareToken?: string;\n};\n\n/** Server-computed itemized quote for a one-time membership purchase — the dues,\n * the one-time setup (joining) fee, tax lines, the selling Center's booking fee,\n * and the authoritative grand total. Drives the headless \"Review\" step. Computed\n * by the SAME engine as the PaymentIntent, so it never diverges from what the\n * customer is charged. */\nexport interface MembershipPreviewResult {\n duesCents: number;\n setupFeeCents: number;\n subtotalCents: number;\n taxLines: {\n rateId: string;\n label: string;\n rateBasisPoints: number;\n mode: \"added\" | \"included\";\n taxableBaseCents: number;\n taxCents: number;\n }[];\n taxTotalCents: number;\n reservationFeeCents: number | null;\n reservationFeeLabel: string | null;\n grandTotalCents: number;\n}\n\n/** Itemized quote for a one-time membership purchase WITHOUT creating a\n * PaymentIntent — feeds the Review step. Requires a signed-in customer (so tax\n * exemptions + the resolved home Center match the eventual charge). */\nexport function previewMembership(\n client: BowlosClient,\n args: MembershipPreviewArgs,\n): Promise<MembershipPreviewResult> {\n return client.call<MembershipPreviewResult>(\n \"previewMembershipOrder\",\n args,\n { auth: true },\n );\n}\n\n/** Inputs for a one-time membership purchase. The SDK generates an idempotency\n * key if omitted. */\nexport type MembershipPurchaseArgs = {\n templateId: string;\n idempotencyKey?: string;\n shareToken?: string;\n};\n\n/** The connected-account PaymentIntent for a one-time membership purchase.\n * Confirm it with `<BowlosPaymentForm>` — it carries `connectedAccountId` + the\n * customer session. Poll `getMembershipStatus(refToken)` for materialization. */\nexport interface MembershipPurchaseIntent {\n paymentIntentId: string;\n clientSecret: string;\n amountCents: number;\n refToken: string | null;\n customerSessionClientSecret: string;\n connectedAccountId: string;\n}\n\n/** Buy a one-time membership — mints the connected-account PaymentIntent\n * (requires a signed-in customer; the charge lands on the operator's connected\n * account). */\nexport function createMembershipOrder(\n client: BowlosClient,\n args: MembershipPurchaseArgs,\n): Promise<MembershipPurchaseIntent> {\n const idempotencyKey = args.idempotencyKey ?? generateIdempotencyKey();\n return client.call<MembershipPurchaseIntent>(\n \"createMembershipPaymentIntent\",\n { ...args, idempotencyKey },\n { auth: true },\n );\n}\n\nexport type MembershipCheckoutStatus =\n | \"not_found\"\n | \"pending_payment\"\n | \"paid_materialized\"\n | \"expired\"\n | \"payment_failed_retryable\"\n | \"abandoned\";\n\nexport interface MembershipStatusResult {\n status: MembershipCheckoutStatus;\n membershipId: string | null;\n}\n\n/** Poll a one-time membership purchase to materialization (by the create's\n * `refToken`). */\nexport function getMembershipStatus(\n client: BowlosClient,\n refToken: string,\n): Promise<MembershipStatusResult> {\n return client.call<MembershipStatusResult>(\n \"getMembershipCheckoutStatus\",\n { refToken },\n { auth: true },\n );\n}\n\n/** Server-computed itemized quote for a RECURRING membership subscription — the\n * same fields as the one-time quote (what's charged today: dues + one-time setup\n * fee + tax + the selling Center's fee), PLUS `recurringTotalCents` (what each\n * renewal charges) and the `cadence`. Drives the recurring \"Review\" step's\n * \"Due today\" + \"Auto-renews at\" lines. Computed by the SAME engine as the\n * subscription's first invoice, so it never diverges. */\nexport interface MembershipSubscriptionPreviewResult extends MembershipPreviewResult {\n recurringTotalCents: number;\n cadence: \"monthly\" | \"annual\" | \"one_time\";\n}\n\n/** Itemized quote for a recurring membership subscription WITHOUT creating the\n * subscription — feeds the Review step. Requires a signed-in customer (so tax\n * exemptions + the resolved home Center match the eventual charge). */\nexport function previewMembershipSubscription(\n client: BowlosClient,\n args: MembershipPreviewArgs,\n): Promise<MembershipSubscriptionPreviewResult> {\n return client.call<MembershipSubscriptionPreviewResult>(\n \"previewMembershipSubscriptionOrder\",\n args,\n { auth: true },\n );\n}\n\n/** Inputs for a recurring membership subscription. (No idempotency key — the\n * subscription itself is the dedupe anchor; the buy is gated to one active\n * membership per customer.) */\nexport type MembershipSubscriptionArgs = {\n templateId: string;\n shareToken?: string;\n};\n\n/** The connected-account first-invoice payment for a recurring membership\n * subscription. Confirm `clientSecret` with `<BowlosPaymentForm>` — it carries\n * `connectedAccountId` + the customer session. There is NO refToken: the\n * subscription materializes via webhook, so re-query `useMyMemberships` after\n * payment rather than polling. */\nexport interface MembershipSubscriptionIntent {\n subscriptionId: string;\n clientSecret: string;\n amountCents: number;\n customerSessionClientSecret: string;\n connectedAccountId: string;\n}\n\n/** Start a recurring membership subscription — mints the subscription + its\n * first-invoice PaymentIntent on the operator's connected account (requires a\n * signed-in customer). Confirm the returned `clientSecret`; the subscription\n * materializes via webhook. */\nexport function createMembershipSubscriptionOrder(\n client: BowlosClient,\n args: MembershipSubscriptionArgs,\n): Promise<MembershipSubscriptionIntent> {\n return client.call<MembershipSubscriptionIntent>(\n \"createMembershipSubscription\",\n args,\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","/**\n * Typed account + flash reads for @bowlos/reservations.\n *\n * Session-scoped account reads (require a signed-in customer) and the\n * session-aware flash-sale reads. Args are typed precisely — every account read\n * is brand-scoped. Results are generic (`<T = unknown>`): parameterize with your\n * own shape, or read `unknown` and narrow. (The backend return shapes are rich\n * and evolving; the SDK doesn't pin them here.) Each read has a framework-agnostic\n * function here and a React hook in `hooks.tsx`.\n */\nimport type { BowlosClient } from \"./client\";\n\n/** Every account read is scoped to the customer's Brand. */\nexport type BrandScoped = { brandId: string };\nexport type ReservationDetailArgs = { brandId: string; displayId: string };\nexport type EventOrderDetailArgs = { brandId: string; orderId: string };\nexport type MembershipDetailArgs = { brandId: string; membershipId: string };\nexport type FlashSaleArgs = { slug: string };\nexport type FlashBookingOptionsArgs = { slug: string; itemId: string };\nexport type FlashSalesArgs = { brandId: string };\n\n// ── account (require a signed-in customer) ───────────────────────────────────\n\nexport function getMyReservations<T = unknown>(client: BowlosClient, args: BrandScoped): Promise<T> {\n return client.call<T>(\"listMyReservations\", args, { auth: true });\n}\n\nexport function getMyReservationDetail<T = unknown>(\n client: BowlosClient,\n args: ReservationDetailArgs,\n): Promise<T> {\n return client.call<T>(\"getMyReservationDetail\", args, { auth: true });\n}\n\nexport function getMyEventOrders<T = unknown>(client: BowlosClient, args: BrandScoped): Promise<T> {\n return client.call<T>(\"listMyEventOrders\", args, { auth: true });\n}\n\nexport function getMyEventOrder<T = unknown>(\n client: BowlosClient,\n args: EventOrderDetailArgs,\n): Promise<T> {\n return client.call<T>(\"getMyEventOrder\", args, { auth: true });\n}\n\nexport function getMyMemberships<T = unknown>(client: BowlosClient, args: BrandScoped): Promise<T> {\n return client.call<T>(\"listMyMemberships\", args, { auth: true });\n}\n\nexport function getMyMembershipDetail<T = unknown>(\n client: BowlosClient,\n args: MembershipDetailArgs,\n): Promise<T> {\n return client.call<T>(\"getMyMembershipDetail\", args, { auth: true });\n}\n\nexport function getMyLoyalty<T = unknown>(client: BowlosClient, args: BrandScoped): Promise<T> {\n return client.call<T>(\"getMyLoyalty\", args, { auth: true });\n}\n\nexport function getMyCredits<T = unknown>(client: BowlosClient, args: BrandScoped): Promise<T> {\n return client.call<T>(\"listMyCredits\", args, { auth: true });\n}\n\nexport function getMyPasses<T = unknown>(client: BowlosClient, args: BrandScoped): Promise<T> {\n return client.call<T>(\"listMyPasses\", args, { auth: true });\n}\n\n// ── flash sales (session-aware: members see prices) ──────────────────────────\n\nexport function getFlashSale<T = unknown>(client: BowlosClient, args: FlashSaleArgs): Promise<T> {\n return client.call<T>(\"getPublicFlashSaleBySlug\", args, { auth: true });\n}\n\n/** The public flash-sale index for a Brand (live + upcoming; no prices). Public. */\nexport function getFlashSales<T = unknown>(client: BowlosClient, args: FlashSalesArgs): Promise<T> {\n return client.call<T>(\"listPublicFlashSales\", args);\n}\n\nexport function getFlashSaleBookingOptions<T = unknown>(\n client: BowlosClient,\n args: FlashBookingOptionsArgs,\n): Promise<T> {\n return client.call<T>(\"getFlashSaleBookingOptions\", args, { auth: true });\n}\n\nexport type CreateFlashSaleBookingArgs = {\n slug: string;\n itemId: string;\n dateISO: string;\n startMinuteOfDay: number;\n durationMinutes: number;\n units: number;\n /** Per-attempt key; replays return the original checkout. */\n idempotencyKey: string;\n};\n\nexport interface FlashSaleBookingResult {\n /** Handle for the rest of the checkout: mint the PaymentIntent with\n * `createCheckoutPaymentIntent(client, { refToken })`, then poll\n * `getCheckoutStatus(client, refToken)` to materialization. */\n refToken: string;\n /** The SALE-priced total the PaymentIntent charges (base at the flash\n * price + tax + the Center fee). */\n amountDueCents: number;\n holdExpiresAt: number;\n breakdown: {\n baseSubtotalCents: number;\n reservationFeeCents: number;\n reservationFeeLabel: string | null;\n taxAddedCents: number;\n taxIncludedCents: number;\n totalCents: number;\n };\n}\n\n/**\n * v0.22.1 — book a flash-sale reservation item at its SALE price (the flash\n * analog of `eventOfferSlug`: the server binds the item's sale price, holds\n * the inventory, and opens a checkout). Signed-in customers only. Pick the\n * date/time from `getFlashSaleBookingOptions` — the purpose-built option\n * list — never the regular booking calendar.\n */\nexport function createFlashSaleBooking(\n client: BowlosClient,\n args: CreateFlashSaleBookingArgs,\n): Promise<FlashSaleBookingResult> {\n return client.call<FlashSaleBookingResult>(\"createFlashSaleBooking\", args, {\n auth: true,\n });\n}\n","/**\n * Public catalog reads for @bowlos/reservations — the \"what can I book/buy here\"\n * surface that powers `<BookingCatalog>`. All anonymous (no customer login).\n * Products + events + memberships are Center-scoped; packages + game cards are\n * Brand-scoped (with an optional Center filter). Results are generic (`<T>`);\n * the component types the display fields it needs.\n */\nimport type { BowlosClient } from \"./client\";\n\nexport type CenterScoped = { centerId: string };\nexport type BrandCatalogArgs = { brandId: string; centerId?: string };\n\n// ── canonical catalog (listPublicCatalog) ─────────────────────────────────────\n// The one read that returns every category grouped + per-surface visibility\n// already applied. Prefer this over the per-category lists below when you want\n// the full, admin-controlled catalog for a surface. Types mirror the backend\n// wire shape (`@bowlos/shared` public-catalog).\n\n/** Which public surface is asking — the backend applies that surface's\n * per-category + per-offer visibility before returning. */\nexport type PublicSurface = \"sdk_custom_site\" | \"white_label_web\" | \"mobile_app\";\n\nexport type CatalogCategory =\n | \"bowling\"\n | \"other_attractions\"\n | \"events\"\n | \"packages\"\n | \"memberships\"\n | \"game_passes\";\n\nexport type CatalogActionType =\n | \"book_reservation\"\n | \"view_event\"\n | \"buy_ticket\"\n | \"buy_package\"\n | \"buy_membership\"\n | \"buy_game_pass\";\n\nexport type CatalogSourceTable =\n | \"products\"\n | \"event_offers\"\n | \"packages\"\n | \"membership_templates\"\n | \"game_card_templates\";\n\n/** A normalized, surface-agnostic catalog item. Route by `action.type`, using\n * the IDs in `action.payload` (e.g. `productId`, `slug`, `packageId`,\n * `templateId`). `priceLabel` is an indicative \"from $X\" only (null for\n * products — show \"See times & pricing\"); the binding price comes from the\n * per-category preview after login. */\nexport interface CatalogItem {\n id: string;\n category: CatalogCategory;\n sourceTable: CatalogSourceTable;\n sourceId: string;\n title: string;\n subtitle?: string | null;\n description?: string | null;\n priceLabel?: string | null;\n imageUrl?: string | null;\n badgeLabel?: string | null;\n action: { type: CatalogActionType; payload: Record<string, string> };\n}\n\nexport interface CatalogSection {\n key: CatalogCategory;\n label: string;\n items: CatalogItem[];\n}\n\nexport interface CatalogResult {\n sections: CatalogSection[];\n}\n\n/** Args for the canonical catalog read. `surface` selects which visibility\n * rules the backend applies. */\nexport type CatalogArgs = {\n brandId: string;\n centerId: string;\n surface: PublicSurface;\n};\n\n/**\n * The canonical public catalog for a surface — every active, public,\n * bookable/sellable item grouped into the six first-class categories, with the\n * Center admin's per-surface category + offer visibility already applied.\n * Anonymous. This is the recommended way to list \"everything bookable here\":\n * one call, all categories, visibility-aware, consistent with the white-label\n * web + mobile surfaces.\n */\nexport function listCatalog<T = CatalogResult>(\n client: BowlosClient,\n args: CatalogArgs,\n): Promise<T> {\n return client.call<T>(\"listPublicCatalog\", args);\n}\n/** One package's full detail. `shareToken` reveals a hidden/unlisted package. */\nexport type PackageDetailArgs = { packageId: string; shareToken?: string };\n/** Args for a Center's operating-hours window on a date, across attraction types. */\nexport type CenterHoursArgs = { centerId: string; attractionTypeKeys: string[]; dateISO: string };\n\n/** Bookable products at a Center (each carries its attraction + `attractionTypeKey`). */\nexport function listProducts<T = unknown>(client: BowlosClient, args: CenterScoped): Promise<T> {\n return client.call<T>(\"listPublicProducts\", args);\n}\n\n/** Upcoming pricing events (NYE Bash, tournaments…) at a Center. */\nexport function listEvents<T = unknown>(client: BowlosClient, args: CenterScoped): Promise<T> {\n return client.call<T>(\"listPublicEvents\", args);\n}\n\n/** Sellable event offers at a Center. These are the public lineup + event\n * landing-page records; use this instead of `listEvents` when routing a\n * customer to an event purchase flow. */\nexport function listEventOffers<T = unknown>(\n client: BowlosClient,\n args: CenterScoped,\n): Promise<T> {\n return client.call<T>(\"listPublicEventOffers\", args);\n}\n\n/** One sellable event offer by landing-page slug. */\nexport function getEventOffer<T = unknown>(\n client: BowlosClient,\n args: { slug: string },\n): Promise<T> {\n return client.call<T>(\"getPublicEventOffer\", args);\n}\n\n/** Purchasable packages at a Brand. */\nexport function listPackages<T = unknown>(client: BowlosClient, args: BrandCatalogArgs): Promise<T> {\n return client.call<T>(\"listPublicPackages\", args);\n}\n\n/** Full detail for one package — components, optional add-ons, allowed start\n * times, duration, and quantity bounds. Drives the headless package config UI\n * (see HEADLESS.md → \"Buying a package\"). */\nexport function getPackage<T = unknown>(client: BowlosClient, args: PackageDetailArgs): Promise<T> {\n return client.call<T>(\"getPublicPackage\", args);\n}\n\n/** A Center's combined open/close window (minutes-from-midnight) for the given\n * attraction types on a date — the intersection across types; `null` if closed.\n * Bound a package's start times with its component attraction-type keys. */\nexport function getCenterHours<T = unknown>(client: BowlosClient, args: CenterHoursArgs): Promise<T> {\n return client.call<T>(\"getCenterOperatingHoursForTypes\", args);\n}\n\n/** Purchasable memberships at a Center. */\nexport function listPublicMemberships<T = unknown>(\n client: BowlosClient,\n args: CenterScoped,\n): Promise<T> {\n return client.call<T>(\"listPublicMemberships\", args);\n}\n\n/** Purchasable game cards / passes at a Brand. */\nexport function listGameCards<T = unknown>(client: BowlosClient, args: BrandCatalogArgs): Promise<T> {\n return client.call<T>(\"listPublicGameCards\", args);\n}\n"]}
package/dist/index.d.cts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { F as FetchLike } from './data-BKlgn8Ln.cjs';
2
2
  export { A as AuthState, a as AvailabilityArgs, b as AvailabilityResult, B as BookingAddonSelection, c as BookingCustomer, d as BookingHold, e as BookingPreviewArgs, f as BookingQuote, g as BowlosClient, h as BowlosClientConfig, C as CheckoutStatus, i as CheckoutStatusResult, j as ConnectedPaymentInput, k as CreateBookingArgs, l as Customer, E as EventTicketCheckoutStatus, m as EventTicketPreviewArgs, n as EventTicketPreviewResult, o as EventTicketPurchaseArgs, p as EventTicketPurchaseIntent, q as EventTicketStatusResult, G as GameCardCheckoutStatus, r as GameCardPreviewArgs, s as GameCardPreviewResult, t as GameCardPurchaseArgs, u as GameCardPurchaseIntent, v as GameCardStatusResult, L as LinkProfile, M as MembershipCheckoutStatus, w as MembershipPreviewArgs, x as MembershipPreviewResult, y as MembershipPurchaseArgs, z as MembershipPurchaseIntent, D as MembershipStatusResult, H as MembershipSubscriptionArgs, I as MembershipSubscriptionIntent, J as MembershipSubscriptionPreviewResult, P as PackageCheckoutStatus, K as PackagePreviewArgs, N as PackagePreviewResult, O as PackagePurchaseArgs, Q as PackagePurchaseIntent, R as PackageStatusResult, S as PaymentIntentInfo, T as PingResult, U as PricingMode, V as PublicAddon, W as StartTimesArgs, X as TokenStore, Y as Tokens, Z as abandonCheckout, _ as availableUnitCount, $ as bookingPreview, a0 as checkAvailability, a1 as createBooking, a2 as createBowlosClient, a3 as createCheckoutPaymentIntent, a4 as createEventTicketOrder, a5 as createGameCardOrder, a6 as createMembershipOrder, a7 as createMembershipSubscriptionOrder, a8 as createPackageOrder, a9 as generateIdempotencyKey, aa as getCheckoutStatus, ab as getEventTicketStatus, ac as getGameCardStatus, ad as getMembershipStatus, ae as getPackageStatus, af as listAddons, ag as listStartTimes, ah as localStorageTokenStore, ai as previewEventTicket, aj as previewGameCard, ak as previewMembership, al as previewMembershipSubscription, am as previewPackage } from './data-BKlgn8Ln.cjs';
3
3
  export { B as BOWLOS_ERROR_CODES, a as BowlosApiError, b as BowlosApiErrorOptions, c as BowlosErrorCode, d as BrandCatalogArgs, C as CatalogActionType, e as CatalogArgs, f as CatalogCategory, g as CatalogItem, h as CatalogResult, i as CatalogSection, j as CatalogSourceTable, k as CenterHoursArgs, l as CenterScoped, P as PackageDetailArgs, m as PublicSurface, n as getCenterHours, o as getEventOffer, p as getPackage, q as listCatalog, r as listEventOffers, s as listEvents, t as listGameCards, u as listPackages, v as listProducts, w as listPublicMemberships } from './catalog-D1VoVaNe.cjs';
4
- export { B as BrandScoped, E as EventOrderDetailArgs, F as FlashBookingOptionsArgs, a as FlashSaleArgs, b as FlashSalesArgs, M as MembershipDetailArgs, R as ReservationDetailArgs, g as getFlashSale, c as getFlashSaleBookingOptions, d as getFlashSales, e as getMyCredits, f as getMyEventOrder, h as getMyEventOrders, i as getMyLoyalty, j as getMyMembershipDetail, k as getMyMemberships, l as getMyPasses, m as getMyReservationDetail, n as getMyReservations } from './account-SqT7et4C.cjs';
4
+ export { B as BrandScoped, C as CreateFlashSaleBookingArgs, E as EventOrderDetailArgs, F as FlashBookingOptionsArgs, a as FlashSaleArgs, b as FlashSaleBookingResult, c as FlashSalesArgs, M as MembershipDetailArgs, R as ReservationDetailArgs, d as createFlashSaleBooking, g as getFlashSale, e as getFlashSaleBookingOptions, f as getFlashSales, h as getMyCredits, i as getMyEventOrder, j as getMyEventOrders, k as getMyLoyalty, l as getMyMembershipDetail, m as getMyMemberships, n as getMyPasses, o as getMyReservationDetail, p as getMyReservations } from './account-CSaBohMT.cjs';
5
5
 
6
6
  type DoctorCheckStatus = "pass" | "warn" | "fail" | "skip";
7
7
  interface DoctorCheck {
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { F as FetchLike } from './data-BKlgn8Ln.js';
2
2
  export { A as AuthState, a as AvailabilityArgs, b as AvailabilityResult, B as BookingAddonSelection, c as BookingCustomer, d as BookingHold, e as BookingPreviewArgs, f as BookingQuote, g as BowlosClient, h as BowlosClientConfig, C as CheckoutStatus, i as CheckoutStatusResult, j as ConnectedPaymentInput, k as CreateBookingArgs, l as Customer, E as EventTicketCheckoutStatus, m as EventTicketPreviewArgs, n as EventTicketPreviewResult, o as EventTicketPurchaseArgs, p as EventTicketPurchaseIntent, q as EventTicketStatusResult, G as GameCardCheckoutStatus, r as GameCardPreviewArgs, s as GameCardPreviewResult, t as GameCardPurchaseArgs, u as GameCardPurchaseIntent, v as GameCardStatusResult, L as LinkProfile, M as MembershipCheckoutStatus, w as MembershipPreviewArgs, x as MembershipPreviewResult, y as MembershipPurchaseArgs, z as MembershipPurchaseIntent, D as MembershipStatusResult, H as MembershipSubscriptionArgs, I as MembershipSubscriptionIntent, J as MembershipSubscriptionPreviewResult, P as PackageCheckoutStatus, K as PackagePreviewArgs, N as PackagePreviewResult, O as PackagePurchaseArgs, Q as PackagePurchaseIntent, R as PackageStatusResult, S as PaymentIntentInfo, T as PingResult, U as PricingMode, V as PublicAddon, W as StartTimesArgs, X as TokenStore, Y as Tokens, Z as abandonCheckout, _ as availableUnitCount, $ as bookingPreview, a0 as checkAvailability, a1 as createBooking, a2 as createBowlosClient, a3 as createCheckoutPaymentIntent, a4 as createEventTicketOrder, a5 as createGameCardOrder, a6 as createMembershipOrder, a7 as createMembershipSubscriptionOrder, a8 as createPackageOrder, a9 as generateIdempotencyKey, aa as getCheckoutStatus, ab as getEventTicketStatus, ac as getGameCardStatus, ad as getMembershipStatus, ae as getPackageStatus, af as listAddons, ag as listStartTimes, ah as localStorageTokenStore, ai as previewEventTicket, aj as previewGameCard, ak as previewMembership, al as previewMembershipSubscription, am as previewPackage } from './data-BKlgn8Ln.js';
3
3
  export { B as BOWLOS_ERROR_CODES, a as BowlosApiError, b as BowlosApiErrorOptions, c as BowlosErrorCode, d as BrandCatalogArgs, C as CatalogActionType, e as CatalogArgs, f as CatalogCategory, g as CatalogItem, h as CatalogResult, i as CatalogSection, j as CatalogSourceTable, k as CenterHoursArgs, l as CenterScoped, P as PackageDetailArgs, m as PublicSurface, n as getCenterHours, o as getEventOffer, p as getPackage, q as listCatalog, r as listEventOffers, s as listEvents, t as listGameCards, u as listPackages, v as listProducts, w as listPublicMemberships } from './catalog-BxyPJdBL.js';
4
- export { B as BrandScoped, E as EventOrderDetailArgs, F as FlashBookingOptionsArgs, a as FlashSaleArgs, b as FlashSalesArgs, M as MembershipDetailArgs, R as ReservationDetailArgs, g as getFlashSale, c as getFlashSaleBookingOptions, d as getFlashSales, e as getMyCredits, f as getMyEventOrder, h as getMyEventOrders, i as getMyLoyalty, j as getMyMembershipDetail, k as getMyMemberships, l as getMyPasses, m as getMyReservationDetail, n as getMyReservations } from './account-CO8xzUs_.js';
4
+ export { B as BrandScoped, C as CreateFlashSaleBookingArgs, E as EventOrderDetailArgs, F as FlashBookingOptionsArgs, a as FlashSaleArgs, b as FlashSaleBookingResult, c as FlashSalesArgs, M as MembershipDetailArgs, R as ReservationDetailArgs, d as createFlashSaleBooking, g as getFlashSale, e as getFlashSaleBookingOptions, f as getFlashSales, h as getMyCredits, i as getMyEventOrder, j as getMyEventOrders, k as getMyLoyalty, l as getMyMembershipDetail, m as getMyMemberships, n as getMyPasses, o as getMyReservationDetail, p as getMyReservations } from './account-Bm2XnaYS.js';
5
5
 
6
6
  type DoctorCheckStatus = "pass" | "warn" | "fail" | "skip";
7
7
  interface DoctorCheck {
package/dist/index.js CHANGED
@@ -207,6 +207,11 @@ function getFlashSales(client, args) {
207
207
  function getFlashSaleBookingOptions(client, args) {
208
208
  return client.call("getFlashSaleBookingOptions", args, { auth: true });
209
209
  }
210
+ function createFlashSaleBooking(client, args) {
211
+ return client.call("createFlashSaleBooking", args, {
212
+ auth: true
213
+ });
214
+ }
210
215
 
211
216
  // src/catalog.ts
212
217
  function listCatalog(client, args) {
@@ -240,6 +245,6 @@ function listGameCards(client, args) {
240
245
  return client.call("listPublicGameCards", args);
241
246
  }
242
247
 
243
- export { getCenterHours, getEventOffer, getFlashSale, getFlashSaleBookingOptions, getFlashSales, getMyCredits, getMyEventOrder, getMyEventOrders, getMyLoyalty, getMyMembershipDetail, getMyMemberships, getMyPasses, getMyReservationDetail, getMyReservations, getPackage, listCatalog, listEventOffers, listEvents, listGameCards, listPackages, listProducts, listPublicMemberships, runDoctor };
248
+ export { createFlashSaleBooking, getCenterHours, getEventOffer, getFlashSale, getFlashSaleBookingOptions, getFlashSales, getMyCredits, getMyEventOrder, getMyEventOrders, getMyLoyalty, getMyMembershipDetail, getMyMemberships, getMyPasses, getMyReservationDetail, getMyReservations, getPackage, listCatalog, listEventOffers, listEvents, listGameCards, listPackages, listProducts, listPublicMemberships, runDoctor };
244
249
  //# sourceMappingURL=index.js.map
245
250
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/doctor.ts","../src/account.ts","../src/catalog.ts"],"names":[],"mappings":";;;;AA0DA,IAAM,cAAA,GAAiB,gBAAA;AAIvB,eAAsB,UAAU,OAAA,EAA+C;AAC7E,EAAA,MAAM,SAAwB,EAAC;AAC/B,EAAA,MAAM,SAAuB,EAAE,EAAA,EAAI,MAAM,MAAA,EAAQ,OAAA,EAAS,QAAQ,OAAA,EAAQ;AAG1E,EAAA,MAAM,eAAyB,EAAC;AAChC,EAAA,IAAI,CAAC,OAAA,CAAQ,MAAA,EAAQ,YAAA,CAAa,KAAK,mBAAmB,CA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AGO,SAAS,UAAA,CAAwB,QAAsB,IAAA,EAAgC;AAC5F,EAAA,OAAO,MAAA,CAAO,IAAA,CAAQ,kBAAA,EAAoB,IAAI,CAAA;AAChD;AAKO,SAAS,eAAA,CACd,QACA,IAAA,EACY;AACZ,EAAA,OAAO,MAAA,CAAO,IAAA,CAAQ,uBAAA,EAAyB,IAAI,CAAA;AACrD;AAGO,SAAS,aAAA,CACd,QACA,IAAA,EACY;AACZ,EAAA,OAAO,MAAA,CAAO,IAAA,CAAQ,qBAAA,EAAuB,IAAI,CAAA;AACnD;AAGO,SAAS,YAAA,CAA0B,QAAsB,IAAA,EAAoC;AAClG,EAAA,OAAO,MAAA,CAAO,IAAA,CAAQ,oBAAA,EAAsB,IAAI,CAAA;AAClD;AAKO,SAAS,UAAA,CAAwB,QAAsB,IAAA,EAAqC;AACjG,EAAA,OAAO,MAAA,CAAO,IAAA,CAAQ,kBAAA,EAAoB,IAAI,CAAA;AAChD;AAKO,SAAS,cAAA,CAA4B,QAAsB,IAAA,EAAmC;AACnG,EAAA,OAAO,MAAA,CAAO,IAAA,CAAQ,iCAAA,EAAmC,IAAI,CAAA;AAC/D;AAGO,SAAS,qBAAA,CACd,QACA,IAAA,EACY;AACZ,EAAA,OAAO,MAAA,CAAO,IAAA,CAAQ,uBAAA,EAAyB,IAAI,CAAA;AACrD;AAGO,SAAS,aAAA,CAA2B,QAAsB,IAAA,EAAoC;AACnG,EAAA,OAAO,MAAA,CAAO,IAAA,CAAQ,qBAAA,EAAuB,IAAI,CAAA;AACnD","file":"index.js","sourcesContent":["/**\n * `runDoctor` — a setup-readiness oracle for a site built on @bowlos/reservations.\n *\n * It runs a short sequence of checks against a configured gateway + API key and\n * returns a structured report (pass / warn / fail / skip), each with a one-line\n * fix when it isn't a pass. The point is to make per-site setup self-debuggable\n * — it walks the failure modes a new center site actually hits, in order:\n * config → gateway reachable → API key valid → origin allow-listed → data plane.\n *\n * Framework-agnostic and dependency-free: it builds a `BowlosClient`, leans on\n * `client.ping()` (one call covers reachability + key + origin + rate-limit),\n * and reports honestly — checks it can't run from the current environment are\n * `skip`ped with guidance rather than faked. The `bowlos doctor` CLI is a thin\n * wrapper that pretty-prints the report.\n */\nimport { createBowlosClient } from \"./client\";\nimport { BowlosApiError, BOWLOS_ERROR_CODES } from \"./errors\";\nimport type { FetchLike, PingResult } from \"./types\";\n\nexport type DoctorCheckStatus = \"pass\" | \"warn\" | \"fail\" | \"skip\";\n\nexport interface DoctorCheck {\n /** Stable id (`config` | `gateway` | `api-key` | `origin` | `rate-limit` | `data-read` | `payments`). */\n id: string;\n title: string;\n status: DoctorCheckStatus;\n detail: string;\n /** One-line remediation, present when `status` isn't `pass`. */\n fix?: string;\n}\n\nexport interface DoctorReport {\n /** True when no check failed (warnings and skips are tolerated). */\n ok: boolean;\n checks: DoctorCheck[];\n /** Echoed back so the CLI can show what it probed. */\n baseUrl: string;\n /** From a successful ping — the key's brand + mode. */\n brandId?: string;\n mode?: \"live\" | \"test\";\n}\n\nexport interface DoctorOptions {\n apiKey: string;\n baseUrl: string;\n /**\n * The deployed site origin. Origin allow-listing is enforced by the gateway\n * only for browser requests (Origin is a forbidden header from Node), so this\n * can be actively verified only in a browser; from Node it informs the\n * skip-guidance message.\n */\n origin?: string;\n /** Skip the (anonymous) data-plane read even when a brand is known. */\n skipDataRead?: boolean;\n /** Injectable transport (tests / SSR polyfills). */\n fetch?: FetchLike;\n}\n\nconst GATEWAY_SUFFIX = \"/api/public/v1\";\n\n/** Run the readiness checks and return a structured report. Never throws — every\n * failure mode is captured as a check. */\nexport async function runDoctor(options: DoctorOptions): Promise<DoctorReport> {\n const checks: DoctorCheck[] = [];\n const report: DoctorReport = { ok: true, checks, baseUrl: options.baseUrl };\n\n // 1) config — can we even build a client?\n const configIssues: string[] = [];\n if (!options.apiKey) configIssues.push(\"`apiKey` is empty\");\n let parsedUrl: URL | null = null;\n try {\n parsedUrl = new URL(options.baseUrl);\n } catch {\n configIssues.push(\"`baseUrl` is not a valid URL\");\n }\n if (configIssues.length > 0) {\n checks.push({\n id: \"config\",\n title: \"Client configuration\",\n status: \"fail\",\n detail: `${configIssues.join(\"; \")}.`,\n fix: \"Pass a brand API key and the gateway base URL, e.g. https://<deployment>.convex.site/api/public/v1\",\n });\n report.ok = false;\n return report; // can't probe without a valid client config\n }\n\n const urlMisaimed =\n parsedUrl !== null && !parsedUrl.pathname.replace(/\\/+$/, \"\").endsWith(GATEWAY_SUFFIX);\n checks.push({\n id: \"config\",\n title: \"Client configuration\",\n status: urlMisaimed ? \"warn\" : \"pass\",\n detail: urlMisaimed\n ? `baseUrl \"${options.baseUrl}\" doesn't end with ${GATEWAY_SUFFIX} — it should point at the gateway, not the site root.`\n : \"API key present; base URL well-formed.\",\n fix: urlMisaimed ? `Use the gateway URL, e.g. ${parsedUrl?.origin}${GATEWAY_SUFFIX}` : undefined,\n });\n\n const client = createBowlosClient({\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n fetch: options.fetch,\n });\n\n // 2) one ping covers: gateway reachable + key valid + (browser) origin + rate-limit.\n let ping: PingResult | null = null;\n try {\n ping = await client.ping();\n report.brandId = ping.brandId;\n report.mode = ping.mode;\n checks.push({\n id: \"gateway\",\n title: \"Gateway reachable\",\n status: \"pass\",\n detail: `Reached ${options.baseUrl} (service \"${ping.service}\", ${ping.version}).`,\n });\n checks.push({\n id: \"api-key\",\n title: \"API key accepted\",\n status: \"pass\",\n detail: `Key valid for brand ${ping.brandId} — mode: ${ping.mode}.`,\n });\n } catch (e) {\n const err = e instanceof BowlosApiError ? e : null;\n const code = err?.code ?? BOWLOS_ERROR_CODES.UNKNOWN;\n // A network error (status 0) or a router 404 means no real gateway answered;\n // any other coded envelope means the gateway responded (and judged the key).\n const reached =\n err !== null && err.status !== 0 && code !== BOWLOS_ERROR_CODES.NETWORK_ERROR && code !== BOWLOS_ERROR_CODES.NOT_FOUND;\n\n checks.push({\n id: \"gateway\",\n title: \"Gateway reachable\",\n status: reached ? \"pass\" : \"fail\",\n detail: reached\n ? `Reached ${options.baseUrl}.`\n : code === BOWLOS_ERROR_CODES.NETWORK_ERROR\n ? `Could not reach ${options.baseUrl} (network error).`\n : `No public-API gateway responded at ${options.baseUrl}.`,\n fix: reached\n ? undefined\n : \"Check the base URL, that the Convex deployment is live, and that the public-API routes are deployed.\",\n });\n\n if (code === BOWLOS_ERROR_CODES.RATE_LIMITED) {\n checks.push({\n id: \"api-key\",\n title: \"API key accepted\",\n status: \"pass\",\n detail: \"Key accepted (this probe was rate-limited).\",\n });\n checks.push({\n id: \"rate-limit\",\n title: \"Rate-limit headroom\",\n status: \"warn\",\n detail: `Currently rate-limited${err?.retryAfterSeconds ? ` — retry after ${err.retryAfterSeconds}s` : \"\"}.`,\n fix: \"Back off and retry; raise the key's per-minute limit if your real traffic is higher.\",\n });\n } else if (code === BOWLOS_ERROR_CODES.ORIGIN_NOT_ALLOWED) {\n checks.push({\n id: \"api-key\",\n title: \"API key accepted\",\n status: \"pass\",\n detail: \"Key accepted; the request was blocked on origin.\",\n });\n checks.push({\n id: \"origin\",\n title: \"Origin allow-listed\",\n status: \"fail\",\n detail: \"The request origin is not on the key's allow-list.\",\n fix: `Add your site origin${options.origin ? ` (${options.origin})` : \"\"} to the API key's allowed origins.`,\n });\n } else if (reached) {\n checks.push({\n id: \"api-key\",\n title: \"API key accepted\",\n status: \"fail\",\n detail:\n code === BOWLOS_ERROR_CODES.API_KEY_INVALID || code === BOWLOS_ERROR_CODES.API_KEY_MISSING\n ? \"The gateway rejected the API key.\"\n : `The gateway returned ${code}.`,\n fix: \"Mint or rotate a brand API key in the operator admin (Super-Admin → API keys) and use that value.\",\n });\n } else {\n checks.push({\n id: \"api-key\",\n title: \"API key accepted\",\n status: \"skip\",\n detail: \"Skipped — the gateway wasn't reachable.\",\n });\n }\n }\n\n // 3) origin — only actively verifiable in a browser (Origin is a forbidden\n // header from Node). A successful ping in a browser means the current\n // origin IS allow-listed; otherwise skip with guidance.\n if (!checks.some((c) => c.id === \"origin\")) {\n const browserOrigin =\n typeof window !== \"undefined\" && typeof window.location?.origin === \"string\"\n ? window.location.origin\n : null;\n if (ping !== null && browserOrigin !== null) {\n checks.push({\n id: \"origin\",\n title: \"Origin allow-listed\",\n status: \"pass\",\n detail: `This origin (${browserOrigin}) is allow-listed for the key.`,\n });\n } else {\n checks.push({\n id: \"origin\",\n title: \"Origin allow-listed\",\n status: \"skip\",\n detail: \"Origin allow-listing is enforced only for browser requests, so it can't be verified from a CLI.\",\n fix: `Ensure your deployed site origin${options.origin ? ` (${options.origin})` : \"\"} is on the key's allowed-origins list; load the site and watch for ORIGIN_NOT_ALLOWED.`,\n });\n }\n }\n\n // 4) data plane — a cheap anonymous read proves gateway → manifest → query → scope.\n if (ping !== null && options.skipDataRead !== true) {\n try {\n const data = await client.call<unknown>(\"listPublicCenters\", { brandId: ping.brandId });\n const innerError = typeof data === \"object\" && data !== null && (data as { ok?: boolean }).ok === false;\n checks.push({\n id: \"data-read\",\n title: \"Data passthrough\",\n status: innerError ? \"warn\" : \"pass\",\n detail: innerError\n ? \"Reached the data plane, but listPublicCenters returned an error envelope.\"\n : \"Anonymous read (listPublicCenters) succeeded — gateway → query passthrough works.\",\n fix: innerError ? \"Confirm the brand has at least one published center.\" : undefined,\n });\n } catch (e) {\n const err = e instanceof BowlosApiError ? e : null;\n checks.push({\n id: \"data-read\",\n title: \"Data passthrough\",\n status: \"warn\",\n detail: `An anonymous read failed${err ? ` (${err.code})` : \"\"}.`,\n fix: \"Key + gateway are fine; this read may need a published center or differ by brand. Safe to ignore if your booking reads work.\",\n });\n }\n } else if (ping === null) {\n checks.push({\n id: \"data-read\",\n title: \"Data passthrough\",\n status: \"skip\",\n detail: \"Skipped — needs a reachable gateway.\",\n });\n }\n\n // 5) payments — Stripe Connect status isn't exposed over the public API yet.\n // Honest skip (no faked pass) so the operator knows to verify it elsewhere.\n checks.push({\n id: \"payments\",\n title: \"Payments connected\",\n status: \"skip\",\n detail: \"Stripe Connect status isn't exposed over the public API yet, so the doctor can't verify it here.\",\n fix: \"Confirm the operator's Stripe account is connected + charges-enabled in the admin (Payments → Connect).\",\n });\n\n report.ok = !checks.some((c) => c.status === \"fail\");\n return report;\n}\n","/**\n * Typed account + flash reads for @bowlos/reservations.\n *\n * Session-scoped account reads (require a signed-in customer) and the\n * session-aware flash-sale reads. Args are typed precisely — every account read\n * is brand-scoped. Results are generic (`<T = unknown>`): parameterize with your\n * own shape, or read `unknown` and narrow. (The backend return shapes are rich\n * and evolving; the SDK doesn't pin them here.) Each read has a framework-agnostic\n * function here and a React hook in `hooks.tsx`.\n */\nimport type { BowlosClient } from \"./client\";\n\n/** Every account read is scoped to the customer's Brand. */\nexport type BrandScoped = { brandId: string };\nexport type ReservationDetailArgs = { brandId: string; displayId: string };\nexport type EventOrderDetailArgs = { brandId: string; orderId: string };\nexport type MembershipDetailArgs = { brandId: string; membershipId: string };\nexport type FlashSaleArgs = { slug: string };\nexport type FlashBookingOptionsArgs = { slug: string; itemId: string };\nexport type FlashSalesArgs = { brandId: string };\n\n// ── account (require a signed-in customer) ───────────────────────────────────\n\nexport function getMyReservations<T = unknown>(client: BowlosClient, args: BrandScoped): Promise<T> {\n return client.call<T>(\"listMyReservations\", args, { auth: true });\n}\n\nexport function getMyReservationDetail<T = unknown>(\n client: BowlosClient,\n args: ReservationDetailArgs,\n): Promise<T> {\n return client.call<T>(\"getMyReservationDetail\", args, { auth: true });\n}\n\nexport function getMyEventOrders<T = unknown>(client: BowlosClient, args: BrandScoped): Promise<T> {\n return client.call<T>(\"listMyEventOrders\", args, { auth: true });\n}\n\nexport function getMyEventOrder<T = unknown>(\n client: BowlosClient,\n args: EventOrderDetailArgs,\n): Promise<T> {\n return client.call<T>(\"getMyEventOrder\", args, { auth: true });\n}\n\nexport function getMyMemberships<T = unknown>(client: BowlosClient, args: BrandScoped): Promise<T> {\n return client.call<T>(\"listMyMemberships\", args, { auth: true });\n}\n\nexport function getMyMembershipDetail<T = unknown>(\n client: BowlosClient,\n args: MembershipDetailArgs,\n): Promise<T> {\n return client.call<T>(\"getMyMembershipDetail\", args, { auth: true });\n}\n\nexport function getMyLoyalty<T = unknown>(client: BowlosClient, args: BrandScoped): Promise<T> {\n return client.call<T>(\"getMyLoyalty\", args, { auth: true });\n}\n\nexport function getMyCredits<T = unknown>(client: BowlosClient, args: BrandScoped): Promise<T> {\n return client.call<T>(\"listMyCredits\", args, { auth: true });\n}\n\nexport function getMyPasses<T = unknown>(client: BowlosClient, args: BrandScoped): Promise<T> {\n return client.call<T>(\"listMyPasses\", args, { auth: true });\n}\n\n// ── flash sales (session-aware: members see prices) ──────────────────────────\n\nexport function getFlashSale<T = unknown>(client: BowlosClient, args: FlashSaleArgs): Promise<T> {\n return client.call<T>(\"getPublicFlashSaleBySlug\", args, { auth: true });\n}\n\n/** The public flash-sale index for a Brand (live + upcoming; no prices). Public. */\nexport function getFlashSales<T = unknown>(client: BowlosClient, args: FlashSalesArgs): Promise<T> {\n return client.call<T>(\"listPublicFlashSales\", args);\n}\n\nexport function getFlashSaleBookingOptions<T = unknown>(\n client: BowlosClient,\n args: FlashBookingOptionsArgs,\n): Promise<T> {\n return client.call<T>(\"getFlashSaleBookingOptions\", args, { auth: true });\n}\n","/**\n * Public catalog reads for @bowlos/reservations — the \"what can I book/buy here\"\n * surface that powers `<BookingCatalog>`. All anonymous (no customer login).\n * Products + events + memberships are Center-scoped; packages + game cards are\n * Brand-scoped (with an optional Center filter). Results are generic (`<T>`);\n * the component types the display fields it needs.\n */\nimport type { BowlosClient } from \"./client\";\n\nexport type CenterScoped = { centerId: string };\nexport type BrandCatalogArgs = { brandId: string; centerId?: string };\n\n// ── canonical catalog (listPublicCatalog) ─────────────────────────────────────\n// The one read that returns every category grouped + per-surface visibility\n// already applied. Prefer this over the per-category lists below when you want\n// the full, admin-controlled catalog for a surface. Types mirror the backend\n// wire shape (`@bowlos/shared` public-catalog).\n\n/** Which public surface is asking — the backend applies that surface's\n * per-category + per-offer visibility before returning. */\nexport type PublicSurface = \"sdk_custom_site\" | \"white_label_web\" | \"mobile_app\";\n\nexport type CatalogCategory =\n | \"bowling\"\n | \"other_attractions\"\n | \"events\"\n | \"packages\"\n | \"memberships\"\n | \"game_passes\";\n\nexport type CatalogActionType =\n | \"book_reservation\"\n | \"view_event\"\n | \"buy_ticket\"\n | \"buy_package\"\n | \"buy_membership\"\n | \"buy_game_pass\";\n\nexport type CatalogSourceTable =\n | \"products\"\n | \"event_offers\"\n | \"packages\"\n | \"membership_templates\"\n | \"game_card_templates\";\n\n/** A normalized, surface-agnostic catalog item. Route by `action.type`, using\n * the IDs in `action.payload` (e.g. `productId`, `slug`, `packageId`,\n * `templateId`). `priceLabel` is an indicative \"from $X\" only (null for\n * products — show \"See times & pricing\"); the binding price comes from the\n * per-category preview after login. */\nexport interface CatalogItem {\n id: string;\n category: CatalogCategory;\n sourceTable: CatalogSourceTable;\n sourceId: string;\n title: string;\n subtitle?: string | null;\n description?: string | null;\n priceLabel?: string | null;\n imageUrl?: string | null;\n badgeLabel?: string | null;\n action: { type: CatalogActionType; payload: Record<string, string> };\n}\n\nexport interface CatalogSection {\n key: CatalogCategory;\n label: string;\n items: CatalogItem[];\n}\n\nexport interface CatalogResult {\n sections: CatalogSection[];\n}\n\n/** Args for the canonical catalog read. `surface` selects which visibility\n * rules the backend applies. */\nexport type CatalogArgs = {\n brandId: string;\n centerId: string;\n surface: PublicSurface;\n};\n\n/**\n * The canonical public catalog for a surface — every active, public,\n * bookable/sellable item grouped into the six first-class categories, with the\n * Center admin's per-surface category + offer visibility already applied.\n * Anonymous. This is the recommended way to list \"everything bookable here\":\n * one call, all categories, visibility-aware, consistent with the white-label\n * web + mobile surfaces.\n */\nexport function listCatalog<T = CatalogResult>(\n client: BowlosClient,\n args: CatalogArgs,\n): Promise<T> {\n return client.call<T>(\"listPublicCatalog\", args);\n}\n/** One package's full detail. `shareToken` reveals a hidden/unlisted package. */\nexport type PackageDetailArgs = { packageId: string; shareToken?: string };\n/** Args for a Center's operating-hours window on a date, across attraction types. */\nexport type CenterHoursArgs = { centerId: string; attractionTypeKeys: string[]; dateISO: string };\n\n/** Bookable products at a Center (each carries its attraction + `attractionTypeKey`). */\nexport function listProducts<T = unknown>(client: BowlosClient, args: CenterScoped): Promise<T> {\n return client.call<T>(\"listPublicProducts\", args);\n}\n\n/** Upcoming pricing events (NYE Bash, tournaments…) at a Center. */\nexport function listEvents<T = unknown>(client: BowlosClient, args: CenterScoped): Promise<T> {\n return client.call<T>(\"listPublicEvents\", args);\n}\n\n/** Sellable event offers at a Center. These are the public lineup + event\n * landing-page records; use this instead of `listEvents` when routing a\n * customer to an event purchase flow. */\nexport function listEventOffers<T = unknown>(\n client: BowlosClient,\n args: CenterScoped,\n): Promise<T> {\n return client.call<T>(\"listPublicEventOffers\", args);\n}\n\n/** One sellable event offer by landing-page slug. */\nexport function getEventOffer<T = unknown>(\n client: BowlosClient,\n args: { slug: string },\n): Promise<T> {\n return client.call<T>(\"getPublicEventOffer\", args);\n}\n\n/** Purchasable packages at a Brand. */\nexport function listPackages<T = unknown>(client: BowlosClient, args: BrandCatalogArgs): Promise<T> {\n return client.call<T>(\"listPublicPackages\", args);\n}\n\n/** Full detail for one package — components, optional add-ons, allowed start\n * times, duration, and quantity bounds. Drives the headless package config UI\n * (see HEADLESS.md → \"Buying a package\"). */\nexport function getPackage<T = unknown>(client: BowlosClient, args: PackageDetailArgs): Promise<T> {\n return client.call<T>(\"getPublicPackage\", args);\n}\n\n/** A Center's combined open/close window (minutes-from-midnight) for the given\n * attraction types on a date — the intersection across types; `null` if closed.\n * Bound a package's start times with its component attraction-type keys. */\nexport function getCenterHours<T = unknown>(client: BowlosClient, args: CenterHoursArgs): Promise<T> {\n return client.call<T>(\"getCenterOperatingHoursForTypes\", args);\n}\n\n/** Purchasable memberships at a Center. */\nexport function listPublicMemberships<T = unknown>(\n client: BowlosClient,\n args: CenterScoped,\n): Promise<T> {\n return client.call<T>(\"listPublicMemberships\", args);\n}\n\n/** Purchasable game cards / passes at a Brand. */\nexport function listGameCards<T = unknown>(client: BowlosClient, args: BrandCatalogArgs): Promise<T> {\n return client.call<T>(\"listPublicGameCards\", args);\n}\n"]}
1
+ {"version":3,"sources":["../src/doctor.ts","../src/account.ts","../src/catalog.ts"],"names":[],"mappings":";;;;AA0DA,IAAM,cAAA,GAAiB,gBAAA;AAIvB,eAAsB,UAAU,OAAA,EAA+C;AAC7E,EAAA,MAAM,SAAwB,EAAC;AAC/B,EAAA,MAAM,SAAuB,EAAE,EAAA,EAAI,MAAM,MAAA,EAAQ,OAAA,EAAS,QAAQ,OAAA,EAAQ;AAG1E,EAAA,MAAM,eAAyB,EAAC;AAChC,EAAA,IAAI,CAAC,OAAA,CAAQ,MAAA,EAAQ,YAAA,CAAa,KAAK,mBAAmB,CAAA;AAC1D,EAAA,IAAI,SAAA,GAAwB,IAAA;AAC5B,EAAA,IAAI;AACF,IAAA,SAAA,GAAY,IAAI,GAAA,CAAI,OAAA,CAAQ,OAAO,CAAA;AAAA,EACrC,CAAA,CAAA,MAAQ;AACN,IAAA,YAAA,CAAa,KAAK,8BAA8B,CAAA;AAAA,EAClD;AACA,EAAA,IAAI,YAAA,CAAa,SAAS,CAAA,EAAG;AAC3B,IAAA,MAAA,CAAO,IAAA,CAAK;AAAA,MACV,EAAA,EAAI,QAAA;AAAA,MACJ,KAAA,EAAO,sBAAA;AAAA,MACP,MAAA,EAAQ,MAAA;AAAA,MACR,MAAA,EAAQ,CAAA,EAAG,YAAA,CAAa,IAAA,CAAK,IAAI,CAAC,CAAA,CAAA,CAAA;AAAA,MAClC,GAAA,EAAK;AAAA,KACN,CAAA;AACD,IAAA,MAAA,CAAO,EAAA,GAAK,KAAA;AACZ,IAAA,OAAO,MAAA;AAAA,EACT;AAEA,EAAA,MAAM,WAAA,GACJ,SAAA,KAAc,IAAA,IAAQ,CAAC,SAAA,CAAU,QAAA,CAAS,OAAA,CAAQ,MAAA,EAAQ,EAAE,CAAA,CAAE,QAAA,CAAS,cAAc,CAAA;AACvF,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O,SAAS,cAAA,CAA4B,QAAsB,IAAA,EAAmC;AACnG,EAAA,OAAO,MAAA,CAAO,IAAA,CAAQ,iCAAA,EAAmC,IAAI,CAAA;AAC/D;AAGO,SAAS,qBAAA,CACd,QACA,IAAA,EACY;AACZ,EAAA,OAAO,MAAA,CAAO,IAAA,CAAQ,uBAAA,EAAyB,IAAI,CAAA;AACrD;AAGO,SAAS,aAAA,CAA2B,QAAsB,IAAA,EAAoC;AACnG,EAAA,OAAO,MAAA,CAAO,IAAA,CAAQ,qBAAA,EAAuB,IAAI,CAAA;AACnD","file":"index.js","sourcesContent":["/**\n * `runDoctor` — a setup-readiness oracle for a site built on @bowlos/reservations.\n *\n * It runs a short sequence of checks against a configured gateway + API key and\n * returns a structured report (pass / warn / fail / skip), each with a one-line\n * fix when it isn't a pass. The point is to make per-site setup self-debuggable\n * — it walks the failure modes a new center site actually hits, in order:\n * config → gateway reachable → API key valid → origin allow-listed → data plane.\n *\n * Framework-agnostic and dependency-free: it builds a `BowlosClient`, leans on\n * `client.ping()` (one call covers reachability + key + origin + rate-limit),\n * and reports honestly — checks it can't run from the current environment are\n * `skip`ped with guidance rather than faked. The `bowlos doctor` CLI is a thin\n * wrapper that pretty-prints the report.\n */\nimport { createBowlosClient } from \"./client\";\nimport { BowlosApiError, BOWLOS_ERROR_CODES } from \"./errors\";\nimport type { FetchLike, PingResult } from \"./types\";\n\nexport type DoctorCheckStatus = \"pass\" | \"warn\" | \"fail\" | \"skip\";\n\nexport interface DoctorCheck {\n /** Stable id (`config` | `gateway` | `api-key` | `origin` | `rate-limit` | `data-read` | `payments`). */\n id: string;\n title: string;\n status: DoctorCheckStatus;\n detail: string;\n /** One-line remediation, present when `status` isn't `pass`. */\n fix?: string;\n}\n\nexport interface DoctorReport {\n /** True when no check failed (warnings and skips are tolerated). */\n ok: boolean;\n checks: DoctorCheck[];\n /** Echoed back so the CLI can show what it probed. */\n baseUrl: string;\n /** From a successful ping — the key's brand + mode. */\n brandId?: string;\n mode?: \"live\" | \"test\";\n}\n\nexport interface DoctorOptions {\n apiKey: string;\n baseUrl: string;\n /**\n * The deployed site origin. Origin allow-listing is enforced by the gateway\n * only for browser requests (Origin is a forbidden header from Node), so this\n * can be actively verified only in a browser; from Node it informs the\n * skip-guidance message.\n */\n origin?: string;\n /** Skip the (anonymous) data-plane read even when a brand is known. */\n skipDataRead?: boolean;\n /** Injectable transport (tests / SSR polyfills). */\n fetch?: FetchLike;\n}\n\nconst GATEWAY_SUFFIX = \"/api/public/v1\";\n\n/** Run the readiness checks and return a structured report. Never throws — every\n * failure mode is captured as a check. */\nexport async function runDoctor(options: DoctorOptions): Promise<DoctorReport> {\n const checks: DoctorCheck[] = [];\n const report: DoctorReport = { ok: true, checks, baseUrl: options.baseUrl };\n\n // 1) config — can we even build a client?\n const configIssues: string[] = [];\n if (!options.apiKey) configIssues.push(\"`apiKey` is empty\");\n let parsedUrl: URL | null = null;\n try {\n parsedUrl = new URL(options.baseUrl);\n } catch {\n configIssues.push(\"`baseUrl` is not a valid URL\");\n }\n if (configIssues.length > 0) {\n checks.push({\n id: \"config\",\n title: \"Client configuration\",\n status: \"fail\",\n detail: `${configIssues.join(\"; \")}.`,\n fix: \"Pass a brand API key and the gateway base URL, e.g. https://<deployment>.convex.site/api/public/v1\",\n });\n report.ok = false;\n return report; // can't probe without a valid client config\n }\n\n const urlMisaimed =\n parsedUrl !== null && !parsedUrl.pathname.replace(/\\/+$/, \"\").endsWith(GATEWAY_SUFFIX);\n checks.push({\n id: \"config\",\n title: \"Client configuration\",\n status: urlMisaimed ? \"warn\" : \"pass\",\n detail: urlMisaimed\n ? `baseUrl \"${options.baseUrl}\" doesn't end with ${GATEWAY_SUFFIX} — it should point at the gateway, not the site root.`\n : \"API key present; base URL well-formed.\",\n fix: urlMisaimed ? `Use the gateway URL, e.g. ${parsedUrl?.origin}${GATEWAY_SUFFIX}` : undefined,\n });\n\n const client = createBowlosClient({\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n fetch: options.fetch,\n });\n\n // 2) one ping covers: gateway reachable + key valid + (browser) origin + rate-limit.\n let ping: PingResult | null = null;\n try {\n ping = await client.ping();\n report.brandId = ping.brandId;\n report.mode = ping.mode;\n checks.push({\n id: \"gateway\",\n title: \"Gateway reachable\",\n status: \"pass\",\n detail: `Reached ${options.baseUrl} (service \"${ping.service}\", ${ping.version}).`,\n });\n checks.push({\n id: \"api-key\",\n title: \"API key accepted\",\n status: \"pass\",\n detail: `Key valid for brand ${ping.brandId} — mode: ${ping.mode}.`,\n });\n } catch (e) {\n const err = e instanceof BowlosApiError ? e : null;\n const code = err?.code ?? BOWLOS_ERROR_CODES.UNKNOWN;\n // A network error (status 0) or a router 404 means no real gateway answered;\n // any other coded envelope means the gateway responded (and judged the key).\n const reached =\n err !== null && err.status !== 0 && code !== BOWLOS_ERROR_CODES.NETWORK_ERROR && code !== BOWLOS_ERROR_CODES.NOT_FOUND;\n\n checks.push({\n id: \"gateway\",\n title: \"Gateway reachable\",\n status: reached ? \"pass\" : \"fail\",\n detail: reached\n ? `Reached ${options.baseUrl}.`\n : code === BOWLOS_ERROR_CODES.NETWORK_ERROR\n ? `Could not reach ${options.baseUrl} (network error).`\n : `No public-API gateway responded at ${options.baseUrl}.`,\n fix: reached\n ? undefined\n : \"Check the base URL, that the Convex deployment is live, and that the public-API routes are deployed.\",\n });\n\n if (code === BOWLOS_ERROR_CODES.RATE_LIMITED) {\n checks.push({\n id: \"api-key\",\n title: \"API key accepted\",\n status: \"pass\",\n detail: \"Key accepted (this probe was rate-limited).\",\n });\n checks.push({\n id: \"rate-limit\",\n title: \"Rate-limit headroom\",\n status: \"warn\",\n detail: `Currently rate-limited${err?.retryAfterSeconds ? ` — retry after ${err.retryAfterSeconds}s` : \"\"}.`,\n fix: \"Back off and retry; raise the key's per-minute limit if your real traffic is higher.\",\n });\n } else if (code === BOWLOS_ERROR_CODES.ORIGIN_NOT_ALLOWED) {\n checks.push({\n id: \"api-key\",\n title: \"API key accepted\",\n status: \"pass\",\n detail: \"Key accepted; the request was blocked on origin.\",\n });\n checks.push({\n id: \"origin\",\n title: \"Origin allow-listed\",\n status: \"fail\",\n detail: \"The request origin is not on the key's allow-list.\",\n fix: `Add your site origin${options.origin ? ` (${options.origin})` : \"\"} to the API key's allowed origins.`,\n });\n } else if (reached) {\n checks.push({\n id: \"api-key\",\n title: \"API key accepted\",\n status: \"fail\",\n detail:\n code === BOWLOS_ERROR_CODES.API_KEY_INVALID || code === BOWLOS_ERROR_CODES.API_KEY_MISSING\n ? \"The gateway rejected the API key.\"\n : `The gateway returned ${code}.`,\n fix: \"Mint or rotate a brand API key in the operator admin (Super-Admin → API keys) and use that value.\",\n });\n } else {\n checks.push({\n id: \"api-key\",\n title: \"API key accepted\",\n status: \"skip\",\n detail: \"Skipped — the gateway wasn't reachable.\",\n });\n }\n }\n\n // 3) origin — only actively verifiable in a browser (Origin is a forbidden\n // header from Node). A successful ping in a browser means the current\n // origin IS allow-listed; otherwise skip with guidance.\n if (!checks.some((c) => c.id === \"origin\")) {\n const browserOrigin =\n typeof window !== \"undefined\" && typeof window.location?.origin === \"string\"\n ? window.location.origin\n : null;\n if (ping !== null && browserOrigin !== null) {\n checks.push({\n id: \"origin\",\n title: \"Origin allow-listed\",\n status: \"pass\",\n detail: `This origin (${browserOrigin}) is allow-listed for the key.`,\n });\n } else {\n checks.push({\n id: \"origin\",\n title: \"Origin allow-listed\",\n status: \"skip\",\n detail: \"Origin allow-listing is enforced only for browser requests, so it can't be verified from a CLI.\",\n fix: `Ensure your deployed site origin${options.origin ? ` (${options.origin})` : \"\"} is on the key's allowed-origins list; load the site and watch for ORIGIN_NOT_ALLOWED.`,\n });\n }\n }\n\n // 4) data plane — a cheap anonymous read proves gateway → manifest → query → scope.\n if (ping !== null && options.skipDataRead !== true) {\n try {\n const data = await client.call<unknown>(\"listPublicCenters\", { brandId: ping.brandId });\n const innerError = typeof data === \"object\" && data !== null && (data as { ok?: boolean }).ok === false;\n checks.push({\n id: \"data-read\",\n title: \"Data passthrough\",\n status: innerError ? \"warn\" : \"pass\",\n detail: innerError\n ? \"Reached the data plane, but listPublicCenters returned an error envelope.\"\n : \"Anonymous read (listPublicCenters) succeeded — gateway → query passthrough works.\",\n fix: innerError ? \"Confirm the brand has at least one published center.\" : undefined,\n });\n } catch (e) {\n const err = e instanceof BowlosApiError ? e : null;\n checks.push({\n id: \"data-read\",\n title: \"Data passthrough\",\n status: \"warn\",\n detail: `An anonymous read failed${err ? ` (${err.code})` : \"\"}.`,\n fix: \"Key + gateway are fine; this read may need a published center or differ by brand. Safe to ignore if your booking reads work.\",\n });\n }\n } else if (ping === null) {\n checks.push({\n id: \"data-read\",\n title: \"Data passthrough\",\n status: \"skip\",\n detail: \"Skipped — needs a reachable gateway.\",\n });\n }\n\n // 5) payments — Stripe Connect status isn't exposed over the public API yet.\n // Honest skip (no faked pass) so the operator knows to verify it elsewhere.\n checks.push({\n id: \"payments\",\n title: \"Payments connected\",\n status: \"skip\",\n detail: \"Stripe Connect status isn't exposed over the public API yet, so the doctor can't verify it here.\",\n fix: \"Confirm the operator's Stripe account is connected + charges-enabled in the admin (Payments → Connect).\",\n });\n\n report.ok = !checks.some((c) => c.status === \"fail\");\n return report;\n}\n","/**\n * Typed account + flash reads for @bowlos/reservations.\n *\n * Session-scoped account reads (require a signed-in customer) and the\n * session-aware flash-sale reads. Args are typed precisely — every account read\n * is brand-scoped. Results are generic (`<T = unknown>`): parameterize with your\n * own shape, or read `unknown` and narrow. (The backend return shapes are rich\n * and evolving; the SDK doesn't pin them here.) Each read has a framework-agnostic\n * function here and a React hook in `hooks.tsx`.\n */\nimport type { BowlosClient } from \"./client\";\n\n/** Every account read is scoped to the customer's Brand. */\nexport type BrandScoped = { brandId: string };\nexport type ReservationDetailArgs = { brandId: string; displayId: string };\nexport type EventOrderDetailArgs = { brandId: string; orderId: string };\nexport type MembershipDetailArgs = { brandId: string; membershipId: string };\nexport type FlashSaleArgs = { slug: string };\nexport type FlashBookingOptionsArgs = { slug: string; itemId: string };\nexport type FlashSalesArgs = { brandId: string };\n\n// ── account (require a signed-in customer) ───────────────────────────────────\n\nexport function getMyReservations<T = unknown>(client: BowlosClient, args: BrandScoped): Promise<T> {\n return client.call<T>(\"listMyReservations\", args, { auth: true });\n}\n\nexport function getMyReservationDetail<T = unknown>(\n client: BowlosClient,\n args: ReservationDetailArgs,\n): Promise<T> {\n return client.call<T>(\"getMyReservationDetail\", args, { auth: true });\n}\n\nexport function getMyEventOrders<T = unknown>(client: BowlosClient, args: BrandScoped): Promise<T> {\n return client.call<T>(\"listMyEventOrders\", args, { auth: true });\n}\n\nexport function getMyEventOrder<T = unknown>(\n client: BowlosClient,\n args: EventOrderDetailArgs,\n): Promise<T> {\n return client.call<T>(\"getMyEventOrder\", args, { auth: true });\n}\n\nexport function getMyMemberships<T = unknown>(client: BowlosClient, args: BrandScoped): Promise<T> {\n return client.call<T>(\"listMyMemberships\", args, { auth: true });\n}\n\nexport function getMyMembershipDetail<T = unknown>(\n client: BowlosClient,\n args: MembershipDetailArgs,\n): Promise<T> {\n return client.call<T>(\"getMyMembershipDetail\", args, { auth: true });\n}\n\nexport function getMyLoyalty<T = unknown>(client: BowlosClient, args: BrandScoped): Promise<T> {\n return client.call<T>(\"getMyLoyalty\", args, { auth: true });\n}\n\nexport function getMyCredits<T = unknown>(client: BowlosClient, args: BrandScoped): Promise<T> {\n return client.call<T>(\"listMyCredits\", args, { auth: true });\n}\n\nexport function getMyPasses<T = unknown>(client: BowlosClient, args: BrandScoped): Promise<T> {\n return client.call<T>(\"listMyPasses\", args, { auth: true });\n}\n\n// ── flash sales (session-aware: members see prices) ──────────────────────────\n\nexport function getFlashSale<T = unknown>(client: BowlosClient, args: FlashSaleArgs): Promise<T> {\n return client.call<T>(\"getPublicFlashSaleBySlug\", args, { auth: true });\n}\n\n/** The public flash-sale index for a Brand (live + upcoming; no prices). Public. */\nexport function getFlashSales<T = unknown>(client: BowlosClient, args: FlashSalesArgs): Promise<T> {\n return client.call<T>(\"listPublicFlashSales\", args);\n}\n\nexport function getFlashSaleBookingOptions<T = unknown>(\n client: BowlosClient,\n args: FlashBookingOptionsArgs,\n): Promise<T> {\n return client.call<T>(\"getFlashSaleBookingOptions\", args, { auth: true });\n}\n\nexport type CreateFlashSaleBookingArgs = {\n slug: string;\n itemId: string;\n dateISO: string;\n startMinuteOfDay: number;\n durationMinutes: number;\n units: number;\n /** Per-attempt key; replays return the original checkout. */\n idempotencyKey: string;\n};\n\nexport interface FlashSaleBookingResult {\n /** Handle for the rest of the checkout: mint the PaymentIntent with\n * `createCheckoutPaymentIntent(client, { refToken })`, then poll\n * `getCheckoutStatus(client, refToken)` to materialization. */\n refToken: string;\n /** The SALE-priced total the PaymentIntent charges (base at the flash\n * price + tax + the Center fee). */\n amountDueCents: number;\n holdExpiresAt: number;\n breakdown: {\n baseSubtotalCents: number;\n reservationFeeCents: number;\n reservationFeeLabel: string | null;\n taxAddedCents: number;\n taxIncludedCents: number;\n totalCents: number;\n };\n}\n\n/**\n * v0.22.1 — book a flash-sale reservation item at its SALE price (the flash\n * analog of `eventOfferSlug`: the server binds the item's sale price, holds\n * the inventory, and opens a checkout). Signed-in customers only. Pick the\n * date/time from `getFlashSaleBookingOptions` — the purpose-built option\n * list — never the regular booking calendar.\n */\nexport function createFlashSaleBooking(\n client: BowlosClient,\n args: CreateFlashSaleBookingArgs,\n): Promise<FlashSaleBookingResult> {\n return client.call<FlashSaleBookingResult>(\"createFlashSaleBooking\", args, {\n auth: true,\n });\n}\n","/**\n * Public catalog reads for @bowlos/reservations — the \"what can I book/buy here\"\n * surface that powers `<BookingCatalog>`. All anonymous (no customer login).\n * Products + events + memberships are Center-scoped; packages + game cards are\n * Brand-scoped (with an optional Center filter). Results are generic (`<T>`);\n * the component types the display fields it needs.\n */\nimport type { BowlosClient } from \"./client\";\n\nexport type CenterScoped = { centerId: string };\nexport type BrandCatalogArgs = { brandId: string; centerId?: string };\n\n// ── canonical catalog (listPublicCatalog) ─────────────────────────────────────\n// The one read that returns every category grouped + per-surface visibility\n// already applied. Prefer this over the per-category lists below when you want\n// the full, admin-controlled catalog for a surface. Types mirror the backend\n// wire shape (`@bowlos/shared` public-catalog).\n\n/** Which public surface is asking — the backend applies that surface's\n * per-category + per-offer visibility before returning. */\nexport type PublicSurface = \"sdk_custom_site\" | \"white_label_web\" | \"mobile_app\";\n\nexport type CatalogCategory =\n | \"bowling\"\n | \"other_attractions\"\n | \"events\"\n | \"packages\"\n | \"memberships\"\n | \"game_passes\";\n\nexport type CatalogActionType =\n | \"book_reservation\"\n | \"view_event\"\n | \"buy_ticket\"\n | \"buy_package\"\n | \"buy_membership\"\n | \"buy_game_pass\";\n\nexport type CatalogSourceTable =\n | \"products\"\n | \"event_offers\"\n | \"packages\"\n | \"membership_templates\"\n | \"game_card_templates\";\n\n/** A normalized, surface-agnostic catalog item. Route by `action.type`, using\n * the IDs in `action.payload` (e.g. `productId`, `slug`, `packageId`,\n * `templateId`). `priceLabel` is an indicative \"from $X\" only (null for\n * products — show \"See times & pricing\"); the binding price comes from the\n * per-category preview after login. */\nexport interface CatalogItem {\n id: string;\n category: CatalogCategory;\n sourceTable: CatalogSourceTable;\n sourceId: string;\n title: string;\n subtitle?: string | null;\n description?: string | null;\n priceLabel?: string | null;\n imageUrl?: string | null;\n badgeLabel?: string | null;\n action: { type: CatalogActionType; payload: Record<string, string> };\n}\n\nexport interface CatalogSection {\n key: CatalogCategory;\n label: string;\n items: CatalogItem[];\n}\n\nexport interface CatalogResult {\n sections: CatalogSection[];\n}\n\n/** Args for the canonical catalog read. `surface` selects which visibility\n * rules the backend applies. */\nexport type CatalogArgs = {\n brandId: string;\n centerId: string;\n surface: PublicSurface;\n};\n\n/**\n * The canonical public catalog for a surface — every active, public,\n * bookable/sellable item grouped into the six first-class categories, with the\n * Center admin's per-surface category + offer visibility already applied.\n * Anonymous. This is the recommended way to list \"everything bookable here\":\n * one call, all categories, visibility-aware, consistent with the white-label\n * web + mobile surfaces.\n */\nexport function listCatalog<T = CatalogResult>(\n client: BowlosClient,\n args: CatalogArgs,\n): Promise<T> {\n return client.call<T>(\"listPublicCatalog\", args);\n}\n/** One package's full detail. `shareToken` reveals a hidden/unlisted package. */\nexport type PackageDetailArgs = { packageId: string; shareToken?: string };\n/** Args for a Center's operating-hours window on a date, across attraction types. */\nexport type CenterHoursArgs = { centerId: string; attractionTypeKeys: string[]; dateISO: string };\n\n/** Bookable products at a Center (each carries its attraction + `attractionTypeKey`). */\nexport function listProducts<T = unknown>(client: BowlosClient, args: CenterScoped): Promise<T> {\n return client.call<T>(\"listPublicProducts\", args);\n}\n\n/** Upcoming pricing events (NYE Bash, tournaments…) at a Center. */\nexport function listEvents<T = unknown>(client: BowlosClient, args: CenterScoped): Promise<T> {\n return client.call<T>(\"listPublicEvents\", args);\n}\n\n/** Sellable event offers at a Center. These are the public lineup + event\n * landing-page records; use this instead of `listEvents` when routing a\n * customer to an event purchase flow. */\nexport function listEventOffers<T = unknown>(\n client: BowlosClient,\n args: CenterScoped,\n): Promise<T> {\n return client.call<T>(\"listPublicEventOffers\", args);\n}\n\n/** One sellable event offer by landing-page slug. */\nexport function getEventOffer<T = unknown>(\n client: BowlosClient,\n args: { slug: string },\n): Promise<T> {\n return client.call<T>(\"getPublicEventOffer\", args);\n}\n\n/** Purchasable packages at a Brand. */\nexport function listPackages<T = unknown>(client: BowlosClient, args: BrandCatalogArgs): Promise<T> {\n return client.call<T>(\"listPublicPackages\", args);\n}\n\n/** Full detail for one package — components, optional add-ons, allowed start\n * times, duration, and quantity bounds. Drives the headless package config UI\n * (see HEADLESS.md → \"Buying a package\"). */\nexport function getPackage<T = unknown>(client: BowlosClient, args: PackageDetailArgs): Promise<T> {\n return client.call<T>(\"getPublicPackage\", args);\n}\n\n/** A Center's combined open/close window (minutes-from-midnight) for the given\n * attraction types on a date — the intersection across types; `null` if closed.\n * Bound a package's start times with its component attraction-type keys. */\nexport function getCenterHours<T = unknown>(client: BowlosClient, args: CenterHoursArgs): Promise<T> {\n return client.call<T>(\"getCenterOperatingHoursForTypes\", args);\n}\n\n/** Purchasable memberships at a Center. */\nexport function listPublicMemberships<T = unknown>(\n client: BowlosClient,\n args: CenterScoped,\n): Promise<T> {\n return client.call<T>(\"listPublicMemberships\", args);\n}\n\n/** Purchasable game cards / passes at a Brand. */\nexport function listGameCards<T = unknown>(client: BowlosClient, args: BrandCatalogArgs): Promise<T> {\n return client.call<T>(\"listPublicGameCards\", args);\n}\n"]}
package/dist/payments.cjs CHANGED
@@ -236,7 +236,15 @@ function PayForm({
236
236
  const payLabel = t.pay.replace("{amount}", amountCents != null ? formatCents(amountCents) : "").trim();
237
237
  return /* @__PURE__ */ jsxRuntime.jsxs("form", { onSubmit: handleSubmit, className, style: s.stack, children: [
238
238
  /* @__PURE__ */ jsxRuntime.jsx(reactStripeJs.PaymentElement, {}),
239
- /* @__PURE__ */ jsxRuntime.jsx("button", { type: "submit", style: s.primaryBtn, disabled: !stripe || submitting, children: submitting ? t.paying : payLabel }),
239
+ /* @__PURE__ */ jsxRuntime.jsx(
240
+ "button",
241
+ {
242
+ type: "submit",
243
+ style: s.primaryBtn,
244
+ disabled: !stripe || !elements || submitting,
245
+ children: submitting ? t.paying : payLabel
246
+ }
247
+ ),
240
248
  message && /* @__PURE__ */ jsxRuntime.jsx("p", { role: "alert", style: s.error, children: message })
241
249
  ] });
242
250
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/components/theme.tsx","../src/components/shared.tsx","../src/components/payment-form.tsx"],"names":["useMemo","loadStripe","jsx","Elements","useStripe","useElements","useState","PaymentElement"],"mappings":";;;;;;;;AA6BA,IAAM,GAAA,GAA+C;AAAA,EACnD,YAAA,EAAc,wBAAA;AAAA,EACd,oBAAA,EAAsB,iCAAA;AAAA,EACtB,SAAA,EAAW,qBAAA;AAAA,EACX,UAAA,EAAY,sBAAA;AAAA,EACZ,OAAA,EAAS,mBAAA;AAAA,EACT,YAAA,EAAc,wBAAA;AAAA,EACd,WAAA,EAAa,uBAAA;AA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AAA,GAAI,KAAA,CAAM,OAAA,IAAW,CAAA,CAAE,YAAA;AAC7B,MAAA,UAAA,CAAW,CAAC,CAAA;AACZ,MAAA,OAAA,GAAU,CAAC,CAAA;AACX,MAAA,aAAA,CAAc,KAAK,CAAA;AACnB,MAAA;AAAA,IACF;AAIA,IAAA,MAAA,EAAO;AAAA,EACT;AAEA,EAAA,MAAM,QAAA,GAAW,CAAA,CAAE,GAAA,CAAI,OAAA,CAAQ,UAAA,EAAY,WAAA,IAAe,IAAA,GAAO,WAAA,CAAY,WAAW,CAAA,GAAI,EAAE,CAAA,CAAE,IAAA,EAAK;AAErG,EAAA,uCACG,MAAA,EAAA,EAAK,QAAA,EAAU,cAAc,SAAA,EAAsB,KAAA,EAAO,EAAE,KAAA,EAC3D,QAAA,EAAA;AAAA,oBAAAJ,eAACK,4BAAA,EAAA,EAAe,CAAA;AAAA,oBAChBL,cAAAA,CAAC,QAAA,EAAA,EAAO,IAAA,EAAK,UAAS,KAAA,EAAO,CAAA,CAAE,UAAA,EAAY,QAAA,EAAU,CAAC,MAAA,IAAU,UAAA,EAC7D,QAAA,EAAA,UAAA,GAAa,CAAA,CAAE,SAAS,QAAA,EAC3B,CAAA;AAAA,IACC,OAAA,oBACCA,cAAAA,CAAC,GAAA,EAAA,EAAE,MAAK,OAAA,EAAQ,KAAA,EAAO,CAAA,CAAE,KAAA,EACtB,QAAA,EAAA,OAAA,EACH;AAAA,GAAA,EAEJ,CAAA;AAEJ","file":"payments.cjs","sourcesContent":["import type { CSSProperties, ReactNode } from \"react\";\n\n/**\n * Themeable design tokens for the `@bowlos/reservations/components` layer.\n *\n * Override any subset; the rest fall back to neutral, **white-label** defaults\n * (deliberately no BowlOS branding — these render on a center's own site).\n * Tokens are applied as CSS custom properties, so you can theme either with\n * `<BowlosTheme theme={...}>` or by setting the `--bowlos-*` variables yourself\n * in CSS.\n */\nexport interface BowlosThemeTokens {\n /** Accent color — buttons, highlights. */\n colorPrimary?: string;\n /** Text/icon color on top of `colorPrimary`. */\n colorPrimaryContrast?: string;\n colorText?: string;\n colorMuted?: string;\n colorBg?: string;\n colorSurface?: string;\n colorBorder?: string;\n colorError?: string;\n colorSuccess?: string;\n /** Corner radius (e.g. \"10px\", \"0.5rem\"). */\n radius?: string;\n /** Font family stack. */\n fontFamily?: string;\n}\n\nconst VAR: Record<keyof BowlosThemeTokens, string> = {\n colorPrimary: \"--bowlos-color-primary\",\n colorPrimaryContrast: \"--bowlos-color-primary-contrast\",\n colorText: \"--bowlos-color-text\",\n colorMuted: \"--bowlos-color-muted\",\n colorBg: \"--bowlos-color-bg\",\n colorSurface: \"--bowlos-color-surface\",\n colorBorder: \"--bowlos-color-border\",\n colorError: \"--bowlos-color-error\",\n colorSuccess: \"--bowlos-color-success\",\n radius: \"--bowlos-radius\",\n fontFamily: \"--bowlos-font\",\n};\n\n/** Neutral, white-label defaults — used as the CSS-var fallbacks, so components\n * look right even with no `<BowlosTheme>` wrapper. */\nexport const BOWLOS_DEFAULT_THEME: Required<BowlosThemeTokens> = {\n colorPrimary: \"#1f2937\",\n colorPrimaryContrast: \"#ffffff\",\n colorText: \"#111827\",\n colorMuted: \"#6b7280\",\n colorBg: \"#ffffff\",\n colorSurface: \"#f9fafb\",\n colorBorder: \"#e5e7eb\",\n colorError: \"#dc2626\",\n colorSuccess: \"#16a34a\",\n radius: \"10px\",\n fontFamily: \"system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif\",\n};\n\nfunction themeToVars(theme: BowlosThemeTokens): CSSProperties {\n const out: Record<string, string> = {};\n for (const key of Object.keys(VAR) as (keyof BowlosThemeTokens)[]) {\n const value = theme[key];\n if (value) out[VAR[key]] = value;\n }\n return out as CSSProperties;\n}\n\n/**\n * Applies a theme by setting the `--bowlos-*` CSS variables on a wrapper, which\n * the components read. Children inherit them; nest another `<BowlosTheme>` to\n * override per-section. Optional — components fall back to neutral defaults\n * without it.\n */\nexport function BowlosTheme({\n theme = {},\n className,\n style,\n children,\n}: {\n theme?: BowlosThemeTokens;\n className?: string;\n style?: CSSProperties;\n children: ReactNode;\n}) {\n return (\n <div className={className} style={{ ...themeToVars(theme), ...style }}>\n {children}\n </div>\n );\n}\n\n/** A CSS-var reference for a token, with the neutral default baked in as the\n * fallback — components use this in inline styles. */\nexport function token(key: keyof BowlosThemeTokens): string {\n return `var(${VAR[key]}, ${BOWLOS_DEFAULT_THEME[key]})`;\n}\n","\"use client\";\n/**\n * Shared primitives for the `@bowlos/reservations/components` layer.\n *\n * One canonical set of themed style atoms + formatters, consumed by every\n * component (booking, account, flash) so there's a single source of truth for\n * the look — no per-surface copies. All visuals read the `--bowlos-*` CSS vars\n * via `token()`, so a `<BowlosTheme>` (or raw CSS) restyles every component at\n * once. White-label by design — neutral defaults, no BowlOS branding.\n */\nimport { useEffect, useState, type CSSProperties } from \"react\";\nimport { token } from \"./theme\";\n\n/** The canonical themed style atoms. Components pick the atoms they need. */\nexport function styles(): Record<string, CSSProperties> {\n return {\n // containers\n card: {\n fontFamily: token(\"fontFamily\"),\n color: token(\"colorText\"),\n background: token(\"colorBg\"),\n border: `1px solid ${token(\"colorBorder\")}`,\n borderRadius: token(\"radius\"),\n padding: \"1.25rem\",\n display: \"flex\",\n flexDirection: \"column\",\n gap: \"0.75rem\",\n maxWidth: 380,\n },\n panel: {\n fontFamily: token(\"fontFamily\"),\n color: token(\"colorText\"),\n background: token(\"colorBg\"),\n border: `1px solid ${token(\"colorBorder\")}`,\n borderRadius: token(\"radius\"),\n padding: \"1rem 1.25rem\",\n display: \"flex\",\n flexDirection: \"column\",\n gap: \"0.625rem\",\n },\n // text\n heading: { margin: \"0 0 0.25rem\", fontSize: \"1.25rem\" },\n sectionTitle: {\n margin: \"0 0 0.5rem\",\n fontSize: \"0.8rem\",\n fontWeight: 700,\n letterSpacing: \"0.04em\",\n textTransform: \"uppercase\",\n color: token(\"colorMuted\"),\n },\n body: { margin: 0, color: token(\"colorText\") },\n meta: { margin: 0, fontSize: \"0.9rem\", color: token(\"colorMuted\"), minHeight: \"1.2em\" },\n muted: { margin: 0, fontSize: \"0.9rem\", color: token(\"colorMuted\") },\n error: { margin: 0, color: token(\"colorError\"), fontSize: \"0.9rem\" },\n // form\n label: {\n display: \"flex\",\n flexDirection: \"column\",\n gap: \"0.25rem\",\n fontSize: \"0.85rem\",\n color: token(\"colorMuted\"),\n },\n input: {\n padding: \"0.5rem 0.625rem\",\n fontSize: \"1rem\",\n color: token(\"colorText\"),\n background: token(\"colorSurface\"),\n border: `1px solid ${token(\"colorBorder\")}`,\n borderRadius: token(\"radius\"),\n },\n // layout\n row: { display: \"flex\", gap: \"0.5rem\", flexWrap: \"wrap\", alignItems: \"center\" },\n rowBetween: { display: \"flex\", gap: \"0.5rem\", justifyContent: \"space-between\", alignItems: \"center\" },\n stack: { display: \"flex\", flexDirection: \"column\", gap: \"0.75rem\" },\n // buttons\n primaryBtn: {\n padding: \"0.625rem 1rem\",\n fontSize: \"1rem\",\n fontWeight: 600,\n color: token(\"colorPrimaryContrast\"),\n background: token(\"colorPrimary\"),\n border: \"none\",\n borderRadius: token(\"radius\"),\n cursor: \"pointer\",\n },\n ghostBtn: {\n padding: \"0.625rem 1rem\",\n fontSize: \"1rem\",\n color: token(\"colorText\"),\n background: \"transparent\",\n border: `1px solid ${token(\"colorBorder\")}`,\n borderRadius: token(\"radius\"),\n cursor: \"pointer\",\n },\n linkBtn: {\n padding: 0,\n fontSize: \"0.9rem\",\n color: token(\"colorPrimary\"),\n background: \"transparent\",\n border: \"none\",\n cursor: \"pointer\",\n textDecoration: \"underline\",\n },\n // list rows (reservations, memberships, ledger, passes, flash items)\n listItem: {\n display: \"flex\",\n justifyContent: \"space-between\",\n alignItems: \"baseline\",\n gap: \"0.75rem\",\n padding: \"0.625rem 0\",\n borderTop: `1px solid ${token(\"colorBorder\")}`,\n },\n listTitle: { margin: 0, fontSize: \"1rem\", fontWeight: 600 },\n listMeta: { margin: 0, fontSize: \"0.85rem\", color: token(\"colorMuted\") },\n // badges + prices\n badge: {\n display: \"inline-block\",\n padding: \"0.125rem 0.5rem\",\n fontSize: \"0.75rem\",\n fontWeight: 600,\n color: token(\"colorMuted\"),\n background: token(\"colorSurface\"),\n border: `1px solid ${token(\"colorBorder\")}`,\n borderRadius: \"999px\",\n whiteSpace: \"nowrap\",\n },\n priceSale: { fontSize: \"1.05rem\", fontWeight: 700, color: token(\"colorText\") },\n priceStrike: { fontSize: \"0.9rem\", color: token(\"colorMuted\"), textDecoration: \"line-through\" },\n // flash hero\n banner: {\n width: \"100%\",\n height: 140,\n objectFit: \"cover\",\n borderTopLeftRadius: token(\"radius\"),\n borderTopRightRadius: token(\"radius\"),\n display: \"block\",\n },\n countdown: { margin: 0, fontSize: \"0.95rem\", fontWeight: 600, color: token(\"colorPrimary\") },\n };\n}\n\n/** Format integer cents as USD. */\nexport function formatCents(cents: number): string {\n return (cents / 100).toLocaleString(undefined, { style: \"currency\", currency: \"USD\" });\n}\n\n/** A min–max money range, collapsing to one value when they're equal. */\nexport function formatCentsRange(minCents: number, maxCents: number): string {\n return maxCents > minCents ? `${formatCents(minCents)} – ${formatCents(maxCents)}` : formatCents(minCents);\n}\n\n/** Minute-of-day → \"HH:MM\" (24h, for `<input type=\"time\">`). */\nexport function minutesToTime(min: number): string {\n const h = Math.floor(min / 60)\n .toString()\n .padStart(2, \"0\");\n const m = (min % 60).toString().padStart(2, \"0\");\n return `${h}:${m}`;\n}\n\n/** \"HH:MM\" → minute-of-day. */\nexport function timeToMinutes(t: string): number {\n const [h, m] = t.split(\":\").map(Number);\n return (h ?? 0) * 60 + (m ?? 0);\n}\n\n/** Minute-of-day → friendly 12-hour label (\"6:00 PM\"), for time dropdowns. */\nexport function formatMinuteLabel(min: number): string {\n const h24 = Math.floor(min / 60) % 24;\n const m = min % 60;\n const period = h24 < 12 ? \"AM\" : \"PM\";\n const h12 = h24 % 12 === 0 ? 12 : h24 % 12;\n return `${h12}:${m.toString().padStart(2, \"0\")} ${period}`;\n}\n\n/**\n * A live countdown to `targetMs`, recomputed every second on the client.\n *\n * Returns `null` on the server / first client render (so SSR markup and the\n * first hydration pass match — no mismatch), then ticks once mounted. `ended`\n * flips true at/after the target. We derive this off a ticking timer rather\n * than a server-computed boolean so it stays live without a refetch.\n */\nexport function useCountdown(targetMs: number | null): { ended: boolean; label: string } | null {\n const [now, setNow] = useState<number | null>(null);\n useEffect(() => {\n if (targetMs === null) return;\n setNow(Date.now());\n const id = setInterval(() => setNow(Date.now()), 1000);\n return () => clearInterval(id);\n }, [targetMs]);\n\n if (now === null || targetMs === null) return null;\n const remaining = targetMs - now;\n if (remaining <= 0) return { ended: true, label: \"\" };\n return { ended: false, label: humanizeRemaining(remaining) };\n}\n\nfunction humanizeRemaining(ms: number): string {\n const totalSec = Math.floor(ms / 1000);\n const d = Math.floor(totalSec / 86400);\n const h = Math.floor((totalSec % 86400) / 3600);\n const m = Math.floor((totalSec % 3600) / 60);\n const s = totalSec % 60;\n if (d > 0) return `${d}d ${h}h ${m}m`;\n if (h > 0) return `${h}h ${m}m ${s}s`;\n if (m > 0) return `${m}m ${s}s`;\n return `${s}s`;\n}\n","\"use client\";\n/**\n * `<BowlosPaymentForm>` — the drop-in Stripe Connect checkout for `<BookingFlow>`.\n *\n * This is the ONE part of the SDK that loads Stripe.js, so it lives in its own\n * entry (`@bowlos/reservations/payments`) and Stripe is an OPTIONAL peer — the\n * core + components bundles never pull it. Wire it into `<BookingFlow>`'s\n * `renderPayment` slot and you never hand-build a Stripe Elements form per site:\n *\n * ```tsx\n * import { BowlosPaymentForm } from \"@bowlos/reservations/payments\";\n *\n * <BookingFlow\n * renderPayment={(ctx) => (\n * <BowlosPaymentForm {...ctx} publishableKey={process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY!} />\n * )}\n * />\n * ```\n *\n * It initializes Stripe.js with the PLATFORM publishable key scoped to the\n * operator's CONNECTED account (`stripeAccount: connectedAccountId`), so the\n * charge lands directly on the operator's Stripe account (their name on the\n * statement/receipt — the white-label requirement). Saved cards + \"save for\n * future\" are enabled by default via the booking's customer session.\n */\nimport { useMemo, useState, type FormEvent } from \"react\";\nimport { loadStripe, type Appearance } from \"@stripe/stripe-js\";\nimport { Elements, PaymentElement, useElements, useStripe } from \"@stripe/react-stripe-js\";\nimport type { ConnectedPaymentInput } from \"../data\";\nimport { formatCents, styles } from \"./shared\";\n\n/** Visible strings — override any subset for copy/i18n. */\nexport interface BowlosPaymentFormLabels {\n /** Button when idle. `{amount}` (if present) is replaced with the formatted total. */\n pay: string;\n paying: string;\n genericError: string;\n}\n\nconst DEFAULT_LABELS: BowlosPaymentFormLabels = {\n pay: \"Pay {amount}\",\n paying: \"Paying…\",\n genericError: \"Payment failed — please try again.\",\n};\n\nexport interface BowlosPaymentFormProps {\n /** The Connect payment to confirm — a booking's `PaymentIntentInfo`, a buy\n * flow's intent, or a subscription's first-invoice client secret. Any value\n * with `{ clientSecret, connectedAccountId, customerSessionClientSecret? }`. */\n paymentIntent: ConnectedPaymentInput;\n /** Your PLATFORM publishable key (browser-safe; e.g. `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY`). */\n publishableKey: string;\n /** Called once the PaymentIntent confirms — start polling for the reservation. */\n onPaid: () => void;\n /** Called with a human-readable message when confirmation fails. */\n onError?: (message: string) => void;\n /** Total, for the button label (\"Pay $45.00\"). Omit to show a plain \"Pay\". */\n amountCents?: number;\n /**\n * Enable saved cards + a \"save for future\" option via the booking's customer\n * session (when the gateway provided one). Default `true`. Set `false` for a\n * one-off charge with no card on file.\n */\n saveCard?: boolean;\n /**\n * Stripe Elements appearance — theme the Payment Element to match your site\n * (e.g. `{ theme: \"night\", variables: { colorPrimary: \"#FFD500\" } }`). Without\n * it Stripe renders its default light theme, which looks off on a dark site.\n */\n appearance?: Appearance;\n labels?: Partial<BowlosPaymentFormLabels>;\n className?: string;\n}\n\n/**\n * The Stripe Connect payment form. Renders the Payment Element scoped to the\n * operator's connected account and confirms the PaymentIntent on submit.\n */\nexport function BowlosPaymentForm({\n paymentIntent,\n publishableKey,\n onPaid,\n onError,\n amountCents,\n saveCard = true,\n appearance,\n labels,\n className,\n}: BowlosPaymentFormProps) {\n // Platform key, scoped to the operator's connected account → the charge is\n // created directly on their Stripe account (white-label receipt/statement).\n const stripePromise = useMemo(\n () => loadStripe(publishableKey, { stripeAccount: paymentIntent.connectedAccountId }),\n [publishableKey, paymentIntent.connectedAccountId],\n );\n\n // Pass the customer session only when present + opted-in, so the Payment\n // Element can offer saved cards / \"save for future\" for this operator.\n const customerSessionClientSecret =\n saveCard && paymentIntent.customerSessionClientSecret\n ? paymentIntent.customerSessionClientSecret\n : undefined;\n\n return (\n <Elements\n stripe={stripePromise}\n options={{ clientSecret: paymentIntent.clientSecret, customerSessionClientSecret, appearance }}\n >\n <PayForm\n onPaid={onPaid}\n onError={onError}\n amountCents={amountCents}\n labels={labels}\n className={className}\n />\n </Elements>\n );\n}\n\nfunction PayForm({\n onPaid,\n onError,\n amountCents,\n labels,\n className,\n}: {\n onPaid: () => void;\n onError?: (message: string) => void;\n amountCents?: number;\n labels?: Partial<BowlosPaymentFormLabels>;\n className?: string;\n}) {\n const t = { ...DEFAULT_LABELS, ...labels };\n const stripe = useStripe();\n const elements = useElements();\n const [submitting, setSubmitting] = useState(false);\n const [message, setMessage] = useState<string | null>(null);\n const s = styles();\n\n async function handleSubmit(e: FormEvent) {\n e.preventDefault();\n if (!stripe || !elements) return;\n setSubmitting(true);\n setMessage(null);\n\n // `redirect: \"if_required\"` keeps card payments on-page; wallets that need\n // a redirect still work.\n const { error } = await stripe.confirmPayment({ elements, redirect: \"if_required\" });\n\n if (error) {\n const m = error.message ?? t.genericError;\n setMessage(m);\n onError?.(m);\n setSubmitting(false);\n return;\n }\n\n // Paid. The gateway's Stripe webhook materializes the reservation\n // asynchronously, so hand control back so the flow can poll for it.\n onPaid();\n }\n\n const payLabel = t.pay.replace(\"{amount}\", amountCents != null ? formatCents(amountCents) : \"\").trim();\n\n return (\n <form onSubmit={handleSubmit} className={className} style={s.stack}>\n <PaymentElement />\n <button type=\"submit\" style={s.primaryBtn} disabled={!stripe || submitting}>\n {submitting ? t.paying : payLabel}\n </button>\n {message && (\n <p role=\"alert\" style={s.error}>\n {message}\n </p>\n )}\n </form>\n );\n}\n"]}
1
+ {"version":3,"sources":["../src/components/theme.tsx","../src/components/shared.tsx","../src/components/payment-form.tsx"],"names":["useMemo","loadStripe","jsx","Elements","useStripe","useElements","useState","PaymentElement"],"mappings":";;;;;;;;AA6BA,IAAM,GAAA,GAA+C;AAAA,EACnD,YAAA,EAAc,wBAAA;AAAA,EACd,oBAAA,EAAsB,iCAAA;AAAA,EACtB,SAAA,EAAW,qBAAA;AAAA,EACX,UAAA,EAAY,sBAAA;AAAA,EACZ,OAAA,EAAS,mBAAA;AAAA,EACT,YAAA,EAAc,wBAAA;AAAA,EACd,WAAA,EAAa,uBAAA;AAAA,EACb,UAAA,EAAY,sBAAA;AAAA,EACZ,YAAA,EAAc,wBAAA;AAAA,EACd,MAAA,EAAQ,iBAAA;AAAA,EACR,UAAA,EAAY;AACd,CAAA;AAIO,IAAM,oBAAA,GAAoD;AAAA,EAC/D,YAAA,EAAc,SAAA;AAAA,EACd,oBAAA,EAAsB,SAAA;AAAA,EACtB,SAAA,EAAW,SAAA;AAAA,EACX,UAAA,EAAY,SAAA;AAAA,EACZ,OAAA,EAAS,SAAA;AAAA,EACT,YAAA,EAAc,SAAA;AAAA,EACd,WAAA,EAAa,SAAA;AAAA,EACb,UAAA,EAAY,SAAA;AAAA,EACZ,YAAA,EAAc,SAAA;AAAA,EACd,MAAA,EAAQ,MAAA;AAAA,EACR,UAAA,EAAY;AACd,CAAA;AAqCO,SAAS,MAAM,GAAA,EAAsC;AAC1D,EAAA,OAAO,OAAO,GAAA,CAAI,GAAG,CAAC,CAAA,EAAA,EAAK,oBAAA,CAAqB,GAAG,CAAC,CAAA,CAAA,CAAA;AACtD;;;AClFO,SAAS,MAAA,GAAwC;AACtD,EAAA,OAAO;AAAA;AAAA,IAEL,IAAA,EAAM;A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IAAY,UAAA;AAAA,QAEjC,QAAA,EAAA,UAAA,GAAa,EAAE,MAAA,GAAS;AAAA;AAAA,KAC3B;AAAA,IACC,OAAA,oBACCA,cAAAA,CAAC,GAAA,EAAA,EAAE,MAAK,OAAA,EAAQ,KAAA,EAAO,CAAA,CAAE,KAAA,EACtB,QAAA,EAAA,OAAA,EACH;AAAA,GAAA,EAEJ,CAAA;AAEJ","file":"payments.cjs","sourcesContent":["import type { CSSProperties, ReactNode } from \"react\";\n\n/**\n * Themeable design tokens for the `@bowlos/reservations/components` layer.\n *\n * Override any subset; the rest fall back to neutral, **white-label** defaults\n * (deliberately no BowlOS branding — these render on a center's own site).\n * Tokens are applied as CSS custom properties, so you can theme either with\n * `<BowlosTheme theme={...}>` or by setting the `--bowlos-*` variables yourself\n * in CSS.\n */\nexport interface BowlosThemeTokens {\n /** Accent color — buttons, highlights. */\n colorPrimary?: string;\n /** Text/icon color on top of `colorPrimary`. */\n colorPrimaryContrast?: string;\n colorText?: string;\n colorMuted?: string;\n colorBg?: string;\n colorSurface?: string;\n colorBorder?: string;\n colorError?: string;\n colorSuccess?: string;\n /** Corner radius (e.g. \"10px\", \"0.5rem\"). */\n radius?: string;\n /** Font family stack. */\n fontFamily?: string;\n}\n\nconst VAR: Record<keyof BowlosThemeTokens, string> = {\n colorPrimary: \"--bowlos-color-primary\",\n colorPrimaryContrast: \"--bowlos-color-primary-contrast\",\n colorText: \"--bowlos-color-text\",\n colorMuted: \"--bowlos-color-muted\",\n colorBg: \"--bowlos-color-bg\",\n colorSurface: \"--bowlos-color-surface\",\n colorBorder: \"--bowlos-color-border\",\n colorError: \"--bowlos-color-error\",\n colorSuccess: \"--bowlos-color-success\",\n radius: \"--bowlos-radius\",\n fontFamily: \"--bowlos-font\",\n};\n\n/** Neutral, white-label defaults — used as the CSS-var fallbacks, so components\n * look right even with no `<BowlosTheme>` wrapper. */\nexport const BOWLOS_DEFAULT_THEME: Required<BowlosThemeTokens> = {\n colorPrimary: \"#1f2937\",\n colorPrimaryContrast: \"#ffffff\",\n colorText: \"#111827\",\n colorMuted: \"#6b7280\",\n colorBg: \"#ffffff\",\n colorSurface: \"#f9fafb\",\n colorBorder: \"#e5e7eb\",\n colorError: \"#dc2626\",\n colorSuccess: \"#16a34a\",\n radius: \"10px\",\n fontFamily: \"system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif\",\n};\n\nfunction themeToVars(theme: BowlosThemeTokens): CSSProperties {\n const out: Record<string, string> = {};\n for (const key of Object.keys(VAR) as (keyof BowlosThemeTokens)[]) {\n const value = theme[key];\n if (value) out[VAR[key]] = value;\n }\n return out as CSSProperties;\n}\n\n/**\n * Applies a theme by setting the `--bowlos-*` CSS variables on a wrapper, which\n * the components read. Children inherit them; nest another `<BowlosTheme>` to\n * override per-section. Optional — components fall back to neutral defaults\n * without it.\n */\nexport function BowlosTheme({\n theme = {},\n className,\n style,\n children,\n}: {\n theme?: BowlosThemeTokens;\n className?: string;\n style?: CSSProperties;\n children: ReactNode;\n}) {\n return (\n <div className={className} style={{ ...themeToVars(theme), ...style }}>\n {children}\n </div>\n );\n}\n\n/** A CSS-var reference for a token, with the neutral default baked in as the\n * fallback — components use this in inline styles. */\nexport function token(key: keyof BowlosThemeTokens): string {\n return `var(${VAR[key]}, ${BOWLOS_DEFAULT_THEME[key]})`;\n}\n","\"use client\";\n/**\n * Shared primitives for the `@bowlos/reservations/components` layer.\n *\n * One canonical set of themed style atoms + formatters, consumed by every\n * component (booking, account, flash) so there's a single source of truth for\n * the look — no per-surface copies. All visuals read the `--bowlos-*` CSS vars\n * via `token()`, so a `<BowlosTheme>` (or raw CSS) restyles every component at\n * once. White-label by design — neutral defaults, no BowlOS branding.\n */\nimport { useEffect, useState, type CSSProperties } from \"react\";\nimport { token } from \"./theme\";\n\n/** The canonical themed style atoms. Components pick the atoms they need. */\nexport function styles(): Record<string, CSSProperties> {\n return {\n // containers\n card: {\n fontFamily: token(\"fontFamily\"),\n color: token(\"colorText\"),\n background: token(\"colorBg\"),\n border: `1px solid ${token(\"colorBorder\")}`,\n borderRadius: token(\"radius\"),\n padding: \"1.25rem\",\n display: \"flex\",\n flexDirection: \"column\",\n gap: \"0.75rem\",\n maxWidth: 380,\n },\n panel: {\n fontFamily: token(\"fontFamily\"),\n color: token(\"colorText\"),\n background: token(\"colorBg\"),\n border: `1px solid ${token(\"colorBorder\")}`,\n borderRadius: token(\"radius\"),\n padding: \"1rem 1.25rem\",\n display: \"flex\",\n flexDirection: \"column\",\n gap: \"0.625rem\",\n },\n // text\n heading: { margin: \"0 0 0.25rem\", fontSize: \"1.25rem\" },\n sectionTitle: {\n margin: \"0 0 0.5rem\",\n fontSize: \"0.8rem\",\n fontWeight: 700,\n letterSpacing: \"0.04em\",\n textTransform: \"uppercase\",\n color: token(\"colorMuted\"),\n },\n body: { margin: 0, color: token(\"colorText\") },\n meta: { margin: 0, fontSize: \"0.9rem\", color: token(\"colorMuted\"), minHeight: \"1.2em\" },\n muted: { margin: 0, fontSize: \"0.9rem\", color: token(\"colorMuted\") },\n error: { margin: 0, color: token(\"colorError\"), fontSize: \"0.9rem\" },\n // form\n label: {\n display: \"flex\",\n flexDirection: \"column\",\n gap: \"0.25rem\",\n fontSize: \"0.85rem\",\n color: token(\"colorMuted\"),\n },\n input: {\n padding: \"0.5rem 0.625rem\",\n fontSize: \"1rem\",\n color: token(\"colorText\"),\n background: token(\"colorSurface\"),\n border: `1px solid ${token(\"colorBorder\")}`,\n borderRadius: token(\"radius\"),\n },\n // layout\n row: { display: \"flex\", gap: \"0.5rem\", flexWrap: \"wrap\", alignItems: \"center\" },\n rowBetween: { display: \"flex\", gap: \"0.5rem\", justifyContent: \"space-between\", alignItems: \"center\" },\n stack: { display: \"flex\", flexDirection: \"column\", gap: \"0.75rem\" },\n // buttons\n primaryBtn: {\n padding: \"0.625rem 1rem\",\n fontSize: \"1rem\",\n fontWeight: 600,\n color: token(\"colorPrimaryContrast\"),\n background: token(\"colorPrimary\"),\n border: \"none\",\n borderRadius: token(\"radius\"),\n cursor: \"pointer\",\n },\n ghostBtn: {\n padding: \"0.625rem 1rem\",\n fontSize: \"1rem\",\n color: token(\"colorText\"),\n background: \"transparent\",\n border: `1px solid ${token(\"colorBorder\")}`,\n borderRadius: token(\"radius\"),\n cursor: \"pointer\",\n },\n linkBtn: {\n padding: 0,\n fontSize: \"0.9rem\",\n color: token(\"colorPrimary\"),\n background: \"transparent\",\n border: \"none\",\n cursor: \"pointer\",\n textDecoration: \"underline\",\n },\n // list rows (reservations, memberships, ledger, passes, flash items)\n listItem: {\n display: \"flex\",\n justifyContent: \"space-between\",\n alignItems: \"baseline\",\n gap: \"0.75rem\",\n padding: \"0.625rem 0\",\n borderTop: `1px solid ${token(\"colorBorder\")}`,\n },\n listTitle: { margin: 0, fontSize: \"1rem\", fontWeight: 600 },\n listMeta: { margin: 0, fontSize: \"0.85rem\", color: token(\"colorMuted\") },\n // badges + prices\n badge: {\n display: \"inline-block\",\n padding: \"0.125rem 0.5rem\",\n fontSize: \"0.75rem\",\n fontWeight: 600,\n color: token(\"colorMuted\"),\n background: token(\"colorSurface\"),\n border: `1px solid ${token(\"colorBorder\")}`,\n borderRadius: \"999px\",\n whiteSpace: \"nowrap\",\n },\n priceSale: { fontSize: \"1.05rem\", fontWeight: 700, color: token(\"colorText\") },\n priceStrike: { fontSize: \"0.9rem\", color: token(\"colorMuted\"), textDecoration: \"line-through\" },\n // flash hero\n banner: {\n width: \"100%\",\n height: 140,\n objectFit: \"cover\",\n borderTopLeftRadius: token(\"radius\"),\n borderTopRightRadius: token(\"radius\"),\n display: \"block\",\n },\n countdown: { margin: 0, fontSize: \"0.95rem\", fontWeight: 600, color: token(\"colorPrimary\") },\n };\n}\n\n/** Format integer cents as USD. */\nexport function formatCents(cents: number): string {\n return (cents / 100).toLocaleString(undefined, { style: \"currency\", currency: \"USD\" });\n}\n\n/** A min–max money range, collapsing to one value when they're equal. */\nexport function formatCentsRange(minCents: number, maxCents: number): string {\n return maxCents > minCents ? `${formatCents(minCents)} – ${formatCents(maxCents)}` : formatCents(minCents);\n}\n\n/** Minute-of-day → \"HH:MM\" (24h, for `<input type=\"time\">`). */\nexport function minutesToTime(min: number): string {\n const h = Math.floor(min / 60)\n .toString()\n .padStart(2, \"0\");\n const m = (min % 60).toString().padStart(2, \"0\");\n return `${h}:${m}`;\n}\n\n/** \"HH:MM\" → minute-of-day. */\nexport function timeToMinutes(t: string): number {\n const [h, m] = t.split(\":\").map(Number);\n return (h ?? 0) * 60 + (m ?? 0);\n}\n\n/** Minute-of-day → friendly 12-hour label (\"6:00 PM\"), for time dropdowns. */\nexport function formatMinuteLabel(min: number): string {\n const h24 = Math.floor(min / 60) % 24;\n const m = min % 60;\n const period = h24 < 12 ? \"AM\" : \"PM\";\n const h12 = h24 % 12 === 0 ? 12 : h24 % 12;\n return `${h12}:${m.toString().padStart(2, \"0\")} ${period}`;\n}\n\n/**\n * A live countdown to `targetMs`, recomputed every second on the client.\n *\n * Returns `null` on the server / first client render (so SSR markup and the\n * first hydration pass match — no mismatch), then ticks once mounted. `ended`\n * flips true at/after the target. We derive this off a ticking timer rather\n * than a server-computed boolean so it stays live without a refetch.\n */\nexport function useCountdown(targetMs: number | null): { ended: boolean; label: string } | null {\n const [now, setNow] = useState<number | null>(null);\n useEffect(() => {\n if (targetMs === null) return;\n setNow(Date.now());\n const id = setInterval(() => setNow(Date.now()), 1000);\n return () => clearInterval(id);\n }, [targetMs]);\n\n if (now === null || targetMs === null) return null;\n const remaining = targetMs - now;\n if (remaining <= 0) return { ended: true, label: \"\" };\n return { ended: false, label: humanizeRemaining(remaining) };\n}\n\nfunction humanizeRemaining(ms: number): string {\n const totalSec = Math.floor(ms / 1000);\n const d = Math.floor(totalSec / 86400);\n const h = Math.floor((totalSec % 86400) / 3600);\n const m = Math.floor((totalSec % 3600) / 60);\n const s = totalSec % 60;\n if (d > 0) return `${d}d ${h}h ${m}m`;\n if (h > 0) return `${h}h ${m}m ${s}s`;\n if (m > 0) return `${m}m ${s}s`;\n return `${s}s`;\n}\n","\"use client\";\n/**\n * `<BowlosPaymentForm>` — the drop-in Stripe Connect checkout for `<BookingFlow>`.\n *\n * This is the ONE part of the SDK that loads Stripe.js, so it lives in its own\n * entry (`@bowlos/reservations/payments`) and Stripe is an OPTIONAL peer — the\n * core + components bundles never pull it. Wire it into `<BookingFlow>`'s\n * `renderPayment` slot and you never hand-build a Stripe Elements form per site:\n *\n * ```tsx\n * import { BowlosPaymentForm } from \"@bowlos/reservations/payments\";\n *\n * <BookingFlow\n * renderPayment={(ctx) => (\n * <BowlosPaymentForm {...ctx} publishableKey={process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY!} />\n * )}\n * />\n * ```\n *\n * It initializes Stripe.js with the PLATFORM publishable key scoped to the\n * operator's CONNECTED account (`stripeAccount: connectedAccountId`), so the\n * charge lands directly on the operator's Stripe account (their name on the\n * statement/receipt — the white-label requirement). Saved cards + \"save for\n * future\" are enabled by default via the booking's customer session.\n */\nimport { useMemo, useState, type FormEvent } from \"react\";\nimport { loadStripe, type Appearance } from \"@stripe/stripe-js\";\nimport { Elements, PaymentElement, useElements, useStripe } from \"@stripe/react-stripe-js\";\nimport type { ConnectedPaymentInput } from \"../data\";\nimport { formatCents, styles } from \"./shared\";\n\n/** Visible strings — override any subset for copy/i18n. */\nexport interface BowlosPaymentFormLabels {\n /** Button when idle. `{amount}` (if present) is replaced with the formatted total. */\n pay: string;\n paying: string;\n genericError: string;\n}\n\nconst DEFAULT_LABELS: BowlosPaymentFormLabels = {\n pay: \"Pay {amount}\",\n paying: \"Paying…\",\n genericError: \"Payment failed — please try again.\",\n};\n\nexport interface BowlosPaymentFormProps {\n /** The Connect payment to confirm — a booking's `PaymentIntentInfo`, a buy\n * flow's intent, or a subscription's first-invoice client secret. Any value\n * with `{ clientSecret, connectedAccountId, customerSessionClientSecret? }`. */\n paymentIntent: ConnectedPaymentInput;\n /** Your PLATFORM publishable key (browser-safe; e.g. `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY`). */\n publishableKey: string;\n /** Called once the PaymentIntent confirms — start polling for the reservation. */\n onPaid: () => void;\n /** Called with a human-readable message when confirmation fails. */\n onError?: (message: string) => void;\n /** Total, for the button label (\"Pay $45.00\"). Omit to show a plain \"Pay\". */\n amountCents?: number;\n /**\n * Enable saved cards + a \"save for future\" option via the booking's customer\n * session (when the gateway provided one). Default `true`. Set `false` for a\n * one-off charge with no card on file.\n */\n saveCard?: boolean;\n /**\n * Stripe Elements appearance — theme the Payment Element to match your site\n * (e.g. `{ theme: \"night\", variables: { colorPrimary: \"#FFD500\" } }`). Without\n * it Stripe renders its default light theme, which looks off on a dark site.\n */\n appearance?: Appearance;\n labels?: Partial<BowlosPaymentFormLabels>;\n className?: string;\n}\n\n/**\n * The Stripe Connect payment form. Renders the Payment Element scoped to the\n * operator's connected account and confirms the PaymentIntent on submit.\n */\nexport function BowlosPaymentForm({\n paymentIntent,\n publishableKey,\n onPaid,\n onError,\n amountCents,\n saveCard = true,\n appearance,\n labels,\n className,\n}: BowlosPaymentFormProps) {\n // Platform key, scoped to the operator's connected account → the charge is\n // created directly on their Stripe account (white-label receipt/statement).\n const stripePromise = useMemo(\n () => loadStripe(publishableKey, { stripeAccount: paymentIntent.connectedAccountId }),\n [publishableKey, paymentIntent.connectedAccountId],\n );\n\n // Pass the customer session only when present + opted-in, so the Payment\n // Element can offer saved cards / \"save for future\" for this operator.\n const customerSessionClientSecret =\n saveCard && paymentIntent.customerSessionClientSecret\n ? paymentIntent.customerSessionClientSecret\n : undefined;\n\n return (\n <Elements\n stripe={stripePromise}\n options={{ clientSecret: paymentIntent.clientSecret, customerSessionClientSecret, appearance }}\n >\n <PayForm\n onPaid={onPaid}\n onError={onError}\n amountCents={amountCents}\n labels={labels}\n className={className}\n />\n </Elements>\n );\n}\n\nfunction PayForm({\n onPaid,\n onError,\n amountCents,\n labels,\n className,\n}: {\n onPaid: () => void;\n onError?: (message: string) => void;\n amountCents?: number;\n labels?: Partial<BowlosPaymentFormLabels>;\n className?: string;\n}) {\n const t = { ...DEFAULT_LABELS, ...labels };\n const stripe = useStripe();\n const elements = useElements();\n const [submitting, setSubmitting] = useState(false);\n const [message, setMessage] = useState<string | null>(null);\n const s = styles();\n\n async function handleSubmit(e: FormEvent) {\n e.preventDefault();\n if (!stripe || !elements) return;\n setSubmitting(true);\n setMessage(null);\n\n // `redirect: \"if_required\"` keeps card payments on-page; wallets that need\n // a redirect still work.\n const { error } = await stripe.confirmPayment({ elements, redirect: \"if_required\" });\n\n if (error) {\n const m = error.message ?? t.genericError;\n setMessage(m);\n onError?.(m);\n setSubmitting(false);\n return;\n }\n\n // Paid. The gateway's Stripe webhook materializes the reservation\n // asynchronously, so hand control back so the flow can poll for it.\n onPaid();\n }\n\n const payLabel = t.pay.replace(\"{amount}\", amountCents != null ? formatCents(amountCents) : \"\").trim();\n\n return (\n <form onSubmit={handleSubmit} className={className} style={s.stack}>\n <PaymentElement />\n {/* v0.22.1: include !elements — the submit handler bails on a not-yet-\n mounted PaymentElement, so a click during mount was a silent no-op\n (the \"first click does nothing\" race a center site reproduced). */}\n <button\n type=\"submit\"\n style={s.primaryBtn}\n disabled={!stripe || !elements || submitting}\n >\n {submitting ? t.paying : payLabel}\n </button>\n {message && (\n <p role=\"alert\" style={s.error}>\n {message}\n </p>\n )}\n </form>\n );\n}\n"]}
package/dist/payments.js CHANGED
@@ -74,7 +74,15 @@ function PayForm({
74
74
  const payLabel = t.pay.replace("{amount}", amountCents != null ? formatCents(amountCents) : "").trim();
75
75
  return /* @__PURE__ */ jsxs("form", { onSubmit: handleSubmit, className, style: s.stack, children: [
76
76
  /* @__PURE__ */ jsx(PaymentElement, {}),
77
- /* @__PURE__ */ jsx("button", { type: "submit", style: s.primaryBtn, disabled: !stripe || submitting, children: submitting ? t.paying : payLabel }),
77
+ /* @__PURE__ */ jsx(
78
+ "button",
79
+ {
80
+ type: "submit",
81
+ style: s.primaryBtn,
82
+ disabled: !stripe || !elements || submitting,
83
+ children: submitting ? t.paying : payLabel
84
+ }
85
+ ),
78
86
  message && /* @__PURE__ */ jsx("p", { role: "alert", style: s.error, children: message })
79
87
  ] });
80
88
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/components/payment-form.tsx"],"names":[],"mappings":";;;;;;AAuCA,IAAM,cAAA,GAA0C;AAAA,EAC9C,GAAA,EAAK,cAAA;AAAA,EACL,MAAA,EAAQ,cAAA;AAAA,EACR,YAAA,EAAc;AAChB,CAAA;AAmCO,SAAS,iBAAA,CAAkB;AAAA,EAChC,aAAA;AAAA,EACA,cAAA;AAAA,EACA,MAAA;AAAA,EACA,OAAA;AAAA,EACA,WAAA;AAAA,EACA,QAAA,GAAW,IAAA;AAAA,EACX,UAAA;AAAA,EACA,MAAA;AAAA,EACA;AACF,CAAA,EAA2B;AAGzB,EAAA,MAAM,aAAA,GAAgB,OAAA;AAAA,IACpB,MAAM,UAAA,CAAW,cAAA,EAAgB,EAAE,aAAA,EAAe,aAAA,CAAc,oBAAoB,CAAA;AAAA,IACpF,CAAC,cAAA,EAAgB,aAAA,CAAc,kBAAkB;AAAA,GACnD;AAIA,EAAA,MAAM,2BAAA,GACJ,QAAA,IAAY,aAAA,CAAc,2BAAA,GACtB,cAAc,2BAAA,GACd,MAAA;AAEN,EAAA,uBACE,GAAA;AAAA,IAAC,QAAA;AAAA,IAAA;AAAA,MACC,MAAA,EAAQ,aAAA;AAAA,MACR,SAAS,EAAE,YAAA,EAAc,aAAA,CAAc,YAAA,EAAc,6BAA6B,UAAA,EAAW;AAAA,MAE7F,QAAA,kBAAA,GAAA;AAAA,QAAC,OAAA;AAAA,QAAA;AAAA,UACC,MAAA;AAAA,UACA,OAAA;AAAA,UACA,WAAA;AAAA,UACA,MAAA;AAAA,UACA;AAAA;AAAA;AACF;AAAA,GACF;AAEJ;AAEA,SAAS,OAAA,CAAQ;AAAA,EACf,MAAA;AAAA,EACA,OAAA;AAAA,EACA,WAAA;AAAA,EACA,MAAA;AAAA,EACA;AACF,CAAA,EAM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CAAA;AAAA,oBAChB,GAAA,CAAC,QAAA,EAAA,EAAO,IAAA,EAAK,QAAA,EAAS,OAAO,CAAA,CAAE,UAAA,EAAY,QAAA,EAAU,CAAC,MAAA,IAAU,UAAA,EAC7D,QAAA,EAAA,UAAA,GAAa,CAAA,CAAE,SAAS,QAAA,EAC3B,CAAA;AAAA,IACC,OAAA,wBACE,GAAA,EAAA,EAAE,IAAA,EAAK,SAAQ,KAAA,EAAO,CAAA,CAAE,OACtB,QAAA,EAAA,OAAA,EACH;AAAA,GAAA,EAEJ,CAAA;AAEJ","file":"payments.js","sourcesContent":["\"use client\";\n/**\n * `<BowlosPaymentForm>` — the drop-in Stripe Connect checkout for `<BookingFlow>`.\n *\n * This is the ONE part of the SDK that loads Stripe.js, so it lives in its own\n * entry (`@bowlos/reservations/payments`) and Stripe is an OPTIONAL peer — the\n * core + components bundles never pull it. Wire it into `<BookingFlow>`'s\n * `renderPayment` slot and you never hand-build a Stripe Elements form per site:\n *\n * ```tsx\n * import { BowlosPaymentForm } from \"@bowlos/reservations/payments\";\n *\n * <BookingFlow\n * renderPayment={(ctx) => (\n * <BowlosPaymentForm {...ctx} publishableKey={process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY!} />\n * )}\n * />\n * ```\n *\n * It initializes Stripe.js with the PLATFORM publishable key scoped to the\n * operator's CONNECTED account (`stripeAccount: connectedAccountId`), so the\n * charge lands directly on the operator's Stripe account (their name on the\n * statement/receipt — the white-label requirement). Saved cards + \"save for\n * future\" are enabled by default via the booking's customer session.\n */\nimport { useMemo, useState, type FormEvent } from \"react\";\nimport { loadStripe, type Appearance } from \"@stripe/stripe-js\";\nimport { Elements, PaymentElement, useElements, useStripe } from \"@stripe/react-stripe-js\";\nimport type { ConnectedPaymentInput } from \"../data\";\nimport { formatCents, styles } from \"./shared\";\n\n/** Visible strings — override any subset for copy/i18n. */\nexport interface BowlosPaymentFormLabels {\n /** Button when idle. `{amount}` (if present) is replaced with the formatted total. */\n pay: string;\n paying: string;\n genericError: string;\n}\n\nconst DEFAULT_LABELS: BowlosPaymentFormLabels = {\n pay: \"Pay {amount}\",\n paying: \"Paying…\",\n genericError: \"Payment failed — please try again.\",\n};\n\nexport interface BowlosPaymentFormProps {\n /** The Connect payment to confirm — a booking's `PaymentIntentInfo`, a buy\n * flow's intent, or a subscription's first-invoice client secret. Any value\n * with `{ clientSecret, connectedAccountId, customerSessionClientSecret? }`. */\n paymentIntent: ConnectedPaymentInput;\n /** Your PLATFORM publishable key (browser-safe; e.g. `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY`). */\n publishableKey: string;\n /** Called once the PaymentIntent confirms — start polling for the reservation. */\n onPaid: () => void;\n /** Called with a human-readable message when confirmation fails. */\n onError?: (message: string) => void;\n /** Total, for the button label (\"Pay $45.00\"). Omit to show a plain \"Pay\". */\n amountCents?: number;\n /**\n * Enable saved cards + a \"save for future\" option via the booking's customer\n * session (when the gateway provided one). Default `true`. Set `false` for a\n * one-off charge with no card on file.\n */\n saveCard?: boolean;\n /**\n * Stripe Elements appearance — theme the Payment Element to match your site\n * (e.g. `{ theme: \"night\", variables: { colorPrimary: \"#FFD500\" } }`). Without\n * it Stripe renders its default light theme, which looks off on a dark site.\n */\n appearance?: Appearance;\n labels?: Partial<BowlosPaymentFormLabels>;\n className?: string;\n}\n\n/**\n * The Stripe Connect payment form. Renders the Payment Element scoped to the\n * operator's connected account and confirms the PaymentIntent on submit.\n */\nexport function BowlosPaymentForm({\n paymentIntent,\n publishableKey,\n onPaid,\n onError,\n amountCents,\n saveCard = true,\n appearance,\n labels,\n className,\n}: BowlosPaymentFormProps) {\n // Platform key, scoped to the operator's connected account → the charge is\n // created directly on their Stripe account (white-label receipt/statement).\n const stripePromise = useMemo(\n () => loadStripe(publishableKey, { stripeAccount: paymentIntent.connectedAccountId }),\n [publishableKey, paymentIntent.connectedAccountId],\n );\n\n // Pass the customer session only when present + opted-in, so the Payment\n // Element can offer saved cards / \"save for future\" for this operator.\n const customerSessionClientSecret =\n saveCard && paymentIntent.customerSessionClientSecret\n ? paymentIntent.customerSessionClientSecret\n : undefined;\n\n return (\n <Elements\n stripe={stripePromise}\n options={{ clientSecret: paymentIntent.clientSecret, customerSessionClientSecret, appearance }}\n >\n <PayForm\n onPaid={onPaid}\n onError={onError}\n amountCents={amountCents}\n labels={labels}\n className={className}\n />\n </Elements>\n );\n}\n\nfunction PayForm({\n onPaid,\n onError,\n amountCents,\n labels,\n className,\n}: {\n onPaid: () => void;\n onError?: (message: string) => void;\n amountCents?: number;\n labels?: Partial<BowlosPaymentFormLabels>;\n className?: string;\n}) {\n const t = { ...DEFAULT_LABELS, ...labels };\n const stripe = useStripe();\n const elements = useElements();\n const [submitting, setSubmitting] = useState(false);\n const [message, setMessage] = useState<string | null>(null);\n const s = styles();\n\n async function handleSubmit(e: FormEvent) {\n e.preventDefault();\n if (!stripe || !elements) return;\n setSubmitting(true);\n setMessage(null);\n\n // `redirect: \"if_required\"` keeps card payments on-page; wallets that need\n // a redirect still work.\n const { error } = await stripe.confirmPayment({ elements, redirect: \"if_required\" });\n\n if (error) {\n const m = error.message ?? t.genericError;\n setMessage(m);\n onError?.(m);\n setSubmitting(false);\n return;\n }\n\n // Paid. The gateway's Stripe webhook materializes the reservation\n // asynchronously, so hand control back so the flow can poll for it.\n onPaid();\n }\n\n const payLabel = t.pay.replace(\"{amount}\", amountCents != null ? formatCents(amountCents) : \"\").trim();\n\n return (\n <form onSubmit={handleSubmit} className={className} style={s.stack}>\n <PaymentElement />\n <button type=\"submit\" style={s.primaryBtn} disabled={!stripe || submitting}>\n {submitting ? t.paying : payLabel}\n </button>\n {message && (\n <p role=\"alert\" style={s.error}>\n {message}\n </p>\n )}\n </form>\n );\n}\n"]}
1
+ {"version":3,"sources":["../src/components/payment-form.tsx"],"names":[],"mappings":";;;;;;AAuCA,IAAM,cAAA,GAA0C;AAAA,EAC9C,GAAA,EAAK,cAAA;AAAA,EACL,MAAA,EAAQ,cAAA;AAAA,EACR,YAAA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C,OAAA,wBACE,GAAA,EAAA,EAAE,IAAA,EAAK,SAAQ,KAAA,EAAO,CAAA,CAAE,OACtB,QAAA,EAAA,OAAA,EACH;AAAA,GAAA,EAEJ,CAAA;AAEJ","file":"payments.js","sourcesContent":["\"use client\";\n/**\n * `<BowlosPaymentForm>` — the drop-in Stripe Connect checkout for `<BookingFlow>`.\n *\n * This is the ONE part of the SDK that loads Stripe.js, so it lives in its own\n * entry (`@bowlos/reservations/payments`) and Stripe is an OPTIONAL peer — the\n * core + components bundles never pull it. Wire it into `<BookingFlow>`'s\n * `renderPayment` slot and you never hand-build a Stripe Elements form per site:\n *\n * ```tsx\n * import { BowlosPaymentForm } from \"@bowlos/reservations/payments\";\n *\n * <BookingFlow\n * renderPayment={(ctx) => (\n * <BowlosPaymentForm {...ctx} publishableKey={process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY!} />\n * )}\n * />\n * ```\n *\n * It initializes Stripe.js with the PLATFORM publishable key scoped to the\n * operator's CONNECTED account (`stripeAccount: connectedAccountId`), so the\n * charge lands directly on the operator's Stripe account (their name on the\n * statement/receipt — the white-label requirement). Saved cards + \"save for\n * future\" are enabled by default via the booking's customer session.\n */\nimport { useMemo, useState, type FormEvent } from \"react\";\nimport { loadStripe, type Appearance } from \"@stripe/stripe-js\";\nimport { Elements, PaymentElement, useElements, useStripe } from \"@stripe/react-stripe-js\";\nimport type { ConnectedPaymentInput } from \"../data\";\nimport { formatCents, styles } from \"./shared\";\n\n/** Visible strings — override any subset for copy/i18n. */\nexport interface BowlosPaymentFormLabels {\n /** Button when idle. `{amount}` (if present) is replaced with the formatted total. */\n pay: string;\n paying: string;\n genericError: string;\n}\n\nconst DEFAULT_LABELS: BowlosPaymentFormLabels = {\n pay: \"Pay {amount}\",\n paying: \"Paying…\",\n genericError: \"Payment failed — please try again.\",\n};\n\nexport interface BowlosPaymentFormProps {\n /** The Connect payment to confirm — a booking's `PaymentIntentInfo`, a buy\n * flow's intent, or a subscription's first-invoice client secret. Any value\n * with `{ clientSecret, connectedAccountId, customerSessionClientSecret? }`. */\n paymentIntent: ConnectedPaymentInput;\n /** Your PLATFORM publishable key (browser-safe; e.g. `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY`). */\n publishableKey: string;\n /** Called once the PaymentIntent confirms — start polling for the reservation. */\n onPaid: () => void;\n /** Called with a human-readable message when confirmation fails. */\n onError?: (message: string) => void;\n /** Total, for the button label (\"Pay $45.00\"). Omit to show a plain \"Pay\". */\n amountCents?: number;\n /**\n * Enable saved cards + a \"save for future\" option via the booking's customer\n * session (when the gateway provided one). Default `true`. Set `false` for a\n * one-off charge with no card on file.\n */\n saveCard?: boolean;\n /**\n * Stripe Elements appearance — theme the Payment Element to match your site\n * (e.g. `{ theme: \"night\", variables: { colorPrimary: \"#FFD500\" } }`). Without\n * it Stripe renders its default light theme, which looks off on a dark site.\n */\n appearance?: Appearance;\n labels?: Partial<BowlosPaymentFormLabels>;\n className?: string;\n}\n\n/**\n * The Stripe Connect payment form. Renders the Payment Element scoped to the\n * operator's connected account and confirms the PaymentIntent on submit.\n */\nexport function BowlosPaymentForm({\n paymentIntent,\n publishableKey,\n onPaid,\n onError,\n amountCents,\n saveCard = true,\n appearance,\n labels,\n className,\n}: BowlosPaymentFormProps) {\n // Platform key, scoped to the operator's connected account → the charge is\n // created directly on their Stripe account (white-label receipt/statement).\n const stripePromise = useMemo(\n () => loadStripe(publishableKey, { stripeAccount: paymentIntent.connectedAccountId }),\n [publishableKey, paymentIntent.connectedAccountId],\n );\n\n // Pass the customer session only when present + opted-in, so the Payment\n // Element can offer saved cards / \"save for future\" for this operator.\n const customerSessionClientSecret =\n saveCard && paymentIntent.customerSessionClientSecret\n ? paymentIntent.customerSessionClientSecret\n : undefined;\n\n return (\n <Elements\n stripe={stripePromise}\n options={{ clientSecret: paymentIntent.clientSecret, customerSessionClientSecret, appearance }}\n >\n <PayForm\n onPaid={onPaid}\n onError={onError}\n amountCents={amountCents}\n labels={labels}\n className={className}\n />\n </Elements>\n );\n}\n\nfunction PayForm({\n onPaid,\n onError,\n amountCents,\n labels,\n className,\n}: {\n onPaid: () => void;\n onError?: (message: string) => void;\n amountCents?: number;\n labels?: Partial<BowlosPaymentFormLabels>;\n className?: string;\n}) {\n const t = { ...DEFAULT_LABELS, ...labels };\n const stripe = useStripe();\n const elements = useElements();\n const [submitting, setSubmitting] = useState(false);\n const [message, setMessage] = useState<string | null>(null);\n const s = styles();\n\n async function handleSubmit(e: FormEvent) {\n e.preventDefault();\n if (!stripe || !elements) return;\n setSubmitting(true);\n setMessage(null);\n\n // `redirect: \"if_required\"` keeps card payments on-page; wallets that need\n // a redirect still work.\n const { error } = await stripe.confirmPayment({ elements, redirect: \"if_required\" });\n\n if (error) {\n const m = error.message ?? t.genericError;\n setMessage(m);\n onError?.(m);\n setSubmitting(false);\n return;\n }\n\n // Paid. The gateway's Stripe webhook materializes the reservation\n // asynchronously, so hand control back so the flow can poll for it.\n onPaid();\n }\n\n const payLabel = t.pay.replace(\"{amount}\", amountCents != null ? formatCents(amountCents) : \"\").trim();\n\n return (\n <form onSubmit={handleSubmit} className={className} style={s.stack}>\n <PaymentElement />\n {/* v0.22.1: include !elements — the submit handler bails on a not-yet-\n mounted PaymentElement, so a click during mount was a silent no-op\n (the \"first click does nothing\" race a center site reproduced). */}\n <button\n type=\"submit\"\n style={s.primaryBtn}\n disabled={!stripe || !elements || submitting}\n >\n {submitting ? t.paying : payLabel}\n </button>\n {message && (\n <p role=\"alert\" style={s.error}>\n {message}\n </p>\n )}\n </form>\n );\n}\n"]}
package/dist/react.d.cts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { U as UseQueryOptions, a as UseQueryResult } from './react-Bc_6yi9q.cjs';
2
2
  export { A as AccountStatus, B as BowlosProvider, b as BowlosProviderProps, c as UseAccountResult, u as useAccount, d as useBowlosClient, e as useBowlosQuery } from './react-Bc_6yi9q.cjs';
3
3
  import { V as PublicAddon, a as AvailabilityArgs, b as AvailabilityResult, e as BookingPreviewArgs, f as BookingQuote, n as EventTicketPreviewResult, m as EventTicketPreviewArgs, s as GameCardPreviewResult, r as GameCardPreviewArgs, x as MembershipPreviewResult, w as MembershipPreviewArgs, J as MembershipSubscriptionPreviewResult, N as PackagePreviewResult, K as PackagePreviewArgs, W as StartTimesArgs, d as BookingHold, S as PaymentIntentInfo, k as CreateBookingArgs, i as CheckoutStatusResult, I as MembershipSubscriptionIntent, H as MembershipSubscriptionArgs, o as EventTicketPurchaseArgs, t as GameCardPurchaseArgs, y as MembershipPurchaseArgs, O as PackagePurchaseArgs } from './data-BKlgn8Ln.cjs';
4
- import { a as FlashSaleArgs, F as FlashBookingOptionsArgs, b as FlashSalesArgs, B as BrandScoped, E as EventOrderDetailArgs, M as MembershipDetailArgs, R as ReservationDetailArgs } from './account-SqT7et4C.cjs';
4
+ import { a as FlashSaleArgs, F as FlashBookingOptionsArgs, c as FlashSalesArgs, B as BrandScoped, E as EventOrderDetailArgs, M as MembershipDetailArgs, R as ReservationDetailArgs } from './account-CSaBohMT.cjs';
5
5
  import { h as CatalogResult, e as CatalogArgs, k as CenterHoursArgs, l as CenterScoped, d as BrandCatalogArgs, P as PackageDetailArgs, a as BowlosApiError } from './catalog-D1VoVaNe.cjs';
6
6
  import 'react/jsx-runtime';
7
7
  import 'react';
package/dist/react.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { U as UseQueryOptions, a as UseQueryResult } from './react-B1uSOozS.js';
2
2
  export { A as AccountStatus, B as BowlosProvider, b as BowlosProviderProps, c as UseAccountResult, u as useAccount, d as useBowlosClient, e as useBowlosQuery } from './react-B1uSOozS.js';
3
3
  import { V as PublicAddon, a as AvailabilityArgs, b as AvailabilityResult, e as BookingPreviewArgs, f as BookingQuote, n as EventTicketPreviewResult, m as EventTicketPreviewArgs, s as GameCardPreviewResult, r as GameCardPreviewArgs, x as MembershipPreviewResult, w as MembershipPreviewArgs, J as MembershipSubscriptionPreviewResult, N as PackagePreviewResult, K as PackagePreviewArgs, W as StartTimesArgs, d as BookingHold, S as PaymentIntentInfo, k as CreateBookingArgs, i as CheckoutStatusResult, I as MembershipSubscriptionIntent, H as MembershipSubscriptionArgs, o as EventTicketPurchaseArgs, t as GameCardPurchaseArgs, y as MembershipPurchaseArgs, O as PackagePurchaseArgs } from './data-BKlgn8Ln.js';
4
- import { a as FlashSaleArgs, F as FlashBookingOptionsArgs, b as FlashSalesArgs, B as BrandScoped, E as EventOrderDetailArgs, M as MembershipDetailArgs, R as ReservationDetailArgs } from './account-CO8xzUs_.js';
4
+ import { a as FlashSaleArgs, F as FlashBookingOptionsArgs, c as FlashSalesArgs, B as BrandScoped, E as EventOrderDetailArgs, M as MembershipDetailArgs, R as ReservationDetailArgs } from './account-Bm2XnaYS.js';
5
5
  import { h as CatalogResult, e as CatalogArgs, k as CenterHoursArgs, l as CenterScoped, d as BrandCatalogArgs, P as PackageDetailArgs, a as BowlosApiError } from './catalog-BxyPJdBL.js';
6
6
  import 'react/jsx-runtime';
7
7
  import 'react';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bowlos/reservations",
3
- "version": "0.22.0",
3
+ "version": "0.22.1",
4
4
  "description": "BowlOS Reservations SDK \u2014 headless client + React hooks for the Module 14 public API gateway. White-label booking, account, and flash-sale reads for third-party-hosted center sites.",
5
5
  "license": "MIT",
6
6
  "author": "BowlOS",
@@ -11,7 +11,7 @@
11
11
  "typecheck": "tsc --noEmit"
12
12
  },
13
13
  "dependencies": {
14
- "@bowlos/reservations": "^0.22.0",
14
+ "@bowlos/reservations": "^0.22.1",
15
15
  "@stripe/react-stripe-js": "6.3.0",
16
16
  "@stripe/stripe-js": "9.4.0",
17
17
  "next": "16.2.4",