@bowlos/reservations 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +14 -7
  2. package/dist/{chunk-NYTGLAQH.js → chunk-E5KVVXSJ.js} +15 -7
  3. package/dist/chunk-E5KVVXSJ.js.map +1 -0
  4. package/dist/{chunk-QGTGKNJW.js → chunk-YICHFUAY.js} +41 -11
  5. package/dist/chunk-YICHFUAY.js.map +1 -0
  6. package/dist/components.cjs +94 -60
  7. package/dist/components.cjs.map +1 -1
  8. package/dist/components.d.cts +41 -7
  9. package/dist/components.d.ts +41 -7
  10. package/dist/components.js +90 -21
  11. package/dist/components.js.map +1 -1
  12. package/dist/index.js +172 -4
  13. package/dist/index.js.map +1 -1
  14. package/dist/{react-B_8H7AyT.d.cts → react-7ruEsubp.d.cts} +5 -2
  15. package/dist/{react-bG9YV_xP.d.ts → react-Cb_NZCXa.d.ts} +5 -2
  16. package/dist/react.cjs +12 -3
  17. package/dist/react.cjs.map +1 -1
  18. package/dist/react.d.cts +2 -2
  19. package/dist/react.d.ts +2 -2
  20. package/dist/react.js +2 -3
  21. package/package.json +1 -1
  22. package/templates/center-site/app/book/page.tsx +55 -28
  23. package/templates/center-site/app/layout.tsx +5 -1
  24. package/templates/center-site/app/providers.tsx +26 -4
  25. package/templates/center-site/app/site-header.tsx +30 -0
  26. package/templates/center-site/env.example +10 -5
  27. package/templates/center-site/lib/bowlos.ts +13 -5
  28. package/templates/center-site/package.json +1 -1
  29. package/dist/chunk-2RMK6BWO.js +0 -41
  30. package/dist/chunk-2RMK6BWO.js.map +0 -1
  31. package/dist/chunk-4FL2QYSS.js +0 -174
  32. package/dist/chunk-4FL2QYSS.js.map +0 -1
  33. package/dist/chunk-NYTGLAQH.js.map +0 -1
  34. package/dist/chunk-QGTGKNJW.js.map +0 -1
  35. package/dist/cli.d.cts +0 -1
  36. package/dist/cli.d.ts +0 -1
  37. package/dist/cli.js +0 -176
  38. package/dist/cli.js.map +0 -1
package/dist/react.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { U as UseQueryOptions, a as UseQueryResult } from './react-B_8H7AyT.cjs';
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-B_8H7AyT.cjs';
1
+ import { U as UseQueryOptions, a as UseQueryResult } from './react-7ruEsubp.cjs';
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-7ruEsubp.cjs';
3
3
  import { a as AvailabilityArgs, b as AvailabilityResult, f as BookingPreviewArgs, g as BookingQuote, e as BookingHold, P as PaymentIntentInfo, h as BowlosApiError, n as CreateBookingArgs, m as CheckoutStatusResult } from './data-DrM0D6Pi.cjs';
4
4
  import { a as FlashSaleArgs, F as FlashBookingOptionsArgs, B as BrandScoped, M as MembershipDetailArgs, R as ReservationDetailArgs } from './account-COEgvwfx.cjs';
5
5
  import 'react/jsx-runtime';
package/dist/react.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { U as UseQueryOptions, a as UseQueryResult } from './react-bG9YV_xP.js';
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-bG9YV_xP.js';
1
+ import { U as UseQueryOptions, a as UseQueryResult } from './react-Cb_NZCXa.js';
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-Cb_NZCXa.js';
3
3
  import { a as AvailabilityArgs, b as AvailabilityResult, f as BookingPreviewArgs, g as BookingQuote, e as BookingHold, P as PaymentIntentInfo, h as BowlosApiError, n as CreateBookingArgs, m as CheckoutStatusResult } from './data-DrM0D6Pi.js';
4
4
  import { a as FlashSaleArgs, F as FlashBookingOptionsArgs, B as BrandScoped, M as MembershipDetailArgs, R as ReservationDetailArgs } from './account-CzyIERC5.js';
5
5
  import 'react/jsx-runtime';
package/dist/react.js CHANGED
@@ -1,5 +1,4 @@
1
- export { BowlosProvider, useAccount, useAvailability, useBookingFlow, useBookingPreview, useBowlosClient, useBowlosQuery, useFlashSale, useFlashSaleBookingOptions, useMyCredits, useMyLoyalty, useMyMembershipDetail, useMyMemberships, useMyPasses, useMyReservationDetail, useMyReservations } from './chunk-NYTGLAQH.js';
2
- import './chunk-2RMK6BWO.js';
3
- import './chunk-QGTGKNJW.js';
1
+ export { BowlosProvider, useAccount, useAvailability, useBookingFlow, useBookingPreview, useBowlosClient, useBowlosQuery, useFlashSale, useFlashSaleBookingOptions, useMyCredits, useMyLoyalty, useMyMembershipDetail, useMyMemberships, useMyPasses, useMyReservationDetail, useMyReservations } from './chunk-E5KVVXSJ.js';
2
+ import './chunk-YICHFUAY.js';
4
3
  //# sourceMappingURL=react.js.map
