@bowlos/reservations 0.36.0 → 0.43.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +306 -0
- package/HEADLESS.md +595 -10
- package/README.md +303 -2
- package/dist/account-B4sZBmPI.d.cts +1837 -0
- package/dist/account-B4sZBmPI.d.ts +1837 -0
- package/dist/booking-change-Dd4PVgd3.d.cts +487 -0
- package/dist/booking-change-DzYs9133.d.ts +487 -0
- package/dist/chunk-4JMGS4YB.js +808 -0
- package/dist/chunk-4JMGS4YB.js.map +1 -0
- package/dist/chunk-I37IJNYU.js +139 -0
- package/dist/chunk-I37IJNYU.js.map +1 -0
- package/dist/{chunk-Y3YSDO3H.js → chunk-T2E6AEC7.js} +150 -6
- package/dist/chunk-T2E6AEC7.js.map +1 -0
- package/dist/{chunk-3JSVEOKG.js → chunk-V4JRDYW4.js} +61 -6
- package/dist/chunk-V4JRDYW4.js.map +1 -0
- package/dist/{chunk-TEHRROVY.js → chunk-YQRTBGXU.js} +47 -192
- package/dist/chunk-YQRTBGXU.js.map +1 -0
- package/dist/cli.cjs +34 -3
- package/dist/cli.cjs.map +1 -1
- package/dist/components.cjs +2059 -153
- package/dist/components.cjs.map +1 -1
- package/dist/components.d.cts +214 -7
- package/dist/components.d.ts +214 -7
- package/dist/components.js +1148 -7
- package/dist/components.js.map +1 -1
- package/dist/index.cjs +303 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +56 -5
- package/dist/index.d.ts +56 -5
- package/dist/index.js +58 -3
- package/dist/index.js.map +1 -1
- package/dist/payments.cjs +225 -0
- package/dist/payments.cjs.map +1 -1
- package/dist/payments.d.cts +24 -2
- package/dist/payments.d.ts +24 -2
- package/dist/payments.js +4 -1
- package/dist/payments.js.map +1 -1
- package/dist/{react-CWAG4cW0.d.cts → react-C6NWC80d.d.cts} +2 -2
- package/dist/{react-0MyyTtE4.d.ts → react-DVdtpw5n.d.ts} +2 -2
- package/dist/react.cjs +870 -27
- package/dist/react.cjs.map +1 -1
- package/dist/react.d.cts +155 -12
- package/dist/react.d.ts +155 -12
- package/dist/react.js +72 -4
- package/dist/react.js.map +1 -1
- package/package.json +8 -2
- package/templates/center-site/README.md +5 -0
- package/templates/center-site/app/account/game-cards/page.tsx +17 -0
- package/templates/center-site/app/account/layout.tsx +16 -0
- package/templates/center-site/app/account/memberships/[id]/page.tsx +23 -0
- package/templates/center-site/app/account/memberships/page.tsx +33 -0
- package/templates/center-site/app/account/orders/page.tsx +17 -0
- package/templates/center-site/app/account/page.tsx +14 -0
- package/templates/center-site/app/account/payment-methods/page.tsx +23 -0
- package/templates/center-site/app/account/privacy/page.tsx +17 -0
- package/templates/center-site/app/account/profile/page.tsx +45 -0
- package/templates/center-site/app/account/reservations/[displayId]/change/page.tsx +46 -0
- package/templates/center-site/app/account/reservations/[displayId]/page.tsx +41 -0
- package/templates/center-site/app/account/reservations/page.tsx +35 -0
- package/templates/center-site/app/account/security/page.tsx +17 -0
- package/templates/center-site/app/events/[slug]/page.tsx +130 -0
- package/templates/center-site/app/events/page.tsx +57 -0
- package/templates/center-site/app/pay/[token]/page.tsx +53 -0
- package/templates/center-site/app/site-header.tsx +1 -0
- package/templates/center-site/lib/reservation.ts +14 -0
- package/templates/center-site/package.json +1 -1
- package/templates/center-site/tsconfig.json +7 -9
- package/dist/account-DfM2COaz.d.ts +0 -210
- package/dist/account-oCvYWmO9.d.cts +0 -210
- package/dist/catalog-DbhdwmnX.d.cts +0 -224
- package/dist/catalog-XkjgPI5C.d.ts +0 -224
- package/dist/chunk-3JSVEOKG.js.map +0 -1
- package/dist/chunk-TEHRROVY.js.map +0 -1
- package/dist/chunk-Y3YSDO3H.js.map +0 -1
- package/dist/data-BJkB-tvM.d.cts +0 -778
- package/dist/data-BJkB-tvM.d.ts +0 -778
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/react.tsx","../src/idempotent-mutation.ts","../src/hooks.tsx"],"names":["useR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OAAO,IAAA,KAA6B;AAClC,MAAA,MAAM,MAAA,GAAS,MAAM,QAAA,CAAS,GAAA,CAAI,IAAI,CAAA;AACtC,MAAA,MAAM,OAAO,OAAA,EAAQ;AACrB,MAAA,OAAO,MAAA;AAAA,IACT,CAAA;AAAA,IACA,CAAC,MAAA,EAAQ,QAAA,CAAS,GAAG;AAAA,GACvB;AACA,EAAA,OAAO,EAAE,GAAG,QAAA,EAAU,GAAA,EAAI;AAC5B","file":"chunk-YQRTBGXU.js","sourcesContent":["/**\n * React layer for @bowlos/reservations.\n *\n * `<BowlosProvider>` holds one `BowlosClient`; `useAccount()` manages the\n * customer session (probe on mount, sign-in/up/link/out, current customer);\n * `useBowlosQuery()` is the generic read hook the typed data hooks\n * (`useAvailability`, `useBookingFlow`, …) will build on next.\n *\n * Lives in its own module so non-React consumers of the core never pull React.\n * (The `@bowlos/reservations/react` export subpath is wired with the publish build.)\n */\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useRef,\n useState,\n type ReactNode,\n} from \"react\";\nimport { BowlosClient, createBowlosClient } from \"./client\";\nimport { BowlosApiError } from \"./errors\";\nimport type { AuthState, BowlosClientConfig, Customer, LinkProfile } from \"./types\";\n\nconst BowlosContext = createContext<BowlosClient | null>(null);\nconst AccountContext = createContext<UseAccountResult | null>(null);\n\nexport interface BowlosProviderProps {\n /** A prebuilt client, or pass `config` to have one created and memoized. */\n client?: BowlosClient;\n config?: BowlosClientConfig;\n children: ReactNode;\n}\n\nexport function BowlosProvider({ client, config, children }: BowlosProviderProps) {\n const ref = useRef<BowlosClient | null>(client ?? null);\n if (!ref.current) {\n if (!config) {\n throw new Error(\"BowlosProvider requires either a `client` or a `config`.\");\n }\n ref.current = createBowlosClient(config);\n }\n const bowlosClient = ref.current as BowlosClient; // non-null after the guard above\n // Run the session machine ONCE here and share it via context, so every\n // useAccount() across the app sees the same session.\n const account = useAccountState(bowlosClient);\n return (\n <BowlosContext.Provider value={bowlosClient}>\n <AccountContext.Provider value={account}>{children}</AccountContext.Provider>\n </BowlosContext.Provider>\n );\n}\n\nexport function useBowlosClient(): BowlosClient {\n const client = useContext(BowlosContext);\n if (!client) {\n throw new Error(\"useBowlosClient must be used within a <BowlosProvider>.\");\n }\n return client;\n}\n\n// ── useAccount ──────────────────────────────────────────────────────────────\n\nexport type AccountStatus = \"loading\" | AuthState;\n\nexport interface UseAccountResult {\n status: AccountStatus;\n customer: Customer | null;\n error: BowlosApiError | null;\n signIn: (email: string, password: string) => Promise<void>;\n /** Atomic sign-up (preferred): login + customer profile in one call. */\n register: (\n email: string,\n password: string,\n profile: Omit<LinkProfile, \"email\">,\n ) => Promise<void>;\n signUp: (email: string, password: string) => Promise<void>;\n link: (profile: LinkProfile) => Promise<void>;\n /** Forgot-password step 1: email a reset code (no session change). Always\n * resolves — the server never reveals whether the email has an account. */\n requestPasswordReset: (email: string) => Promise<void>;\n /** Forgot-password step 2: verify the code + set a new password. On success\n * the customer is signed in (status flips to linked). */\n resetPassword: (\n email: string,\n code: string,\n newPassword: string,\n ) => Promise<void>;\n signOut: () => Promise<void>;\n refresh: () => Promise<void>;\n}\n\n/** The session state machine — runs ONCE inside `<BowlosProvider>` and is shared\n * via context. Probes once on mount; each action re-probes so `status`/`customer`\n * stay current. Consumers use `useAccount()`, never this directly. */\nfunction useAccountState(client: BowlosClient): UseAccountResult {\n const [status, setStatus] = useState<AccountStatus>(\"loading\");\n const [customer, setCustomer] = useState<Customer | null>(null);\n const [error, setError] = useState<BowlosApiError | null>(null);\n\n const refresh = useCallback(async () => {\n try {\n const state = await client.probe();\n setStatus(state);\n setCustomer(state === \"linked\" ? await client.me() : null);\n setError(null);\n } catch (e) {\n setStatus(\"unauthenticated\");\n setCustomer(null);\n if (e instanceof BowlosApiError) setError(e);\n }\n }, [client]);\n\n useEffect(() => {\n void refresh();\n }, [refresh]);\n\n const run = useCallback(\n async (action: () => Promise<unknown>) => {\n setError(null);\n try {\n await action();\n await refresh();\n } catch (e) {\n if (e instanceof BowlosApiError) setError(e);\n throw e;\n }\n },\n [refresh],\n );\n\n const signIn = useCallback(\n (email: string, password: string) => run(() => client.signIn(email, password)),\n [client, run],\n );\n const register = useCallback(\n (email: string, password: string, profile: Omit<LinkProfile, \"email\">) =>\n run(() => client.register(email, password, profile)),\n [client, run],\n );\n const signUp = useCallback(\n (email: string, password: string) => run(() => client.signUp(email, password)),\n [client, run],\n );\n const link = useCallback((profile: LinkProfile) => run(() => client.link(profile)), [client, run]);\n // Step 1 doesn't change the session, so it doesn't re-probe — just surfaces\n // errors. Step 2 signs the customer in, so it runs through `run` (re-probe).\n const requestPasswordReset = useCallback(\n async (email: string) => {\n setError(null);\n try {\n await client.requestPasswordReset(email);\n } catch (e) {\n if (e instanceof BowlosApiError) setError(e);\n throw e;\n }\n },\n [client],\n );\n const resetPassword = useCallback(\n (email: string, code: string, newPassword: string) =>\n run(() => client.resetPassword(email, code, newPassword)),\n [client, run],\n );\n const signOut = useCallback(() => run(() => client.signOut()), [client, run]);\n\n return {\n status,\n customer,\n error,\n signIn,\n register,\n signUp,\n link,\n requestPasswordReset,\n resetPassword,\n signOut,\n refresh,\n };\n}\n\n/**\n * The customer session (state + actions), shared across the whole app. Every\n * call returns the SAME session — signing in or out anywhere updates the header,\n * the booking form, everywhere at once. Must be used within a `<BowlosProvider>`.\n */\nexport function useAccount(): UseAccountResult {\n const account = useContext(AccountContext);\n if (!account) {\n throw new Error(\"useAccount must be used within a <BowlosProvider>.\");\n }\n return account;\n}\n\n// ── useBowlosQuery ────────────────────────────────────────────────────────────\n\nexport interface UseQueryOptions {\n /** Send the customer bearer token (for session-scoped reads). */\n auth?: boolean;\n /** Skip fetching until true. Defaults to true. */\n enabled?: boolean;\n}\n\nexport interface UseQueryResult<T> {\n data: T | null;\n error: BowlosApiError | null;\n loading: boolean;\n refetch: () => Promise<void>;\n}\n\n/** Generic read hook over a gateway route. The typed data hooks\n * (`useAvailability`, etc.) will wrap this with route names + arg types. */\nexport function useBowlosQuery<T = unknown>(\n name: string,\n args: Record<string, unknown> = {},\n options: UseQueryOptions = {},\n): UseQueryResult<T> {\n const client = useBowlosClient();\n const auth = options.auth ?? false;\n const enabled = options.enabled ?? true;\n const [data, setData] = useState<T | null>(null);\n const [error, setError] = useState<BowlosApiError | null>(null);\n const [loading, setLoading] = useState<boolean>(enabled);\n // Stabilize the args object across renders so the effect doesn't loop.\n const argsKey = JSON.stringify(args);\n\n const refetch = useCallback(async () => {\n setLoading(true);\n setError(null);\n try {\n const result = await client.call<T>(name, JSON.parse(argsKey) as Record<string, unknown>, {\n auth,\n });\n setData(result);\n } catch (e) {\n if (e instanceof BowlosApiError) setError(e);\n setData(null);\n } finally {\n setLoading(false);\n }\n }, [client, name, argsKey, auth]);\n\n useEffect(() => {\n if (enabled) void refetch();\n }, [enabled, refetch]);\n\n return { data, error, loading, refetch };\n}\n\n// ── useBowlosMutation ─────────────────────────────────────────────────────────\n\nexport interface UseMutationResult<TArgs, TData> {\n /** Fire the mutation. Resolves with the data, or throws BowlosApiError. */\n run: (args: TArgs) => Promise<TData>;\n data: TData | null;\n error: BowlosApiError | null;\n loading: boolean;\n reset: () => void;\n}\n\n/** Generic write hook over a gateway route. The typed mutation hooks\n * (`useCancelMyReservation`, etc.) wrap this with a route name + arg type. */\nexport function useBowlosMutation<TArgs extends Record<string, unknown>, TData = unknown>(\n name: string,\n options: { auth?: boolean } = {},\n): UseMutationResult<TArgs, TData> {\n const client = useBowlosClient();\n const auth = options.auth ?? false;\n const [data, setData] = useState<TData | null>(null);\n const [error, setError] = useState<BowlosApiError | null>(null);\n const [loading, setLoading] = useState<boolean>(false);\n\n const run = useCallback(\n async (args: TArgs) => {\n setLoading(true);\n setError(null);\n try {\n const result = await client.call<TData>(name, args, { auth });\n setData(result);\n return result;\n } catch (e) {\n if (e instanceof BowlosApiError) setError(e);\n throw e;\n } finally {\n setLoading(false);\n }\n },\n [client, name, auth],\n );\n\n const reset = useCallback(() => {\n setData(null);\n setError(null);\n setLoading(false);\n }, []);\n\n return { run, data, error, loading, reset };\n}\n","import { useCallback, useRef } from \"react\";\nimport { BowlosApiError } from \"./errors\";\nimport { generateIdempotencyKey } from \"./data\";\nimport { useBowlosMutation, type UseMutationResult } from \"./react\";\n\n/** Retain a key after an uncertain outcome; changed inputs begin another action. */\nexport function useIdempotentMutation<\n TArgs extends Record<string, unknown> & { idempotencyKey: string },\n TData,\n>(\n name: string,\n options: { auth?: boolean } = {},\n): UseMutationResult<Omit<TArgs, \"idempotencyKey\">, TData> {\n const mutation = useBowlosMutation<TArgs, TData>(name, options);\n const pending = useRef<{ fingerprint: string; key: string } | null>(null);\n const run = useCallback(\n async (args: Omit<TArgs, \"idempotencyKey\">) => {\n const fingerprint = JSON.stringify(args, (_key, value: unknown) => {\n if (value && typeof value === \"object\" && !Array.isArray(value)) {\n return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)));\n }\n return value;\n });\n if (!pending.current || pending.current.fingerprint !== fingerprint) {\n pending.current = { fingerprint, key: generateIdempotencyKey() };\n }\n const action = pending.current;\n try {\n const result = await mutation.run({ ...args, idempotencyKey: action.key } as TArgs);\n if (pending.current === action) pending.current = null;\n return result;\n } catch (error) {\n // Network/timeout/server/rate-limit failures can leave the outcome uncertain.\n const retryable =\n !(error instanceof BowlosApiError) ||\n error.status === 0 ||\n error.status === 408 ||\n error.status === 429 ||\n error.status >= 500;\n if (!retryable && pending.current === action) pending.current = null;\n throw error;\n }\n },\n [mutation.run],\n );\n const reset = useCallback(() => {\n pending.current = null;\n mutation.reset();\n }, [mutation.reset]);\n return { ...mutation, run, reset };\n}\n","/**\n * Typed React data hooks for the booking funnel, built on `useBowlosQuery`.\n * Same arg/result types as the framework-agnostic functions in `data.ts`.\n */\nimport type {\n SavedCardScope,\n SavedCardArgs,\n SavedCardsResult,\n CardSetupResult,\n ChangePasswordArgs,\n} from \"./account\";\nimport { useCallback } from \"react\";\nimport {\n useBowlosClient,\n useBowlosQuery,\n useBowlosMutation,\n type UseQueryOptions,\n type UseQueryResult,\n type UseMutationResult,\n} from \"./react\";\nimport { useIdempotentMutation } from \"./idempotent-mutation\";\nimport type {\n CancelPreview,\n CancelResult,\n MyGameCard,\n ReservationCancelArgs,\n OrderCancelArgs,\n GameCardCancelArgs,\n} from \"./account\";\nimport type {\n AvailabilityArgs,\n AvailabilityResult,\n BookingPreviewArgs,\n BookingQuote,\n PublicAddon,\n StartTimesArgs,\n PackagePreviewArgs,\n PackagePreviewResult,\n GameCardPreviewArgs,\n GameCardPreviewResult,\n EventTicketPreviewArgs,\n EventTicketPreviewResult,\n MembershipPreviewArgs,\n MembershipPreviewResult,\n MembershipSubscriptionPreviewResult,\n} from \"./data\";\nimport type {\n BrandScoped,\n EventOrderDetailArgs,\n FlashBookingOptionsArgs,\n FlashSaleArgs,\n FlashSalesArgs,\n MembershipDetailArgs,\n ReservationDetailArgs,\n} from \"./account\";\nimport type {\n BrandCatalogArgs,\n CatalogArgs,\n CatalogResult,\n CenterScoped,\n PackageDetailArgs,\n CenterHoursArgs,\n RetailPricing,\n} from \"./catalog\";\n\n/** Live available-unit (unoccupied) count for a product / date / time window. */\nexport function useAvailability(\n args: AvailabilityArgs,\n options?: UseQueryOptions,\n): UseQueryResult<AvailabilityResult> {\n return useBowlosQuery<AvailabilityResult>(\"checkAvailability\", args, options);\n}\n\n/** Authoritative price quote for the chosen booking inputs. */\nexport function useBookingPreview(\n args: BookingPreviewArgs,\n options?: UseQueryOptions,\n): UseQueryResult<BookingQuote> {\n return useBowlosQuery<BookingQuote>(\"bookingPreview\", args, options);\n}\n\n/** Bookable add-ons (shoe rental, upgrades…) for a product. */\nexport function useAddons(\n args: { productId: string },\n options?: UseQueryOptions,\n): UseQueryResult<PublicAddon[]> {\n return useBowlosQuery<PublicAddon[]>(\"listPublicAddons\", args, options);\n}\n\n/** Bookable start times (minute-of-day) for a product on a date. */\nexport function useStartTimes(\n args: StartTimesArgs,\n options?: UseQueryOptions,\n): UseQueryResult<number[]> {\n return useBowlosQuery<number[]>(\"availableStartTimes\", args, options);\n}\n\n// ── account (require a signed-in customer) ───────────────────────────────────\n// Results are generic (`<T = unknown>`) — parameterize with your own shape.\n\n/** The signed-in customer's reservations. */\nexport function useMyReservations<T = unknown>(\n args: BrandScoped,\n options?: UseQueryOptions,\n): UseQueryResult<T> {\n return useBowlosQuery<T>(\"listMyReservations\", args, { ...options, auth: true });\n}\n\n/** One of the customer's reservations, by displayId. */\nexport function useMyReservationDetail<T = unknown>(\n args: ReservationDetailArgs,\n options?: UseQueryOptions,\n): UseQueryResult<T> {\n return useBowlosQuery<T>(\"getMyReservationDetail\", args, { ...options, auth: true });\n}\n\n/** The signed-in customer's event ticket orders. */\nexport function useMyEventOrders<T = unknown>(\n args: BrandScoped,\n options?: UseQueryOptions,\n): UseQueryResult<T> {\n return useBowlosQuery<T>(\"listMyEventOrders\", args, { ...options, auth: true });\n}\n\n/** One of the customer's event ticket orders. */\nexport function useMyEventOrder<T = unknown>(\n args: EventOrderDetailArgs,\n options?: UseQueryOptions,\n): UseQueryResult<T> {\n return useBowlosQuery<T>(\"getMyEventOrder\", args, { ...options, auth: true });\n}\n\n/** The customer's memberships. */\nexport function useMyMemberships<T = unknown>(\n args: BrandScoped,\n options?: UseQueryOptions,\n): UseQueryResult<T> {\n return useBowlosQuery<T>(\"listMyMemberships\", args, { ...options, auth: true });\n}\n\n/** One membership's detail. */\nexport function useMyMembershipDetail<T = unknown>(\n args: MembershipDetailArgs,\n options?: UseQueryOptions,\n): UseQueryResult<T> {\n return useBowlosQuery<T>(\"getMyMembershipDetail\", args, { ...options, auth: true });\n}\n\n/** Loyalty tier + points. */\nexport function useMyLoyalty<T = unknown>(\n args: BrandScoped,\n options?: UseQueryOptions,\n): UseQueryResult<T> {\n return useBowlosQuery<T>(\"getMyLoyalty\", args, { ...options, auth: true });\n}\n\n/** Account credit balance + ledger. */\nexport function useMyCredits<T = unknown>(\n args: BrandScoped,\n options?: UseQueryOptions,\n): UseQueryResult<T> {\n return useBowlosQuery<T>(\"listMyCredits\", args, { ...options, auth: true });\n}\n\n/** Issued wallet passes. */\nexport function useMyPasses<T = unknown>(\n args: BrandScoped,\n options?: UseQueryOptions,\n): UseQueryResult<T> {\n return useBowlosQuery<T>(\"listMyPasses\", args, { ...options, auth: true });\n}\n\n/** The customer's game cards for this Brand (with the unused-only `cancellable`\n * flag), so a headless site can list them + drive cancel. */\nexport function useMyGameCards<T = MyGameCard[]>(\n args: BrandScoped,\n options?: UseQueryOptions,\n): UseQueryResult<T> {\n return useBowlosQuery<T>(\"listMyGameCards\", args, { ...options, auth: true });\n}\n\n// ── self-serve cancel (v0.23.0): preview reads + cancel mutations ─────────────\n//\n// Per type: preview \"what you'll get back\" → confirm → cancel. The cancel hooks\n// retain an idempotencyKey across retries of the same action.\n// Game cards cancel only while fully unused (locked rule) → full credit.\n\n/** Preview the credit for cancelling a reservation (advisory; cancel re-computes). */\nexport function useReservationCancelPreview<T = CancelPreview>(\n args: { brandId: string; reservationId: string },\n options?: UseQueryOptions,\n): UseQueryResult<T> {\n return useBowlosQuery<T>(\"previewMyCancellation\", args, { ...options, auth: true });\n}\n/** Preview the credit for cancelling an event order. */\nexport function useEventOrderCancelPreview<T = CancelPreview>(\n args: { brandId: string; orderId: string },\n options?: UseQueryOptions,\n): UseQueryResult<T> {\n return useBowlosQuery<T>(\"previewMyEventOrderCancellation\", args, { ...options, auth: true });\n}\n/** Preview the credit for cancelling a package order. */\nexport function usePackageOrderCancelPreview<T = CancelPreview>(\n args: { brandId: string; orderId: string },\n options?: UseQueryOptions,\n): UseQueryResult<T> {\n return useBowlosQuery<T>(\"previewMyPackageOrderCancellation\", args, { ...options, auth: true });\n}\n/** Preview the credit for cancelling a game card (full credit only if unused). */\nexport function useGameCardCancelPreview<T = CancelPreview>(\n args: { brandId: string; cardId: string },\n options?: UseQueryOptions,\n): UseQueryResult<T> {\n return useBowlosQuery<T>(\"previewMyGameCardCancellation\", args, { ...options, auth: true });\n}\n\n/** Cancel a reservation → store credit per policy. Pass the `version` from the\n * list/detail as `expectedVersion`; the hook supplies the idempotency key. */\nexport function useCancelMyReservation() {\n return useIdempotentMutation<ReservationCancelArgs, CancelResult>(\"cancelMyReservation\", {\n auth: true,\n });\n}\n/** Cancel an event order → store credit per policy. */\nexport function useCancelMyEventOrder() {\n return useIdempotentMutation<OrderCancelArgs, CancelResult>(\"cancelMyEventOrder\", { auth: true });\n}\n/** Cancel a package order → store credit per policy; releases the slot. */\nexport function useCancelMyPackageOrder() {\n return useIdempotentMutation<OrderCancelArgs, CancelResult>(\"cancelMyPackageOrder\", {\n auth: true,\n });\n}\n/** Cancel a game card → full credit (unused cards only). */\nexport function useCancelMyGameCard() {\n return useIdempotentMutation<GameCardCancelArgs, CancelResult>(\"cancelMyGameCard\", {\n auth: true,\n });\n}\n\n// ── flash sales (session-aware: members see prices) ──────────────────────────\n\n/** The public flash-sale page (members see prices; anonymous gets the locked view). */\nexport function useFlashSale<T = unknown>(\n args: FlashSaleArgs,\n options?: UseQueryOptions,\n): UseQueryResult<T> {\n return useBowlosQuery<T>(\"getPublicFlashSaleBySlug\", args, { ...options, auth: true });\n}\n\n/** The public flash-sale index for a Brand (live + upcoming; no prices). Public. */\nexport function useFlashSales<T = unknown>(\n args: FlashSalesArgs,\n options?: UseQueryOptions,\n): UseQueryResult<T> {\n return useBowlosQuery<T>(\"listPublicFlashSales\", args, options);\n}\n\n/** Per-start-hour options for a flash-sale reservation item (members only). */\nexport function useFlashSaleBookingOptions<T = unknown>(\n args: FlashBookingOptionsArgs,\n options?: UseQueryOptions,\n): UseQueryResult<T> {\n return useBowlosQuery<T>(\"getFlashSaleBookingOptions\", args, { ...options, auth: true });\n}\n\n// ── public catalog (anonymous; power `<BookingCatalog>`) ──────────────────────\n\n/**\n * The canonical public catalog for a surface — every category grouped, with the\n * Center admin's per-surface visibility already applied. Prefer this over the\n * per-category hooks below when you want the full, visibility-aware catalog\n * (it stays consistent with the white-label web + mobile surfaces). Anonymous.\n */\nexport function useCatalog<T = CatalogResult>(\n args: CatalogArgs,\n options?: UseQueryOptions,\n): UseQueryResult<T> {\n return useBowlosQuery<T>(\"listPublicCatalog\", args, options);\n}\n\n/**\n * Full Test Mode (2026-06-23): is this Center in operator-enabled test mode?\n * Reads the same `listPublicCatalog` payload as `useCatalog`, so it's free when\n * you already render the catalog. Show `<MaintenanceBanner>` (or your own themed\n * notice) when `maintenanceMode` is true — normal-customer bookings are\n * server-refused in this state (`CENTER_IN_MAINTENANCE`); only admin\n * Test-Account customers transact.\n */\nexport function useTestMode(\n args: CatalogArgs,\n options?: UseQueryOptions,\n): { maintenanceMode: boolean; loading: boolean } {\n const res = useCatalog(args, options);\n return {\n maintenanceMode: res.data?.maintenanceMode === true,\n loading: res.loading,\n };\n}\n\n/** Bookable products at a Center (each carries `attractionTypeKey`). */\nexport function useProducts<T = unknown>(\n args: CenterScoped,\n options?: UseQueryOptions,\n): UseQueryResult<T> {\n return useBowlosQuery<T>(\"listPublicProducts\", args, options);\n}\n\n/** Upcoming pricing events at a Center. */\nexport function useEvents<T = unknown>(\n args: CenterScoped,\n options?: UseQueryOptions,\n): UseQueryResult<T> {\n return useBowlosQuery<T>(\"listPublicEvents\", args, options);\n}\n\n/** Sellable event offers at a Center. Use these for the product lineup and\n * event landing pages; each row carries a slug and purchase mode. */\nexport function useEventOffers<T = import(\"./toolkit-types\").EventOffer[]>(\n args: CenterScoped & { includeWithoutLandingPage?: boolean },\n options?: UseQueryOptions,\n): UseQueryResult<T> {\n return useBowlosQuery<T>(\"listPublicEventOffers\", args, options);\n}\n\n/** One sellable event offer by landing-page slug. */\nexport function useEventOffer<T = unknown>(\n args: { slug: string },\n options?: UseQueryOptions,\n): UseQueryResult<T> {\n return useBowlosQuery<T>(\"getPublicEventOffer\", args, options);\n}\n\n/** Purchasable packages at a Brand. */\nexport function usePackages<T = unknown>(\n args: BrandCatalogArgs,\n options?: UseQueryOptions,\n): UseQueryResult<T> {\n return useBowlosQuery<T>(\"listPublicPackages\", args, options);\n}\n\n/** Full detail for one package (components, add-ons, allowed start times, …) —\n * drives the headless package config UI before `usePackagePurchase`. */\nexport function usePackage<T = unknown>(\n args: PackageDetailArgs,\n options?: UseQueryOptions,\n): UseQueryResult<T> {\n return useBowlosQuery<T>(\"getPublicPackage\", args, options);\n}\n\n/** A Center's public price list — walk-in (matrix) rates grouped by attraction\n * plus opted-in \"website specials\". Anonymous, read-only; drives a printed-\n * menu-style pricing page (or the reference `<PricingTable>`). Not a booking\n * surface — render-only. */\nexport function useRetailPricing<T = RetailPricing>(\n args: CenterScoped,\n options?: UseQueryOptions,\n): UseQueryResult<T> {\n return useBowlosQuery<T>(\"listRetailPricing\", args, options);\n}\n\n/** A Center's open/close window for the given attraction types on a date — use\n * the package's component attraction-type keys to bound its bookable slots. */\nexport function useCenterHours<T = unknown>(\n args: CenterHoursArgs,\n options?: UseQueryOptions,\n): UseQueryResult<T> {\n return useBowlosQuery<T>(\"getCenterOperatingHoursForTypes\", args, options);\n}\n\n/** Itemized quote for a package order — base, add-ons, tax lines, the selling\n * Center's booking fee, and the authoritative grand total. Drives the headless\n * **Review** step. Requires a signed-in customer (tax exemptions are applied),\n * and is computed by the same engine as the PaymentIntent, so it never diverges\n * from what the customer is charged. */\nexport function usePackagePreview<T = PackagePreviewResult>(\n args: PackagePreviewArgs,\n options?: UseQueryOptions,\n): UseQueryResult<T> {\n return useBowlosQuery<T>(\"previewPackageOrder\", args, { ...options, auth: true });\n}\n\n/** Purchasable memberships at a Center. */\nexport function usePublicMemberships<T = unknown>(\n args: CenterScoped,\n options?: UseQueryOptions,\n): UseQueryResult<T> {\n return useBowlosQuery<T>(\"listPublicMemberships\", args, options);\n}\n\n/** Purchasable game cards / passes at a Brand. */\nexport function useGameCards<T = unknown>(\n args: BrandCatalogArgs,\n options?: UseQueryOptions,\n): UseQueryResult<T> {\n return useBowlosQuery<T>(\"listPublicGameCards\", args, options);\n}\n\n/** Itemized quote for a game-pass purchase — the base price, tax lines, the\n * selling Center's booking fee, and the authoritative grand total. Drives the\n * headless **Review** step. Requires a signed-in customer (tax exemptions are\n * applied + the home Center is resolved server-side), and is computed by the\n * same engine as the PaymentIntent, so it never diverges from what the\n * customer is charged. */\nexport function useGameCardPreview<T = GameCardPreviewResult>(\n args: GameCardPreviewArgs,\n options?: UseQueryOptions,\n): UseQueryResult<T> {\n return useBowlosQuery<T>(\"previewGameCardOrder\", args, { ...options, auth: true });\n}\n\n/** Itemized quote for a ticket-mode event offer — base tickets, tax lines,\n * Center event fee, and authoritative grand total. Requires a signed-in\n * customer so tax exemptions match the eventual charge. */\nexport function useEventTicketPreview<T = EventTicketPreviewResult>(\n args: EventTicketPreviewArgs,\n options?: UseQueryOptions,\n): UseQueryResult<T> {\n return useBowlosQuery<T>(\"previewEventTicketOrder\", args, { ...options, auth: true });\n}\n\n/** Itemized quote for a one-time membership purchase — dues, the one-time setup\n * fee, tax lines, the selling Center's booking fee, and the authoritative grand\n * total. Drives the headless **Review** step. Requires a signed-in customer (tax\n * exemptions are applied + the home Center is resolved server-side), and is\n * computed by the same engine as the PaymentIntent, so it never diverges from\n * what the customer is charged. */\nexport function useMembershipPreview<T = MembershipPreviewResult>(\n args: MembershipPreviewArgs,\n options?: UseQueryOptions,\n): UseQueryResult<T> {\n return useBowlosQuery<T>(\"previewMembershipOrder\", args, { ...options, auth: true });\n}\n\n/** Itemized quote for a RECURRING membership subscription — the one-time Review\n * fields (\"Due today\") PLUS `recurringTotalCents` + `cadence` (\"Auto-renews\n * at\"). Drives the recurring **Review** step. Requires a signed-in customer, and\n * is computed by the same engine as the subscription's first invoice, so it\n * never diverges from what the customer is charged. */\nexport function useMembershipSubscriptionPreview<T = MembershipSubscriptionPreviewResult>(\n args: MembershipPreviewArgs,\n options?: UseQueryOptions,\n): UseQueryResult<T> {\n return useBowlosQuery<T>(\"previewMembershipSubscriptionOrder\", args, {\n ...options,\n auth: true,\n });\n}\n\nexport function useSavedCards(\n args: SavedCardScope,\n options?: UseQueryOptions,\n): UseQueryResult<SavedCardsResult> {\n return useBowlosQuery<SavedCardsResult>(\"listMyPaymentMethods\", args, { ...options, auth: true });\n}\nexport function useCreateCardSetup(): UseMutationResult<SavedCardScope, CardSetupResult> {\n return useBowlosMutation<SavedCardScope, CardSetupResult>(\"createSetupIntentForAddingCard\", {\n auth: true,\n });\n}\nexport function useRemoveCard(): UseMutationResult<SavedCardArgs, { detached: boolean }> {\n return useBowlosMutation<SavedCardArgs, { detached: boolean }>(\"detachPaymentMethod\", {\n auth: true,\n });\n}\nexport function useSetDefaultCard(): UseMutationResult<SavedCardArgs, { ok: boolean }> {\n return useBowlosMutation<SavedCardArgs, { ok: boolean }>(\"setDefaultPaymentMethod\", {\n auth: true,\n });\n}\nexport function useChangePassword(): UseMutationResult<ChangePasswordArgs, { ok: true }> {\n const client = useBowlosClient();\n const mutation = useBowlosMutation<ChangePasswordArgs, { ok: true }>(\"changeMyPassword\", {\n auth: true,\n });\n const run = useCallback(\n async (args: ChangePasswordArgs) => {\n const result = await mutation.run(args);\n await client.signOut();\n return result;\n },\n [client, mutation.run],\n );\n return { ...mutation, run };\n}\n"]}
|
package/dist/cli.cjs
CHANGED
|
@@ -18,6 +18,7 @@ var BOWLOS_ERROR_CODES = {
|
|
|
18
18
|
SCOPE_REVOKED: "SCOPE_REVOKED",
|
|
19
19
|
NOT_FOUND: "NOT_FOUND",
|
|
20
20
|
// Client-side
|
|
21
|
+
ROUTE_NOT_FOUND: "ROUTE_NOT_FOUND",
|
|
21
22
|
NETWORK_ERROR: "NETWORK_ERROR",
|
|
22
23
|
UNKNOWN: "ERROR"
|
|
23
24
|
};
|
|
@@ -26,6 +27,7 @@ var BowlosApiError = class _BowlosApiError extends Error {
|
|
|
26
27
|
code;
|
|
27
28
|
/** HTTP status (0 for a network failure before any response). */
|
|
28
29
|
status;
|
|
30
|
+
details;
|
|
29
31
|
/** Seconds to wait before retrying — present only on `RATE_LIMITED`. */
|
|
30
32
|
retryAfterSeconds;
|
|
31
33
|
constructor(code, message, status, options = {}) {
|
|
@@ -33,9 +35,15 @@ var BowlosApiError = class _BowlosApiError extends Error {
|
|
|
33
35
|
this.name = "BowlosApiError";
|
|
34
36
|
this.code = code;
|
|
35
37
|
this.status = status;
|
|
38
|
+
this.details = options.details;
|
|
36
39
|
this.retryAfterSeconds = options.retryAfterSeconds;
|
|
37
40
|
Object.setPrototypeOf(this, _BowlosApiError.prototype);
|
|
38
41
|
}
|
|
42
|
+
/** Typed additive createAnonymousBooking slot-full details, when present. */
|
|
43
|
+
get slotFullDetails() {
|
|
44
|
+
const d = this.details;
|
|
45
|
+
return this.code === "VALIDATION_FAILED" && d?.reason === "slot_full" && typeof d.waitlistAvailable === "boolean" && typeof d.requested === "number" && typeof d.available === "number" ? d : void 0;
|
|
46
|
+
}
|
|
39
47
|
/** Too many requests — caller should back off `retryAfterSeconds`. */
|
|
40
48
|
get isRateLimited() {
|
|
41
49
|
return this.code === BOWLOS_ERROR_CODES.RATE_LIMITED;
|
|
@@ -111,7 +119,10 @@ var BowlosClient = class {
|
|
|
111
119
|
code,
|
|
112
120
|
env.error?.message ?? `Health ping failed (HTTP ${status}).`,
|
|
113
121
|
status,
|
|
114
|
-
{
|
|
122
|
+
{
|
|
123
|
+
details: errorDetails(env.error?.details),
|
|
124
|
+
retryAfterSeconds: code === BOWLOS_ERROR_CODES.RATE_LIMITED ? retryAfterSeconds : void 0
|
|
125
|
+
}
|
|
115
126
|
);
|
|
116
127
|
}
|
|
117
128
|
// ── low-level transport ────────────────────────────────────────────────
|
|
@@ -142,9 +153,18 @@ var BowlosClient = class {
|
|
|
142
153
|
try {
|
|
143
154
|
body = JSON.parse(text);
|
|
144
155
|
} catch {
|
|
145
|
-
body = {
|
|
156
|
+
body = {
|
|
157
|
+
ok: false,
|
|
158
|
+
error: {
|
|
159
|
+
code: res.status === 404 ? BOWLOS_ERROR_CODES.ROUTE_NOT_FOUND : BOWLOS_ERROR_CODES.UNKNOWN,
|
|
160
|
+
message: text.slice(0, 200)
|
|
161
|
+
}
|
|
162
|
+
};
|
|
146
163
|
}
|
|
147
164
|
}
|
|
165
|
+
if (!text && res.status === 404) {
|
|
166
|
+
body = { ok: false, error: { code: BOWLOS_ERROR_CODES.ROUTE_NOT_FOUND } };
|
|
167
|
+
}
|
|
148
168
|
return { status: res.status, body, retryAfterSeconds };
|
|
149
169
|
}
|
|
150
170
|
/**
|
|
@@ -167,7 +187,8 @@ var BowlosClient = class {
|
|
|
167
187
|
throw new BowlosApiError(
|
|
168
188
|
inner.error?.code ?? BOWLOS_ERROR_CODES.UNKNOWN,
|
|
169
189
|
inner.error?.message ?? `Request to "${name}" failed.`,
|
|
170
|
-
status
|
|
190
|
+
status,
|
|
191
|
+
{ details: errorDetails(inner.error?.details) }
|
|
171
192
|
);
|
|
172
193
|
}
|
|
173
194
|
return inner.data;
|
|
@@ -181,6 +202,7 @@ var BowlosClient = class {
|
|
|
181
202
|
if (refreshed) return this.callInternal(name, args, auth, true, method);
|
|
182
203
|
}
|
|
183
204
|
throw new BowlosApiError(code, message, status, {
|
|
205
|
+
details: errorDetails(env.error?.details),
|
|
184
206
|
retryAfterSeconds: code === BOWLOS_ERROR_CODES.RATE_LIMITED ? retryAfterSeconds : void 0
|
|
185
207
|
});
|
|
186
208
|
}
|
|
@@ -300,6 +322,13 @@ var defaultFetch = (input, init) => {
|
|
|
300
322
|
function createBowlosClient(config) {
|
|
301
323
|
return new BowlosClient(config);
|
|
302
324
|
}
|
|
325
|
+
function errorDetails(value) {
|
|
326
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
|
|
327
|
+
const entries = Object.entries(value).filter(
|
|
328
|
+
([, v]) => typeof v === "string" || typeof v === "boolean" || typeof v === "number" && Number.isFinite(v)
|
|
329
|
+
);
|
|
330
|
+
return entries.length ? Object.fromEntries(entries) : void 0;
|
|
331
|
+
}
|
|
303
332
|
|
|
304
333
|
// src/doctor.ts
|
|
305
334
|
var GATEWAY_SUFFIX = "/api/public/v1";
|
|
@@ -571,6 +600,8 @@ function initNextSteps(absDir, displayDir) {
|
|
|
571
600
|
"",
|
|
572
601
|
`\u2713 Scaffolded a BowlOS center site \u2192 ${absDir}`,
|
|
573
602
|
"",
|
|
603
|
+
"Complete site build guide: node_modules/@bowlos/reservations/AGENTS.md",
|
|
604
|
+
"",
|
|
574
605
|
"Next steps:",
|
|
575
606
|
` cd ${displayDir}`,
|
|
576
607
|
" npm install",
|
package/dist/cli.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/client.ts","../src/doctor.ts","../src/init.ts","../src/cli.ts"],"names":["resolve","existsSync","readdirSync","mkdirSync","cpSync","join","renameSync"],"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,EAGd,0BAAA,EAA4B,4BAAA;AAAA,EAC5B,yBAAA,EAA2B,2BAAA;AAAA,EAC3B,mBAAA,EAAqB,qBAAA;AAAA,EAIrB,iBAAA,EAAmB,mBAAA;AAAA,EACnB,aAAA,EAAe,eAAA;AAAA,EACf,SAAA,EAAW,WAAA;AAAA,EAKO;AAAA,EAElB,aAAA,EAAe,eAAA;AAAA,EACf,OAAA,EAAS;AACX,CAAA;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,KAAA,EAAO,CAAA;AACjF,IAAA,IAAA,CAAK,IAAA,GAAO,gBAAA;AACZ,IAAA,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7B,MAAA;AAAA,IACA,OAAA;AAAA,IACA,QAAQ,OAAO,IAAA,CAAK,MAAA,KAAW,QAAA,GAAW,KAAK,MAAA,GAAS,MAAA;AAAA,IACxD,YAAA,EAAc,IAAA,CAAK,gBAAgB,CAAA,KAAM;AAAA,GAC1C,CAAA;AAED,EAAA,OAAA,CAAQ,MAAA,CAAO,KAAA,CAAM,IAAA,CAAK,IAAA,KAAS,IAAA,GAAO,CAAA,EAAG,IAAA,CAAK,SAAA,CAAU,MAAA,EAAQ,IAAA,EAAM,CAAC,CAAC;AAAA,CAAA,GAAO,MAAA,CAAO,MAAM,CAAC,CAAA;AACjG,EAAA,IAAI,CAAC,MAAA,CAAO,EAAA,EAAI,OAAA,CAAQ,QAAA,GAAW,CAAA;AACrC;AAEA,IAAA,EAAK,CAAE,KAAA,CAAM,CAAC,CAAA,KAAe;AAC3B,EAAA,OAAA,CAAQ,MAAA,CAAO,MAAM,CAAA,uBAAA,EAA0B,CAAA,YAAa,QAAQ,CAAA,CAAE,OAAA,GAAU,MAAA,CAAO,CAAC,CAAC;AAAA,CAAI,CAAA;AAC7F,EAAA,OAAA,CAAQ,QAAA,GAAW,CAAA;AACrB,CAAC,CAAA","file":"cli.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 PASSWORD_TOO_WEAK: \"PASSWORD_TOO_WEAK\",\n CURRENT_PASSWORD_INCORRECT: \"CURRENT_PASSWORD_INCORRECT\",\n CURRENT_PASSWORD_REQUIRED: \"CURRENT_PASSWORD_REQUIRED\",\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 (\n isConfigErrorCode(code) ||\n code === BOWLOS_ERROR_CODES.CURRENT_PASSWORD_INCORRECT ||\n code === BOWLOS_ERROR_CODES.CURRENT_PASSWORD_REQUIRED\n )\n 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 // Password verification failures must never refresh or discard the session,\n // including legacy gateways that return INVALID_CREDENTIALS with HTTP 401.\n if (\n name !== \"changeMyPassword\" &&\n auth &&\n !retried &&\n this.store.get() &&\n looksLikeExpiredSession(status, code)\n ) {\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 /**\n * Atomic sign-up (preferred): create the login AND the brand-scoped customer\n * profile in ONE server call, then store the session. Use this instead of\n * `signUp()` + `link()` — the two-step path can strand a login with no\n * customer profile if `link()` is missed or races the new session.\n */\n async register(\n email: string,\n password: string,\n profile: Omit<LinkProfile, \"email\">,\n ): Promise<Tokens> {\n const { tokens } = await this.call<{ tokens: Tokens }>(\"auth/register\", {\n email,\n password,\n ...profile,\n });\n this.store.set(tokens);\n return tokens;\n }\n\n /** Low-level: create a login only (no customer profile). Prefer `register()`;\n * if you use this you MUST follow with `link()` or the customer is orphaned. */\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 /**\n * Forgot-password step 1: email a reset code to the address (if it has an\n * account at this center). Resolves regardless of whether the email exists —\n * the server never reveals that, to prevent account enumeration. No session\n * needed.\n */\n async requestPasswordReset(email: string): Promise<void> {\n await this.call(\"auth/request-reset\", { email });\n }\n\n /**\n * Forgot-password step 2: verify the emailed code + set a new password. On\n * success the customer is signed in (the session is stored), so the UI can\n * continue straight into the funnel. Throws `INVALID_RESET` on a bad/expired\n * code and `PASSWORD_TOO_WEAK` if the new password fails the policy.\n */\n async resetPassword(\n email: string,\n code: string,\n newPassword: string,\n ): Promise<Tokens> {\n const { tokens } = await this.call<{ tokens: Tokens }>(\"auth/reset\", {\n email,\n code,\n newPassword,\n });\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","/// <reference types=\"node\" />\n/**\n * `bowlos init` — scaffolds a ready-to-run BowlOS center site into a new folder,\n * so a builder gets the full starter (the same one in `examples/center-site`)\n * without needing the BowlOS monorepo. The starter files ship in the package's\n * `templates/center-site/` (generated from the canonical example at build time);\n * this just copies them out and restores the `.gitignore`.\n */\nimport { cpSync, existsSync, mkdirSync, readdirSync, renameSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\n\nexport interface InitOptions {\n /** Where to scaffold (created if missing). */\n targetDir: string;\n /** Absolute path to the shipped `templates/center-site` dir. */\n templatesDir: string;\n /** Scaffold into a non-empty directory anyway. */\n force?: boolean;\n}\n\nexport type InitCode = \"ok\" | \"template_missing\" | \"dir_not_empty\";\n\nexport interface InitResult {\n ok: boolean;\n code: InitCode;\n targetDir: string;\n message: string;\n}\n\n/** Copy the starter template into `targetDir`. Pure file I/O — the CLI handles\n * arg parsing + the next-steps message; tests drive this directly. */\nexport function runInit(opts: InitOptions): InitResult {\n const target = resolve(opts.targetDir);\n\n if (!existsSync(opts.templatesDir)) {\n return {\n ok: false,\n code: \"template_missing\",\n targetDir: target,\n message: `Starter template not found (${opts.templatesDir}). This @bowlos/reservations build is missing its templates/ — try reinstalling.`,\n };\n }\n\n if (existsSync(target) && readdirSync(target).length > 0 && !opts.force) {\n return {\n ok: false,\n code: \"dir_not_empty\",\n targetDir: target,\n message: `Directory is not empty: ${target}. Pick an empty directory or pass --force.`,\n };\n }\n\n mkdirSync(target, { recursive: true });\n cpSync(opts.templatesDir, target, { recursive: true });\n\n // The template ships its ignore file as `gitignore` (npm strips a literal\n // `.gitignore` from tarballs); restore the dot in the scaffolded project.\n const shipped = join(target, \"gitignore\");\n if (existsSync(shipped) && !existsSync(join(target, \".gitignore\"))) {\n renameSync(shipped, join(target, \".gitignore\"));\n }\n\n return { ok: true, code: \"ok\", targetDir: target, message: \"scaffolded\" };\n}\n","#!/usr/bin/env node\n/// <reference types=\"node\" />\n/**\n * `bowlos` CLI. Two commands:\n * - `bowlos init [dir]` — scaffold a ready-to-run center site into `dir`.\n * - `bowlos doctor` — validate a site's @bowlos/reservations setup against a\n * gateway + API key and print a readiness report.\n * Reads flags or env vars; exits non-zero on failure (so it drops into CI / a\n * setup script). Dependency-free argv parsing.\n */\nimport { join } from \"node:path\";\nimport { runDoctor, type DoctorCheck, type DoctorReport } from \"./doctor\";\nimport { runInit } from \"./init\";\n\ntype ParsedArgs = { _command?: string } & Record<string, string | boolean>;\n\nfunction parseArgs(argv: string[]): ParsedArgs {\n const out: ParsedArgs = {};\n for (let i = 0; i < argv.length; i++) {\n const a = argv[i];\n if (a === undefined) continue;\n if (a.startsWith(\"--\")) {\n const key = a.slice(2);\n const next = argv[i + 1];\n if (next !== undefined && !next.startsWith(\"--\")) {\n out[key] = next;\n i++;\n } else {\n out[key] = true;\n }\n } else if (out._command === undefined) {\n out._command = a;\n } else if (out[\"_target\"] === undefined) {\n out[\"_target\"] = a; // second positional (e.g. `init <dir>`)\n }\n }\n return out;\n}\n\nconst ICON: Record<DoctorCheck[\"status\"], string> = {\n pass: \"✓\", // ✓\n warn: \"⚠\", // ⚠\n fail: \"✗\", // ✗\n skip: \"·\", // ·\n};\n\nfunction render(report: DoctorReport): string {\n const lines: string[] = [\"\", `bowlos doctor — ${report.baseUrl}`];\n if (report.brandId) lines.push(`brand ${report.brandId} · mode ${report.mode}`);\n lines.push(\"\");\n for (const c of report.checks) {\n lines.push(` ${ICON[c.status]} ${c.title}: ${c.detail}`);\n if (c.fix && c.status !== \"pass\") lines.push(` → ${c.fix}`);\n }\n const fails = report.checks.filter((c) => c.status === \"fail\").length;\n const warns = report.checks.filter((c) => c.status === \"warn\").length;\n lines.push(\n \"\",\n report.ok\n ? warns > 0\n ? `Ready, with ${warns} warning(s).`\n : \"All checks passed — ready.\"\n : `${fails} check(s) failed — not ready.`,\n \"\",\n );\n return lines.join(\"\\n\");\n}\n\nconst HELP = [\n \"Usage: bowlos <command> [options]\",\n \"\",\n \"Commands:\",\n \" init [dir] Scaffold a ready-to-run center site (default dir: bowlos-center-site)\",\n \" doctor Validate a @bowlos/reservations setup against the gateway + API key\",\n \"\",\n \"init options:\",\n \" --force Scaffold into a non-empty directory\",\n \"\",\n \"doctor options:\",\n \" --api-key <key> Brand API key (or env BOWLOS_API_KEY)\",\n \" --base-url <url> Gateway base URL (or env BOWLOS_BASE_URL)\",\n \" --origin <url> Your deployed site origin (informs the allow-list note)\",\n \" --skip-data-read Skip the anonymous data-plane read\",\n \" --json Print the raw JSON report instead of the table\",\n \"\",\n \" --help Show this help\",\n \"\",\n].join(\"\\n\");\n\nfunction initNextSteps(absDir: string, displayDir: string): string {\n return [\n \"\",\n `✓ Scaffolded a BowlOS center site → ${absDir}`,\n \"\",\n \"Next steps:\",\n ` cd ${displayDir}`,\n \" npm install\",\n \" cp env.example .env.local # then fill in your API key + brand/center/product IDs\",\n \" npm run dev # http://localhost:3000\",\n \"\",\n \"Verify the wiring any time:\",\n ' npx bowlos doctor --api-key \"$NEXT_PUBLIC_BOWLOS_API_KEY\" --base-url \"$NEXT_PUBLIC_BOWLOS_BASE_URL\"',\n \"\",\n \"What you got: /book (headless hooks) + /account and /flash/[slug] (themeable\",\n \"components) — a working reference for both build styles. Keep what fits, swap the\",\n \"rest. See the BowlOS center-website team runbook.\",\n \"\",\n ].join(\"\\n\");\n}\n\nasync function main(): Promise<void> {\n const args = parseArgs(process.argv.slice(2));\n const command = args._command ?? \"doctor\";\n\n if (args.help === true || command === \"help\") {\n process.stdout.write(`${HELP}\\n`);\n return;\n }\n\n if (command === \"init\") {\n const target = typeof args[\"_target\"] === \"string\" ? args[\"_target\"] : \"bowlos-center-site\";\n // The bin runs from dist/cli.cjs; the starter ships at <pkg>/templates/center-site.\n const templatesDir = join(__dirname, \"..\", \"templates\", \"center-site\");\n const result = runInit({ targetDir: target, templatesDir, force: args.force === true });\n if (!result.ok) {\n process.stderr.write(`bowlos init: ${result.message}\\n`);\n process.exitCode = 1;\n return;\n }\n process.stdout.write(initNextSteps(result.targetDir, target));\n return;\n }\n\n if (command !== \"doctor\") {\n process.stderr.write(`Unknown command \"${command}\". Try: bowlos --help\\n`);\n process.exitCode = 1;\n return;\n }\n\n const apiKey = (typeof args[\"api-key\"] === \"string\" ? args[\"api-key\"] : undefined) ?? process.env.BOWLOS_API_KEY ?? \"\";\n const baseUrl = (typeof args[\"base-url\"] === \"string\" ? args[\"base-url\"] : undefined) ?? process.env.BOWLOS_BASE_URL ?? \"\";\n\n if (!apiKey || !baseUrl) {\n process.stderr.write(\n \"Missing --api-key / --base-url (or BOWLOS_API_KEY / BOWLOS_BASE_URL).\\nRun `bowlos doctor --help`.\\n\",\n );\n process.exitCode = 1;\n return;\n }\n\n const report = await runDoctor({\n apiKey,\n baseUrl,\n origin: typeof args.origin === \"string\" ? args.origin : undefined,\n skipDataRead: args[\"skip-data-read\"] === true,\n });\n\n process.stdout.write(args.json === true ? `${JSON.stringify(report, null, 2)}\\n` : render(report));\n if (!report.ok) process.exitCode = 1;\n}\n\nmain().catch((e: unknown) => {\n process.stderr.write(`bowlos doctor crashed: ${e instanceof Error ? e.message : String(e)}\\n`);\n process.exitCode = 1;\n});\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/client.ts","../src/doctor.ts","../src/init.ts","../src/cli.ts"],"names":["resolve","existsSync","readdirSync","mkdirSync","cpSync","join","renameSync"],"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,EAGd,0BAAA,EAA4B,4BAAA;AAAA,EAC5B,yBAAA,EAA2B,2BAAA;AAAA,EAC3B,mBAAA,EAAqB,qBAAA;AAAA,EAIrB,iBAAA,EAAmB,mBAAA;AAAA,EACnB,aAAA,EAAe,eAAA;AAAA,EACf,SAAA,EAAW,WAAA;AAAA,EAQO;AAAA,EAElB,eAAA,EAAiB,iBAAA;AAAA,EACjB,aAAA,EAAe,eAAA;AAAA,EACf,OAAA,EAAS;AACX,CAAA;AAYO,IAAM,cAAA,GAAN,MAAM,eAAA,SAAuB,KAAA,CAAM;AAAA;AAAA,EAE/B,IAAA;AAAA;AAAA,EAEA,MAAA;AAAA,EACA,OAAA;AAAA;AAAA,EAEA,iBAAA;AAAA,EAET,YACE,IAAA,EACA,OAAA,EACA,MAAA,EACA,OAAA,GAAiC,EAAC,EAClC;AACA,IAAA,KAAA,CAAM,OAAA,EAAS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,OAAA,CAAQ,GAAA,CAAI,eAAA,IAAmB,EAAA;AAExH,EAAA,IAAI,CAAC,MAAA,IAAU,CAAC,OAAA,EAAS;AACvB,IAAA,OAAA,CAAQ,MAAA,CAAO,KAAA;AAAA,MACb;AAAA,KACF;AACA,IAAA,OAAA,CAAQ,QAAA,GAAW,CAAA;AACnB,IAAA;AAAA,EACF;AAEA,EAAA,MAAM,MAAA,GAAS,MAAM,SAAA,CAAU;AAAA,IAC7B,MAAA;AAAA,IACA,OAAA;AAAA,IACA,QAAQ,OAAO,IAAA,CAAK,MAAA,KAAW,QAAA,GAAW,KAAK,MAAA,GAAS,MAAA;AAAA,IACxD,YAAA,EAAc,IAAA,CAAK,gBAAgB,CAAA,KAAM;AAAA,GAC1C,CAAA;AAED,EAAA,OAAA,CAAQ,MAAA,CAAO,KAAA,CAAM,IAAA,CAAK,IAAA,KAAS,IAAA,GAAO,CAAA,EAAG,IAAA,CAAK,SAAA,CAAU,MAAA,EAAQ,IAAA,EAAM,CAAC,CAAC;AAAA,CAAA,GAAO,MAAA,CAAO,MAAM,CAAC,CAAA;AACjG,EAAA,IAAI,CAAC,MAAA,CAAO,EAAA,EAAI,OAAA,CAAQ,QAAA,GAAW,CAAA;AACrC;AAEA,IAAA,EAAK,CAAE,KAAA,CAAM,CAAC,CAAA,KAAe;AAC3B,EAAA,OAAA,CAAQ,MAAA,CAAO,MAAM,CAAA,uBAAA,EAA0B,CAAA,YAAa,QAAQ,CAAA,CAAE,OAAA,GAAU,MAAA,CAAO,CAAC,CAAC;AAAA,CAAI,CAAA;AAC7F,EAAA,OAAA,CAAQ,QAAA,GAAW,CAAA;AACrB,CAAC,CAAA","file":"cli.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 PASSWORD_TOO_WEAK: \"PASSWORD_TOO_WEAK\",\n CURRENT_PASSWORD_INCORRECT: \"CURRENT_PASSWORD_INCORRECT\",\n CURRENT_PASSWORD_REQUIRED: \"CURRENT_PASSWORD_REQUIRED\",\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 BILLING_PORTAL_UNAVAILABLE: \"BILLING_PORTAL_UNAVAILABLE\",\n RETURN_URL_NOT_ALLOWED: \"RETURN_URL_NOT_ALLOWED\",\n CONFLICT_RETRY: \"CONFLICT_RETRY\",\n CHECKOUT_EXPIRED: \"CHECKOUT_EXPIRED\",\n // Client-side\n ROUTE_NOT_FOUND: \"ROUTE_NOT_FOUND\",\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 details?: Record<string, string | number | boolean>;\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 readonly details?: Record<string, string | number | boolean>;\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.details = options.details;\n this.retryAfterSeconds = options.retryAfterSeconds;\n // Restore prototype chain for instanceof across transpile targets.\n Object.setPrototypeOf(this, BowlosApiError.prototype);\n }\n\n /** Typed additive createAnonymousBooking slot-full details, when present. */\n get slotFullDetails(): import(\"./route-types\").SlotFullDetails | undefined {\n const d = this.details;\n return this.code === \"VALIDATION_FAILED\" &&\n d?.reason === \"slot_full\" &&\n typeof d.waitlistAvailable === \"boolean\" &&\n typeof d.requested === \"number\" &&\n typeof d.available === \"number\"\n ? (d as import(\"./route-types\").SlotFullDetails)\n : undefined;\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; details?: unknown };\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 (\n isConfigErrorCode(code) ||\n code === BOWLOS_ERROR_CODES.CURRENT_PASSWORD_INCORRECT ||\n code === BOWLOS_ERROR_CODES.CURRENT_PASSWORD_REQUIRED\n )\n 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 {\n details: errorDetails(env.error?.details),\n retryAfterSeconds: code === BOWLOS_ERROR_CODES.RATE_LIMITED ? retryAfterSeconds : undefined,\n },\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 = {\n ok: false,\n error: {\n code:\n res.status === 404 ? BOWLOS_ERROR_CODES.ROUTE_NOT_FOUND : BOWLOS_ERROR_CODES.UNKNOWN,\n message: text.slice(0, 200),\n },\n };\n }\n }\n if (!text && res.status === 404) {\n body = { ok: false, error: { code: BOWLOS_ERROR_CODES.ROUTE_NOT_FOUND } };\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; details?: unknown };\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 { details: errorDetails(inner.error?.details) },\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 // Password verification failures must never refresh or discard the session,\n // including legacy gateways that return INVALID_CREDENTIALS with HTTP 401.\n if (\n name !== \"changeMyPassword\" &&\n auth &&\n !retried &&\n this.store.get() &&\n looksLikeExpiredSession(status, code)\n ) {\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 details: errorDetails(env.error?.details),\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 /**\n * Atomic sign-up (preferred): create the login AND the brand-scoped customer\n * profile in ONE server call, then store the session. Use this instead of\n * `signUp()` + `link()` — the two-step path can strand a login with no\n * customer profile if `link()` is missed or races the new session.\n */\n async register(\n email: string,\n password: string,\n profile: Omit<LinkProfile, \"email\">,\n ): Promise<Tokens> {\n const { tokens } = await this.call<{ tokens: Tokens }>(\"auth/register\", {\n email,\n password,\n ...profile,\n });\n this.store.set(tokens);\n return tokens;\n }\n\n /** Low-level: create a login only (no customer profile). Prefer `register()`;\n * if you use this you MUST follow with `link()` or the customer is orphaned. */\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 /**\n * Forgot-password step 1: email a reset code to the address (if it has an\n * account at this center). Resolves regardless of whether the email exists —\n * the server never reveals that, to prevent account enumeration. No session\n * needed.\n */\n async requestPasswordReset(email: string): Promise<void> {\n await this.call(\"auth/request-reset\", { email });\n }\n\n /**\n * Forgot-password step 2: verify the emailed code + set a new password. On\n * success the customer is signed in (the session is stored), so the UI can\n * continue straight into the funnel. Throws `INVALID_RESET` on a bad/expired\n * code and `PASSWORD_TOO_WEAK` if the new password fails the policy.\n */\n async resetPassword(\n email: string,\n code: string,\n newPassword: string,\n ): Promise<Tokens> {\n const { tokens } = await this.call<{ tokens: Tokens }>(\"auth/reset\", {\n email,\n code,\n newPassword,\n });\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\nfunction errorDetails(value: unknown): Record<string, string | number | boolean> | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n const entries = Object.entries(value).filter(\n ([, v]) =>\n typeof v === \"string\" ||\n typeof v === \"boolean\" ||\n (typeof v === \"number\" && Number.isFinite(v)),\n );\n return entries.length ? Object.fromEntries(entries) : undefined;\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","/// <reference types=\"node\" />\n/**\n * `bowlos init` — scaffolds a ready-to-run BowlOS center site into a new folder,\n * so a builder gets the full starter (the same one in `examples/center-site`)\n * without needing the BowlOS monorepo. The starter files ship in the package's\n * `templates/center-site/` (generated from the canonical example at build time);\n * this just copies them out and restores the `.gitignore`.\n */\nimport { cpSync, existsSync, mkdirSync, readdirSync, renameSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\n\nexport interface InitOptions {\n /** Where to scaffold (created if missing). */\n targetDir: string;\n /** Absolute path to the shipped `templates/center-site` dir. */\n templatesDir: string;\n /** Scaffold into a non-empty directory anyway. */\n force?: boolean;\n}\n\nexport type InitCode = \"ok\" | \"template_missing\" | \"dir_not_empty\";\n\nexport interface InitResult {\n ok: boolean;\n code: InitCode;\n targetDir: string;\n message: string;\n}\n\n/** Copy the starter template into `targetDir`. Pure file I/O — the CLI handles\n * arg parsing + the next-steps message; tests drive this directly. */\nexport function runInit(opts: InitOptions): InitResult {\n const target = resolve(opts.targetDir);\n\n if (!existsSync(opts.templatesDir)) {\n return {\n ok: false,\n code: \"template_missing\",\n targetDir: target,\n message: `Starter template not found (${opts.templatesDir}). This @bowlos/reservations build is missing its templates/ — try reinstalling.`,\n };\n }\n\n if (existsSync(target) && readdirSync(target).length > 0 && !opts.force) {\n return {\n ok: false,\n code: \"dir_not_empty\",\n targetDir: target,\n message: `Directory is not empty: ${target}. Pick an empty directory or pass --force.`,\n };\n }\n\n mkdirSync(target, { recursive: true });\n cpSync(opts.templatesDir, target, { recursive: true });\n\n // The template ships its ignore file as `gitignore` (npm strips a literal\n // `.gitignore` from tarballs); restore the dot in the scaffolded project.\n const shipped = join(target, \"gitignore\");\n if (existsSync(shipped) && !existsSync(join(target, \".gitignore\"))) {\n renameSync(shipped, join(target, \".gitignore\"));\n }\n\n return { ok: true, code: \"ok\", targetDir: target, message: \"scaffolded\" };\n}\n","#!/usr/bin/env node\n/// <reference types=\"node\" />\n/**\n * `bowlos` CLI. Two commands:\n * - `bowlos init [dir]` — scaffold a ready-to-run center site into `dir`.\n * - `bowlos doctor` — validate a site's @bowlos/reservations setup against a\n * gateway + API key and print a readiness report.\n * Reads flags or env vars; exits non-zero on failure (so it drops into CI / a\n * setup script). Dependency-free argv parsing.\n */\nimport { join } from \"node:path\";\nimport { runDoctor, type DoctorCheck, type DoctorReport } from \"./doctor\";\nimport { runInit } from \"./init\";\n\ntype ParsedArgs = { _command?: string } & Record<string, string | boolean>;\n\nfunction parseArgs(argv: string[]): ParsedArgs {\n const out: ParsedArgs = {};\n for (let i = 0; i < argv.length; i++) {\n const a = argv[i];\n if (a === undefined) continue;\n if (a.startsWith(\"--\")) {\n const key = a.slice(2);\n const next = argv[i + 1];\n if (next !== undefined && !next.startsWith(\"--\")) {\n out[key] = next;\n i++;\n } else {\n out[key] = true;\n }\n } else if (out._command === undefined) {\n out._command = a;\n } else if (out[\"_target\"] === undefined) {\n out[\"_target\"] = a; // second positional (e.g. `init <dir>`)\n }\n }\n return out;\n}\n\nconst ICON: Record<DoctorCheck[\"status\"], string> = {\n pass: \"✓\", // ✓\n warn: \"⚠\", // ⚠\n fail: \"✗\", // ✗\n skip: \"·\", // ·\n};\n\nfunction render(report: DoctorReport): string {\n const lines: string[] = [\"\", `bowlos doctor — ${report.baseUrl}`];\n if (report.brandId) lines.push(`brand ${report.brandId} · mode ${report.mode}`);\n lines.push(\"\");\n for (const c of report.checks) {\n lines.push(` ${ICON[c.status]} ${c.title}: ${c.detail}`);\n if (c.fix && c.status !== \"pass\") lines.push(` → ${c.fix}`);\n }\n const fails = report.checks.filter((c) => c.status === \"fail\").length;\n const warns = report.checks.filter((c) => c.status === \"warn\").length;\n lines.push(\n \"\",\n report.ok\n ? warns > 0\n ? `Ready, with ${warns} warning(s).`\n : \"All checks passed — ready.\"\n : `${fails} check(s) failed — not ready.`,\n \"\",\n );\n return lines.join(\"\\n\");\n}\n\nconst HELP = [\n \"Usage: bowlos <command> [options]\",\n \"\",\n \"Commands:\",\n \" init [dir] Scaffold a ready-to-run center site (default dir: bowlos-center-site)\",\n \" doctor Validate a @bowlos/reservations setup against the gateway + API key\",\n \"\",\n \"init options:\",\n \" --force Scaffold into a non-empty directory\",\n \"\",\n \"doctor options:\",\n \" --api-key <key> Brand API key (or env BOWLOS_API_KEY)\",\n \" --base-url <url> Gateway base URL (or env BOWLOS_BASE_URL)\",\n \" --origin <url> Your deployed site origin (informs the allow-list note)\",\n \" --skip-data-read Skip the anonymous data-plane read\",\n \" --json Print the raw JSON report instead of the table\",\n \"\",\n \" --help Show this help\",\n \"\",\n].join(\"\\n\");\n\nfunction initNextSteps(absDir: string, displayDir: string): string {\n return [\n \"\",\n `✓ Scaffolded a BowlOS center site → ${absDir}`,\n \"\",\n \"Complete site build guide: node_modules/@bowlos/reservations/AGENTS.md\",\n \"\",\n \"Next steps:\",\n ` cd ${displayDir}`,\n \" npm install\",\n \" cp env.example .env.local # then fill in your API key + brand/center/product IDs\",\n \" npm run dev # http://localhost:3000\",\n \"\",\n \"Verify the wiring any time:\",\n ' npx bowlos doctor --api-key \"$NEXT_PUBLIC_BOWLOS_API_KEY\" --base-url \"$NEXT_PUBLIC_BOWLOS_BASE_URL\"',\n \"\",\n \"What you got: /book (headless hooks) + /account and /flash/[slug] (themeable\",\n \"components) — a working reference for both build styles. Keep what fits, swap the\",\n \"rest. See the BowlOS center-website team runbook.\",\n \"\",\n ].join(\"\\n\");\n}\n\nasync function main(): Promise<void> {\n const args = parseArgs(process.argv.slice(2));\n const command = args._command ?? \"doctor\";\n\n if (args.help === true || command === \"help\") {\n process.stdout.write(`${HELP}\\n`);\n return;\n }\n\n if (command === \"init\") {\n const target = typeof args[\"_target\"] === \"string\" ? args[\"_target\"] : \"bowlos-center-site\";\n // The bin runs from dist/cli.cjs; the starter ships at <pkg>/templates/center-site.\n const templatesDir = join(__dirname, \"..\", \"templates\", \"center-site\");\n const result = runInit({ targetDir: target, templatesDir, force: args.force === true });\n if (!result.ok) {\n process.stderr.write(`bowlos init: ${result.message}\\n`);\n process.exitCode = 1;\n return;\n }\n process.stdout.write(initNextSteps(result.targetDir, target));\n return;\n }\n\n if (command !== \"doctor\") {\n process.stderr.write(`Unknown command \"${command}\". Try: bowlos --help\\n`);\n process.exitCode = 1;\n return;\n }\n\n const apiKey = (typeof args[\"api-key\"] === \"string\" ? args[\"api-key\"] : undefined) ?? process.env.BOWLOS_API_KEY ?? \"\";\n const baseUrl = (typeof args[\"base-url\"] === \"string\" ? args[\"base-url\"] : undefined) ?? process.env.BOWLOS_BASE_URL ?? \"\";\n\n if (!apiKey || !baseUrl) {\n process.stderr.write(\n \"Missing --api-key / --base-url (or BOWLOS_API_KEY / BOWLOS_BASE_URL).\\nRun `bowlos doctor --help`.\\n\",\n );\n process.exitCode = 1;\n return;\n }\n\n const report = await runDoctor({\n apiKey,\n baseUrl,\n origin: typeof args.origin === \"string\" ? args.origin : undefined,\n skipDataRead: args[\"skip-data-read\"] === true,\n });\n\n process.stdout.write(args.json === true ? `${JSON.stringify(report, null, 2)}\\n` : render(report));\n if (!report.ok) process.exitCode = 1;\n}\n\nmain().catch((e: unknown) => {\n process.stderr.write(`bowlos doctor crashed: ${e instanceof Error ? e.message : String(e)}\\n`);\n process.exitCode = 1;\n});\n"]}
|