@openrails/billing-ui 0.253.0 → 0.254.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/admin/lib/api/types.d.ts +1 -1
  2. package/dist/admin/messages.d.ts +10 -0
  3. package/dist/{admin-catalog-Bsxo2gyS.js → admin-catalog-rrFZd5N8.js} +2 -2
  4. package/dist/{admin-catalog-Bsxo2gyS.js.map → admin-catalog-rrFZd5N8.js.map} +1 -1
  5. package/dist/{admin-price-detail-ByCmrx_W.js → admin-price-detail-Bwk9PXHP.js} +2 -2
  6. package/dist/{admin-price-detail-ByCmrx_W.js.map → admin-price-detail-Bwk9PXHP.js.map} +1 -1
  7. package/dist/{admin-price-wizard-m7Qjhq6W.js → admin-price-wizard-ByD7j8mB.js} +2 -2
  8. package/dist/admin-price-wizard-ByD7j8mB.js.map +1 -0
  9. package/dist/{admin-settings-BIUgvclv.js → admin-settings-D_8L1Hho.js} +101 -76
  10. package/dist/admin-settings-D_8L1Hho.js.map +1 -0
  11. package/dist/admin.js +15 -5
  12. package/dist/admin.js.map +1 -1
  13. package/dist/client/generated/error-codes.d.ts +1 -1
  14. package/dist/client/generated/wire.d.ts +51 -20
  15. package/dist/{client-Di2a3HGM.js → client-B301IAQD.js} +3 -3
  16. package/dist/client-B301IAQD.js.map +1 -0
  17. package/dist/client.js +1 -1
  18. package/dist/components/platform-card-form.d.ts +3 -1
  19. package/dist/{hooks-Bx0aLyvy.js → hooks-DARbMTwv.js} +69 -59
  20. package/dist/hooks-DARbMTwv.js.map +1 -0
  21. package/dist/index.js +302 -270
  22. package/dist/index.js.map +1 -1
  23. package/dist/locales/de.js +1 -0
  24. package/dist/locales/de.js.map +1 -1
  25. package/dist/locales/en.d.ts +1 -0
  26. package/dist/locales/en.js +1 -0
  27. package/dist/locales/en.js.map +1 -1
  28. package/dist/locales/es.js +1 -0
  29. package/dist/locales/es.js.map +1 -1
  30. package/dist/locales/ja.js +1 -0
  31. package/dist/locales/ja.js.map +1 -1
  32. package/dist/locales/ko.js +1 -0
  33. package/dist/locales/ko.js.map +1 -1
  34. package/dist/locales/zh.js +1 -0
  35. package/dist/locales/zh.js.map +1 -1
  36. package/dist/psp.d.ts +1 -1
  37. package/dist/react.js +1 -1
  38. package/package.json +1 -1
  39. package/dist/admin-price-wizard-m7Qjhq6W.js.map +0 -1
  40. package/dist/admin-settings-BIUgvclv.js.map +0 -1
  41. package/dist/client-Di2a3HGM.js.map +0 -1
  42. package/dist/hooks-Bx0aLyvy.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"admin-settings-BIUgvclv.js","names":[],"sources":["../src/admin/pages/settings/configuration-edit.ts","../src/admin/pages/settings/setting-fields.tsx","../src/admin/pages/settings/notifications.tsx","../src/admin/pages/settings/index.tsx"],"sourcesContent":["import { useAdminServices } from \"#orck/admin/context\"\nimport * as React from \"react\"\nimport { useMutation, useQueryClient } from \"@tanstack/react-query\"\n\nimport { ApiError } from \"#orck/admin/lib/api/client\"\nimport type {\n MerchantConfigurationState,\n UpdateMerchantConfigurationParams,\n} from \"#orck/client/generated/wire\"\n\ntype Change = Omit<UpdateMerchantConfigurationParams, \"expected_revision\">\n\n// useConfigurationEdit edits the merchant's configuration at the revision it\n// held when the edit opened, so a change made since is refused instead of\n// overwritten; a refused edit closes and the configuration reloads.\nexport function useConfigurationEdit(\n configuration: MerchantConfigurationState | undefined\n) {\n const { toast, toastApiError, toastStaleEdit, adminMutations } =\n useAdminServices()\n\n const [revision, setRevision] = React.useState<number | null>(null)\n const queryClient = useQueryClient()\n const update = useMutation(\n adminMutations.updateMerchantConfiguration(queryClient)\n )\n return {\n editing: revision !== null,\n open: () => {\n if (configuration) setRevision(configuration.revision)\n },\n close: () => setRevision(null),\n save: async (change: Change, saved: string, action: string) => {\n if (revision === null) return\n try {\n await update.mutateAsync({ ...change, expected_revision: revision })\n toast.success(saved)\n setRevision(null)\n } catch (err) {\n if (err instanceof ApiError && err.revisionMismatch) {\n toastStaleEdit(\"The configuration\")\n setRevision(null)\n return\n }\n toastApiError(err, action)\n if (err instanceof ApiError && err.merchantConfigReadOnly)\n setRevision(null)\n }\n },\n }\n}\n","import { AdminMessage, useAdminUI } from \"#orck/admin/ui-context\"\nimport { useAdminServices } from \"#orck/admin/context\"\nimport * as React from \"react\"\nimport { useQuery } from \"@tanstack/react-query\"\n\nimport { Button } from \"#orck/admin/components/ui/button\"\nimport { Label } from \"#orck/admin/components/ui/label\"\n\n// ReadOnlyNotice explains the missing edit controls when the merchant's\n// configuration comes from a file.\nexport function ReadOnlyNotice() {\n const { adminQueries } = useAdminServices()\n\n const { data } = useQuery(adminQueries.config())\n if (!data || data.capabilities.features?.merchant_config_edits) return null\n return (\n <p className=\"rounded-md border px-3 py-2 text-sm text-muted-foreground\">\n <AdminMessage\n id={\n \"Read-only: this merchant's configuration comes from a file. Change it there.\"\n }\n />\n </p>\n )\n}\n\n// EditActions is a section's Edit button, or Cancel and Save while editing.\n// Without edits it renders nothing.\nexport function EditActions({\n edits,\n editing,\n form,\n saving,\n canSave = true,\n onEdit,\n onCancel,\n}: {\n edits: boolean\n editing: boolean\n form: string\n saving: boolean\n canSave?: boolean\n onEdit: () => void\n onCancel: () => void\n}) {\n if (!edits) return null\n if (!editing)\n return (\n <Button type=\"button\" variant=\"outline\" size=\"sm\" onClick={onEdit}>\n <AdminMessage id={\"Edit\"} />\n </Button>\n )\n return (\n <div className=\"flex items-center gap-2\">\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n disabled={saving}\n onClick={onCancel}\n >\n <AdminMessage id={\"Cancel\"} />\n </Button>\n <Button type=\"submit\" size=\"sm\" form={form} disabled={!canSave || saving}>\n {saving ? \"Saving…\" : \"Save\"}\n </Button>\n </div>\n )\n}\n\nexport function SettingDetail({\n label,\n value,\n}: {\n label: string\n value?: string\n}) {\n return (\n <div className=\"grid gap-1.5 md:grid-cols-[11rem_minmax(0,1fr)] md:gap-6\">\n <dt className=\"text-sm text-muted-foreground\">{label}</dt>\n <dd\n className={\n value\n ? \"min-w-0 text-sm break-words\"\n : \"text-sm text-muted-foreground\"\n }\n >\n {value || \"Not set\"}\n </dd>\n </div>\n )\n}\n\nexport function SettingEditField({\n label,\n id,\n children,\n}: {\n label: string\n id: string\n children: React.ReactNode\n}) {\n const { id: adminId } = useAdminUI()\n\n return (\n <div className=\"grid gap-2 md:grid-cols-[11rem_minmax(0,1fr)] md:items-center md:gap-6\">\n <Label htmlFor={adminId(id)}>{label}</Label>\n <div className=\"min-w-0\">{children}</div>\n </div>\n )\n}\n","import { AdminMessage, useAdminUI } from \"#orck/admin/ui-context\"\nimport { useAdminServices } from \"#orck/admin/context\"\nimport { HugeiconsIcon } from \"@hugeicons/react\"\nimport { Add01Icon, Delete02Icon } from \"@hugeicons/core-free-icons\"\nimport * as React from \"react\"\n\nimport { useForm } from \"@tanstack/react-form\"\nimport { useMutation, useQuery, useQueryClient } from \"@tanstack/react-query\"\n\nimport { FormFieldErrors } from \"#orck/admin/components/form-field-errors\"\nimport { TypedConfirmDialog } from \"#orck/admin/components/typed-confirm-dialog\"\nimport { Badge } from \"#orck/admin/components/ui/badge\"\nimport { Button } from \"#orck/admin/components/ui/button\"\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n DialogTrigger,\n} from \"#orck/admin/components/ui/dialog\"\nimport { Input } from \"#orck/admin/components/ui/input\"\nimport { Label } from \"#orck/admin/components/ui/label\"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from \"#orck/admin/components/ui/select\"\nimport {\n Table,\n TableBody,\n TableCell,\n TableHead,\n TableHeader,\n TableRow,\n} from \"#orck/admin/components/ui/table\"\nimport { Switch } from \"#orck/admin/components/ui/switch\"\nimport { DIALOG_FORM } from \"#orck/admin/lib/dialog-width\"\nimport type {\n AlertWebhook,\n MerchantConfigurationState,\n} from \"#orck/client/generated/wire\"\nimport { useMerchantConfigEdits } from \"#orck/admin/lib/capabilities\"\n\nimport { useConfigurationEdit } from \"./configuration-edit\"\nimport {\n EditActions,\n ReadOnlyNotice,\n SettingDetail,\n SettingEditField,\n} from \"./setting-fields\"\n\ntype WebhookFormat = AlertWebhook[\"format\"]\n\n// --- Page ------------------------------------------------------------------\n\nexport function NotificationsTab() {\n const { adminQueries } = useAdminServices()\n\n const configurationQuery = useQuery(\n adminQueries.merchantConfiguration(\"Load settings\")\n )\n const webhooksQuery = useQuery(adminQueries.webhooks())\n const edits = useMerchantConfigEdits()\n\n const hooks = webhooksQuery.data?.data ?? []\n\n return (\n <div className=\"flex flex-col gap-10\">\n <ReadOnlyNotice />\n {configurationQuery.data ? (\n <NotificationEmailSection\n configuration={configurationQuery.data}\n edits={edits}\n />\n ) : (\n <p className=\"text-sm text-muted-foreground\">\n <AdminMessage id={\"Loading…\"} />\n </p>\n )}\n <WebhooksSection\n webhooks={hooks}\n loading={webhooksQuery.isPending}\n edits={edits}\n />\n </div>\n )\n}\n\n// --- Alert email -----------------------------------------------------------\n\nfunction NotificationEmailSection({\n configuration,\n edits,\n}: {\n configuration: MerchantConfigurationState\n edits: boolean\n}) {\n const { id: adminId, text: adminText } = useAdminUI()\n\n const email = configuration.settings.alert_email ?? \"\"\n const edit = useConfigurationEdit(configuration)\n const form = useForm({\n defaultValues: { email },\n // An empty address clears the email channel.\n onSubmit: ({ value }) =>\n edit.save(\n { settings: { alert_email: value.email.trim() } },\n value.email.trim() ? \"Alert email saved\" : \"Alert email cleared\",\n \"Save alert email\"\n ),\n })\n\n return (\n <section className=\"grid gap-5\">\n <div className=\"flex flex-wrap items-start justify-between gap-4\">\n <div className=\"grid gap-1\">\n <h2 className=\"text-base font-semibold\">\n <AdminMessage id={\"Email delivery\"} />\n </h2>\n <p className=\"text-sm text-muted-foreground\">\n <AdminMessage id={\"Send email alerts to this address.\"} />\n </p>\n </div>\n <form.Subscribe selector={(state) => state.isSubmitting}>\n {(isSubmitting) => (\n <EditActions\n edits={edits}\n editing={edit.editing}\n form=\"alert-email-form\"\n saving={isSubmitting}\n onEdit={() => {\n form.reset({ email })\n edit.open()\n }}\n onCancel={edit.close}\n />\n )}\n </form.Subscribe>\n </div>\n {edit.editing ? (\n <form\n id={adminId(\"alert-email-form\")}\n onSubmit={(event) => {\n event.preventDefault()\n event.stopPropagation()\n void form.handleSubmit()\n }}\n >\n <form.Field name=\"email\">\n {(field) => (\n <SettingEditField\n label={adminText(\"Alert email\")}\n id={\"alert-email\"}\n >\n <Input\n id={adminId(\"alert-email\")}\n type=\"email\"\n placeholder={adminText(\"alerts@example.com\")}\n value={field.state.value}\n onBlur={field.handleBlur}\n onChange={(event) => field.handleChange(event.target.value)}\n />\n </SettingEditField>\n )}\n </form.Field>\n </form>\n ) : (\n <dl>\n <SettingDetail label={adminText(\"Alert email\")} value={email} />\n </dl>\n )}\n </section>\n )\n}\n\n// --- Webhooks --------------------------------------------------------------\n\nconst WEBHOOK_FORMATS: { value: WebhookFormat; label: string }[] = [\n { value: \"generic\", label: \"Generic (your own receiver)\" },\n { value: \"discord\", label: \"Discord\" },\n { value: \"slack\", label: \"Slack\" },\n]\n\nfunction WebhooksSection({\n webhooks,\n loading,\n edits,\n}: {\n webhooks: AlertWebhook[]\n loading: boolean\n edits: boolean\n}) {\n return (\n <section className=\"grid gap-5\">\n <div className=\"flex flex-wrap items-start justify-between gap-4\">\n <div className=\"grid max-w-2xl gap-1\">\n <h2 className=\"text-base font-semibold\">\n <AdminMessage id={\"Webhooks\"} />\n </h2>\n <p className=\"text-sm text-pretty text-muted-foreground\">\n <AdminMessage\n id={\"Send alerts to Discord, Slack, or your own endpoint.\"}\n />\n </p>\n </div>\n {edits && <WebhookDialog />}\n </div>\n {loading ? (\n <p className=\"text-sm text-muted-foreground\">\n <AdminMessage id={\"Loading…\"} />\n </p>\n ) : webhooks.length === 0 ? (\n <p className=\"py-2 text-sm text-muted-foreground\">\n <AdminMessage id={\"No webhooks configured.\"} />\n </p>\n ) : (\n <Table className=\"min-w-[36rem]\">\n <TableHeader>\n <TableRow className=\"hover:bg-transparent\">\n <TableHead className=\"text-muted-foreground\">\n <AdminMessage id={\"Name\"} />\n </TableHead>\n <TableHead className=\"text-muted-foreground\">\n <AdminMessage id={\"Format\"} />\n </TableHead>\n <TableHead className=\"text-muted-foreground\">URL</TableHead>\n {edits && (\n <TableHead className=\"text-right text-muted-foreground\">\n <AdminMessage id={\"Action\"} />\n </TableHead>\n )}\n </TableRow>\n </TableHeader>\n <TableBody>\n {webhooks.map((w) => (\n <WebhookRow key={w.id} webhook={w} edits={edits} />\n ))}\n </TableBody>\n </Table>\n )}\n </section>\n )\n}\n\nfunction WebhookRow({\n webhook,\n edits,\n}: {\n webhook: AlertWebhook\n edits: boolean\n}) {\n const { toast, toastApiError, adminMutations } = useAdminServices()\n\n const { text: adminText } = useAdminUI()\n\n const [confirmOpen, setConfirmOpen] = React.useState(false)\n const queryClient = useQueryClient()\n const removeWebhook = useMutation(adminMutations.deleteWebhook(queryClient))\n const name = webhook.name ?? webhook.destination_host\n return (\n <TableRow className={webhook.enabled ? undefined : \"opacity-60\"}>\n <TableCell className=\"py-3 font-medium\">{name}</TableCell>\n <TableCell className=\"py-3\">\n <span className=\"flex flex-wrap gap-1\">\n <Badge variant=\"secondary\">{webhook.format}</Badge>\n {!webhook.enabled && (\n <Badge variant=\"outline\">\n <AdminMessage id={\"disabled\"} />\n </Badge>\n )}\n </span>\n </TableCell>\n <TableCell\n className=\"max-w-[22rem] truncate py-3 text-xs text-muted-foreground\"\n title={webhook.destination_host}\n >\n {webhook.destination_host}\n </TableCell>\n {edits && (\n <TableCell className=\"py-3 text-right\">\n <div className=\"flex justify-end gap-1\">\n <WebhookDialog webhook={webhook} />\n <Button\n variant=\"ghost\"\n size=\"icon\"\n aria-label={adminText(\"Delete webhook\")}\n onClick={() => setConfirmOpen(true)}\n >\n <HugeiconsIcon\n icon={Delete02Icon}\n className=\"size-4 text-muted-foreground\"\n />\n </Button>\n <TypedConfirmDialog\n open={confirmOpen}\n onOpenChange={setConfirmOpen}\n title={`Delete \"${name}\"?`}\n description={adminText(\n \"Operational notifications will stop delivering to this webhook. This cannot be undone.\"\n )}\n confirmationWord=\"DELETE\"\n actionLabel=\"Delete webhook\"\n onConfirm={async () => {\n try {\n await removeWebhook.mutateAsync(webhook.id)\n toast.success(\"Webhook deleted\")\n } catch (err) {\n toastApiError(err, \"Delete webhook\")\n }\n }}\n />\n </div>\n </TableCell>\n )}\n </TableRow>\n )\n}\n\n// WebhookDialog adds a webhook or edits one. The URL carries the receiver's\n// secret, so it is write-only: an edit leaves it blank to keep it.\nfunction WebhookDialog({ webhook }: { webhook?: AlertWebhook }) {\n const { toast, toastApiError, adminMutations } = useAdminServices()\n\n const { id: adminId, text: adminText } = useAdminUI()\n\n const [open, setOpen] = React.useState(false)\n const queryClient = useQueryClient()\n const addWebhook = useMutation(adminMutations.createWebhook(queryClient))\n const updateWebhook = useMutation(adminMutations.updateWebhook(queryClient))\n const initial = () => ({\n name: webhook?.name ?? \"\",\n url: \"\",\n format: webhook?.format ?? (\"generic\" as WebhookFormat),\n enabled: webhook?.enabled ?? true,\n })\n const form = useForm({\n defaultValues: initial(),\n onSubmit: async ({ value }) => {\n const url = value.url.trim()\n try {\n if (webhook)\n await updateWebhook.mutateAsync({\n id: webhook.id,\n webhook: {\n name: value.name.trim() || null,\n format: value.format,\n enabled: value.enabled,\n ...(url ? { url } : {}),\n },\n })\n else\n await addWebhook.mutateAsync({\n name: value.name.trim(),\n url,\n format: value.format,\n })\n toast.success(webhook ? \"Webhook saved\" : \"Webhook added\")\n handleOpen(false)\n } catch (err) {\n toastApiError(err, webhook ? \"Save webhook\" : \"Add webhook\")\n }\n },\n })\n\n const handleOpen = (next: boolean) => {\n if (next) form.reset(initial())\n else form.reset()\n setOpen(next)\n }\n\n return (\n <Dialog open={open} onOpenChange={handleOpen}>\n <DialogTrigger\n render={\n <Button size=\"sm\" variant=\"outline\">\n {!webhook && <HugeiconsIcon icon={Add01Icon} className=\"size-4\" />}{\" \"}\n {webhook ? \"Edit\" : \"Add webhook\"}\n </Button>\n }\n />\n <DialogContent className={DIALOG_FORM}>\n <DialogHeader>\n <DialogTitle>\n {webhook\n ? `Edit ${webhook.name ?? webhook.destination_host}`\n : \"Add webhook\"}\n </DialogTitle>\n <DialogDescription>\n {webhook\n ? \"The current URL is never shown. Paste a new one to replace it, or leave it blank to keep it.\"\n : \"Paste a webhook address from Discord, Slack, or your own alert receiver.\"}\n </DialogDescription>\n </DialogHeader>\n <form\n onSubmit={(event) => {\n event.preventDefault()\n event.stopPropagation()\n void form.handleSubmit()\n }}\n className=\"grid gap-4\"\n >\n <div className=\"grid gap-3\">\n <form.Field\n name=\"name\"\n validators={{\n onChange: ({ value }) =>\n webhook || value.trim() ? undefined : \"Enter a webhook name\",\n }}\n >\n {(field) => (\n <div className=\"grid gap-1.5\">\n <Label htmlFor={adminId(\"wh-name\")}>\n <AdminMessage id={\"Name\"} />\n </Label>\n <Input\n id={adminId(\"wh-name\")}\n placeholder={adminText(\"e.g. #billing-alerts\")}\n value={field.state.value}\n onBlur={field.handleBlur}\n onChange={(event) => field.handleChange(event.target.value)}\n aria-invalid={field.state.meta.errors.length > 0}\n />\n <FormFieldErrors errors={field.state.meta.errors} />\n </div>\n )}\n </form.Field>\n <form.Field name=\"format\">\n {(field) => (\n <div className=\"grid gap-1.5\">\n <Label htmlFor={adminId(\"wh-format\")}>\n <AdminMessage id={\"Format\"} />\n </Label>\n <Select\n value={field.state.value}\n onValueChange={(value) =>\n field.handleChange(value as WebhookFormat)\n }\n >\n <SelectTrigger id={adminId(\"wh-format\")} className=\"w-full\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {WEBHOOK_FORMATS.map((format) => (\n <SelectItem key={format.value} value={format.value}>\n {format.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n )}\n </form.Field>\n <form.Field\n name=\"url\"\n validators={{\n onChange: ({ value }) => {\n if (!value.trim())\n return webhook ? undefined : \"Enter a webhook URL\"\n try {\n new URL(value)\n return undefined\n } catch {\n return \"Enter a valid webhook URL\"\n }\n },\n }}\n >\n {(field) => (\n <div className=\"grid gap-1.5\">\n <Label htmlFor={adminId(\"wh-url\")}>\n <AdminMessage id={\"Webhook URL\"} />\n </Label>\n <Input\n id={adminId(\"wh-url\")}\n type=\"url\"\n autoComplete=\"off\"\n className=\"text-xs\"\n placeholder={\n webhook\n ? \"unchanged\"\n : \"https://discord.com/api/webhooks/…\"\n }\n value={field.state.value}\n onBlur={field.handleBlur}\n onChange={(event) => field.handleChange(event.target.value)}\n aria-invalid={field.state.meta.errors.length > 0}\n />\n <FormFieldErrors errors={field.state.meta.errors} />\n </div>\n )}\n </form.Field>\n {webhook && (\n <form.Field name=\"enabled\">\n {(field) => (\n <div className=\"flex items-center gap-2\">\n <Switch\n id={adminId(\"wh-enabled\")}\n checked={field.state.value}\n onCheckedChange={field.handleChange}\n />\n <Label htmlFor={adminId(\"wh-enabled\")}>\n <AdminMessage id={\"Enabled\"} />\n </Label>\n </div>\n )}\n </form.Field>\n )}\n </div>\n <DialogFooter>\n <form.Subscribe\n selector={(state) =>\n [\n state.values.name,\n state.values.url,\n state.isDirty,\n state.canSubmit,\n state.isSubmitting,\n ] as const\n }\n >\n {([name, url, isDirty, canSubmit, isSubmitting]) => (\n <Button\n type=\"submit\"\n disabled={\n (webhook ? !isDirty : !name.trim() || !url.trim()) ||\n !canSubmit ||\n isSubmitting\n }\n >\n {isSubmitting ? \"Saving…\" : webhook ? \"Save\" : \"Add webhook\"}\n </Button>\n )}\n </form.Subscribe>\n </DialogFooter>\n </form>\n </DialogContent>\n </Dialog>\n )\n}\n","import { AdminMessage, useAdminUI } from \"#orck/admin/ui-context\"\nimport { useAdminContext } from \"#orck/admin/context\"\nimport { useAdminServices } from \"#orck/admin/context\"\nimport * as React from \"react\"\nimport { useSearchParams } from \"#orck/admin/router\"\n\nimport { useForm } from \"@tanstack/react-form\"\nimport { useMutation, useQuery, useQueryClient } from \"@tanstack/react-query\"\n\nimport { Badge } from \"#orck/admin/components/ui/badge\"\nimport { TypedConfirmDialog } from \"#orck/admin/components/typed-confirm-dialog\"\nimport { FormFieldErrors } from \"#orck/admin/components/form-field-errors\"\nimport { useConfirm } from \"#orck/admin/lib/confirm\"\nimport { Button } from \"#orck/admin/components/ui/button\"\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n DialogTrigger,\n} from \"#orck/admin/components/ui/dialog\"\nimport { Input } from \"#orck/admin/components/ui/input\"\nimport { Label } from \"#orck/admin/components/ui/label\"\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from \"#orck/admin/components/ui/select\"\nimport {\n Table,\n TableBody,\n TableCell,\n TableHead,\n TableHeader,\n TableRow,\n} from \"#orck/admin/components/ui/table\"\nimport {\n Tabs,\n TabsContent,\n TabsList,\n TabsTrigger,\n} from \"#orck/admin/components/ui/tabs\"\nimport type {\n MerchantConfigurationState,\n PSP,\n PSPCredential,\n RailDefinition,\n} from \"#orck/client/generated/wire\"\nimport {\n amountFromInput,\n currencyScale,\n formatDate,\n formatNativeAmount,\n} from \"#orck/admin/lib/format\"\nimport { DIALOG_FORM } from \"#orck/admin/lib/dialog-width\"\n\nimport { ApiError } from \"#orck/admin/lib/api/client\"\n\nimport {\n settingsTab,\n useAdminArea,\n useAdminUpdates,\n useMerchantConfig,\n useMerchantConfigEdits,\n} from \"#orck/admin/lib/capabilities\"\nimport { useConfigurationEdit } from \"./configuration-edit\"\nimport {\n EditActions,\n ReadOnlyNotice,\n SettingDetail,\n SettingEditField,\n} from \"./setting-fields\"\nimport { NotificationsTab } from \"./notifications\"\n\nconst LINE_TAB =\n \"flex-none px-0 after:bg-primary group-data-horizontal/tabs:after:bottom-[-1px]\"\n\nexport function SettingsPage() {\n // The tab lives in the URL so a settings page can be linked to, and so the\n // back button steps through tabs the way it looks like it should.\n const [params, setParams] = useSearchParams()\n const config = useMerchantConfig()\n const admin = useAdminArea()\n const hosted = useAdminContext().props.settingsTabs ?? []\n const values = hosted.map((h) => h.value)\n const first = settingsTab(null, config, admin, values)\n const tab = settingsTab(params.get(\"tab\"), config, admin, values)\n\n return (\n <Tabs\n value={tab}\n onValueChange={(next) => {\n const updated = new URLSearchParams(params)\n if (!next || next === first) updated.delete(\"tab\")\n else updated.set(\"tab\", next)\n setParams(updated)\n }}\n className=\"flex flex-col gap-4\"\n >\n <div className=\"overflow-x-auto\">\n <TabsList\n variant=\"line\"\n className=\"w-max min-w-full justify-start gap-6 rounded-none p-0\"\n >\n {config && (\n <TabsTrigger value=\"merchant\" className={LINE_TAB}>\n <AdminMessage id={\"Merchant\"} />\n </TabsTrigger>\n )}\n {config && (\n <TabsTrigger value=\"notifications\" className={LINE_TAB}>\n <AdminMessage id={\"Notifications\"} />\n </TabsTrigger>\n )}\n {config && (\n <TabsTrigger value=\"psps\" className={LINE_TAB}>\n <AdminMessage id={\"PSPs\"} />\n </TabsTrigger>\n )}\n {admin && (\n <TabsTrigger value=\"customer-controls\" className={LINE_TAB}>\n <AdminMessage id={\"Customer controls\"} />\n </TabsTrigger>\n )}\n {hosted.map((h) => (\n <TabsTrigger key={h.value} value={h.value} className={LINE_TAB}>\n {h.title}\n </TabsTrigger>\n ))}\n </TabsList>\n </div>\n {config && (\n <TabsContent value=\"merchant\">\n <MerchantSettingsTab />\n </TabsContent>\n )}\n {config && (\n <TabsContent value=\"notifications\">\n <NotificationsTab />\n </TabsContent>\n )}\n {config && (\n <TabsContent value=\"psps\">\n <PSPsTab />\n </TabsContent>\n )}\n {admin && (\n <TabsContent value=\"customer-controls\">\n <CustomerControlsTab />\n </TabsContent>\n )}\n {hosted.map((h) => (\n <TabsContent key={h.value} value={h.value}>\n {h.element}\n </TabsContent>\n ))}\n </Tabs>\n )\n}\n\nexport function MerchantSettingsTab() {\n const { adminQueries } = useAdminServices()\n\n const { data } = useQuery(adminQueries.merchantConfiguration(\"Load settings\"))\n const edits = useMerchantConfigEdits()\n if (!data)\n return (\n <p className=\"text-sm text-muted-foreground\">\n <AdminMessage id={\"Loading…\"} />\n </p>\n )\n return (\n <div className=\"grid gap-10\">\n <ReadOnlyNotice />\n <MerchantProfileForm configuration={data} edits={edits} />\n <RepriceNoticeWindowForm configuration={data} edits={edits} />\n </div>\n )\n}\n\nfunction MerchantProfileForm({\n configuration,\n edits,\n}: {\n configuration: MerchantConfigurationState\n edits: boolean\n}) {\n const { id: adminId, text: adminText } = useAdminUI()\n\n // The merchant's one name is the configuration's display_name.\n const profile = configuration.settings.profile\n const current = () => ({\n displayName: configuration.display_name,\n fromEmail: profile?.from_email ?? \"\",\n supportURL: profile?.support_url ?? \"\",\n subscribeURL: profile?.subscribe_url ?? \"\",\n billingURL: profile?.billing_url ?? \"\",\n logoURL: profile?.logo_url ?? \"\",\n })\n const edit = useConfigurationEdit(configuration)\n const form = useForm({\n defaultValues: current(),\n onSubmit: ({ value }) =>\n edit.save(\n {\n display_name: value.displayName.trim(),\n settings: {\n profile: {\n from_email: value.fromEmail || undefined,\n support_url: value.supportURL || undefined,\n subscribe_url: value.subscribeURL || undefined,\n billing_url: value.billingURL || undefined,\n logo_url: value.logoURL || undefined,\n },\n },\n },\n \"Profile saved\",\n \"Save profile\"\n ),\n })\n\n return (\n <section className=\"grid gap-5\">\n <div className=\"flex flex-wrap items-start justify-between gap-4\">\n <div className=\"grid gap-1\">\n <h2 className=\"text-base font-semibold\">\n <AdminMessage id={\"Merchant profile\"} />\n </h2>\n <p className=\"text-sm text-pretty text-muted-foreground\">\n <AdminMessage\n id={\n \"Customer-facing merchant details used on invoices and emails.\"\n }\n />\n </p>\n </div>\n <form.Subscribe\n selector={(state) => [state.canSubmit, state.isSubmitting]}\n >\n {([canSubmit, isSubmitting]) => (\n <EditActions\n edits={edits}\n editing={edit.editing}\n form=\"merchant-profile-form\"\n saving={isSubmitting}\n canSave={canSubmit}\n onEdit={() => {\n form.reset(current())\n edit.open()\n }}\n onCancel={edit.close}\n />\n )}\n </form.Subscribe>\n </div>\n\n {edit.editing ? (\n <form\n id={adminId(\"merchant-profile-form\")}\n onSubmit={(event) => {\n event.preventDefault()\n event.stopPropagation()\n void form.handleSubmit()\n }}\n className=\"grid gap-4\"\n >\n <form.Field\n name=\"displayName\"\n validators={{\n onChange: ({ value }) =>\n value.trim() ? undefined : \"Enter the merchant's name\",\n }}\n >\n {(field) => (\n <SettingEditField label={adminText(\"Display name\")} id={\"s-name\"}>\n <div className=\"grid gap-1.5\">\n <Input\n id={adminId(\"s-name\")}\n value={field.state.value}\n onBlur={field.handleBlur}\n onChange={(event) => field.handleChange(event.target.value)}\n autoComplete=\"organization\"\n aria-invalid={field.state.meta.errors.length > 0}\n />\n <FormFieldErrors errors={field.state.meta.errors} />\n </div>\n </SettingEditField>\n )}\n </form.Field>\n <form.Field name=\"fromEmail\">\n {(field) => (\n <SettingEditField label={adminText(\"From email\")} id={\"s-email\"}>\n <Input\n id={adminId(\"s-email\")}\n type=\"email\"\n value={field.state.value}\n onBlur={field.handleBlur}\n onChange={(event) => field.handleChange(event.target.value)}\n autoComplete=\"email\"\n />\n </SettingEditField>\n )}\n </form.Field>\n <form.Field name=\"supportURL\">\n {(field) => (\n <SettingEditField\n label={adminText(\"Support URL\")}\n id={\"s-support\"}\n >\n <Input\n id={adminId(\"s-support\")}\n type=\"url\"\n value={field.state.value}\n onBlur={field.handleBlur}\n onChange={(event) => field.handleChange(event.target.value)}\n placeholder={adminText(\"https://example.com/support\")}\n />\n </SettingEditField>\n )}\n </form.Field>\n <form.Field name=\"subscribeURL\">\n {(field) => (\n <SettingEditField\n label={adminText(\"Subscribe URL\")}\n id={\"s-subscribe\"}\n >\n <Input\n id={adminId(\"s-subscribe\")}\n type=\"url\"\n value={field.state.value}\n onBlur={field.handleBlur}\n onChange={(event) => field.handleChange(event.target.value)}\n placeholder={adminText(\"https://example.com/subscribe\")}\n />\n </SettingEditField>\n )}\n </form.Field>\n <form.Field name=\"billingURL\">\n {(field) => (\n <SettingEditField\n label={adminText(\"Billing URL\")}\n id={\"s-billing\"}\n >\n <Input\n id={adminId(\"s-billing\")}\n type=\"url\"\n value={field.state.value}\n onBlur={field.handleBlur}\n onChange={(event) => field.handleChange(event.target.value)}\n placeholder={adminText(\"https://example.com/account\")}\n />\n </SettingEditField>\n )}\n </form.Field>\n <form.Field name=\"logoURL\">\n {(field) => (\n <SettingEditField label={adminText(\"Logo URL\")} id={\"s-logo\"}>\n <Input\n id={adminId(\"s-logo\")}\n type=\"url\"\n value={field.state.value}\n onBlur={field.handleBlur}\n onChange={(event) => field.handleChange(event.target.value)}\n placeholder={adminText(\"https://example.com/logo.png\")}\n />\n </SettingEditField>\n )}\n </form.Field>\n </form>\n ) : (\n <dl className=\"grid gap-4\">\n <SettingDetail\n label={adminText(\"Display name\")}\n value={configuration.display_name}\n />\n <SettingDetail\n label={adminText(\"From email\")}\n value={profile?.from_email}\n />\n <SettingDetail\n label={adminText(\"Support URL\")}\n value={profile?.support_url}\n />\n <SettingDetail\n label={adminText(\"Subscribe URL\")}\n value={profile?.subscribe_url}\n />\n <SettingDetail\n label={adminText(\"Billing URL\")}\n value={profile?.billing_url}\n />\n <SettingDetail\n label={adminText(\"Logo URL\")}\n value={profile?.logo_url}\n />\n </dl>\n )}\n </section>\n )\n}\n\n// RepriceNoticeWindowForm (#781): the minimum advance notice (days) a\n// subscription price increase must give existing subscribers. The price-change\n// wizard reads the same value; the API enforces it regardless.\nfunction RepriceNoticeWindowForm({\n configuration,\n edits,\n}: {\n configuration: MerchantConfigurationState\n edits: boolean\n}) {\n const { id: adminId, text: adminText } = useAdminUI()\n\n const days = configuration.settings.reprice_notice_window_days ?? 30\n const edit = useConfigurationEdit(configuration)\n const form = useForm({\n defaultValues: { days: String(days) },\n onSubmit: ({ value }) =>\n edit.save(\n { settings: { reprice_notice_window_days: Number(value.days) } },\n \"Notice window saved\",\n \"Save notice window\"\n ),\n })\n\n return (\n <section className=\"grid gap-5\">\n <div className=\"flex flex-wrap items-start justify-between gap-4\">\n <div className=\"grid max-w-2xl gap-1\">\n <h2 className=\"text-base font-semibold\">\n <AdminMessage id={\"Pricing policies\"} />\n </h2>\n <p className=\"text-sm text-pretty text-muted-foreground\">\n <AdminMessage\n id={\n \"Set how much notice customers receive before a price increase.\"\n }\n />\n </p>\n </div>\n <form.Subscribe\n selector={(state) => [state.canSubmit, state.isSubmitting]}\n >\n {([canSubmit, isSubmitting]) => (\n <EditActions\n edits={edits}\n editing={edit.editing}\n form=\"notice-window-form\"\n saving={isSubmitting}\n canSave={canSubmit}\n onEdit={() => {\n form.reset({ days: String(days) })\n edit.open()\n }}\n onCancel={edit.close}\n />\n )}\n </form.Subscribe>\n </div>\n\n {edit.editing ? (\n <form\n id={adminId(\"notice-window-form\")}\n onSubmit={(event) => {\n event.preventDefault()\n event.stopPropagation()\n void form.handleSubmit()\n }}\n >\n <form.Field\n name=\"days\"\n validators={{\n onChange: ({ value }) => {\n const days = Number(value)\n return value.trim() && Number.isInteger(days) && days >= 0\n ? undefined\n : \"Enter a whole number of days\"\n },\n }}\n >\n {(field) => (\n <SettingEditField\n label={adminText(\"Notice period (days)\")}\n id={\"s-notice-window\"}\n >\n <div className=\"grid gap-1.5\">\n <Input\n id={adminId(\"s-notice-window\")}\n type=\"number\"\n step=\"1\"\n min=\"0\"\n value={field.state.value}\n onBlur={field.handleBlur}\n onChange={(event) => field.handleChange(event.target.value)}\n aria-invalid={field.state.meta.errors.length > 0}\n />\n <FormFieldErrors errors={field.state.meta.errors} />\n </div>\n </SettingEditField>\n )}\n </form.Field>\n </form>\n ) : (\n <dl>\n <SettingDetail\n label={adminText(\"Notice period\")}\n value={`${days} ${days === 1 ? \"day\" : \"days\"}`}\n />\n </dl>\n )}\n </section>\n )\n}\n\nexport function PSPsTab() {\n const { selectedMerchant, adminQueries } = useAdminServices()\n\n const psps = useQuery(adminQueries.psps())\n const rails = useQuery(adminQueries.rails())\n const edits = useMerchantConfigEdits()\n if (psps.isPending || rails.isPending)\n return (\n <p className=\"text-sm text-muted-foreground\">\n <AdminMessage id={\"Loading…\"} />\n </p>\n )\n\n const railDefinitions = rails.data ?? []\n\n return (\n <div className=\"grid gap-6\">\n <ReadOnlyNotice />\n <section className=\"grid gap-5\">\n <div className=\"flex flex-wrap items-start justify-between gap-4\">\n <div className=\"grid gap-1\">\n <h2 className=\"text-base font-semibold\">\n <AdminMessage id={\"PSPs\"} />\n </h2>\n <p className=\"text-sm text-muted-foreground\">\n <AdminMessage\n id={\n \"The accounts this merchant takes payments through, one or more per rail.\"\n }\n />\n </p>\n </div>\n {edits && (\n <PSPDialog\n key={selectedMerchant() ?? \"\"}\n railDefinitions={railDefinitions}\n />\n )}\n </div>\n {!psps.data?.data?.length ? (\n <p className=\"py-2 text-sm text-muted-foreground\">\n <AdminMessage id={\"No PSPs configured.\"} />\n </p>\n ) : (\n <Table className=\"min-w-[44rem]\">\n <TableHeader>\n <TableRow className=\"hover:bg-transparent\">\n <TableHead className=\"text-muted-foreground\">PSP</TableHead>\n <TableHead className=\"text-muted-foreground\">\n <AdminMessage id={\"Environment\"} />\n </TableHead>\n <TableHead className=\"text-muted-foreground\">\n <AdminMessage id={\"Credentials\"} />\n </TableHead>\n <TableHead className=\"text-muted-foreground\">\n <AdminMessage id={\"State\"} />\n </TableHead>\n {edits && (\n <TableHead className=\"text-right text-muted-foreground\">\n <AdminMessage id={\"Action\"} />\n </TableHead>\n )}\n </TableRow>\n </TableHeader>\n <TableBody>\n {psps.data.data.map((psp) => (\n <PSPRow\n key={psp.id}\n psp={psp}\n railDefinitions={railDefinitions}\n edits={edits}\n />\n ))}\n </TableBody>\n </Table>\n )}\n </section>\n </div>\n )\n}\n\n// Credentials are write-only: a PSP shows whether each is set, never a value.\nfunction credentialTitle(c: PSPCredential) {\n if (c.validated_at) return `Validated ${formatDate(c.validated_at)}`\n return c.configured ? \"Configured\" : \"Not configured\"\n}\n\nfunction PSPRow({\n psp,\n railDefinitions,\n edits,\n}: {\n psp: PSP\n railDefinitions: RailDefinition[]\n edits: boolean\n}) {\n const {\n toast,\n toastApiError,\n toastStaleEdit,\n adminMutations,\n selectedMerchant,\n } = useAdminServices()\n\n const { text: adminText } = useAdminUI()\n\n const queryClient = useQueryClient()\n const updatePSP = useMutation(adminMutations.updatePSP(queryClient))\n const [confirmLastOpen, setConfirmLastOpen] = React.useState(false)\n const confirm = useConfirm()\n const definition = railDefinitions.find((d) => d.rail === psp.rail)\n const railName = definition?.display_name ?? psp.rail\n const credentials = psp.credentials ?? {}\n // Archive exactly this PSP (#655). It never contacts the provider, so a\n // terminated account archives too. The rail's last active PSP needs an\n // explicit confirmation.\n const archive = async (allowLast: boolean) => {\n if (\n !allowLast &&\n !(await confirm({\n title: `Archive ${psp.key}?`,\n description:\n \"New purchase stops routing to it. Existing subscriptions, refunds and webhooks keep using it.\",\n confirmLabel: \"Archive PSP\",\n }))\n )\n return\n try {\n await updatePSP.mutateAsync({\n id: psp.id,\n psp: {\n archived: true,\n expected_revision: psp.revision,\n ...(allowLast ? { allow_last: true } : {}),\n },\n })\n toast.success(\"PSP archived\")\n } catch (err) {\n if (err instanceof ApiError && err.code === \"psp_last_active\") {\n if (!allowLast) setConfirmLastOpen(true)\n else toastApiError(err, \"Archive PSP\")\n return\n }\n if (err instanceof ApiError && err.revisionMismatch) {\n toastStaleEdit(`PSP ${psp.key}`)\n return\n }\n toastApiError(err, \"Archive PSP\")\n }\n }\n return (\n <TableRow className={psp.archived ? \"opacity-60\" : undefined}>\n <TableCell className=\"py-3\">\n <div className=\"grid min-w-0 leading-tight\">\n <span className=\"font-medium\">{psp.key}</span>\n <span className=\"truncate text-xs text-muted-foreground\">\n {railName} · {psp.account_id}\n </span>\n </div>\n </TableCell>\n <TableCell className=\"py-3 capitalize\">{psp.environment}</TableCell>\n <TableCell className=\"py-3\">\n {Object.keys(credentials).length > 0 ? (\n <span className=\"flex flex-wrap gap-1\">\n {Object.entries(credentials).map(([name, credential]) => (\n <Badge\n key={name}\n variant=\"secondary\"\n className={\n credential.configured ? \"\" : \"bg-held-surface text-held\"\n }\n title={credentialTitle(credential)}\n >\n {name}\n </Badge>\n ))}\n </span>\n ) : (\n <span className=\"text-sm text-muted-foreground\">\n <AdminMessage id={\"None required\"} />\n </span>\n )}\n </TableCell>\n <TableCell className=\"py-3\">\n {psp.archived && psp.open_obligations === 0 ? (\n <Badge variant=\"secondary\">\n <AdminMessage id={\"archived\"} />\n </Badge>\n ) : psp.archived ? (\n <Badge variant=\"secondary\" className=\"bg-held-surface text-held\">\n <AdminMessage id={\"draining (\"} />\n {psp.open_obligations})\n </Badge>\n ) : (\n <Badge\n variant=\"secondary\"\n className=\"bg-settled-surface text-settled\"\n >\n <AdminMessage id={\"active\"} />\n </Badge>\n )}\n </TableCell>\n {edits && (\n <TableCell className=\"py-3 text-right\">\n {!psp.archived && (\n <div className=\"flex justify-end gap-2\">\n <RotateCredentialsDialog\n key={`${selectedMerchant() ?? \"\"}:${psp.id}`}\n psp={psp}\n credentialKeys={\n definition?.credential_keys ?? Object.keys(credentials)\n }\n />\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={updatePSP.isPending}\n onClick={() => archive(false)}\n >\n <AdminMessage id={\"Archive\"} />\n </Button>\n <TypedConfirmDialog\n open={confirmLastOpen}\n onOpenChange={setConfirmLastOpen}\n title={`Archive the last active ${railName} PSP?`}\n description={adminText(\n \"New purchase on this rail is refused until another PSP is armed. Existing subscriptions, refunds and webhooks keep using this one.\"\n )}\n confirmationWord=\"ARCHIVE\"\n actionLabel=\"Archive PSP\"\n onConfirm={() => archive(true)}\n />\n </div>\n )}\n </TableCell>\n )}\n </TableRow>\n )\n}\n\n// RotateCredentialsDialog writes new credentials; the current ones are never\n// shown. The provider checks the new ones before anything is stored, so a\n// rejected credential changes nothing. The edit names the revision read when\n// the dialog opened, and secret fields clear whenever it closes.\nexport function RotateCredentialsDialog({\n psp,\n credentialKeys,\n}: {\n psp: PSP\n credentialKeys: string[]\n}) {\n const {\n toast,\n toastApiError,\n toastStaleEdit,\n adminMutations,\n selectedMerchant,\n } = useAdminServices()\n\n const { id: adminId } = useAdminUI()\n\n const [open, setOpen] = React.useState(false)\n const [merchant] = React.useState(() => selectedMerchant() ?? \"\")\n const revision = React.useRef(psp.revision)\n const queryClient = useQueryClient()\n const updatePSP = useMutation(adminMutations.updatePSP(queryClient))\n const credentials = psp.credentials ?? {}\n const form = useForm({\n defaultValues: { credentials: {} as Record<string, string> },\n onSubmit: async ({ value }) => {\n const supplied = Object.fromEntries(\n Object.entries(value.credentials).filter(([, item]) => item.trim())\n )\n try {\n if ((selectedMerchant() ?? \"\") !== merchant)\n throw new Error(\"Merchant changed; reopen this form\")\n await updatePSP.mutateAsync({\n id: psp.id,\n psp: { expected_revision: revision.current, credentials: supplied },\n })\n toast.success(`${psp.key} credentials validated and rotated`)\n close(false)\n } catch (err) {\n if (err instanceof ApiError && err.revisionMismatch) {\n toastStaleEdit(`PSP ${psp.key}`)\n close(false)\n return\n }\n toastApiError(err, \"Rotate credentials\")\n } finally {\n updatePSP.reset()\n }\n },\n })\n\n const close = (next: boolean) => {\n if (!next) form.reset()\n if (next) revision.current = psp.revision\n setOpen(next)\n }\n\n return (\n <Dialog open={open} onOpenChange={close}>\n <DialogTrigger\n render={\n <Button variant=\"outline\" size=\"sm\">\n <AdminMessage id={\"Rotate\"} />\n </Button>\n }\n />\n <DialogContent className={DIALOG_FORM}>\n <DialogHeader>\n <DialogTitle>\n <AdminMessage id={\"Rotate \"} />\n {psp.key}\n <AdminMessage id={\" credentials · \"} />\n {psp.account_id}\n </DialogTitle>\n <DialogDescription>\n <AdminMessage\n id={\n \"Current credentials are never shown. A new one is validated against the live provider before it is stored; if that check fails, nothing is written. Leave a field blank to keep the credential it holds now.\"\n }\n />\n </DialogDescription>\n </DialogHeader>\n <form\n onSubmit={(event) => {\n event.preventDefault()\n event.stopPropagation()\n void form.handleSubmit()\n }}\n className=\"grid gap-4\"\n >\n <form.Field name=\"credentials\">\n {(field) => (\n <div className=\"grid gap-3\">\n {credentialKeys.map((name) => {\n const current = credentials[name]\n return (\n <Field key={name} label={name} id={`rot-${psp.id}-${name}`}>\n <Input\n id={adminId(`rot-${psp.id}-${name}`)}\n type=\"password\"\n autoComplete=\"new-password\"\n placeholder={\n current?.configured ? \"unchanged\" : \"not configured\"\n }\n value={field.state.value[name] ?? \"\"}\n onChange={(event) =>\n field.handleChange({\n ...field.state.value,\n [name]: event.target.value,\n })\n }\n />\n {current?.validated_at && (\n <p className=\"text-xs text-muted-foreground\">\n <AdminMessage id={\"Last validated \"} />\n {formatDate(current.validated_at)}\n </p>\n )}\n </Field>\n )\n })}\n <p className=\"text-xs text-muted-foreground\">\n <AdminMessage\n id={\n \"Once this succeeds, the new credential is used for the next charge and every one after it. Previous webhook signing secrets remain accepted while their required overlap is active.\"\n }\n />\n </p>\n </div>\n )}\n </form.Field>\n <DialogFooter>\n <form.Subscribe\n selector={(state) =>\n [state.values.credentials, state.isSubmitting] as const\n }\n >\n {([values, isSubmitting]) => (\n <Button\n type=\"submit\"\n disabled={\n isSubmitting ||\n !Object.values(values).some((value) => value.trim())\n }\n >\n {isSubmitting ? \"Validating…\" : \"Validate & rotate\"}\n </Button>\n )}\n </form.Subscribe>\n </DialogFooter>\n </form>\n </DialogContent>\n </Dialog>\n )\n}\n\n// Where the account ID comes from differs per rail, and the merchant reads it\n// off a different dashboard each time. Naming that is the only way this field\n// is answerable without a support ticket.\nfunction accountIDHint(rail: string): string | undefined {\n switch (rail) {\n case \"nmi\":\n return \"The Gateway ID shown in your NMI dashboard.\"\n case \"stripe\":\n return \"Your Stripe account ID. It starts with acct_.\"\n case \"ccbill\":\n return \"Your account and sub-account joined with a dash, such as 999999-0000.\"\n case \"solana\":\n return \"Taken from your signing key, so whatever you enter here is ignored.\"\n default:\n return undefined\n }\n}\n\n// What each environment means for money, in the merchant's words.\nconst ENVIRONMENT_LABELS: Record<string, string> = {\n live: \"Live: real money\",\n test: \"Test: the provider's own system, no money moves\",\n sandbox: \"Sandbox: the provider's separate sandbox\",\n}\n\nconst RAIL_NAMES: Record<string, string> = {\n nmi: \"NMI\",\n ccbill: \"CCBill\",\n stripe: \"Stripe\",\n solana: \"Solana\",\n}\n\n// Several rails carry the same display name (\"Credit Card\"), so the rail has to\n// stay visible or the list offers the same option twice.\nfunction railProviderLabel(rail: string, displayName: string): string {\n const railName = RAIL_NAMES[rail] ?? rail\n if (!displayName || displayName.toLowerCase() === railName.toLowerCase()) {\n return railName\n }\n return `${displayName} (${railName})`\n}\n\n// Credential names arrive as storage keys. Read them as words, and keep the\n// acronyms the merchant sees on the provider's own dashboard.\nconst CREDENTIAL_ACRONYMS: Record<string, string> = {\n api: \"API\",\n id: \"ID\",\n url: \"URL\",\n}\n\nfunction credentialLabel(name: string): string {\n const words = name.split(/[_-]+/).filter(Boolean)\n return words\n .map((word, index) => {\n const acronym = CREDENTIAL_ACRONYMS[word.toLowerCase()]\n if (acronym) return acronym\n if (index > 0) return word.toLowerCase()\n return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()\n })\n .join(\" \")\n}\n\nfunction PSPDialog({ railDefinitions }: { railDefinitions: RailDefinition[] }) {\n const { toast, toastApiError, adminMutations, selectedMerchant } =\n useAdminServices()\n\n const { text: adminText, id: adminId } = useAdminUI()\n\n const [open, setOpen] = React.useState(false)\n const [merchant] = React.useState(() => selectedMerchant() ?? \"\")\n const queryClient = useQueryClient()\n const createPSP = useMutation(adminMutations.createPSP(queryClient))\n const form = useForm({\n defaultValues: {\n rail: \"\",\n environment: \"\",\n key: \"\",\n accountID: \"\",\n credentials: {} as Record<string, string>,\n },\n onSubmit: async ({ value }) => {\n const credentials = Object.fromEntries(\n Object.entries(value.credentials).filter(([, item]) => item !== \"\")\n )\n try {\n if ((selectedMerchant() ?? \"\") !== merchant)\n throw new Error(\"Merchant changed; reopen this form\")\n await createPSP.mutateAsync({\n key: value.key.trim().toLowerCase(),\n rail: value.rail as PSP[\"rail\"],\n environment: value.environment,\n account_id: value.accountID.trim(),\n ...(Object.keys(credentials).length ? { credentials } : {}),\n })\n form.reset()\n toast.success(\"PSP added\")\n setOpen(false)\n } catch (err) {\n toastApiError(err, \"Add PSP\")\n } finally {\n createPSP.reset()\n }\n },\n })\n\n const handleOpenChange = (next: boolean) => {\n if (!next) form.reset()\n setOpen(next)\n }\n\n return (\n <Dialog open={open} onOpenChange={handleOpenChange}>\n <DialogTrigger\n render={\n <Button size=\"sm\">\n <AdminMessage id={\"Add PSP\"} />\n </Button>\n }\n />\n <DialogContent className={DIALOG_FORM}>\n <DialogHeader>\n <DialogTitle>\n <AdminMessage id={\"Add a PSP\"} />\n </DialogTitle>\n <DialogDescription>\n <AdminMessage\n id={\n \"Connect the account that will take money for you. Credentials go straight into the secret store and are never shown again.\"\n }\n />\n </DialogDescription>\n </DialogHeader>\n <form\n onSubmit={(event) => {\n event.preventDefault()\n event.stopPropagation()\n void form.handleSubmit()\n }}\n className=\"grid gap-4\"\n >\n <div className=\"grid gap-3\">\n <form.Field\n name=\"rail\"\n validators={{\n onChange: ({ value }) =>\n value ? undefined : \"Choose a payment rail\",\n }}\n >\n {(field) => (\n <Field label={adminText(\"Payment rail\")} id={\"pv-rail\"}>\n <Select\n items={railDefinitions.map((definition) => ({\n value: definition.rail,\n label: railProviderLabel(\n definition.rail,\n definition.display_name\n ),\n }))}\n value={field.state.value || null}\n onValueChange={(value) => {\n field.handleChange(value ?? \"\")\n // Each rail asks for different credentials and has its\n // own environments, so neither carries over.\n form.setFieldValue(\"credentials\", {})\n form.setFieldValue(\"environment\", \"\")\n }}\n >\n <SelectTrigger\n id={adminId(\"pv-rail\")}\n className=\"w-full\"\n aria-invalid={field.state.meta.errors.length > 0}\n >\n <SelectValue placeholder={adminText(\"Pick a rail…\")} />\n </SelectTrigger>\n <SelectContent>\n {railDefinitions.map((definition) => (\n <SelectItem\n key={definition.rail}\n value={definition.rail}\n >\n {railProviderLabel(\n definition.rail,\n definition.display_name\n )}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <FormFieldErrors errors={field.state.meta.errors} />\n </Field>\n )}\n </form.Field>\n <form.Subscribe selector={(state) => state.values.rail}>\n {(rail) => {\n const environments =\n railDefinitions.find((definition) => definition.rail === rail)\n ?.environments ?? []\n return (\n <form.Field\n name=\"environment\"\n validators={{\n onChange: ({ value }) =>\n value\n ? undefined\n : \"Choose whether it moves real money\",\n }}\n >\n {(field) => (\n <Field\n label={adminText(\"Environment\")}\n id={\"pv-environment\"}\n hint=\"Whether this PSP moves real money. It is checked with the provider before the PSP is used.\"\n >\n <Select\n items={environments.map((environment) => ({\n value: environment,\n label: adminText(\n ENVIRONMENT_LABELS[environment] ?? environment\n ),\n }))}\n value={field.state.value || null}\n onValueChange={(value) =>\n field.handleChange(value ?? \"\")\n }\n >\n <SelectTrigger\n id={adminId(\"pv-environment\")}\n className=\"w-full\"\n disabled={!rail}\n aria-invalid={field.state.meta.errors.length > 0}\n >\n <SelectValue\n placeholder={adminText(\"Pick an environment…\")}\n />\n </SelectTrigger>\n <SelectContent>\n {environments.map((environment) => (\n <SelectItem key={environment} value={environment}>\n {adminText(\n ENVIRONMENT_LABELS[environment] ?? environment\n )}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <FormFieldErrors errors={field.state.meta.errors} />\n </Field>\n )}\n </form.Field>\n )\n }}\n </form.Subscribe>\n <form.Field\n name=\"key\"\n validators={{\n onChange: ({ value }) =>\n /^[a-z0-9][a-z0-9_-]{0,62}$/.test(value.trim().toLowerCase())\n ? undefined\n : \"Lowercase letters, digits, - or _\",\n }}\n >\n {(field) => (\n <Field\n label={adminText(\"Key\")}\n id={\"pv-key\"}\n hint=\"Your name for this PSP, such as mobius. Prices and purchase name it by this key.\"\n >\n <Input\n id={adminId(\"pv-key\")}\n value={field.state.value}\n onBlur={field.handleBlur}\n onChange={(event) => field.handleChange(event.target.value)}\n aria-invalid={field.state.meta.errors.length > 0}\n />\n <FormFieldErrors errors={field.state.meta.errors} />\n </Field>\n )}\n </form.Field>\n <form.Subscribe selector={(state) => state.values.rail}>\n {(rail) => (\n <form.Field\n name=\"accountID\"\n validators={{\n onChange: ({ value }) =>\n value.trim()\n ? undefined\n : \"Enter the provider account ID\",\n }}\n >\n {(field) => (\n <Field\n label={adminText(\"Account ID\")}\n id={\"pv-acct\"}\n hint={accountIDHint(rail)}\n >\n <Input\n id={adminId(\"pv-acct\")}\n value={field.state.value}\n onBlur={field.handleBlur}\n onChange={(event) =>\n field.handleChange(event.target.value)\n }\n aria-invalid={field.state.meta.errors.length > 0}\n />\n <FormFieldErrors errors={field.state.meta.errors} />\n </Field>\n )}\n </form.Field>\n )}\n </form.Subscribe>\n <form.Subscribe selector={(state) => state.values.rail}>\n {(rail) => {\n const selectedProvider = railDefinitions.find(\n (definition) => definition.rail === rail\n )\n return (\n <form.Field name=\"credentials\">\n {(field) => (\n <>\n {selectedProvider?.credential_keys.map((name) => (\n <Field\n key={name}\n label={credentialLabel(name)}\n id={`pv-credential-${name}`}\n >\n <Input\n id={adminId(`pv-credential-${name}`)}\n type=\"password\"\n autoComplete=\"new-password\"\n value={field.state.value[name] ?? \"\"}\n onChange={(event) =>\n field.handleChange({\n ...field.state.value,\n [name]: event.target.value,\n })\n }\n />\n </Field>\n ))}\n </>\n )}\n </form.Field>\n )\n }}\n </form.Subscribe>\n </div>\n <DialogFooter>\n <form.Subscribe\n selector={(state) =>\n [\n state.values.rail,\n state.values.environment,\n state.values.key,\n state.values.accountID,\n state.canSubmit,\n state.isSubmitting,\n ] as const\n }\n >\n {([\n rail,\n environment,\n key,\n accountID,\n canSubmit,\n isSubmitting,\n ]) => (\n <>\n <Button\n type=\"button\"\n variant=\"outline\"\n onClick={() => handleOpenChange(false)}\n >\n <AdminMessage id={\"Cancel\"} />\n </Button>\n <Button\n type=\"submit\"\n disabled={\n !rail ||\n !environment ||\n !key.trim() ||\n !accountID.trim() ||\n !canSubmit ||\n isSubmitting\n }\n >\n {isSubmitting ? \"Saving…\" : \"Add PSP\"}\n </Button>\n </>\n )}\n </form.Subscribe>\n </DialogFooter>\n </form>\n </DialogContent>\n </Dialog>\n )\n}\n\nfunction CustomerControlsTab() {\n const { toast, toastApiError, adminMutations } = useAdminServices()\n\n const { text: adminText, id: adminId } = useAdminUI()\n\n const [result, setResult] = React.useState<{\n customerID: string\n currency: string\n creditLimit: string\n trustLevel: string\n }>()\n const lookupControls = useMutation(adminMutations.lookupCustomerControls())\n const updateCreditLimit = useMutation(adminMutations.setCreditLimit())\n const canUpdate = useAdminUpdates()\n const creditForm = useForm({\n defaultValues: { newLimit: \"\" },\n onSubmit: async ({ value }) => {\n if (!result) return\n const scale = currencyScale(result.currency)\n const amount =\n scale === undefined ? null : amountFromInput(value.newLimit, scale)\n if (amount === null || amount.startsWith(\"-\")) return\n try {\n await updateCreditLimit.mutateAsync({\n customerId: result.customerID,\n currency: result.currency,\n amount,\n })\n setResult((current) =>\n current ? { ...current, creditLimit: amount } : current\n )\n creditForm.reset()\n toast.success(\"Credit limit updated\")\n } catch (err) {\n toastApiError(err, \"Set credit limit\")\n }\n },\n })\n const lookupForm = useForm({\n defaultValues: { customerID: \"\", currency: \"usd\" },\n onSubmit: async ({ value }) => {\n const customerID = value.customerID.trim()\n const currency = value.currency.trim().toLowerCase()\n try {\n const controls = await lookupControls.mutateAsync({\n customerId: customerID,\n currency,\n })\n setResult({ customerID, ...controls })\n creditForm.reset()\n } catch (err) {\n toastApiError(err, \"Lookup customer controls\")\n setResult(undefined)\n }\n },\n })\n\n return (\n <div className=\"grid gap-10\">\n <section className=\"grid gap-5\">\n <div className=\"grid gap-1\">\n <h2 className=\"text-base font-semibold\">\n <AdminMessage id={\"Customer lookup\"} />\n </h2>\n <p className=\"text-sm text-muted-foreground\">\n <AdminMessage id={\"Find a customer by ID and currency.\"} />\n </p>\n </div>\n <form\n onSubmit={(event) => {\n event.preventDefault()\n event.stopPropagation()\n void lookupForm.handleSubmit()\n }}\n className=\"grid gap-4 md:grid-cols-[minmax(0,1fr)_10rem_auto] md:items-end\"\n >\n <lookupForm.Field\n name=\"customerID\"\n validators={{\n onChange: ({ value }) =>\n value.trim() ? undefined : \"Enter a customer ID\",\n }}\n >\n {(field) => (\n <Field\n label={adminText(\"Customer ID\")}\n id={\"customer-controls-id\"}\n >\n <Input\n id={adminId(\"customer-controls-id\")}\n placeholder={adminText(\"Customer UUID\")}\n value={field.state.value}\n onBlur={field.handleBlur}\n onChange={(event) => field.handleChange(event.target.value)}\n aria-invalid={field.state.meta.errors.length > 0}\n />\n <FormFieldErrors errors={field.state.meta.errors} />\n </Field>\n )}\n </lookupForm.Field>\n <lookupForm.Field\n name=\"currency\"\n validators={{\n onChange: ({ value }) =>\n value.trim() ? undefined : \"Enter a currency\",\n }}\n >\n {(field) => (\n <Field\n label={adminText(\"Currency\")}\n id={\"customer-controls-currency\"}\n >\n <Input\n id={adminId(\"customer-controls-currency\")}\n placeholder={adminText(\"USD\")}\n value={field.state.value}\n onBlur={field.handleBlur}\n onChange={(event) => field.handleChange(event.target.value)}\n aria-invalid={field.state.meta.errors.length > 0}\n />\n <FormFieldErrors errors={field.state.meta.errors} />\n </Field>\n )}\n </lookupForm.Field>\n <lookupForm.Subscribe\n selector={(state) =>\n [\n state.values.customerID,\n state.values.currency,\n state.canSubmit,\n state.isSubmitting,\n ] as const\n }\n >\n {([customerID, currency, canSubmit, isSubmitting]) => (\n <Button\n type=\"submit\"\n variant=\"outline\"\n disabled={\n !customerID.trim() ||\n !currency.trim() ||\n !canSubmit ||\n isSubmitting\n }\n >\n {isSubmitting ? \"Looking up…\" : \"Look up\"}\n </Button>\n )}\n </lookupForm.Subscribe>\n </form>\n </section>\n\n {result && (\n <section className=\"grid gap-5\">\n <div className=\"grid gap-1\">\n <h2 className=\"text-base font-semibold\">\n <AdminMessage id={\"Credit and trust\"} />\n </h2>\n <p className=\"text-sm text-muted-foreground\">\n <span className=\"font-mono text-xs break-all text-foreground\">\n {result.customerID}\n </span>{\" \"}\n · {result.currency.toUpperCase()}\n </p>\n </div>\n <dl className=\"grid gap-4\">\n <SettingDetail\n label={adminText(\"Trust level\")}\n value={result.trustLevel || \"Default\"}\n />\n <SettingDetail\n label={adminText(\"Credit limit\")}\n value={\n result.creditLimit !== \"0\"\n ? formatNativeAmount(result.creditLimit, result.currency)\n : \"Off\"\n }\n />\n </dl>\n {canUpdate && (\n <form\n onSubmit={(event) => {\n event.preventDefault()\n event.stopPropagation()\n void creditForm.handleSubmit()\n }}\n >\n <SettingEditField\n label={`New limit (${result.currency.toUpperCase()})`}\n id={\"customer-controls-limit\"}\n >\n <creditForm.Field\n name=\"newLimit\"\n validators={{\n onChange: ({ value }) => {\n const scale = currencyScale(result.currency)\n const amount =\n scale === undefined\n ? null\n : amountFromInput(value, scale)\n return value !== \"\" &&\n amount !== null &&\n !amount.startsWith(\"-\")\n ? undefined\n : \"Enter a valid amount\"\n },\n }}\n >\n {(field) => (\n <div className=\"grid gap-1.5\">\n <div className=\"flex gap-2\">\n <Input\n id={adminId(\"customer-controls-limit\")}\n placeholder=\"0.00\"\n type=\"number\"\n step=\"any\"\n min=\"0\"\n value={field.state.value}\n onBlur={field.handleBlur}\n onChange={(event) =>\n field.handleChange(event.target.value)\n }\n aria-invalid={field.state.meta.errors.length > 0}\n />\n <creditForm.Subscribe\n selector={(state) =>\n [\n state.values.newLimit,\n state.canSubmit,\n state.isSubmitting,\n ] as const\n }\n >\n {([newLimit, canSubmit, isSubmitting]) => (\n <Button\n type=\"submit\"\n disabled={!newLimit || !canSubmit || isSubmitting}\n >\n {isSubmitting ? \"Updating…\" : \"Update\"}\n </Button>\n )}\n </creditForm.Subscribe>\n </div>\n <FormFieldErrors errors={field.state.meta.errors} />\n <p className=\"text-xs text-muted-foreground\">\n <AdminMessage id={\"Enter 0 to turn credit off.\"} />\n </p>\n </div>\n )}\n </creditForm.Field>\n </SettingEditField>\n </form>\n )}\n </section>\n )}\n </div>\n )\n}\n\n// hint carries the invisible constraint: where a value comes from, or what\n// happens if it is left empty. Anything the control already says is left out.\nfunction Field({\n label,\n id,\n hint,\n children,\n}: {\n label: string\n id: string\n hint?: string\n children: React.ReactNode\n}) {\n const { id: adminId } = useAdminUI()\n\n return (\n <div className=\"grid gap-1.5\">\n <Label htmlFor={adminId(id)}>{label}</Label>\n {hint ? (\n <p className=\"text-[13px] text-muted-foreground\">{hint}</p>\n ) : null}\n {children}\n </div>\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAeA,SAAgB,EACd,GACA;CACA,IAAM,EAAE,UAAO,kBAAe,mBAAgB,sBAC5C,EAAiB,GAEb,CAAC,GAAU,KAAe,EAAM,SAAwB,IAAI,GAC5D,IAAc,EAAe,GAC7B,IAAS,EACb,EAAe,4BAA4B,CAAW,CACxD;CACA,OAAO;EACL,SAAS,MAAa;EACtB,YAAY;GACV,AAAI,KAAe,EAAY,EAAc,QAAQ;EACvD;EACA,aAAa,EAAY,IAAI;EAC7B,MAAM,OAAO,GAAgB,GAAe,MAAmB;GACzD,UAAa,MACjB,IAAI;IAGF,AAFA,MAAM,EAAO,YAAY;KAAE,GAAG;KAAQ,mBAAmB;IAAS,CAAC,GACnE,EAAM,QAAQ,CAAK,GACnB,EAAY,IAAI;GAClB,SAAS,GAAK;IACZ,IAAI,aAAe,KAAY,EAAI,kBAAkB;KAEnD,AADA,EAAe,mBAAmB,GAClC,EAAY,IAAI;KAChB;IACF;IAEA,AADA,EAAc,GAAK,CAAM,GACrB,aAAe,KAAY,EAAI,0BACjC,EAAY,IAAI;GACpB;EACF;CACF;AACF;;;ACxCA,SAAgB,IAAiB;CAC/B,IAAM,EAAE,oBAAiB,EAAiB,GAEpC,EAAE,YAAS,EAAS,EAAa,OAAO,CAAC;CAE/C,OADI,CAAC,KAAQ,EAAK,aAAa,UAAU,wBAA8B,OAErE,kBAAC,KAAD;EAAG,WAAU;EACX,UAAA,kBAAC,GAAD,EACE,IACE,+EAEH,CAAA;CACA,CAAA;AAEP;AAIA,SAAgB,EAAY,EAC1B,UACA,YACA,SACA,WACA,aAAU,IACV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AA,IACxD;GACH;EACE;;AAET"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"client-Di2a3HGM.js","names":[],"sources":["../src/client/errors.ts","../src/client/generated/currencies.ts","../src/client/token-source.ts","../src/psp.ts","../src/lib/money.ts","../src/client/types.ts","../src/client/client.ts"],"sourcesContent":["// Mirrors OpenRails internal/api.ErrorResponse:\n// {\"error\":{\"type\",\"code\",\"message\",\"request_id?\",\"param?\",\"metadata?\"}}.\nexport interface BillingErrorBody {\n type: string\n code: string\n message: string\n request_id?: string\n param?: string\n metadata?: Record<string, unknown>\n /** The order a failed payment left open (402 card_error). */\n order?: unknown\n}\n\n// Local codes: network_error, invalid_response, unknown_error, and the wallet\n// codes a wallet next action raises (wallet_rejected, wallet_no_signature,\n// wallet_required).\nexport class BillingError extends Error {\n readonly status: number\n readonly type: string\n readonly code: string\n readonly param?: string\n readonly requestId?: string\n readonly metadata: Record<string, unknown>\n /** The order a failed payment left open, unvalidated. */\n readonly order?: unknown\n\n constructor(status: number, body: BillingErrorBody) {\n super(body.message)\n this.name = \"BillingError\"\n this.status = status\n this.type = body.type\n this.code = body.code\n this.param = body.param\n this.requestId = body.request_id\n this.metadata = body.metadata ?? {}\n this.order = body.order\n }\n}\n\nexport const isBillingError = (value: unknown): value is BillingError =>\n value instanceof BillingError\n\n/** A server failure (HTTP 5xx) from any client or host source that carries a numeric `status`. */\nexport const isServerError = (value: unknown): boolean => {\n const status = (value as { status?: unknown } | null)?.status\n return typeof status === \"number\" && status >= 500 && status < 600\n}\n\nexport function localError(code: string, message: string): BillingError {\n return new BillingError(0, { type: \"local\", code, message })\n}\n\nexport async function readBillingError(res: Response): Promise<BillingError> {\n let body: unknown\n try {\n body = await res.json()\n } catch {\n body = undefined\n }\n const err = (body as { error?: unknown } | undefined)?.error\n if (err && typeof err === \"object\") {\n const e = err as Partial<BillingErrorBody>\n if (typeof e.code === \"string\" && e.code) {\n return new BillingError(res.status, {\n type: typeof e.type === \"string\" ? e.type : \"\",\n code: e.code,\n message: typeof e.message === \"string\" ? e.message : e.code,\n request_id:\n typeof e.request_id === \"string\"\n ? e.request_id\n : (res.headers.get(\"X-Request-ID\") ?? undefined),\n param: typeof e.param === \"string\" ? e.param : undefined,\n metadata:\n e.metadata && typeof e.metadata === \"object\" ? e.metadata : undefined,\n order: e.order,\n })\n }\n }\n return new BillingError(res.status, {\n type: res.status >= 500 ? \"api_error\" : \"\",\n code:\n typeof err === \"string\" && err\n ? err\n : res.status >= 500\n ? \"server_error\"\n : \"unknown_error\",\n message: `HTTP ${res.status}`,\n })\n}\n\n// Normalizes anything a client call can throw into a BillingError.\nexport function toBillingError(error: unknown): BillingError {\n if (error instanceof BillingError) return error\n if (error instanceof TypeError)\n return localError(\"network_error\", error.message)\n return localError(\n \"unknown_error\",\n error instanceof Error ? error.message : String(error)\n )\n}\n","// Generated by `go run ./scripts/contracts -write` from the currency registry (billing.Currencies). Do not edit.\n\n// Currency code to native-unit decimals.\nexport const OPENRAILS_CURRENCY_SCALES: Readonly<Record<string, number>> = {\n AED: 6,\n AUD: 6,\n BRL: 6,\n CAD: 6,\n CHF: 6,\n CNY: 6,\n CZK: 6,\n DKK: 6,\n EUR: 6,\n GBP: 6,\n HKD: 6,\n ILS: 6,\n INR: 6,\n JPY: 4,\n KRW: 4,\n MXN: 6,\n MYR: 6,\n NOK: 6,\n NZD: 6,\n PHP: 6,\n PLN: 6,\n PYUSD: 6,\n SAR: 6,\n SEK: 6,\n SGD: 6,\n SOL: 9,\n THB: 6,\n TRY: 6,\n USD: 6,\n USD1: 6,\n USDC: 6,\n USDG: 6,\n USDT: 6,\n ZAR: 6,\n}\n","import { localError, readBillingError } from \"./errors\"\n\n/** A token endpoint's answer (RFC 6749 §5.1). */\nexport interface TokenResponse {\n access_token: string\n /** Seconds until the token expires. */\n expires_in: number\n}\n\nexport interface TokenSourceOptions {\n /**\n * Asks the host for the customer's access token: one bound to the\n * merchant, from the host's own backend or `redeemAssertion`.\n */\n fetchToken: () => Promise<TokenResponse>\n /** Seconds before its expiry at which a token is replaced. Default 60. */\n skew?: number\n}\n\n/**\n * A `getToken` for `createBillingClient`: the current token, fetched when\n * there is none or the cached one is about to expire.\n */\nexport interface TokenSource {\n (): Promise<string>\n /**\n * Drops the cached token, so the next call fetches a new one. With\n * `token`, only when that is the one cached.\n */\n invalidate(token?: string): void\n}\n\n/**\n * Keeps the customer's access token for a billing client: it caches the\n * token until `skew` seconds before it expires and fetches the next one with\n * a single request, however many calls are waiting. A failed fetch is not\n * cached. Tokens stay in memory, never in browser storage, so a reload\n * fetches again. The client retries a call answered 401 `credential_expired`\n * once with a new token.\n */\nexport function tokenSource({\n fetchToken,\n skew = 60,\n}: TokenSourceOptions): TokenSource {\n let cached: { token: string; staleAt: number } | undefined\n let pending: Promise<string> | undefined\n\n const source = (): Promise<string> => {\n if (cached && Date.now() < cached.staleAt)\n return Promise.resolve(cached.token)\n pending ??= fetchToken()\n .then((answer) => {\n if (\n typeof answer?.access_token !== \"string\" ||\n !answer.access_token ||\n !Number.isFinite(answer.expires_in)\n )\n throw localError(\n \"invalid_response\",\n \"fetchToken answered no access_token and expires_in\"\n )\n cached = {\n token: answer.access_token,\n staleAt: Date.now() + (answer.expires_in - skew) * 1000,\n }\n return answer.access_token\n })\n .finally(() => {\n pending = undefined\n })\n return pending\n }\n source.invalidate = (token?: string) => {\n if (token === undefined || cached?.token === token) cached = undefined\n }\n return source\n}\n\n/** Whether `getToken` is a `tokenSource`, whose token the client can replace. */\nexport const isTokenSource = (getToken: unknown): getToken is TokenSource =>\n typeof getToken === \"function\" &&\n typeof (getToken as Partial<TokenSource>).invalidate === \"function\"\n\nexport interface RedeemAssertionOptions {\n /** The authorization server's token endpoint, such as `https://billing.example/oauth2/token`. */\n tokenEndpoint: string\n /**\n * The assertion the merchant's backend signed for this customer (RFC\n * 7523): single use and minutes long, so redeem each one once.\n */\n assertion: string\n /**\n * Transport. Pass a fetch that adds a DPoP proof (auth-ui's `dpopFetch`)\n * to bind the token to the browser's key.\n */\n fetch?: (input: string, init: RequestInit) => Promise<Response>\n}\n\n/**\n * Redeems a customer assertion for an access token to OpenRails\n * (`scope=openrails:self`): a `fetchToken` for `tokenSource`, after the\n * host's backend signed the assertion.\n */\nexport async function redeemAssertion(\n options: RedeemAssertionOptions\n): Promise<TokenResponse & { token_type: string }> {\n const doFetch =\n options.fetch ?? ((input: string, init: RequestInit) => fetch(input, init))\n const res = await doFetch(options.tokenEndpoint, {\n method: \"POST\",\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n },\n body: new URLSearchParams({\n grant_type: \"urn:ietf:params:oauth:grant-type:jwt-bearer\",\n assertion: options.assertion,\n scope: \"openrails:self\",\n }).toString(),\n })\n if (!res.ok) throw await readBillingError(res)\n const answer = (await res.json().catch(() => null)) as Record<\n string,\n unknown\n > | null\n if (\n typeof answer?.access_token !== \"string\" ||\n typeof answer.expires_in !== \"number\"\n )\n throw localError(\n \"invalid_response\",\n \"the token endpoint answered no access_token and expires_in\"\n )\n return {\n access_token: answer.access_token,\n expires_in: answer.expires_in,\n token_type:\n typeof answer.token_type === \"string\" ? answer.token_type : \"Bearer\",\n }\n}\n","// OpenRails's browser-safe PSP projection (GET /config's payment). Which\n// browser flow a PSP needs is decided here, never by the host.\nimport { z } from \"zod\"\n\nexport const pspConfigSchema = z.object({\n psp_id: z.string().min(1),\n /** The PSP's key. */\n key: z.string().min(1),\n rail: z.string(),\n /** Who holds the card: \"psp\" or a third-party custodian. */\n custodian: z.string(),\n display_name: z.string(),\n /** `tokenize | card | elements | redirect | wallet` */\n flow: z.string(),\n config: z.record(z.string(), z.string()).nullish(),\n /**\n * New purchases and new cards use this PSP under the merchant's routing.\n * Other PSPs stay listed so existing cards and subscriptions keep working.\n */\n routed: z.boolean().nullish(),\n /**\n * `temporarily_unavailable`: the PSP could not be checked just now and is\n * listed without `config`; ask again after `retry_after` seconds.\n */\n status: z.string().nullish(),\n retry_after: z.number().int().nullish(),\n})\nexport type PspConfig = z.infer<typeof pspConfigSchema>\n\n/** PSPs that take new purchases and new cards. */\nexport const routedPsps = (psps: readonly PspConfig[]): PspConfig[] =>\n psps.filter((psp) => psp.routed !== false)\n\nconst cardFlows = new Set([\"tokenize\", \"card\", \"elements\"])\n\n/**\n * Seconds until a card PSP listed as temporarily unavailable is worth asking\n * for again; null when none is.\n */\nexport function cardRetryAfter(psps: readonly PspConfig[]): number | null {\n const waits = psps\n .filter(\n (psp) =>\n !!psp.status && psp.custodian === \"psp\" && cardFlows.has(psp.flow)\n )\n .map((psp) => psp.retry_after ?? 30)\n return waits.length > 0 ? Math.min(...waits) : null\n}\n\nexport type CardSetupDriver = \"collect_js\" | \"card\" | \"stripe_elements\"\n\nconst usable = (value?: string) => !!value && !value.startsWith(\"preview_\")\n\nconst stripeKey = (psp: PspConfig) =>\n psp.rail === \"stripe\" && !!psp.config?.publishable_key?.startsWith(\"pk_\")\n\n/** How a card is saved with this PSP in the page, or null when it cannot be. */\nexport function cardSetupDriver(psp: PspConfig): CardSetupDriver | null {\n if (psp.custodian !== \"psp\" || psp.status) return null\n // The PSP takes cards on OpenRails itself (card_entry: server).\n if (psp.flow === \"card\" && psp.rail === \"nmi\") return \"card\"\n if (\n psp.flow === \"tokenize\" &&\n usable(psp.config?.tokenization_key) &&\n !!psp.config?.tokenization_url\n )\n return \"collect_js\"\n if (stripeKey(psp)) return \"stripe_elements\"\n return null\n}\n\nexport const canSavePaymentMethod = (psp: PspConfig): boolean =>\n cardSetupDriver(psp) !== null\n\n/** Whether a pending payment on this PSP can be authenticated in the page. */\nexport const canAuthenticatePayment = (psp: PspConfig): boolean =>\n cardSetupDriver(psp) === \"stripe_elements\"\n","// Exact money. Every amount OpenRails serves is a signed int64 decimal string\n// of the plan currency's native unit, at plan.unit_decimals (the currency\n// registry's scale). Amounts are scaled with BigInt, never a JS number; only\n// the exact major-unit decimal reaches Intl.\n\n// Amount is an int64 decimal string, e.g. \"99000000\" (99 USD at 6 decimals).\nexport type Amount = string\n\nconst INT64_MIN = -(1n << 63n)\nconst INT64_MAX = (1n << 63n) - 1n\nexport const MAX_UNIT_DECIMALS = 18\n\n// amountUnits parses an exact int64 decimal string, or null.\nexport function amountUnits(amount: unknown): bigint | null {\n if (typeof amount !== \"string\" || !/^-?\\d{1,19}$/.test(amount)) return null\n const value = BigInt(amount)\n return value < INT64_MIN || value > INT64_MAX ? null : value\n}\n\nexport function isAmount(value: unknown): value is Amount {\n return amountUnits(value) !== null\n}\n\nexport function isUnitDecimals(value: unknown): value is number {\n return (\n typeof value === \"number\" &&\n Number.isInteger(value) &&\n value >= 0 &&\n value <= MAX_UNIT_DECIMALS\n )\n}\n\n// addAmounts sums exact amounts; null when an input or the sum leaves int64.\nexport function addAmounts(...amounts: Amount[]): Amount | null {\n let total = 0n\n for (const amount of amounts) {\n const units = amountUnits(amount)\n if (units === null) return null\n total += units\n }\n return total < INT64_MIN || total > INT64_MAX ? null : total.toString()\n}\n\n// Intl.NumberFormat formats a decimal string exactly only since ECMA-402 2023\n// (Chrome/Edge 106, Firefox 116, Safari 15.4); older engines coerce it through\n// Number. Probed once with 2^53 + 1, which a Number cannot hold.\nexport const intlFormatsDecimalStringsExactly: boolean = (() => {\n try {\n return (\n new Intl.NumberFormat(\"en\", { useGrouping: false }).format(\n \"9007199254740993\" as `${number}`\n ) === \"9007199254740993\"\n )\n } catch {\n return false\n }\n})()\n\n// Below 10^15 native units a Number-coerced decimal still rounds back to the\n// exact digits at every registry scale; from 10^15 the coerced value can differ\n// in the last digit, so a legacy engine refuses instead of misformatting.\nconst LEGACY_EXACT_UNITS = 10n ** 15n\n\nfunction decimalFromUnits(value: bigint, decimals: number): string {\n const absolute = value < 0n ? -value : value\n const scale = 10n ** BigInt(decimals)\n const fraction = (absolute % scale)\n .toString()\n .padStart(decimals, \"0\")\n .replace(/0+$/, \"\")\n return `${value < 0n ? \"-\" : \"\"}${absolute / scale}${fraction ? `.${fraction}` : \"\"}`\n}\n\n// amountToDecimal renders native units as the exact major-unit decimal with\n// trailing zeros trimmed (\"99000000\" at 6 -> \"99\", \"1234567\" -> \"1.234567\"),\n// or null when the amount or scale is invalid.\nexport function amountToDecimal(\n amount: Amount,\n decimals: number\n): string | null {\n const units = amountUnits(amount)\n if (units === null || !isUnitDecimals(decimals)) return null\n return decimalFromUnits(units, decimals)\n}\n\n// amountToMinorUnits is an amount in the provider's minor units (Stripe's\n// `amount`: \"12500000\" USD at 6 and 2 -> 1250), or null when the amount is not\n// a whole number of them or leaves the exact range of a JS number.\nexport function amountToMinorUnits(\n amount: Amount,\n decimals: number,\n minorDecimals: number\n): number | null {\n const units = amountUnits(amount)\n if (\n units === null ||\n !isUnitDecimals(decimals) ||\n !isUnitDecimals(minorDecimals) ||\n minorDecimals > decimals\n )\n return null\n const scale = 10n ** BigInt(decimals - minorDecimals)\n if (units % scale !== 0n) return null\n const minor = units / scale\n return minor > BigInt(Number.MAX_SAFE_INTEGER) ||\n minor < -BigInt(Number.MAX_SAFE_INTEGER)\n ? null\n : Number(minor)\n}\n\n// decimalToAmount parses a major-unit decimal exactly (\"100.25\" at 6 ->\n// \"100250000\"). Excess precision, scientific notation and int64 overflow\n// are refused; input is never rounded or converted through a JS number.\nexport function decimalToAmount(\n decimal: string,\n decimals: number\n): Amount | null {\n if (!isUnitDecimals(decimals) || decimal.length > 40) return null\n const match = /^(-?)(\\d+)(?:\\.(\\d+))?$/.exec(decimal)\n if (!match) return null\n const fraction = match[3] ?? \"\"\n if (fraction.length > decimals) return null\n const units =\n BigInt(match[2]) * 10n ** BigInt(decimals) +\n BigInt(fraction.padEnd(decimals, \"0\") || \"0\")\n const signed = match[1] ? -units : units\n return signed < INT64_MIN || signed > INT64_MAX ? null : signed.toString()\n}\n\n// formatAmount renders an exact amount in its currency for the buyer. It never\n// passes money through a JS number; an amount it cannot show exactly is\n// refused with a visible notice rather than a rounded figure.\nexport function formatAmount(\n amount: Amount | null | undefined,\n currency: string,\n decimals: number,\n locale?: string\n): string {\n const code = currency.trim().toUpperCase()\n const units = amountUnits(amount)\n if (units === null || !isUnitDecimals(decimals))\n return `${code} amount exceeds the exact display range`\n if (\n !intlFormatsDecimalStringsExactly &&\n (units >= LEGACY_EXACT_UNITS || units <= -LEGACY_EXACT_UNITS)\n )\n return `${code} amount exceeds this browser's exact display range`\n const decimal = decimalFromUnits(units, decimals) as `${number}`\n try {\n return new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency: code,\n maximumFractionDigits: decimals,\n }).format(decimal)\n } catch {\n return `${decimal} ${code}`\n }\n}\n","// Wire types of the OpenRails customer surface (`/billing/v1/me/*`) and public\n// catalog, validated at the boundary. Money is an int64 string in the\n// currency's native unit; its scale comes from GET /config's currencies.\n// Fixtures: the repository's canonical testdata/wire.\nimport { z } from \"zod\"\n\nimport { pspConfigSchema } from \"../psp\"\n\nimport type { CardEntry } from \"../lib/card-entry\"\nimport { isAmount } from \"../lib/money\"\n\nimport type * as wire from \"./generated/wire\"\n\nconst amount = z.string().refine(isAmount, \"amount must be an int64 string\")\nconst time = z.string()\n\nexport const pageSchema = <T extends z.ZodType>(item: T) =>\n z.object({\n data: z\n .array(item)\n .nullish()\n .transform((v) => v ?? []),\n total: z.number().nullish(),\n limit: z.number().nullish(),\n offset: z.number().nullish(),\n has_more: z.boolean().nullish(),\n next_cursor: z.string().nullish(),\n })\n\nexport interface Page<T> {\n data: T[]\n total?: number | null\n limit?: number | null\n offset?: number | null\n has_more?: boolean | null\n /** The next page's cursor; null on the last page of a cursor list. */\n next_cursor?: string | null\n}\n\n/** One page of a cursor list; `next_cursor` is null on the last page. */\nexport const listPageSchema = <T extends z.ZodType>(item: T) =>\n z.object({\n data: z\n .array(item)\n .nullish()\n .transform((v) => v ?? []),\n next_cursor: z\n .string()\n .nullish()\n .transform((v) => v ?? null),\n })\n\nexport interface ListPage<T> {\n data: T[]\n next_cursor: string | null\n}\n\nexport const subscriptionStatusSchema = z.string()\n/** `pending | active | past_due | awaiting_method | unverified | canceled`; kept open for new values. */\nexport type SubscriptionStatus =\n | \"pending\"\n | \"active\"\n | \"past_due\"\n | \"awaiting_method\"\n | \"unverified\"\n | \"canceled\"\n | (string & {})\n\nexport const pspLinkStateSchema = z.object({\n /** `linked | pending_manual_link | sync_disabled | error` */\n status: z.string(),\n ids: z.record(z.string(), z.string()).nullish(),\n sync_status: z.string().nullish(),\n})\n\n/**\n * A catalog price, embedded in a product (`GET /products`): `unit_amount` of\n * `currency` for `access_duration_hours` of access (null: for good),\n * charging every `billing_interval_hours` (null: one-time).\n */\nexport const priceSchema = z.object({\n id: z.string(),\n key: z.string(),\n /** The price key's revision: every change to any of its versions; absent on older servers. */\n revision: z.number().int().nonnegative().optional(),\n /** This price's terms within its key, from zero; absent on older servers. */\n version: z.number().int().nonnegative().optional(),\n product_id: z.string(),\n archived: z.boolean(),\n unit_amount: amount,\n /** Optional bounds for a deposit whose amount is selected before purchase. */\n customer_amount: z\n .object({ min_amount: amount, max_amount: amount })\n .nullish(),\n currency: z.string(),\n access_duration_hours: z.number().nullable(),\n billing_interval_hours: z.number().nullable(),\n trial_unit_amount: amount.nullable(),\n trial_duration_hours: z.number().nullable(),\n /** Keyed by PSP key. */\n psps: z.record(z.string(), pspLinkStateSchema).nullish(),\n created_at: time,\n updated_at: time,\n})\nexport type Price = z.infer<typeof priceSchema>\n\nexport const subscriptionProductSchema = z.object({\n id: z.string(),\n key: z.string().nullish(),\n revision: z.number().int().nonnegative().optional(),\n display_name: z.string().nullish(),\n description: z.string().nullish(),\n tier_group: z.string().nullish(),\n tier_rank: z.number().nullish(),\n})\nexport type SubscriptionProduct = z.infer<typeof subscriptionProductSchema>\n\nexport const cardSummarySchema = z.object({\n brand: z.string().nullish(),\n last4: z.string().nullish(),\n exp_month: z.number().nullish(),\n exp_year: z.number().nullish(),\n})\nexport type CardSummary = z.infer<typeof cardSummarySchema>\n\nexport const paymentRecoverySchema = z.object({\n last_failure_reason: z.string().nullish(),\n retryable: z.boolean(),\n blocked_reason: z.string().nullish(),\n /** An engine-owned subscription's unpaid renewal: the order to pay. */\n order_id: z.string().nullish(),\n})\nexport type PaymentRecovery = z.infer<typeof paymentRecoverySchema>\n\n/**\n * What the customer completes before an action or payment can finish:\n * `authenticate` runs the PSP's own script with `payload` (Stripe.js\n * `handleNextAction` with `client_secret`), then the payable is confirmed;\n * `redirect_to_url` leaves for `url`; with `solana_sign_transactions` the\n * wallet signs and sends `transactions` in order and the action is repeated\n * with the last signature. `capture` initializes vendor-owned card fields\n * from the scoped payload, then confirms the pending payment method with\n * the vendor session token. Capturing never charges the card.\n */\nexport const nextActionSchema = z.object({\n type: z.string(),\n url: z.string().nullish(),\n psp_id: z.string().nullish(),\n transactions: z.array(z.string()).nullish(),\n payload: z.record(z.string(), z.string()).nullish(),\n})\nexport type NextAction = z.infer<typeof nextActionSchema>\n\n/**\n * A declined renewal being collected. `retries_left` and `final_retry_at`\n * follow the merchant's dunning policy; both are null when the provider runs\n * the retries. While `waiting_for_new_card`, nothing is charged until the card\n * is replaced, and the subscription ends at `final_retry_at`.\n */\nexport const subscriptionDunningSchema = z.object({\n attempts: z.number(),\n retries_left: z.number().nullish(),\n next_retry_at: time.nullish(),\n final_retry_at: time.nullish(),\n waiting_for_new_card: z.boolean(),\n last_failure_reason: z.string().nullish(),\n})\nexport type SubscriptionDunning = z.infer<typeof subscriptionDunningSchema>\n\nexport const subscriptionSchema = z.object({\n id: z.string(),\n status: subscriptionStatusSchema,\n rail: z.string().nullish(),\n product_id: z.string().nullish(),\n price_id: z.string().nullish(),\n /** Seats of a per-seat price; null otherwise. */\n quantity: z.number().nullish(),\n psp_id: z.string().nullish(),\n /** `engine | nmi_schedule | provider` */\n collection_policy: z.string().nullish(),\n /** The subscription's own card; null follows the default card. */\n payment_method_id: z.string().nullish(),\n started_at: time.nullish(),\n ended_at: time.nullish(),\n current_period_starts_at: time.nullish(),\n current_period_ends_at: time.nullish(),\n canceled_at: time.nullish(),\n cancel_type: z.string().nullish(),\n resumable: z.boolean().nullish(),\n cancel_scheduled: z.boolean().nullish(),\n /** `reversible | destructive | external_portal` */\n cancel_mode: z.string().nullish(),\n cancel_portal_url: z.string().nullish(),\n access: z.object({ starts_at: time, ends_at: time.nullish() }).nullish(),\n /** Null unless the subscription is `past_due` or `awaiting_method`. */\n dunning: subscriptionDunningSchema.nullish(),\n price: priceSchema.nullish(),\n product: subscriptionProductSchema.nullish(),\n /** The change waiting for the next renewal, with its price and product. */\n scheduled_change: z\n .object({\n price_id: z.string(),\n quantity: z.number().nullish(),\n effective_at: time,\n /** `change | migration` */\n source: z.string(),\n price: priceSchema.nullish(),\n product: subscriptionProductSchema.nullish(),\n })\n .nullish(),\n card: cardSummarySchema.nullish(),\n recovery: paymentRecoverySchema.nullish(),\n /** Set on an action's answer when the rail needs the customer's step. */\n next_action: nextActionSchema.nullish(),\n created_at: time.nullish(),\n updated_at: time.nullish(),\n})\nexport type Subscription = z.infer<typeof subscriptionSchema> & {\n status: SubscriptionStatus\n}\n\nexport const billingDetailsSchema = z.object({\n name: z.string().nullish(),\n email: z.string().nullish(),\n phone: z.string().nullish(),\n address: z\n .object({\n line1: z.string().nullish(),\n line2: z.string().nullish(),\n city: z.string().nullish(),\n state: z.string().nullish(),\n postal_code: z.string().nullish(),\n country: z.string().nullish(),\n })\n .nullish(),\n})\nexport type BillingDetails = z.infer<typeof billingDetailsSchema>\n\nexport const paymentMethodSchema = z.object({\n id: z.string(),\n /** `requires_action` while vendor card entry or bank authentication waits. */\n status: z.string().nullish(),\n /** Vendor card capture or the bank's authentication of a card being saved. */\n next_action: z\n .object({\n type: z.string(),\n psp_id: z.string().nullish(),\n payload: z.record(z.string(), z.string()).nullish(),\n })\n .nullish(),\n rail: z.string().nullish(),\n /** The PSP holding the card; null for a card a custodian holds. */\n psp_id: z.string().nullish(),\n card: cardSummarySchema.nullish(),\n billing_details: billingDetailsSchema.nullish(),\n /** Kept for one-click buys; a card stored only for a subscription is not. */\n reusable: z.boolean().nullish(),\n health: z\n .object({\n /** `valid | expiring_soon | expired` */\n expiry_status: z.string().nullish(),\n last_charged_at: time.nullish(),\n last_charge_outcome: z.string().nullish(),\n active: z.boolean().nullish(),\n })\n .nullish(),\n subscriptions: z\n .array(\n z.object({\n id: z.string(),\n display_name: z.string().nullish(),\n })\n )\n .nullish(),\n /** Currencies whose usage orders this card pays. */\n default_currencies: z.array(z.string()).nullish(),\n created_at: time.nullish(),\n})\nexport type PaymentMethod = z.infer<typeof paymentMethodSchema>\n\n/** Why the latest payment attempt failed, in the customer's words. */\nexport const paymentFailureSchema = z.object({\n reason: z.string(),\n message: z.string(),\n field: z.string().nullish(),\n})\nexport type PaymentFailure = z.infer<typeof paymentFailureSchema>\n\n/**\n * One line of an order. A purchased line names its price and product; a\n * usage order's line names its accrual source (`metered:<meter>`) instead.\n */\nexport const orderLineSchema = z.object({\n id: z.string(),\n price_id: z.string().nullish(),\n product_id: z.string().nullish(),\n source: z.string().nullish(),\n description: z.string(),\n quantity: z.number().nullish(),\n unit_amount: amount,\n amount: amount,\n billing_interval_hours: z.number().nullish(),\n access_duration_hours: z.number().nullish(),\n subscription_id: z.string().nullish(),\n product_access_id: z.string().nullish(),\n})\nexport type OrderLine = z.infer<typeof orderLineSchema>\n\n/**\n * A purchase, a subscription's renewal (`origin: subscription`) or usage\n * billed in arrears (`origin: usage`): frozen lines and total, read and paid\n * by its own customer. `status` is the order's (`open | processing |\n * complete | canceled | expired | void | uncollectible`); `payment.status`\n * its payment's (`requires_payment_method | requires_action | processing |\n * succeeded`).\n */\nexport const orderSchema = z.object({\n id: z.string(),\n customer_id: z.string(),\n origin: z.string(),\n /** Only `engine` orders accept generic payment commands. */\n collection_owner: z.string().nullish(),\n collection_psp_id: z.string().nullish(),\n provider_bills: z.array(z.object({\n psp_id: z.string(),\n kind: z.string(),\n reference: z.string(),\n settlement_source: z.string().nullish(),\n non_cash_amount: amount,\n settled_at: time.nullish(),\n })).nullish().transform((bills) => bills ?? []),\n status: z.string(),\n number: z.number().int().nullish(),\n currency: z.string(),\n total: amount,\n lines: z.array(orderLineSchema),\n payment: z.object({\n status: z.string(),\n next_action: nextActionSchema.nullish(),\n last_payment_error: paymentFailureSchema.nullish(),\n payment_method_id: z.string().nullish(),\n payment_id: z.string().nullish(),\n }),\n payment_options: z\n .array(\n z.object({\n psp_id: z.string(),\n rail: z.string(),\n accepts: z.array(z.string()),\n saved_payment_method_ids: z.array(z.string()).optional(),\n /** The order's failed payments through the PSP. */\n failed_attempts: z\n .number()\n .nullish()\n .transform((v) => v ?? 0),\n })\n )\n .nullish()\n .transform((v) => v ?? []),\n /** Where the customer pays the order; only on the answer that made it. */\n pay_url: z.string().nullish(),\n /** When the pay URL stops working; null without one. */\n pay_url_expires_at: time.nullish(),\n /** The merchant's page frames the pay URL. */\n embedded: z.boolean().nullish().transform((v) => v ?? false),\n /** A merchant order's return; none on a customer's embedded one. */\n success_url: z.string().nullish(),\n cancel_url: z.string().nullish(),\n saved_payment_methods: z\n .boolean()\n .nullish()\n .transform((v) => v ?? false),\n renewal: z\n .object({\n subscription_id: z.string(),\n period_starts_at: time,\n period_ends_at: time,\n due_at: time,\n })\n .nullish(),\n /**\n * A usage order's period, when it is due and how much of it is paid (a\n * funded balance and remittances pay part of it). `delinquent`: overdue\n * past grace, so new usage in its currency is refused until it is paid.\n */\n usage: z\n .object({\n period_starts_at: time,\n period_ends_at: time,\n due_at: time,\n amount_paid: amount,\n amount_due: amount,\n collection_method: z.string(),\n next_collection_attempt_at: time.nullish(),\n po_number: z.string().nullish(),\n memo: z.string().nullish(),\n delinquent: z.boolean(),\n })\n .nullish(),\n expires_at: time.nullish(),\n completed_at: time.nullish(),\n canceled_at: time.nullish(),\n expired_at: time.nullish(),\n voided_at: time.nullish(),\n uncollectible_at: time.nullish(),\n created_at: time,\n})\nexport type Order = z.infer<typeof orderSchema>\n\n/** Why a line cannot be bought: `already_owned`, `entitlement_required`, `unavailable`, ... */\nexport const orderLineRefusalSchema = z.object({\n code: z.string(),\n message: z.string(),\n owned_by: z.string().nullish(),\n hint: z.string().nullish(),\n /** `entitlement_required`: the required keys the customer lacks. */\n missing: z.array(z.string()).optional(),\n})\nexport type OrderLineRefusal = z.infer<typeof orderLineRefusalSchema>\n\n/** One line priced as an order would freeze it, or why it cannot be bought. */\nexport const orderPreviewLineSchema = z.object({\n price_id: z.string(),\n product_id: z.string(),\n description: z.string(),\n quantity: z.number().nullish(),\n unit_amount: amount,\n amount: amount,\n ownership: z.string(),\n billing_interval_hours: z.number().nullish(),\n access_duration_hours: z.number().nullish(),\n refusal: orderLineRefusalSchema.nullish(),\n})\nexport type OrderPreviewLine = z.infer<typeof orderPreviewLineSchema>\n\n/**\n * The customer's cart, priced live: one per customer of a merchant, shared by\n * the merchant's sites. `last_changed_at` and `expires_at` are null while it\n * is empty.\n */\nexport const cartSchema = z.object({\n currency: z.string(),\n total: amount,\n lines: z.array(orderPreviewLineSchema),\n payment_options: orderSchema.shape.payment_options,\n last_changed_at: time.nullish(),\n expires_at: time.nullish(),\n})\nexport type Cart = z.infer<typeof cartSchema>\n\n/**\n * How to pay an order: a saved card, a card just entered (the token of the\n * PSP's own fields, its `psp_id`), a Solana wallet (`token_symbol`, the\n * token it pays in) or the PSP's hosted page (`return_url`).\n */\nexport type OrderPaymentInput =\n | { payment_method_id: string }\n | {\n token: string\n psp_id?: string\n billing_details?: NewCard[\"billing_details\"]\n }\n | { token_symbol: string; psp_id?: string }\n | { return_url: string; psp_id?: string }\n\n/** A price's state on one PSP; public routes carry the status only. */\nexport const productSchema = z.object({\n id: z.string(),\n key: z.string(),\n /** Current mutation counter; absent on older servers. */\n revision: z.number().int().nonnegative().optional(),\n display_name: z.string(),\n description: z.string(),\n /** Opaque entitlement keys granted by the product. */\n entitlements: z.array(z.string()),\n /** Keys a customer must already hold to order the product. */\n required_entitlements: z.array(z.string()).optional(),\n /** Prepaid balance fulfilled once for each qualifying successful payment. */\n credit_grant: z\n .object({\n currency: z.string(),\n amount: amount.nullish(),\n from_payment: z.boolean().optional(),\n expires_after_days: z.number().int().positive().nullish(),\n })\n .nullish(),\n /** Products sharing a group are tiers a subscription can change between. */\n tier_group: z.string().nullable(),\n tier_rank: z.number(),\n archived: z.boolean(),\n prices: z\n .array(priceSchema)\n .nullish()\n .transform((v) => v ?? []),\n created_at: time,\n updated_at: time,\n})\nexport type Product = z.infer<typeof productSchema>\n\nexport const paymentSchema = z.object({\n id: z.string(),\n /** `charge | refund | chargeback | dispute_reversal` */\n kind: z.string(),\n /** `succeeded | pending | failed | refunded | partially_refunded` */\n status: z.string(),\n /** Negative for a refund or chargeback. */\n amount: amount,\n amount_refunded: amount.nullish(),\n currency: z.string(),\n subscription_id: z.string().nullish(),\n /** The bill this money movement settles or reverses. */\n order_id: z.string().nullish(),\n /** `rail | manual | admin` */\n channel: z.string().nullish(),\n rail: z.string().nullish(),\n created_at: time,\n card: cardSummarySchema.nullish(),\n /** Normalized decline of a failed payment. */\n failure: z\n .object({\n reason: z.string(),\n message: z.string(),\n field: z.string().nullish(),\n })\n .nullish(),\n})\nexport type Payment = z.infer<typeof paymentSchema>\n\n/**\n * An entitlement key the customer holds through a product. `quantity` is the\n * most seats a held per-seat product grants it; null when none is per seat.\n */\nexport const customerEntitlementSchema: z.ZodType<wire.CustomerEntitlement> =\n z.object({\n customer_id: z.string(),\n entitlement: z.string(),\n quantity: z.number().int().nullable(),\n })\nexport type CustomerEntitlement = wire.CustomerEntitlement\n\n/**\n * A customer's money in one currency, as of `as_of`. `accrued_amount` is what\n * its running charges have charged and the ledger does not hold yet, already\n * taken off `available_amount`; until `depletes_at` (null with no running\n * charge) show `available_amount - accrual_rate_per_hour x hours since as_of`.\n */\nexport const balanceSchema = z.object({\n currency: z.string(),\n billing_mode: z.string(),\n balance_amount: amount,\n held_amount: amount,\n accrued_amount: amount,\n available_amount: amount,\n owed_amount: amount,\n accrual_rate_per_hour: amount,\n as_of: z.string(),\n depletes_at: z.string().nullable(),\n})\nexport type Balance = z.infer<typeof balanceSchema>\n\n/**\n * The low-balance line a balance is judged at: the customer is told when what\n * it may spend is under the larger of `amount` and its burn rate times\n * `runway_hours`. `source` is `customer`, `merchant` or `default`.\n */\nexport const lowBalanceLineSchema = z.object({\n currency: z.string(),\n amount: amount,\n runway_hours: z.number().int(),\n source: z.enum([\"customer\", \"merchant\", \"default\"]),\n})\nexport type LowBalanceLine = z.infer<typeof lowBalanceLineSchema>\n\n/**\n * The signed-in customer's summary (`GET /me`): money per currency, the\n * default card of each currency, and the low-balance line of each balance.\n */\nexport const accountSchema = z.object({\n id: z.string(),\n balances: z.array(balanceSchema),\n default_payment_methods: z.array(\n z.object({ currency: z.string(), payment_method_id: z.string() })\n ),\n low_balance_lines: z.array(lowBalanceLineSchema),\n})\nexport type Account = z.infer<typeof accountSchema>\n\n/**\n * One group of a usage report: its events and their total `amount`.\n * `dimensions` are the summed event dimensions when grouped by event type.\n * Grouped by meter, `key` is the meter, `cell` its matrix cell and\n * `quantity` what it priced.\n */\nexport const usageRowSchema = z.object({\n key: z.string(),\n cell: z.string().nullish(),\n event_count: z.number(),\n amount,\n quantity: z.number().nullish(),\n dimensions: z.record(z.string(), z.number()).nullish(),\n})\nexport type UsageRow = z.infer<typeof usageRowSchema>\n\n/**\n * One page of the customer's usage in `currency` over [`from`, `to`): its\n * groups by total amount, largest first, then by key. `next_cursor` reads the\n * next page; null on the last.\n */\nexport const usageSchema = z.object({\n customer_id: z.string(),\n currency: z.string(),\n from: time,\n to: time,\n /** `event_type | resource | invoker`; kept open for new values. */\n group_by: z.string(),\n rows: z.array(usageRowSchema),\n next_cursor: z\n .string()\n .nullish()\n .transform((v) => v ?? null),\n})\nexport type Usage = z.infer<typeof usageSchema>\n\n/** Currency code (upper case) to its native-unit scale. */\nexport type CurrencyScales = Readonly<Record<string, number>>\n\nexport const currencySchema = z.object({\n code: z.string(),\n /** Native-unit decimals of every amount on the wire. */\n decimals: z.number(),\n /** Decimals the provider settles in. */\n minor_decimals: z.number().nullish(),\n})\nexport type Currency = z.infer<typeof currencySchema>\n\nexport const subscriptionChangePreviewSchema = z.object({\n price_id: z.string(),\n /** Seats of a per-seat price; null otherwise. */\n quantity: z.number().nullish(),\n rail: z.string().nullish(),\n currency: z.string(),\n /** Charged immediately; `\"0\"` for a change at period end. */\n amount_due_now: amount,\n /** The new price, charged at the next renewal. */\n next_charge_amount: amount,\n next_charge_date: time.nullish(),\n /** `now | period_end` */\n effective: z.string(),\n /** The rail finalizes the exact amount (Stripe provider changes). */\n is_estimate: z.boolean().nullish(),\n message: z.string().nullish(),\n})\nexport type SubscriptionChangePreview = z.infer<\n typeof subscriptionChangePreviewSchema\n>\n\nexport const subscriptionChangeSchema = z.object({\n /** `succeeded | processing | requires_action | blocked` */\n status: z.string(),\n /** `now | period_end` */\n effective: z.string().nullish(),\n price_id: z.string().nullish(),\n quantity: z.number().nullish(),\n /** The subscription now carrying the plan (an upgrade may open a successor). */\n subscription_id: z.string().nullish(),\n /** On `requires_action`: complete it, then `confirmSubscriptionChange`. */\n next_action: nextActionSchema.nullish(),\n /** When a change at period end takes effect. */\n delayed_start: time.nullish(),\n currency: z.string().nullish(),\n amount_due_now: amount.nullish(),\n next_charge_amount: amount.nullish(),\n next_charge_date: time.nullish(),\n message: z.string().nullish(),\n})\nexport type SubscriptionChange = z.infer<typeof subscriptionChangeSchema>\n\n/**\n * The merchant's browser payment setup: its armed PSPs with their public\n * values and, with a Solana PSP, the network and accepted tokens a wallet\n * adapter is configured with.\n */\nexport const paymentConfigSchema = z.object({\n psps: z\n .array(pspConfigSchema)\n .nullish()\n .transform((v) => v ?? []),\n solana: z\n .object({\n /** `mainnet | devnet | testnet` */\n network: z.string(),\n /** `solana:<network>` */\n chain: z.string(),\n preferred_token: z.string().nullish(),\n tokens: z\n .array(\n z.object({\n symbol: z.string(),\n name: z.string().nullish(),\n mint: z.string(),\n decimals: z.number().int(),\n preferred: z.boolean().nullish(),\n recurring_eligible: z.boolean().nullish(),\n })\n )\n .nullish()\n .transform((v) => v ?? []),\n })\n .nullish(),\n})\nexport type PaymentConfig = z.infer<typeof paymentConfigSchema>\n\n/**\n * The challenge to solve when a request answers 403 `captcha_required`: load\n * `script_url`, solve with `site_key` and `action`, and resend the request\n * with the token in the `token_header` header.\n */\nexport const captchaConfigSchema = z.object({\n provider: z.string(),\n site_key: z.string(),\n script_url: z.string(),\n action: z.string(),\n token_header: z.string(),\n})\nexport type CaptchaConfig = z.infer<typeof captchaConfigSchema>\n\n/** The merchant as its customers see it; logo and support are https. */\nexport const publicMerchantSchema = z.object({\n display_name: z.string(),\n logo_url: z.string().nullish(),\n support_url: z.string().nullish(),\n /** The origins that may frame its embedded payment pages. */\n embed_origins: z\n .array(z.string())\n .nullish()\n .transform((v) => v ?? []),\n})\nexport type PublicMerchant = z.infer<typeof publicMerchantSchema>\n\n/**\n * What any browser needs to know about the deployment (`GET /config`, no\n * credential): the mount's capabilities, the currency registry and the\n * captcha (null when the deployment challenges nobody).\n */\nexport const publicConfigSchema = z.object({\n capabilities: z.object({\n route_groups: z.record(z.string(), z.boolean()),\n features: z.record(z.string(), z.boolean()),\n }),\n currencies: z\n .array(currencySchema)\n .nullish()\n .transform((v) => v ?? []),\n captcha: captchaConfigSchema.nullish(),\n /**\n * The payment page's sign-in to the customer network (OpenID Connect,\n * code and PKCE); null without the network or a payment page.\n */\n network: z.object({ issuer: z.string(), client_id: z.string() }).nullish(),\n})\nexport type PublicConfig = z.infer<typeof publicConfigSchema>\n\n/**\n * What a customer's browser needs to know about the merchant it pays\n * (`GET /me/config`): its payment setup and how it presents itself.\n */\nexport const customerConfigSchema = z.object({\n payment: paymentConfigSchema,\n merchant: publicMerchantSchema,\n})\nexport type CustomerConfig = z.infer<typeof customerConfigSchema>\n\nexport const networkLinkChallengeSchema = z.object({\n id: z.string(),\n nonce: z.string(),\n expires_at: time,\n})\nexport type NetworkLinkChallenge = z.infer<typeof networkLinkChallengeSchema>\n\nexport const customerLinkSchema = z.object({\n id: z.string(),\n merchant_id: z.string(),\n customer_id: z.string(),\n account_id: z.string(),\n method: z.string(),\n status: z.string(),\n linked_at: time,\n revoked_at: time.nullish(),\n revoked_by: z.string().nullish(),\n})\nexport type CustomerLink = z.infer<typeof customerLinkSchema>\n\n/**\n * What a card setup hands the server: tokenized data only, never a PAN.\n * OpenRails reads the saved card's brand, last four and expiry from the PSP.\n */\ninterface NewCardFields {\n /** The PSP the card is saved with (`psp_id` of a rail option); required. */\n psp_id: string\n billing_details?: {\n name?: string\n email?: string\n address?: { postal_code?: string; country?: string }\n }\n}\n\n/**\n * A card to save: the single-use token of the PSP's own fields (a Collect.js\n * token, a Stripe `pm_`), or, for a PSP whose card_entry is server\n * (`cardSetupDriver` \"card\"), the card itself, posted to OpenRails and never\n * kept by this package. A HyperSwitch capture starts without either; reuse an\n * Idempotency-Key and confirm the pending method with its vendor session token.\n */\nexport type NewCard = NewCardFields &\n (\n | { token: string; card?: never }\n | { card: CardEntry; token?: never }\n | { token?: never; card?: never }\n )\n\n/** A token issued by the vendor session of an owned pending payment method. */\nexport interface CardCaptureReference {\n custodian_id: string\n session_id: string\n token: string\n}\n","import type { z } from \"zod\"\n\nimport {\n BillingError,\n isBillingError,\n localError,\n readBillingError,\n} from \"./errors\"\nimport { OPENRAILS_CURRENCY_SCALES } from \"./generated/currencies\"\nimport type * as wire from \"./generated/wire\"\nimport { isTokenSource } from \"./token-source\"\nimport {\n accountSchema,\n customerConfigSchema,\n customerEntitlementSchema,\n customerLinkSchema,\n lowBalanceLineSchema,\n networkLinkChallengeSchema,\n publicConfigSchema,\n listPageSchema,\n orderSchema,\n cartSchema,\n paymentMethodSchema,\n paymentSchema,\n subscriptionSchema,\n subscriptionChangePreviewSchema,\n subscriptionChangeSchema,\n usageSchema,\n type Account,\n type CustomerConfig,\n type CustomerEntitlement,\n type CustomerLink,\n type LowBalanceLine,\n type NetworkLinkChallenge,\n type PublicConfig,\n type CurrencyScales,\n type ListPage,\n type NewCard,\n type CardCaptureReference,\n type NextAction,\n type Cart,\n type Order,\n type OrderPaymentInput,\n type Payment,\n type PaymentMethod,\n type Subscription,\n type SubscriptionChange,\n type SubscriptionChangePreview,\n type Usage,\n} from \"./types\"\n\nexport interface BillingClientOptions {\n /** OpenRails embedded mount. Default \"/billing/v1\". */\n baseUrl?: string\n /**\n * Transport. Pass an authenticating fetch (auth-ui's `client.authFetch`)\n * or combine the default with `getToken`.\n */\n fetch?: (input: string, init: RequestInit) => Promise<Response>\n /**\n * The customer's access token, sent as the bearer of every request but\n * the public read (`getConfig`); omit when `fetch` authenticates. A\n * `tokenSource` keeps it fresh: a call answered 401\n * `credential_expired` is then retried once with a new token.\n */\n getToken?: () =>\n string | null | undefined | Promise<string | null | undefined>\n /** Sent as Accept-Language. */\n language?: () => string | null | undefined\n /**\n * Extra or overriding currency scales (code -> native-unit decimals). The\n * pinned OpenRails registry is built in; `/me` amounts carry no scale.\n */\n currencies?: CurrencyScales\n}\n\nexport interface ListOptions {\n limit?: number\n offset?: number\n /** A cursor list's next page: the previous page's `next_cursor`. */\n cursor?: string\n signal?: AbortSignal\n}\n\n/**\n * A subscription change: another price of its tier group, other seats of a\n * per-seat price, or both. A quantity for a price that is not per seat is\n * refused (`quantity_not_allowed`).\n */\nexport interface SubscriptionChangeInput {\n priceId?: string\n quantity?: number\n}\n\nexport interface CursorOptions {\n limit?: number\n cursor?: string | null\n signal?: AbortSignal\n}\n\n/**\n * A page of the customer's usage report in `currency`, grouped by `groupBy`\n * (event type by default). `from` and `to` are RFC 3339 or a date; left out,\n * the month before now, or with `cursor` the window of the page it came from.\n * `limit` is at most 1,000 groups (default 100).\n */\nexport interface UsageOptions extends CursorOptions {\n currency: string\n groupBy?: \"event_type\" | \"resource\" | \"invoker\" | \"meter\"\n from?: string\n to?: string\n}\n\n/**\n * Signs and submits a base64 transaction with the customer's wallet and\n * returns its signature. Throw `WalletRejectedError` when the user declines.\n */\nexport type SendSolanaTransaction = (\n transactionBase64: string\n) => Promise<string>\n\nexport class WalletRejectedError extends Error {\n constructor(message = \"The wallet request was declined.\") {\n super(message)\n this.name = \"WalletRejectedError\"\n }\n}\n\nexport const CANCEL_REASON_MIN = 4\nexport const CANCEL_REASON_MAX = 500\n\n/** A next action the customer's wallet completes. */\nexport const isWalletAction = (next: NextAction | null | undefined): boolean =>\n next?.type === \"solana_sign_transactions\" && !!next.transactions?.length\n\n/**\n * Signs and sends a `solana_sign_transactions` next action's transactions in\n * order and returns the last signature, the value the action is repeated\n * with. A declined prompt is a local `wallet_rejected` error.\n */\nexport async function signWalletAction(\n next: NextAction,\n sendTransaction: SendSolanaTransaction\n): Promise<string> {\n let signature = \"\"\n for (const transaction of next.transactions ?? []) {\n try {\n signature = await sendTransaction(transaction)\n } catch (err) {\n if (isWalletRejection(err))\n throw localError(\"wallet_rejected\", \"The wallet request was declined.\")\n throw err\n }\n if (!signature)\n throw localError(\n \"wallet_no_signature\",\n \"The wallet returned no signature.\"\n )\n }\n if (!signature)\n throw localError(\"wallet_no_signature\", \"The wallet returned no signature.\")\n return signature\n}\n\ntype Query = Record<string, string | number | boolean | string[] | undefined>\n\ninterface RequestOptions {\n method?: string\n query?: Query\n body?: unknown\n signal?: AbortSignal\n headers?: Record<string, string>\n /** A public route: it reads no credential, so none is sent. */\n public?: boolean\n}\n\n/** Total wait a GET may spend on its one retry. */\nexport const RETRY_BUDGET_MS = 2_000\nconst RETRY_DELAY_MS = 300\n\n// The wait before retrying a GET answered with res, or null if it is final.\nfunction retryDelay(res: Response): number | null {\n const retryAfter = parseRetryAfter(res.headers.get(\"Retry-After\"))\n switch (res.status) {\n case 429:\n return retryAfter\n case 503:\n return retryAfter ?? RETRY_DELAY_MS\n case 502:\n case 504:\n return RETRY_DELAY_MS\n default:\n return null\n }\n}\n\nfunction parseRetryAfter(value: string | null): number | null {\n if (!value) return null\n if (/^\\d+$/.test(value.trim())) return Number(value.trim()) * 1000\n const at = Date.parse(value)\n return Number.isNaN(at) ? null : Math.max(0, at - Date.now())\n}\n\nfunction pause(ms: number, signal?: AbortSignal): Promise<number> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) return reject(signal.reason)\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", abort)\n resolve(ms)\n }, ms)\n const abort = () => {\n clearTimeout(timer)\n reject(signal?.reason)\n }\n signal?.addEventListener(\"abort\", abort, { once: true })\n })\n}\n\n/**\n * An order request's answer. `error` is set when the payment failed: the\n * order is open again and its `payment.last_payment_error` says why.\n */\nexport interface OrderResult {\n order: Order\n error?: BillingError\n}\n\nexport function createBillingClient(options: BillingClientOptions = {}) {\n const base = (options.baseUrl ?? \"/billing/v1\").replace(/\\/+$/, \"\")\n const doFetch =\n options.fetch ?? ((input: string, init: RequestInit) => fetch(input, init))\n const currencies = normalizeScales({\n ...OPENRAILS_CURRENCY_SCALES,\n ...options.currencies,\n })\n\n function url(path: string, query?: Query): string {\n const qs = new URLSearchParams()\n for (const [k, v] of Object.entries(query ?? {}))\n if (Array.isArray(v)) for (const item of v) qs.append(k, item)\n else if (v !== undefined && v !== \"\") qs.set(k, String(v))\n const q = qs.toString()\n return `${base}${path}${q ? `?${q}` : \"\"}`\n }\n\n async function send(\n path: string,\n opts: RequestOptions = {}\n ): Promise<Response> {\n const headers = new Headers({ Accept: \"application/json\", ...opts.headers })\n if (opts.body !== undefined) headers.set(\"Content-Type\", \"application/json\")\n let token = opts.public ? undefined : await options.getToken?.()\n if (token) headers.set(\"Authorization\", `Bearer ${token}`)\n const lang = options.language?.()\n if (lang) headers.set(\"Accept-Language\", lang)\n const method = opts.method ?? \"GET\"\n const init = {\n method,\n headers,\n body: opts.body === undefined ? undefined : JSON.stringify(opts.body),\n signal: opts.signal,\n }\n // Only a GET is retried: once, on a network error or 502/503/504 (and a\n // 429 that names its wait), within RETRY_BUDGET_MS. Writes never are.\n const retries = method === \"GET\" ? 1 : 0\n let waited = 0\n let renewed = false\n for (let attempt = 0; ; attempt++) {\n let res: Response\n try {\n res = await doFetch(url(path, opts.query), init)\n } catch (cause) {\n const delay = RETRY_DELAY_MS\n if (\n attempt >= retries ||\n opts.signal?.aborted ||\n !(cause instanceof TypeError) ||\n waited + delay > RETRY_BUDGET_MS\n )\n throw cause\n waited += await pause(delay, opts.signal)\n continue\n }\n if (res.ok) return res\n // The gate refused an expired token before the route ran: any call,\n // a write too, is sent once more with the source's next token.\n if (\n res.status === 401 &&\n token &&\n !renewed &&\n isTokenSource(options.getToken)\n ) {\n const refusal = await readBillingError(res)\n if (refusal.code !== \"credential_expired\") throw refusal\n options.getToken.invalidate(token)\n token = await options.getToken()\n headers.set(\"Authorization\", `Bearer ${token}`)\n renewed = true\n attempt--\n continue\n }\n const delay = retryDelay(res)\n if (\n attempt >= retries ||\n delay === null ||\n waited + delay > RETRY_BUDGET_MS\n )\n throw await readBillingError(res)\n await res.body?.cancel().catch(() => undefined)\n waited += await pause(delay, opts.signal)\n }\n }\n\n async function json<S extends z.ZodType>(\n schema: S,\n path: string,\n opts?: RequestOptions\n ): Promise<z.output<S>> {\n const res = await send(path, opts)\n let body: unknown\n try {\n body = await res.json()\n } catch {\n throw localError(\"invalid_response\", `${path}: body is not JSON`)\n }\n const parsed = schema.safeParse(body)\n if (!parsed.success)\n throw localError(\n \"invalid_response\",\n `${path}: ${parsed.error.issues[0]?.path.join(\".\")} ${parsed.error.issues[0]?.message}`\n )\n return parsed.data\n }\n\n const id = (value: string) => encodeURIComponent(value)\n const subscriptionPage = listPageSchema(subscriptionSchema)\n const methodPage = listPageSchema(paymentMethodSchema)\n const paymentPage = listPageSchema(paymentSchema)\n const orderPage = listPageSchema(orderSchema)\n const entitlementPage = listPageSchema(customerEntitlementSchema)\n const cursorQuery = (opts: CursorOptions, limit: number) => ({\n limit: opts.limit ?? limit,\n cursor: opts.cursor ?? undefined,\n })\n\n // An order answer: the order, or a failed payment's 402 with it.\n async function orderResult(\n path: string,\n opts: RequestOptions\n ): Promise<OrderResult> {\n try {\n return { order: await json(orderSchema, path, opts) }\n } catch (cause) {\n if (isBillingError(cause) && cause.status === 402 && cause.order) {\n const order = orderSchema.safeParse(cause.order)\n if (order.success) return { order: order.data, error: cause }\n }\n throw cause\n }\n }\n\n const client = {\n baseUrl: base,\n\n /** One page of the customer's subscriptions, newest first. */\n listSubscriptions(\n opts: CursorOptions & { status?: string } = {}\n ): Promise<ListPage<Subscription>> {\n return json(subscriptionPage, \"/me/subscriptions\", {\n query: { status: opts.status ?? \"all\", ...cursorQuery(opts, 100) },\n signal: opts.signal,\n })\n },\n\n /** Includes `recovery` (list rows do not). */\n getSubscription(\n subscriptionId: string,\n signal?: AbortSignal\n ): Promise<Subscription> {\n return json(\n subscriptionSchema,\n `/me/subscriptions/${id(subscriptionId)}`,\n {\n signal,\n }\n )\n },\n\n /**\n * Cancels at period end and answers the subscription. When the rail needs\n * the customer's step (`next_action`, a Solana wallet signature), the\n * subscription is unchanged: complete it with `signWalletAction` and\n * repeat with `signature`.\n */\n cancelSubscription(\n subscriptionId: string,\n input: { reason: string; signature?: string }\n ): Promise<Subscription> {\n return json(\n subscriptionSchema,\n `/me/subscriptions/${id(subscriptionId)}/cancel`,\n {\n method: \"POST\",\n body: {\n reason: input.reason.trim(),\n signature: input.signature,\n } satisfies wire.CustomerCancelSubscriptionParams,\n }\n )\n },\n\n /** Undoes a scheduled cancel before the period ends. */\n resumeSubscription(subscriptionId: string): Promise<Subscription> {\n return json(\n subscriptionSchema,\n `/me/subscriptions/${id(subscriptionId)}/resume`,\n { method: \"POST\", body: {} }\n )\n },\n\n /** Gives the subscription its own card; `null` makes it follow the default. */\n setSubscriptionPaymentMethod(\n subscriptionId: string,\n paymentMethodId: string | null\n ): Promise<Subscription> {\n return json(\n subscriptionSchema,\n `/me/subscriptions/${id(subscriptionId)}/payment-method`,\n {\n method: \"PUT\",\n body: {\n payment_method_id: paymentMethodId,\n } satisfies wire.SetSubscriptionPaymentMethodParams,\n }\n )\n },\n\n /** What `changeSubscription` would charge now and at the next renewal. */\n previewSubscriptionChange(\n subscriptionId: string,\n change: SubscriptionChangeInput,\n signal?: AbortSignal\n ): Promise<SubscriptionChangePreview> {\n return json(\n subscriptionChangePreviewSchema,\n `/me/subscriptions/${id(subscriptionId)}/change/preview`,\n {\n method: \"POST\",\n body: {\n price_id: change.priceId,\n quantity: change.quantity,\n } satisfies wire.PreviewSubscriptionChangeParams,\n signal,\n }\n )\n },\n\n /**\n * Reads the provider for a change awaiting the customer, after they\n * completed its `next_action` (the issuer's authentication), and answers\n * the change as it now stands.\n */\n confirmSubscriptionChange(\n subscriptionId: string\n ): Promise<SubscriptionChange> {\n return json(\n subscriptionChangeSchema,\n `/me/subscriptions/${id(subscriptionId)}/confirm`,\n { method: \"POST\", body: {} }\n )\n },\n\n /**\n * Moves the subscription to another price of its tier group, to other\n * seats of a per-seat price, or both. An upgrade and more seats charge\n * the saved card now; a downgrade and fewer seats apply at period end.\n * Reuse `idempotencyKey` until the change resolves (`processing`, a\n * `subscription_change_in_flight` refusal or a lost response) so the\n * stored result replays instead of charging twice. A Solana wallet next\n * action is completed with `signWalletAction`, then repeated with\n * `signature`; an `authenticate` one with `authenticateChange`.\n */\n changeSubscription(\n subscriptionId: string,\n input: SubscriptionChangeInput & {\n idempotencyKey: string\n signature?: string\n }\n ): Promise<SubscriptionChange> {\n return json(\n subscriptionChangeSchema,\n `/me/subscriptions/${id(subscriptionId)}/change`,\n {\n method: \"POST\",\n body: {\n price_id: input.priceId,\n quantity: input.quantity,\n signature: input.signature,\n } satisfies wire.CustomerChangeSubscriptionParams,\n headers: { \"Idempotency-Key\": input.idempotencyKey },\n }\n )\n },\n\n listPaymentMethods(\n opts: CursorOptions = {}\n ): Promise<ListPage<PaymentMethod>> {\n return json(methodPage, \"/me/payment-methods\", {\n query: cursorQuery(opts, 100),\n signal: opts.signal,\n })\n },\n\n /**\n * Saves a card entered in the page with the PSP `psp_id` in one call: the\n * token of its own fields, or the card itself (\"card\"). A Stripe card the\n * bank wants authenticated answers `requires_action`. HyperSwitch capture\n * starts without token/card and requires a stable `idempotencyKey`.\n */\n addPaymentMethod(\n card: NewCard,\n idempotencyKey?: string\n ): Promise<PaymentMethod> {\n return json(paymentMethodSchema, \"/me/payment-methods\", {\n method: \"POST\",\n body: card,\n headers: idempotencyKey\n ? { \"Idempotency-Key\": idempotencyKey }\n : undefined,\n })\n },\n\n /** The customer's cart, priced now. */\n getCart(signal?: AbortSignal): Promise<Cart> {\n return json(cartSchema, \"/me/cart\", { signal })\n },\n\n /**\n * Puts a price in the cart or changes its line, and answers the cart.\n * `quantity` 0 removes the line; omitted, the price's default. `amount`\n * is the customer's choice on a price that takes one.\n */\n setCartLine(\n priceId: string,\n input: { quantity?: number; amount?: string } = {}\n ): Promise<Cart> {\n return json(cartSchema, `/me/cart/lines/${id(priceId)}`, {\n method: \"PUT\",\n body: input satisfies wire.SetCartLineParams,\n })\n },\n\n /** Empties the cart. */\n async clearCart(): Promise<void> {\n await send(\"/me/cart\", { method: \"DELETE\" })\n },\n\n /**\n * Creates an order from `lines` or the cart (`cart: true`), and with\n * `payment` pays it in the same call; `expectedTotal` is the total the\n * customer saw; `idempotencyKey`, required with `payment`, names the\n * payment attempt. A failed payment resolves as payOrder's does. Without\n * `payment` the customer's open order of the same lines is answered when\n * there is one. With `payUrl` the order answers its embedded pay URL,\n * `order.pay_url` on the payment origin, for `<EmbeddedPayment>`, fresh\n * on every answer: the merchant's own signed-in person only.\n */\n createOrder(input: {\n lines?: { price_id: string; quantity?: number; amount?: string }[]\n cart?: boolean\n expectedTotal?: string\n payment?: OrderPaymentInput\n reusable?: boolean\n payUrl?: wire.MyOrderPayURLParams\n idempotencyKey?: string\n }): Promise<OrderResult> {\n return orderResult(\"/me/orders\", {\n method: \"POST\",\n body: {\n ...(input.cart ? { cart: true } : { lines: input.lines ?? [] }),\n ...(input.expectedTotal === undefined\n ? {}\n : { expected_total: input.expectedTotal }),\n ...(input.payment === undefined ? {} : { payment: input.payment }),\n ...(input.reusable === undefined ? {} : { reusable: input.reusable }),\n ...(input.payUrl === undefined ? {} : { pay_url: input.payUrl }),\n },\n headers: input.idempotencyKey\n ? { \"Idempotency-Key\": input.idempotencyKey }\n : undefined,\n })\n },\n\n /**\n * The customer's orders, newest first: `origin: \"usage\"` their usage\n * orders, `overdue` those still owed past their due date.\n */\n listOrders(\n opts: CursorOptions & {\n /** Read exactly these orders (at most 100), e.g. a page of payments'. */\n ids?: string[]\n origin?: string\n status?: string\n subscriptionId?: string\n overdue?: boolean\n } = {}\n ): Promise<ListPage<Order>> {\n // A set of ids is the whole query: it takes no paging or filter.\n if (opts.ids?.length)\n return json(orderPage, \"/me/orders\", {\n query: { ids: opts.ids.join(\",\") },\n signal: opts.signal,\n })\n return json(orderPage, \"/me/orders\", {\n query: {\n ...cursorQuery(opts, 20),\n origin: opts.origin,\n status: opts.status,\n subscription_id: opts.subscriptionId,\n overdue: opts.overdue ? \"true\" : undefined,\n },\n signal: opts.signal,\n })\n },\n\n /** One of the customer's orders: the resumable handle of a purchase. */\n getOrder(orderId: string, signal?: AbortSignal): Promise<Order> {\n return json(orderSchema, `/me/orders/${id(orderId)}`, { signal })\n },\n\n /**\n * Pays an open order. A failed payment resolves with the order (open,\n * `payment.last_payment_error` saying why) and `error`, the 402.\n * `idempotencyKey` is minted when the pay button renders: a retry with it\n * answers what the first request answered.\n */\n payOrder(\n orderId: string,\n input: {\n payment: OrderPaymentInput\n expectedTotal: string\n reusable?: boolean\n idempotencyKey: string\n }\n ): Promise<OrderResult> {\n return orderResult(`/me/orders/${id(orderId)}/pay`, {\n method: \"POST\",\n body: {\n payment: input.payment,\n expected_total: input.expectedTotal,\n ...(input.reusable === undefined ? {} : { reusable: input.reusable }),\n },\n headers: { \"Idempotency-Key\": input.idempotencyKey },\n })\n },\n\n /**\n * Reads the provider after the customer completed `next_action`. A Solana\n * wallet's `signature` names the transaction it sent: a subscription's\n * first payment enrolls from it at once.\n */\n confirmOrder(\n orderId: string,\n input?: { signature?: string }\n ): Promise<OrderResult> {\n return orderResult(`/me/orders/${id(orderId)}/confirm`, {\n method: \"POST\",\n body: input?.signature ? { signature: input.signature } : {},\n })\n },\n\n /**\n * Finishes saving a card the bank asked to authenticate, after the PSP's\n * script answered its `next_action`.\n */\n confirmPaymentMethod(\n paymentMethodId: string,\n capture?: CardCaptureReference\n ): Promise<PaymentMethod> {\n return json(\n paymentMethodSchema,\n `/me/payment-methods/${id(paymentMethodId)}/confirm`,\n { method: \"POST\", body: capture ? { capture } : {} }\n )\n },\n\n /** `pending` when the provider is still converging (202). */\n async removePaymentMethod(\n paymentMethodId: string\n ): Promise<\"removed\" | \"pending\"> {\n const res = await send(`/me/payment-methods/${id(paymentMethodId)}`, {\n method: \"DELETE\",\n })\n return res.status === 202 ? \"pending\" : \"removed\"\n },\n\n /**\n * Makes the card the default for one currency: it pays the currency's\n * usage orders and every subscription in it without its own card.\n */\n async setDefaultPaymentMethod(input: {\n currency: string\n paymentMethodId: string\n }): Promise<void> {\n await send(\n `/me/default-payment-methods/${id(input.currency.toUpperCase())}`,\n {\n method: \"PUT\",\n body: {\n payment_method_id: input.paymentMethodId,\n } satisfies wire.SetDefaultPaymentMethodParams,\n }\n )\n },\n\n /** Charges and refunds, newest first. `rail` filters by rail. */\n listPayments(\n opts: CursorOptions & { rail?: string } = {}\n ): Promise<ListPage<Payment>> {\n return json(paymentPage, \"/me/payments\", {\n query: { ...cursorQuery(opts, 20), rail: opts.rail },\n signal: opts.signal,\n })\n },\n\n /**\n * One page of the entitlement keys the customer holds (up to 500 by\n * default), by key. `at` reads them as of an RFC 3339 instant; `prefix`\n * keeps the keys that start with it.\n */\n getEntitlements(\n opts: CursorOptions & { at?: string; prefix?: string } = {}\n ): Promise<ListPage<CustomerEntitlement>> {\n return json(entitlementPage, \"/me/entitlements\", {\n query: { ...cursorQuery(opts, 500), at: opts.at, prefix: opts.prefix },\n signal: opts.signal,\n })\n },\n\n /**\n * The customer's summary: balance and amount owed per currency, the card\n * that pays each currency, and the low-balance line of each balance.\n */\n getAccount(signal?: AbortSignal): Promise<Account> {\n return json(accountSchema, \"/me\", { signal })\n },\n\n /**\n * Sets the customer's own low-balance line in one currency and answers\n * the line its balance is judged at. `null` inherits the merchant's; 0\n * turns that part off.\n */\n setLowBalanceLine(input: {\n currency: string\n amount: string | null\n runwayHours: number | null\n }): Promise<LowBalanceLine> {\n return json(\n lowBalanceLineSchema,\n `/me/low-balance-lines/${id(input.currency.toUpperCase())}`,\n {\n method: \"PUT\",\n body: {\n amount: input.amount,\n runway_hours: input.runwayHours,\n } satisfies wire.SetLowBalanceLineParams,\n }\n )\n },\n\n /**\n * A page of the customer's usage: its groups by total amount, largest\n * first. Pass the answer's `next_cursor` as `cursor` for the next page.\n */\n getUsage(opts: UsageOptions): Promise<Usage> {\n return json(usageSchema, \"/me/usage\", {\n query: {\n currency: opts.currency,\n group_by: opts.groupBy,\n from: opts.from,\n to: opts.to,\n limit: opts.limit,\n cursor: opts.cursor ?? undefined,\n },\n signal: opts.signal,\n })\n },\n\n /**\n * A challenge to link the customer to an openrails.dev account: its\n * `nonce` goes in the network sign-in's authorization request.\n */\n createNetworkLinkChallenge(): Promise<NetworkLinkChallenge> {\n return json(networkLinkChallengeSchema, \"/me/network-link/challenges\", {\n method: \"POST\",\n body: {},\n })\n },\n\n /**\n * Links the customer to the openrails.dev account whose fresh sign-in\n * answered the challenge (its ID token).\n */\n createNetworkLink(params: {\n challengeId: string\n idToken: string\n }): Promise<CustomerLink> {\n return json(customerLinkSchema, \"/me/network-link\", {\n method: \"POST\",\n body: { challenge_id: params.challengeId, id_token: params.idToken },\n })\n },\n\n /**\n * The deployment's configuration, a public read: what the mount serves,\n * the currency registry and the captcha. React components share one\n * copy through `useConfig()`.\n */\n getConfig(signal?: AbortSignal): Promise<PublicConfig> {\n return json(publicConfigSchema, \"/config\", { signal, public: true })\n },\n\n /**\n * The customer's merchant: its payment setup (PSPs, Solana network and\n * tokens) and how it presents itself. React components share one copy\n * through `useCustomerConfig()`.\n */\n getCustomerConfig(signal?: AbortSignal): Promise<CustomerConfig> {\n return json(customerConfigSchema, \"/me/config\", { signal })\n },\n\n /** Currency code (upper case) to native-unit decimals. */\n currencies,\n }\n return client\n}\n\nfunction normalizeScales(scales: CurrencyScales): CurrencyScales {\n return Object.fromEntries(\n Object.entries(scales).map(([code, decimals]) => [\n code.toUpperCase(),\n decimals,\n ])\n )\n}\n\nexport type BillingClient = ReturnType<typeof createBillingClient>\n\nexport const isWalletRejection = (error: unknown): boolean =>\n error instanceof WalletRejectedError ||\n (error instanceof Error && error.name === \"WalletRejectedError\") ||\n (error instanceof BillingError && error.code === \"wallet_rejected\")\n"],"mappings":";;AAgBA,IAAa,IAAb,cAAkC,MAAM;CACtC;CACA;CACA;CACA;CACA;CACA;CAEA;CAEA,YAAY,GAAgB,GAAwB;EASlD,AARA,MAAM,EAAK,OAAO,GAClB,KAAK,OAAO,gBACZ,KAAK,SAAS,GACd,KAAK,OAAO,EAAK,MACjB,KAAK,OAAO,EAAK,MACjB,KAAK,QAAQ,EAAK,OAClB,KAAK,YAAY,EAAK,YACtB,KAAK,WAAW,EAAK,YAAY,CAAC,GAClC,KAAK,QAAQ,EAAK;CACpB;AACF,GAEa,KAAkB,MAC7B,aAAiB,GAGN,KAAiB,MAA4B;CACxD,IAAM,IAAU,GAAuC;CACvD,OAAO,OAAO,KAAW,YAAY,KAAU,OAAO,IAAS;AACjE;AAEA,SAAgB,EAAW,GAAc,GAA+B;CACtE,OAAO,IAAI,EAAa,GAAG;EAAE,MAAM;EAAS;EAAM;CAAQ,CAAC;AAC7D;AAEA,eAAsB,EAAiB,GAAsC;CAC3E,IAAI;CACJ,IAAI;EACF,IAAO,MAAM,EAAI,KAAK;CACxB,QAAQ;EACN,IAAO,KAAA;CACT;CACA,IAAM,IAAO,GAA0C;CACvD,IAAI,KAAO,OAAO,KAAQ,UAAU;EAClC,IAAM,IAAI;EACV,IAAI,OAAO,EAAE,QAAS,YAAY,EAAE,MAClC,OAAO,IAAI,EAAa,EAAI,QAAQ;GAClC,MAAM,OAAO,EAAE,QAAS,WAAW,EAAE,OAAO;GAC5C,MAAM,EAAE;GACR,SAAS,OAAO,EAAE,WAAY,WAAW,EAAE,UAAU,EAAE;G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