5
4
  //# sourceMappingURL=react.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bowlos/reservations",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "BowlOS Reservations SDK — 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",
@@ -1,17 +1,25 @@
1
1
  "use client";
2
- import { useMemo, useState, type FormEvent } from "react";
3
- import { useAvailability, useBookingPreview, useBookingFlow } from "@bowlos/reservations/react";
2
+ import { useEffect, useMemo, useRef, useState, type FormEvent } from "react";
3
+ import {
4
+ useAccount,
5
+ useAvailability,
6
+ useBookingPreview,
7
+ useBookingFlow,
8
+ } from "@bowlos/reservations/react";
4
9
  import { availableUnitCount, type CreateBookingArgs } from "@bowlos/reservations";
5
10
  import { CENTER_ID, DEMO_PRODUCT_ID, formatCents } from "../../lib/bowlos";
6
11
  import { CheckoutForm } from "./checkout-form";
7
12
 
8
13
  /**
9
- * The booking funnel as a single page, driven by `useBookingFlow`:
10
- * form → startHold → (held) → preparePayment → (awaitingPayment) → pay
11
- * → startPolling → (confirmed).
12
- * Availability + the price quote are live reads via the typed hooks.
14
+ * The booking funnel as a single page, driven by `useBookingFlow` — the headless
15
+ * (Path B) reference. Account-aware (hides Name/Email and books as the signed-in
16
+ * customer) and pay-to-confirm: the moment the hold lands we advance straight to
17
+ * payment, so the customer never sees a held-but-unpaid reservation.
13
18
  */
14
19
  export default function BookPage() {
20
+ const account = useAccount();
21
+ const signedIn = account.status === "linked" && account.customer !== null;
22
+
15
23
  const [dateISO, setDateISO] = useState("2026-07-04");
16
24
  const [startMinuteOfDay, setStartMinuteOfDay] = useState(18 * 60); // 6:00 PM
17
25
  const endMinuteOfDay = startMinuteOfDay + 60;
@@ -36,6 +44,13 @@ export default function BookPage() {
36
44
  });
37
45
  const flow = useBookingFlow();
38
46
 
47
+ // Complete-sale-only: as soon as the hold lands, go straight to payment.
48
+ const prepareRef = useRef(flow.preparePayment);
49
+ prepareRef.current = flow.preparePayment;
50
+ useEffect(() => {
51
+ if (flow.status === "held") void prepareRef.current();
52
+ }, [flow.status]);
53
+
39
54
  const freeUnits = availability.data ? availableUnitCount(availability.data) : null;
40
55
  const quoteCents = preview.data?.totalCentsPerPlan?.[0]?.totalCents ?? null;
41
56
 
@@ -48,12 +63,18 @@ export default function BookPage() {
48
63
  endMinuteOfDay,
49
64
  mode: "per_unit_per_hour",
50
65
  units,
51
- customer: { fullName, email, marketingOptIn: false },
66
+ customer: signedIn
67
+ ? {
68
+ fullName: account.customer?.fullName ?? "",
69
+ email: account.customer?.email ?? "",
70
+ marketingOptIn: false,
71
+ }
72
+ : { fullName, email, marketingOptIn: false },
52
73
  }),
53
- [dateISO, startMinuteOfDay, endMinuteOfDay, units, fullName, email],
74
+ [dateISO, startMinuteOfDay, endMinuteOfDay, units, signedIn, account.customer, fullName, email],
54
75
  );
55
76
 
56
- async function onHold(e: FormEvent) {
77
+ async function onBook(e: FormEvent) {
57
78
  e.preventDefault();
58
79
  await flow.startHold(bookingArgs);
59
80
  }
@@ -83,17 +104,11 @@ export default function BookPage() {
83
104
  );
84
105
  }
85
106
 
86
- // ── held: lane reserved, continue to payment ─────────────────────────────────
107
+ // ── held / preparing: transient — auto-advancing to payment ──────────────────
87
108
  if (flow.status === "held" || flow.status === "preparingPayment") {
88
- const preparing = flow.status === "preparingPayment";
89
109
  return (
90
110
  <main>
91
- <h1>Lane held</h1>
92
- <p>Your lane is held for a few minutes. Continue to payment to confirm.</p>
93
- <button onClick={() => flow.preparePayment()} disabled={preparing}>
94
- {preparing ? "Preparing…" : "Continue to payment →"}
95
- </button>{" "}
96
- <button onClick={flow.abandon}>Release hold</button>
111
+ <h1>Securing your spot…</h1>
97
112
  {flow.error && <p role="alert">Error: {flow.error.code}</p>}
98
113
  </main>
99
114
  );
@@ -104,7 +119,7 @@ export default function BookPage() {
104
119
  return (
105
120
  <main>
106
121
  <h1>Book a lane</h1>
107
- <form onSubmit={onHold} style={{ display: "grid", gap: "0.75rem", maxWidth: 360 }}>
122
+ <form onSubmit={onBook} style={{ display: "grid", gap: "0.75rem", maxWidth: 360 }}>
108
123
  <label>
109
124
  Date{" "}
110
125
  <input type="date" value={dateISO} onChange={(e) => setDateISO(e.target.value)} />
@@ -126,14 +141,26 @@ export default function BookPage() {
126
141
  onChange={(e) => setUnits(Math.max(1, Number(e.target.value) || 1))}
127
142
  />
128
143
  </label>
129
- <label>
130
- Name{" "}
131
- <input value={fullName} onChange={(e) => setFullName(e.target.value)} required />
132
- </label>
133
- <label>
134
- Email{" "}
135
- <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required />
136
- </label>
144
+
145
+ {signedIn ? (
146
+ <p>
147
+ Booking as <strong>{account.customer?.fullName}</strong>.
148
+ </p>
149
+ ) : (
150
+ <>
151
+ <label>
152
+ Name{" "}
153
+ <input value={fullName} onChange={(e) => setFullName(e.target.value)} required />
154
+ </label>
155
+ <label>
156
+ Email{" "}
157
+ <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required />
158
+ </label>
159
+ <p style={{ fontSize: "0.85rem" }}>
160
+ <a href="/account">Sign in to book faster</a>
161
+ </p>
162
+ </>
163
+ )}
137
164
 
138
165
  <p aria-live="polite">
139
166
  {availability.loading
@@ -154,8 +181,8 @@ export default function BookPage() {
154
181
  : ""}
155
182
  </p>
156
183
 
157
- <button type="submit" disabled={holding || !fullName || !email}>
158
- {holding ? "Holding…" : "Hold my lane"}
184
+ <button type="submit" disabled={holding || (!signedIn && (!fullName || !email))}>
185
+ {holding ? "Booking…" : "Book my lane"}
159
186
  </button>
160
187
  </form>
161
188
  {flow.error && (
@@ -1,5 +1,6 @@
1
1
  import type { ReactNode } from "react";
2
2
  import { Providers } from "./providers";
3
+ import { SiteHeader } from "./site-header";
3
4
 
4
5
  export const metadata = {
5
6
  title: "Lucky Strike Lanes",
@@ -10,7 +11,10 @@ export default function RootLayout({ children }: { children: ReactNode }) {
10
11
  return (
11
12
  <html lang="en">
12
13
  <body style={{ fontFamily: "system-ui, sans-serif", maxWidth: 640, margin: "2rem auto", padding: "0 1rem" }}>
13
- <Providers>{children}</Providers>
14
+ <Providers>
15
+ <SiteHeader />
16
+ {children}
17
+ </Providers>
14
18
  </body>
15
19
  </html>
16
20
  );
@@ -6,16 +6,38 @@ import { makeBowlosClient } from "../lib/bowlos";
6
6
 
7
7
  /**
8
8
  * Wraps the app in the SDK provider + a `<BowlosTheme>`. The client is created
9
- * once (lazy `useState` initializer) and shared via context to every hook below;
10
- * the theme sets the `--bowlos-*` CSS vars so every drop-in component
11
- * (`<BookingFlow>`, `<AccountDashboard>`, `<FlashSale>`) picks up this center's
12
- * accent + radius. Restyle the whole site by editing the `theme` here.
9
+ * once (lazy `useState` initializer). If the BowlOS env vars aren't set yet,
10
+ * `makeBowlosClient()` returns null and we render a branded "connecting" notice
11
+ * instead of throwing — so the build/page never breaks (e.g. a fresh Vercel
12
+ * deploy before you've added the env vars). The theme sets the `--bowlos-*` CSS
13
+ * vars so every drop-in component picks up this center's accent + radius.
13
14
  */
14
15
  export function Providers({ children }: { children: ReactNode }) {
15
16
  const [client] = useState(() => makeBowlosClient());
17
+
18
+ if (!client) {
19
+ return <BookingUnavailable />;
20
+ }
21
+
16
22
  return (
17
23
  <BowlosProvider client={client}>
18
24
  <BowlosTheme theme={{ colorPrimary: "#e4002b", radius: "8px" }}>{children}</BowlosTheme>
19
25
  </BowlosProvider>
20
26
  );
21
27
  }
28
+
29
+ /** Shown when the BowlOS env vars aren't configured (no key/base URL). */
30
+ function BookingUnavailable() {
31
+ return (
32
+ <main style={{ maxWidth: 520, margin: "4rem auto", padding: "0 1.25rem", textAlign: "center" }}>
33
+ <h1 style={{ fontSize: "1.5rem", marginBottom: "0.5rem" }}>Connecting the booking system…</h1>
34
+ <p style={{ color: "#6b7280" }}>
35
+ Online booking is being set up. Please check back soon.
36
+ </p>
37
+ <p style={{ color: "#9ca3af", fontSize: "0.8rem", marginTop: "1.5rem" }}>
38
+ (Set the <code>NEXT_PUBLIC_BOWLOS_*</code> env vars in your host and redeploy to enable
39
+ booking.)
40
+ </p>
41
+ </main>
42
+ );
43
+ }
@@ -0,0 +1,30 @@
1
+ "use client";
2
+ import Link from "next/link";
3
+ import { AccountMenu } from "@bowlos/reservations/components";
4
+
5
+ /**
6
+ * Site header with a persistent login indicator. `<AccountMenu>` reads the
7
+ * shared session (from the root `<BowlosProvider>`), so it shows the same thing
8
+ * on every page and updates the moment a customer signs in or out anywhere.
9
+ */
10
+ export function SiteHeader() {
11
+ return (
12
+ <header
13
+ style={{
14
+ display: "flex",
15
+ justifyContent: "space-between",
16
+ alignItems: "center",
17
+ padding: "0.5rem 0",
18
+ borderBottom: "1px solid #e5e7eb",
19
+ marginBottom: "1.5rem",
20
+ }}
21
+ >
22
+ <nav style={{ display: "flex", gap: "1rem", fontSize: "0.9rem" }}>
23
+ <Link href="/">Home</Link>
24
+ <Link href="/book">Book</Link>
25
+ <Link href="/account">My account</Link>
26
+ </nav>
27
+ <AccountMenu accountHref="/account" />
28
+ </header>
29
+ );
30
+ }
@@ -4,13 +4,18 @@
4
4
  # publishable key). Never put a secret key in a NEXT_PUBLIC_* var.
5
5
 
6
6
  # Gateway base URL (include the version prefix) + the brand publishable key.
7
+ # The key is a publishable `bpk_<mode>_…` string from the BowlOS admin's
8
+ # "Public API keys" page, shown once at mint (test keys start `bpk_test_`,
9
+ # live keys `bpk_live_`). Browser-safe, like a Stripe publishable key.
7
10
  NEXT_PUBLIC_BOWLOS_BASE_URL=https://your-deployment.convex.site/api/public/v1
8
- NEXT_PUBLIC_BOWLOS_API_KEY=bpk_live_xxxxxxxxxxxx
11
+ NEXT_PUBLIC_BOWLOS_API_KEY=bpk_test_xxxxxxxxxxxx
9
12
 
10
- # The brand + center this site books against, and a bookable product.
11
- NEXT_PUBLIC_BOWLOS_BRAND_ID=brand_xxxxxxxx
12
- NEXT_PUBLIC_BOWLOS_CENTER_ID=center_xxxxxxxx
13
- NEXT_PUBLIC_DEMO_PRODUCT_ID=product_xxxxxxxx
13
+ # The brand + center this site books against, and a bookable product. These are
14
+ # the raw IDs from the BowlOS admin (NO "brand_"/"center_" prefix — they look
15
+ # like k17b60wd8vz1mhgqxz1a36bjvh869mfs).
16
+ NEXT_PUBLIC_BOWLOS_BRAND_ID=your-brand-id
17
+ NEXT_PUBLIC_BOWLOS_CENTER_ID=your-center-id
18
+ NEXT_PUBLIC_DEMO_PRODUCT_ID=your-product-id
14
19
 
15
20
  # Platform Stripe *publishable* key — used WITH the operator's connected
16
21
  # account id (returned by the SDK) so the charge lands on the operator's
@@ -5,14 +5,22 @@ import { createBowlosClient, localStorageTokenStore } from "@bowlos/reservations
5
5
  * (gated by the gateway's origin allow-list), so reading it from a public env
6
6
  * var is intentional. The session is persisted in localStorage.
7
7
  */
8
+ /** True once the BowlOS env vars are set (so the booking UI can mount). */
9
+ export function isBowlosConfigured(): boolean {
10
+ return Boolean(process.env.NEXT_PUBLIC_BOWLOS_API_KEY && process.env.NEXT_PUBLIC_BOWLOS_BASE_URL);
11
+ }
12
+
13
+ /**
14
+ * A configured client, or `null` when the env vars aren't set yet — so the app
15
+ * renders a "connecting the booking system" notice instead of throwing and
16
+ * breaking the build/render. (NEXT_PUBLIC_* vars are inlined at build time, so a
17
+ * fresh deploy without them set falls into this null path until you add them in
18
+ * the host and redeploy.)
19
+ */
8
20
  export function makeBowlosClient() {
9
21
  const apiKey = process.env.NEXT_PUBLIC_BOWLOS_API_KEY;
10
22
  const baseUrl = process.env.NEXT_PUBLIC_BOWLOS_BASE_URL;
11
- if (!apiKey || !baseUrl) {
12
- throw new Error(
13
- "Missing NEXT_PUBLIC_BOWLOS_API_KEY / NEXT_PUBLIC_BOWLOS_BASE_URL — copy env.example to .env.local.",
14
- );
15
- }
23
+ if (!apiKey || !baseUrl) return null;
16
24
  return createBowlosClient({ apiKey, baseUrl, tokenStore: localStorageTokenStore() });
17
25
  }
18
26
 
@@ -11,7 +11,7 @@
11
11
  "typecheck": "tsc --noEmit"
12
12
  },
13
13
  "dependencies": {
14
- "@bowlos/reservations": "^0.4.0",
14
+ "@bowlos/reservations": "^0.5.0",
15
15
  "@stripe/react-stripe-js": "6.3.0",
16
16
  "@stripe/stripe-js": "9.4.0",
17
17
  "next": "16.2.4",
@@ -1,41 +0,0 @@
1
- // src/data.ts
2
- function checkAvailability(client, args) {
3
- return client.call("checkAvailability", args);
4
- }
5
- function bookingPreview(client, args) {
6
- return client.call("bookingPreview", args);
7
- }
8
- function availableUnitCount(availability) {
9
- return Math.max(0, availability.totalUnits - availability.busyUnitIds.length);
10
- }
11
- function generateIdempotencyKey() {
12
- if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
13
- return crypto.randomUUID();
14
- }
15
- return `idem_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
16
- }
17
- function createBooking(client, args) {
18
- const idempotencyKey = args.idempotencyKey ?? generateIdempotencyKey();
19
- return client.call(
20
- "createAnonymousBooking",
21
- { ...args, idempotencyKey },
22
- { auth: true }
23
- );
24
- }
25
- function createCheckoutPaymentIntent(client, refToken) {
26
- return client.call(
27
- "createCheckoutPaymentIntent",
28
- { refToken },
29
- { auth: true }
30
- );
31
- }
32
- function getCheckoutStatus(client, refToken) {
33
- return client.call("getCheckoutStatus", { refToken }, { auth: true });
34
- }
35
- function abandonCheckout(client, refToken) {
36
- return client.call("abandonCheckout", { refToken }, { auth: true });
37
- }
38
-
39
- export { abandonCheckout, availableUnitCount, bookingPreview, checkAvailability, createBooking, createCheckoutPaymentIntent, generateIdempotencyKey, getCheckoutStatus };
40
- //# sourceMappingURL=chunk-2RMK6BWO.js.map
41
- //# sourceMappingURL=chunk-2RMK6BWO.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/data.ts"],"names":[],"mappings":";AAwDO,SAAS,iBAAA,CACd,QACA,IAAA,EAC6B;AAC7B,EAAA,OAAO,MAAA,CAAO,IAAA,CAAyB,mBAAA,EAAqB,IAAI,CAAA;AAClE;AAIO,SAAS,cAAA,CACd,QACA,IAAA,EACuB;AACvB,EAAA,OAAO,MAAA,CAAO,IAAA,CAAmB,gBAAA,EAAkB,IAAI,CAAA;AACzD;AAGO,SAAS,mBAAmB,YAAA,EAA0C;AAC3E,EAAA,OAAO,KAAK,GAAA,CAAI,CAAA,EAAG,aAAa,UAAA,GAAa,YAAA,CAAa,YAAY,MAAM,CAAA;AAC9E;AA+EO,SAAS,sBAAA,GAAiC;AAC/C,EAAA,IAAI,OAAO,MAAA,KAAW,WAAA,IAAe,OAAO,MAAA,CAAO,eAAe,UAAA,EAAY;AAC5E,IAAA,OAAO,OAAO,UAAA,EAAW;AAAA,EAC3B;AACA,EAAA,OAAO,CAAA,KAAA,EAAQ,IAAA,CAAK,GAAA,EAAK,IAAI,IAAA,CAAK,MAAA,EAAO,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,KAAA,CAAM,CAAA,EAAG,EAAE,CAAC,CAAA,CAAA;AACtE;AAIO,SAAS,aAAA,CACd,QACA,IAAA,EACsB;AACtB,EAAA,MAAM,cAAA,GAAiB,IAAA,CAAK,cAAA,IAAkB,sBAAA,EAAuB;AACrE,EAAA,OAAO,MAAA,CAAO,IAAA;AAAA,IACZ,wBAAA;AAAA,IACA,EAAE,GAAG,IAAA,EAAM,cAAA,EAAe;AAAA,IAC1B,EAAE,MAAM,IAAA;AAAK,GACf;AACF;AAGO,SAAS,2BAAA,CACd,QACA,QAAA,EAC4B;AAC5B,EAAA,OAAO,MAAA,CAAO,IAAA;AAAA,IACZ,6BAAA;AAAA,IACA,EAAE,QAAA,EAAS;AAAA,IACX,EAAE,MAAM,IAAA;AAAK,GACf;AACF;AAGO,SAAS,iBAAA,CACd,QACA,QAAA,EAC+B;AAC/B,EAAA,OAAO,MAAA,CAAO,KAA2B,mBAAA,EAAqB,EAAE,UAAS,EAAG,EAAE,IAAA,EAAM,IAAA,EAAM,CAAA;AAC5F;AAGO,SAAS,eAAA,CACd,QACA,QAAA,EAC0B;AAC1B,EAAA,OAAO,MAAA,CAAO,KAAsB,iBAAA,EAAmB,EAAE,UAAS,EAAG,EAAE,IAAA,EAAM,IAAA,EAAM,CAAA;AACrF","file":"chunk-2RMK6BWO.js","sourcesContent":["/**\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/** Inputs for `bookingPreview` (the authoritative price quote). */\nexport type BookingPreviewArgs = {\n centerId: string;\n productId: string;\n dateISO: string;\n startMinuteOfDay: number;\n endMinuteOfDay: number;\n mode: PricingMode;\n units?: number;\n persons?: number;\n games?: number;\n addons?: BookingAddonSelection[];\n shareToken?: string;\n subtypeId?: string;\n};\n\n/** The price quote. Headline fields are typed; the engine's full breakdown\n * (line items, discounts, tax, credit) is passed through. */\nexport interface BookingQuote {\n reservationFee: Record<string, unknown> | null;\n totalCentsPerPlan: Array<{ pricePlanId: string; totalCents: number }>;\n [key: string]: unknown;\n}\n\n/** Free units for a product/date/time window (anonymous). */\nexport function checkAvailability(\n client: BowlosClient,\n args: AvailabilityArgs,\n): Promise<AvailabilityResult> {\n return client.call<AvailabilityResult>(\"checkAvailability\", args);\n}\n\n/** Authoritative price quote for the chosen inputs (anonymous; a signed-in\n * session unlocks member rates + account credit). */\nexport function bookingPreview(\n client: BowlosClient,\n args: BookingPreviewArgs,\n): Promise<BookingQuote> {\n return client.call<BookingQuote>(\"bookingPreview\", args);\n}\n\n/** Convenience: free units = total minus the busy set (never negative). */\nexport function availableUnitCount(availability: AvailabilityResult): number {\n return Math.max(0, availability.totalUnits - availability.busyUnitIds.length);\n}\n\n// ── booking flow (hold → pay → confirm) ──────────────────────────────────────\n\n/** Customer identity for a booking (collected in the booking form; the server\n * links/creates the customer per the booking-flow-only signup rule). */\nexport type BookingCustomer = {\n fullName: string;\n email: string;\n mobile?: string;\n marketingOptIn: boolean;\n};\n\n/** Inputs for `createAnonymousBooking` — places the inventory hold. */\nexport type CreateBookingArgs = {\n centerId: string;\n productId: string;\n dateISO: string;\n startMinuteOfDay: number;\n endMinuteOfDay: number;\n mode: PricingMode;\n units?: number;\n persons?: number;\n games?: number;\n addons?: BookingAddonSelection[];\n customer: BookingCustomer;\n /** Apply account credit (requires a signed-in customer). */\n applyCredit?: boolean;\n /** Idempotency key for the create. The SDK generates one if omitted. */\n idempotencyKey?: string;\n shareToken?: string;\n subtypeId?: string;\n};\n\n/** Result of placing a booking. The hold→pay path returns `checkoutRefToken`\n * with `requiresPayment: true`; a credit-covered / $0 booking returns the\n * materialized `reservationId` + `reservationDisplayId` with\n * `requiresPayment: false`. Headline fields typed; the rest passes through. */\nexport interface BookingHold {\n checkoutRefToken?: string;\n reservationId?: string | null;\n reservationDisplayId?: string | null;\n requiresPayment: boolean;\n finalCents: number;\n appliedCreditCents: number;\n paidCents?: number;\n holdExpiresAt?: number;\n replayed?: boolean;\n [key: string]: unknown;\n}\n\nexport type CheckoutStatus =\n | \"not_found\"\n | \"pending_payment\"\n | \"paid_materialized\"\n | \"expired\"\n | \"payment_failed_retryable\"\n | \"abandoned\";\n\nexport interface CheckoutStatusResult {\n status: CheckoutStatus;\n reservationDisplayId: string | null;\n reservationId: string | null;\n}\n\n/** Stripe (Connect) PaymentIntent data for the UI layer to render Elements.\n * The SDK does NOT load Stripe.js — initialize it with `connectedAccountId`\n * (the operator's connected account) + `clientSecret`. */\nexport interface PaymentIntentInfo {\n paymentIntentId: string;\n clientSecret: string;\n amountCents: number;\n customerId: string;\n ephemeralKey: string;\n customerSessionClientSecret: string;\n connectedAccountId: string;\n}\n\n/** Browser/Node-safe idempotency key for booking creates. */\nexport function generateIdempotencyKey(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n return `idem_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;\n}\n\n/** Place the inventory hold + open a checkout. Sends the session when present\n * (member rates + account credit); falls back to anonymous. */\nexport function createBooking(\n client: BowlosClient,\n args: CreateBookingArgs,\n): Promise<BookingHold> {\n const idempotencyKey = args.idempotencyKey ?? generateIdempotencyKey();\n return client.call<BookingHold>(\n \"createAnonymousBooking\",\n { ...args, idempotencyKey },\n { auth: true },\n );\n}\n\n/** Mint the Stripe Connect PaymentIntent for a held checkout (by refToken). */\nexport function createCheckoutPaymentIntent(\n client: BowlosClient,\n refToken: string,\n): Promise<PaymentIntentInfo> {\n return client.call<PaymentIntentInfo>(\n \"createCheckoutPaymentIntent\",\n { refToken },\n { auth: true },\n );\n}\n\n/** Poll the hold→pay→materialize state for a checkout (by refToken). */\nexport function getCheckoutStatus(\n client: BowlosClient,\n refToken: string,\n): Promise<CheckoutStatusResult> {\n return client.call<CheckoutStatusResult>(\"getCheckoutStatus\", { refToken }, { auth: true });\n}\n\n/** Release the hold + cancel the checkout (the \"Back\" button). */\nexport function abandonCheckout(\n client: BowlosClient,\n refToken: string,\n): Promise<{ ok: boolean }> {\n return client.call<{ ok: boolean }>(\"abandonCheckout\", { refToken }, { auth: true });\n}\n"]}
@@ -1,174 +0,0 @@
1
- import { createBowlosClient, BOWLOS_ERROR_CODES, BowlosApiError } from './chunk-QGTGKNJW.js';
2
-
3
- // src/doctor.ts
4
- var GATEWAY_SUFFIX = "/api/public/v1";
5
- async function runDoctor(options) {
6
- const checks = [];
7
- const report = { ok: true, checks, baseUrl: options.baseUrl };
8
- const configIssues = [];
9
- if (!options.apiKey) configIssues.push("`apiKey` is empty");
10
- let parsedUrl = null;
11
- try {
12
- parsedUrl = new URL(options.baseUrl);
13
- } catch {
14
- configIssues.push("`baseUrl` is not a valid URL");
15
- }
16
- if (configIssues.length > 0) {
17
- checks.push({
18
- id: "config",
19
- title: "Client configuration",
20
- status: "fail",
21
- detail: `${configIssues.join("; ")}.`,
22
- fix: "Pass a brand API key and the gateway base URL, e.g. https://<deployment>.convex.site/api/public/v1"
23
- });
24
- report.ok = false;
25
- return report;
26
- }
27
- const urlMisaimed = parsedUrl !== null && !parsedUrl.pathname.replace(/\/+$/, "").endsWith(GATEWAY_SUFFIX);
28
- checks.push({
29
- id: "config",
30
- title: "Client configuration",
31
- status: urlMisaimed ? "warn" : "pass",
32
- detail: urlMisaimed ? `baseUrl "${options.baseUrl}" doesn't end with ${GATEWAY_SUFFIX} \u2014 it should point at the gateway, not the site root.` : "API key present; base URL well-formed.",
33
- fix: urlMisaimed ? `Use the gateway URL, e.g. ${parsedUrl?.origin}${GATEWAY_SUFFIX}` : void 0
34
- });
35
- const client = createBowlosClient({
36
- apiKey: options.apiKey,
37
- baseUrl: options.baseUrl,
38
- fetch: options.fetch
39
- });
40
- let ping = null;
41
- try {
42
- ping = await client.ping();
43
- report.brandId = ping.brandId;
44
- report.mode = ping.mode;
45
- checks.push({
46
- id: "gateway",
47
- title: "Gateway reachable",
48
- status: "pass",
49
- detail: `Reached ${options.baseUrl} (service "${ping.service}", ${ping.version}).`
50
- });
51
- checks.push({
52
- id: "api-key",
53
- title: "API key accepted",
54
- status: "pass",
55
- detail: `Key valid for brand ${ping.brandId} \u2014 mode: ${ping.mode}.`
56
- });
57
- } catch (e) {
58
- const err = e instanceof BowlosApiError ? e : null;
59
- const code = err?.code ?? BOWLOS_ERROR_CODES.UNKNOWN;
60
- const reached = err !== null && err.status !== 0 && code !== BOWLOS_ERROR_CODES.NETWORK_ERROR && code !== BOWLOS_ERROR_CODES.NOT_FOUND;
61
- checks.push({
62
- id: "gateway",
63
- title: "Gateway reachable",
64
- status: reached ? "pass" : "fail",
65
- detail: reached ? `Reached ${options.baseUrl}.` : code === BOWLOS_ERROR_CODES.NETWORK_ERROR ? `Could not reach ${options.baseUrl} (network error).` : `No public-API gateway responded at ${options.baseUrl}.`,
66
- fix: reached ? void 0 : "Check the base URL, that the Convex deployment is live, and that the public-API routes are deployed."
67
- });
68
- if (code === BOWLOS_ERROR_CODES.RATE_LIMITED) {
69
- checks.push({
70
- id: "api-key",
71
- title: "API key accepted",
72
- status: "pass",
73
- detail: "Key accepted (this probe was rate-limited)."
74
- });
75
- checks.push({
76
- id: "rate-limit",
77
- title: "Rate-limit headroom",
78
- status: "warn",
79
- detail: `Currently rate-limited${err?.retryAfterSeconds ? ` \u2014 retry after ${err.retryAfterSeconds}s` : ""}.`,
80
- fix: "Back off and retry; raise the key's per-minute limit if your real traffic is higher."
81
- });
82
- } else if (code === BOWLOS_ERROR_CODES.ORIGIN_NOT_ALLOWED) {
83
- checks.push({
84
- id: "api-key",
85
- title: "API key accepted",
86
- status: "pass",
87
- detail: "Key accepted; the request was blocked on origin."
88
- });
89
- checks.push({
90
- id: "origin",
91
- title: "Origin allow-listed",
92
- status: "fail",
93
- detail: "The request origin is not on the key's allow-list.",
94
- fix: `Add your site origin${options.origin ? ` (${options.origin})` : ""} to the API key's allowed origins.`
95
- });
96
- } else if (reached) {
97
- checks.push({
98
- id: "api-key",
99
- title: "API key accepted",
100
- status: "fail",
101
- detail: code === BOWLOS_ERROR_CODES.API_KEY_INVALID || code === BOWLOS_ERROR_CODES.API_KEY_MISSING ? "The gateway rejected the API key." : `The gateway returned ${code}.`,
102
- fix: "Mint or rotate a brand API key in the operator admin (Super-Admin \u2192 API keys) and use that value."
103
- });
104
- } else {
105
- checks.push({
106
- id: "api-key",
107
- title: "API key accepted",
108
- status: "skip",
109
- detail: "Skipped \u2014 the gateway wasn't reachable."
110
- });
111
- }
112
- }
113
- if (!checks.some((c) => c.id === "origin")) {
114
- const browserOrigin = typeof window !== "undefined" && typeof window.location?.origin === "string" ? window.location.origin : null;
115
- if (ping !== null && browserOrigin !== null) {
116
- checks.push({
117
- id: "origin",
118
- title: "Origin allow-listed",
119
- status: "pass",
120
- detail: `This origin (${browserOrigin}) is allow-listed for the key.`
121
- });
122
- } else {
123
- checks.push({
124
- id: "origin",
125
- title: "Origin allow-listed",
126
- status: "skip",
127
- detail: "Origin allow-listing is enforced only for browser requests, so it can't be verified from a CLI.",
128
- 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.`
129
- });
130
- }
131
- }
132
- if (ping !== null && options.skipDataRead !== true) {
133
- try {
134
- const data = await client.call("listPublicCenters", { brandId: ping.brandId });
135
- const innerError = typeof data === "object" && data !== null && data.ok === false;
136
- checks.push({
137
- id: "data-read",
138
- title: "Data passthrough",
139
- status: innerError ? "warn" : "pass",
140
- detail: innerError ? "Reached the data plane, but listPublicCenters returned an error envelope." : "Anonymous read (listPublicCenters) succeeded \u2014 gateway \u2192 query passthrough works.",
141
- fix: innerError ? "Confirm the brand has at least one published center." : void 0
142
- });
143
- } catch (e) {
144
- const err = e instanceof BowlosApiError ? e : null;
145
- checks.push({
146
- id: "data-read",
147
- title: "Data passthrough",
148
- status: "warn",
149
- detail: `An anonymous read failed${err ? ` (${err.code})` : ""}.`,
150
- fix: "Key + gateway are fine; this read may need a published center or differ by brand. Safe to ignore if your booking reads work."
151
- });
152
- }
153
- } else if (ping === null) {
154
- checks.push({
155
- id: "data-read",
156
- title: "Data passthrough",
157
- status: "skip",
158
- detail: "Skipped \u2014 needs a reachable gateway."
159
- });
160
- }
161
- checks.push({
162
- id: "payments",
163
- title: "Payments connected",
164
- status: "skip",
165
- detail: "Stripe Connect status isn't exposed over the public API yet, so the doctor can't verify it here.",
166
- fix: "Confirm the operator's Stripe account is connected + charges-enabled in the admin (Payments \u2192 Connect)."
167
- });
168
- report.ok = !checks.some((c) => c.status === "fail");
169
- return report;
170
- }
171
-
172
- export { runDoctor };
173
- //# sourceMappingURL=chunk-4FL2QYSS.js.map
174
- //# sourceMappingURL=chunk-4FL2QYSS.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/doctor.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;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,SAAS,IAAA,EAAM;AACxB,IAAA,MAAA,CAAO,IAAA,CAAK;AAAA,MACV,EAAA,EAAI,WAAA;AAAA,MACJ,KAAA,EAAO,kBAAA;AAAA,MACP,MAAA,EAAQ,MAAA;AAAA,MACR,MAAA,EAAQ;AAAA,KACT,CAAA;AAAA,EACH;AAIA,EAAA,MAAA,CAAO,IAAA,CAAK;AAAA,IACV,EAAA,EAAI,UAAA;AAAA,IACJ,KAAA,EAAO,oBAAA;AAAA,IACP,MAAA,EAAQ,MAAA;AAAA,IACR,MAAA,EAAQ,kGAAA;AAAA,IACR,GAAA,EAAK;AAAA,GACN,CAAA;AAED,EAAA,MAAA,CAAO,EAAA,GAAK,CAAC,MAAA,CAAO,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,WAAW,MAAM,CAAA;AACnD,EAAA,OAAO,MAAA;AACT","file":"chunk-4FL2QYSS.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"]}