@openrails/billing-ui 0.273.0 → 0.275.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/admin/components/customer-search.d.ts +5 -0
- package/dist/admin/components/missing-record.d.ts +6 -0
- package/dist/admin/components/status-badge.d.ts +1 -0
- package/dist/admin/context.d.ts +34 -2
- package/dist/admin/lib/api/endpoints.d.ts +4 -1
- package/dist/admin/lib/api/index.d.ts +3 -0
- package/dist/admin/lib/api/order-endpoints.d.ts +1 -0
- package/dist/admin/lib/api/types.d.ts +4 -12
- package/dist/admin/lib/capabilities.d.ts +4 -0
- package/dist/admin/lib/dialog-width.d.ts +4 -3
- package/dist/admin/lib/error-text.d.ts +4 -0
- package/dist/admin/lib/format.d.ts +5 -1
- package/dist/admin/lib/mutations.d.ts +6 -1
- package/dist/admin/lib/order-queries.d.ts +3 -0
- package/dist/admin/lib/queries.d.ts +6 -0
- package/dist/admin/lib/tile-grids.d.ts +6 -0
- package/dist/admin/messages.d.ts +102 -8
- package/dist/admin/pages/dashboard/lib.d.ts +1 -0
- package/dist/admin/pages/imports/shared.d.ts +1 -0
- package/dist/admin/pages/payments/index.d.ts +1 -2
- package/dist/admin/pages/subscriptions/change-subscription-dialog.d.ts +4 -7
- package/dist/admin/pages/subscriptions/index.d.ts +1 -2
- package/dist/admin/pages/subscriptions/subscription-change-options.d.ts +6 -15
- package/dist/admin-attempts-CP5CWyNR.js +419 -0
- package/dist/admin-attempts-CP5CWyNR.js.map +1 -0
- package/dist/{admin-auth-1aZIgXiS.js → admin-auth-DlIOmwPo.js} +2 -2
- package/dist/{admin-auth-1aZIgXiS.js.map → admin-auth-DlIOmwPo.js.map} +1 -1
- package/dist/{admin-badge-pgG6D9-a.js → admin-badge-DR_8AhdC.js} +2 -2
- package/dist/{admin-badge-pgG6D9-a.js.map → admin-badge-DR_8AhdC.js.map} +1 -1
- package/dist/{admin-button-CrcYk5r0.js → admin-button-DBzTD6By.js} +2 -2
- package/dist/{admin-button-CrcYk5r0.js.map → admin-button-DBzTD6By.js.map} +1 -1
- package/dist/{admin-capabilities-BDcZeHL_.js → admin-capabilities-CZdT1Pxe.js} +35 -14
- package/dist/admin-capabilities-CZdT1Pxe.js.map +1 -0
- package/dist/{admin-card-DvTMc5Se.js → admin-card-mZl4-s5d.js} +2 -2
- package/dist/{admin-card-DvTMc5Se.js.map → admin-card-mZl4-s5d.js.map} +1 -1
- package/dist/{admin-catalog-BlF5mnu4.js → admin-catalog-DpTjS0Yo.js} +298 -298
- package/dist/{admin-catalog-BlF5mnu4.js.map → admin-catalog-DpTjS0Yo.js.map} +1 -1
- package/dist/{admin-cursor-pager-CIb3Jw2F.js → admin-cursor-pager-C-KjCIy9.js} +6 -6
- package/dist/{admin-cursor-pager-CIb3Jw2F.js.map → admin-cursor-pager-C-KjCIy9.js.map} +1 -1
- package/dist/{admin-customers-EpfoWDh-.js → admin-customers-BE3N839X.js} +22 -21
- package/dist/{admin-customers-EpfoWDh-.js.map → admin-customers-BE3N839X.js.map} +1 -1
- package/dist/admin-dashboard-BxjkV15J.js +464 -0
- package/dist/admin-dashboard-BxjkV15J.js.map +1 -0
- package/dist/admin-data-table-D89AwWz_.js +107 -0
- package/dist/admin-data-table-D89AwWz_.js.map +1 -0
- package/dist/admin-detail-BKe9xqPd.js +338 -0
- package/dist/admin-detail-BKe9xqPd.js.map +1 -0
- package/dist/admin-detail-C8lD7U2t.js +699 -0
- package/dist/admin-detail-C8lD7U2t.js.map +1 -0
- package/dist/admin-detail-D6zD085K.js +354 -0
- package/dist/admin-detail-D6zD085K.js.map +1 -0
- package/dist/{admin-detail-3wFIDPNB.js → admin-detail-Ln56otK0.js} +83 -83
- package/dist/{admin-detail-3wFIDPNB.js.map → admin-detail-Ln56otK0.js.map} +1 -1
- package/dist/admin-detail-P-UnNvXJ.js +1357 -0
- package/dist/admin-detail-P-UnNvXJ.js.map +1 -0
- package/dist/{admin-dialog-BSRf9Zre.js → admin-dialog-Dn2FRJu4.js} +3 -3
- package/dist/{admin-dialog-BSRf9Zre.js.map → admin-dialog-Dn2FRJu4.js.map} +1 -1
- package/dist/admin-dialog-width-CC7QHT1p.js +6 -0
- package/dist/admin-dialog-width-CC7QHT1p.js.map +1 -0
- package/dist/{admin-dropdown-menu-D0E5rwmn.js → admin-dropdown-menu-DLUn6Uj3.js} +2 -2
- package/dist/{admin-dropdown-menu-D0E5rwmn.js.map → admin-dropdown-menu-DLUn6Uj3.js.map} +1 -1
- package/dist/{admin-dunning-B2zgtrOo.js → admin-dunning-COaHzrmN.js} +2 -2
- package/dist/{admin-dunning-B2zgtrOo.js.map → admin-dunning-COaHzrmN.js.map} +1 -1
- package/dist/{admin-fact-card-BPSVhS15.js → admin-fact-card-DKvBnUXB.js} +2 -2
- package/dist/{admin-fact-card-BPSVhS15.js.map → admin-fact-card-DKvBnUXB.js.map} +1 -1
- package/dist/admin-format-BbiTCqUG.js +171 -0
- package/dist/admin-format-BbiTCqUG.js.map +1 -0
- package/dist/{admin-health-D0L5Kig7.js → admin-health-DmnI4e8K.js} +249 -248
- package/dist/admin-health-DmnI4e8K.js.map +1 -0
- package/dist/{admin-imports-CgZB5JAV.js → admin-imports-C0aMP6sj.js} +65 -65
- package/dist/{admin-imports-CgZB5JAV.js.map → admin-imports-C0aMP6sj.js.map} +1 -1
- package/dist/{admin-input-DJAK9nmk.js → admin-input-JKrQIGfD.js} +2 -2
- package/dist/{admin-input-DJAK9nmk.js.map → admin-input-JKrQIGfD.js.map} +1 -1
- package/dist/{admin-label-aviN9Gng.js → admin-label-CHWsVIZC.js} +2 -2
- package/dist/{admin-label-aviN9Gng.js.map → admin-label-CHWsVIZC.js.map} +1 -1
- package/dist/{admin-linked-table-row-BGr7JXeM.js → admin-linked-table-row-BMZYYsuk.js} +4 -4
- package/dist/{admin-linked-table-row-BGr7JXeM.js.map → admin-linked-table-row-BMZYYsuk.js.map} +1 -1
- package/dist/{admin-map-dialog-DS2Wz6G3.js → admin-map-dialog-BHUGdCcv.js} +24 -24
- package/dist/{admin-map-dialog-DS2Wz6G3.js.map → admin-map-dialog-BHUGdCcv.js.map} +1 -1
- package/dist/{admin-metering-D-e-37Jn.js → admin-metering-CDqueHUh.js} +307 -307
- package/dist/{admin-metering-D-e-37Jn.js.map → admin-metering-CDqueHUh.js.map} +1 -1
- package/dist/admin-missing-record-BPFs3MmO.js +42 -0
- package/dist/admin-missing-record-BPFs3MmO.js.map +1 -0
- package/dist/admin-ops-CL2kjDwi.js +359 -0
- package/dist/admin-ops-CL2kjDwi.js.map +1 -0
- package/dist/admin-orders-C1Sf2qhc.js +192 -0
- package/dist/admin-orders-C1Sf2qhc.js.map +1 -0
- package/dist/admin-parked-a0tB5bhG.js +193 -0
- package/dist/admin-parked-a0tB5bhG.js.map +1 -0
- package/dist/admin-payments-DJcjwRA4.js +221 -0
- package/dist/admin-payments-DJcjwRA4.js.map +1 -0
- package/dist/{admin-price-detail-CSI5oKdb.js → admin-price-detail-BOmeWw15.js} +103 -103
- package/dist/{admin-price-detail-CSI5oKdb.js.map → admin-price-detail-BOmeWw15.js.map} +1 -1
- package/dist/{admin-price-format-BVUpDoSC.js → admin-price-format-CqOmHrIn.js} +2 -2
- package/dist/{admin-price-format-BVUpDoSC.js.map → admin-price-format-CqOmHrIn.js.map} +1 -1
- package/dist/{admin-price-wizard-CBEcNGvP.js → admin-price-wizard-B6s5OJeO.js} +63 -63
- package/dist/{admin-price-wizard-CBEcNGvP.js.map → admin-price-wizard-B6s5OJeO.js.map} +1 -1
- package/dist/{admin-proposals-Cuj7tvaM.js → admin-proposals-DVrl-ym4.js} +70 -70
- package/dist/{admin-proposals-Cuj7tvaM.js.map → admin-proposals-DVrl-ym4.js.map} +1 -1
- package/dist/admin-provider-prices-BVVogH7Q.js +241 -0
- package/dist/admin-provider-prices-BVVogH7Q.js.map +1 -0
- package/dist/{admin-range-picker-De36L-AP.js → admin-range-picker-C6BtSm2B.js} +9 -9
- package/dist/{admin-range-picker-De36L-AP.js.map → admin-range-picker-C6BtSm2B.js.map} +1 -1
- package/dist/{admin-records-H0MlhEVY.js → admin-records-DKtcgN11.js} +50 -50
- package/dist/{admin-records-H0MlhEVY.js.map → admin-records-DKtcgN11.js.map} +1 -1
- package/dist/{admin-reports-BFGS_PWf.js → admin-reports-CtPoiceH.js} +50 -50
- package/dist/{admin-reports-BFGS_PWf.js.map → admin-reports-CtPoiceH.js.map} +1 -1
- package/dist/{admin-select-BUcEU5Rg.js → admin-select-6Yuh5M1Q.js} +2 -2
- package/dist/{admin-select-BUcEU5Rg.js.map → admin-select-6Yuh5M1Q.js.map} +1 -1
- package/dist/admin-settings-DscHu4ww.js +1823 -0
- package/dist/admin-settings-DscHu4ww.js.map +1 -0
- package/dist/{admin-shared-lfIUEbPY.js → admin-shared-BywM-MMp.js} +28 -24
- package/dist/{admin-shared-lfIUEbPY.js.map → admin-shared-BywM-MMp.js.map} +1 -1
- package/dist/{admin-skeleton-B0yzYY_X.js → admin-skeleton-lndmw89u.js} +2 -2
- package/dist/{admin-skeleton-B0yzYY_X.js.map → admin-skeleton-lndmw89u.js.map} +1 -1
- package/dist/admin-status-badge-IL8ofZ_6.js +51 -0
- package/dist/admin-status-badge-IL8ofZ_6.js.map +1 -0
- package/dist/admin-subscriptions-Cd5CGrue.js +271 -0
- package/dist/admin-subscriptions-Cd5CGrue.js.map +1 -0
- package/dist/{admin-switch-DDorugaw.js → admin-switch-DpwQSzEm.js} +2 -2
- package/dist/{admin-switch-DDorugaw.js.map → admin-switch-DpwQSzEm.js.map} +1 -1
- package/dist/{admin-table-BU6Tie69.js → admin-table-D-GdGM1m.js} +2 -2
- package/dist/{admin-table-BU6Tie69.js.map → admin-table-D-GdGM1m.js.map} +1 -1
- package/dist/admin-tabs-B--1flzO.js +158 -0
- package/dist/admin-tabs-B--1flzO.js.map +1 -0
- package/dist/{admin-textarea-Dc6lnEub.js → admin-textarea-xsp5V9xM.js} +2 -2
- package/dist/{admin-textarea-Dc6lnEub.js.map → admin-textarea-xsp5V9xM.js.map} +1 -1
- package/dist/admin-tile-grids-CzGpidd9.js +6 -0
- package/dist/admin-tile-grids-CzGpidd9.js.map +1 -0
- package/dist/{admin-typed-confirm-dialog-Bk6XxmPb.js → admin-typed-confirm-dialog-NiEDwX_0.js} +11 -11
- package/dist/{admin-typed-confirm-dialog-Bk6XxmPb.js.map → admin-typed-confirm-dialog-NiEDwX_0.js.map} +1 -1
- package/dist/{admin-utils-B9eEBNsR.js → admin-utils-wuPUD0uh.js} +341 -283
- package/dist/admin-utils-wuPUD0uh.js.map +1 -0
- package/dist/admin-widget-viz-kHHVmDEx.js +646 -0
- package/dist/admin-widget-viz-kHHVmDEx.js.map +1 -0
- package/dist/admin.css +1 -1
- package/dist/admin.js +544 -413
- package/dist/admin.js.map +1 -1
- package/dist/client/generated/routes.d.ts +17 -0
- package/dist/client/generated/wire.d.ts +4 -0
- package/dist/client/types.d.ts +6 -0
- package/dist/{client-BYgnI6_h.js → client-ctrbivyN.js} +3 -2
- package/dist/client-ctrbivyN.js.map +1 -0
- package/dist/client.js +1 -1
- package/dist/{hooks-t2tSrCpa.js → hooks-KpTetx6F.js} +2 -2
- package/dist/{hooks-t2tSrCpa.js.map → hooks-KpTetx6F.js.map} +1 -1
- package/dist/index.js +750 -711
- package/dist/index.js.map +1 -1
- package/dist/lib/card-brands.d.ts +1 -0
- package/dist/locales/de.js +3 -0
- package/dist/locales/de.js.map +1 -1
- package/dist/locales/en.d.ts +3 -0
- package/dist/locales/en.js +3 -0
- package/dist/locales/en.js.map +1 -1
- package/dist/locales/es.js +3 -0
- package/dist/locales/es.js.map +1 -1
- package/dist/locales/ja.js +3 -0
- package/dist/locales/ja.js.map +1 -1
- package/dist/locales/ko.js +3 -0
- package/dist/locales/ko.js.map +1 -1
- package/dist/locales/zh.js +3 -0
- package/dist/locales/zh.js.map +1 -1
- package/dist/react.js +1 -1
- package/dist/styles.css +1 -1
- package/package.json +1 -1
- package/dist/admin-attempts-DyDDt-qw.js +0 -418
- package/dist/admin-attempts-DyDDt-qw.js.map +0 -1
- package/dist/admin-capabilities-BDcZeHL_.js.map +0 -1
- package/dist/admin-dashboard-CJE63yz4.js +0 -420
- package/dist/admin-dashboard-CJE63yz4.js.map +0 -1
- package/dist/admin-data-table-hvFcJepL.js +0 -96
- package/dist/admin-data-table-hvFcJepL.js.map +0 -1
- package/dist/admin-detail-BRP6pL7t.js +0 -328
- package/dist/admin-detail-BRP6pL7t.js.map +0 -1
- package/dist/admin-detail-CRzFb_pa.js +0 -1331
- package/dist/admin-detail-CRzFb_pa.js.map +0 -1
- package/dist/admin-detail-QLxU8r-5.js +0 -344
- package/dist/admin-detail-QLxU8r-5.js.map +0 -1
- package/dist/admin-detail-pPC8Q9l-.js +0 -710
- package/dist/admin-detail-pPC8Q9l-.js.map +0 -1
- package/dist/admin-dialog-width-BPrgdYlj.js +0 -6
- package/dist/admin-dialog-width-BPrgdYlj.js.map +0 -1
- package/dist/admin-format-DoohJ7Fg.js +0 -136
- package/dist/admin-format-DoohJ7Fg.js.map +0 -1
- package/dist/admin-health-D0L5Kig7.js.map +0 -1
- package/dist/admin-ops-CQP4TzWM.js +0 -235
- package/dist/admin-ops-CQP4TzWM.js.map +0 -1
- package/dist/admin-orders-BJ7W5S8P.js +0 -192
- package/dist/admin-orders-BJ7W5S8P.js.map +0 -1
- package/dist/admin-parked-B8xHkV2e.js +0 -193
- package/dist/admin-parked-B8xHkV2e.js.map +0 -1
- package/dist/admin-payments-CzkzqYA1.js +0 -246
- package/dist/admin-payments-CzkzqYA1.js.map +0 -1
- package/dist/admin-provider-prices-B6vwnVPi.js +0 -246
- package/dist/admin-provider-prices-B6vwnVPi.js.map +0 -1
- package/dist/admin-settings-DYC-c7mJ.js +0 -1813
- package/dist/admin-settings-DYC-c7mJ.js.map +0 -1
- package/dist/admin-status-badge-0-K37EfN.js +0 -43
- package/dist/admin-status-badge-0-K37EfN.js.map +0 -1
- package/dist/admin-subscriptions-CvW-YFs0.js +0 -301
- package/dist/admin-subscriptions-CvW-YFs0.js.map +0 -1
- package/dist/admin-tabs-D5lqdVcC.js +0 -46
- package/dist/admin-tabs-D5lqdVcC.js.map +0 -1
- package/dist/admin-utils-B9eEBNsR.js.map +0 -1
- package/dist/admin-widget-viz-8aukE3v_.js +0 -581
- package/dist/admin-widget-viz-8aukE3v_.js.map +0 -1
- package/dist/client-BYgnI6_h.js.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/scope.tsx","../src/components/ui/button.tsx","../src/lib/period.ts","../src/account/format.ts","../src/components/ui/card.tsx","../src/components/ui/skeleton.tsx","../src/account/section.tsx","../src/components/ui/badge.tsx","../src/account/status-badge.tsx","../src/account/payment-history.tsx","../src/lib/card-brands.ts","../src/components/card-brands.tsx","../src/components/ui/alert-dialog.tsx","../src/components/ui/dialog.tsx","../src/components/ui/spinner.tsx","../src/components/ui/input.tsx","../src/components/ui/label.tsx","../src/lib/billing.ts","../src/components/billing-fields.tsx","../src/components/card-fields.tsx","../src/components/pay-button.tsx","../src/components/platform-card-form.tsx","../src/lib/stripe.ts","../src/lib/collect.ts","../src/lib/stripe-appearance.ts","../src/components/stripe-card.tsx","../src/lib/card-entry.ts","../src/tokenized-card-form.tsx","../src/save-payment-method.tsx","../src/account/notice.tsx","../src/account/payment-methods-panel.tsx","../src/components/ui/textarea.tsx","../src/account/cancel-dialog.tsx","../src/components/ui/radio-group.tsx","../src/account/change-card-dialog.tsx","../src/authenticate.ts","../src/account/change-plan.tsx","../src/account/resume-dialog.tsx","../src/account/subscriptions-panel.tsx","../src/account/account-billing.tsx","../src/account/renewal-prompt.tsx","../src/components/qr.tsx","../src/components/saved-methods.tsx","../src/components/states.tsx","../src/components/stripe-wallets.tsx","../src/fallbacks.ts","../src/order-payment.tsx","../src/embedded-payment.tsx","../src/cart.tsx","../src/lib/price-label.ts","../src/modal.tsx","../src/buy-button.tsx","../src/product-list.tsx","../src/lib/billing-notification.ts","../src/components/billing-notification.tsx"],"sourcesContent":["import type { ComponentProps } from \"react\"\n\nimport type { BillingAppearance } from \"./appearance\"\nimport { cn } from \"cn\"\nimport { useScopeProps } from \"./scope-context\"\n\n/** Styling root for in-page billing surfaces. */\nexport function BillingUiRoot({\n appearance,\n className,\n style,\n ...props\n}: ComponentProps<\"div\"> & { appearance?: BillingAppearance }) {\n const scope = useScopeProps(appearance)\n return (\n <div\n data-orck-theme={scope[\"data-orck-theme\"]}\n className={cn(scope.className, className)}\n style={{ ...scope.style, ...style }}\n {...props}\n />\n )\n}\n","import { Button as ButtonPrimitive } from \"@base-ui/react/button\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\nimport { cn } from \"cn\"\n\nconst buttonVariants = cva(\n \"group/button inline-flex shrink-0 items-center justify-center rounded-md border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\",\n {\n variants: {\n variant: {\n default: \"bg-primary text-primary-foreground hover:bg-primary/80\",\n outline:\n \"border-border bg-background shadow-xs hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50\",\n secondary:\n \"bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground\",\n ghost:\n \"hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50\",\n destructive:\n \"bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40\",\n link: \"text-primary underline-offset-4 hover:underline\",\n },\n size: {\n default:\n \"h-9 gap-1.5 px-2.5 in-data-[slot=button-group]:rounded-md has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2\",\n xs: \"h-6 gap-1 rounded-[min(var(--radius-md),8px)] px-2 text-xs in-data-[slot=button-group]:rounded-md has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3\",\n sm: \"h-8 gap-1 rounded-[min(var(--radius-md),10px)] px-2.5 in-data-[slot=button-group]:rounded-md has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5\",\n lg: \"h-10 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2\",\n icon: \"size-9\",\n \"icon-xs\":\n \"size-6 rounded-[min(var(--radius-md),8px)] in-data-[slot=button-group]:rounded-md [&_svg:not([class*='size-'])]:size-3\",\n \"icon-sm\":\n \"size-8 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-md\",\n \"icon-lg\": \"size-10\",\n },\n },\n defaultVariants: {\n variant: \"default\",\n size: \"default\",\n },\n }\n)\n\nfunction Button({\n className,\n variant = \"default\",\n size = \"default\",\n ...props\n}: ButtonPrimitive.Props & VariantProps<typeof buttonVariants>) {\n return (\n <ButtonPrimitive\n data-slot=\"button\"\n className={cn(buttonVariants({ variant, size, className }))}\n {...props}\n />\n )\n}\n\nexport { Button, buttonVariants }\n","import type { Translator } from \"../i18n/messages\"\n\n// OpenRails durations are exact hours (720h is 30 days, never \"a month\"), so\n// labels name only units that divide the window exactly.\nexport type PeriodUnit = \"hour\" | \"day\" | \"week\"\n\nexport interface Period {\n unit: PeriodUnit\n count: number\n}\n\nexport function periodOf(hours: number | null | undefined): Period | null {\n if (!hours || !Number.isSafeInteger(hours) || hours <= 0) return null\n if (hours % 168 === 0) return { unit: \"week\", count: hours / 168 }\n if (hours % 24 === 0) return { unit: \"day\", count: hours / 24 }\n return { unit: \"hour\", count: hours }\n}\n\n/** \"every 30 days\" */\nexport function everyLabel(hours: number | null | undefined, m: Translator) {\n const p = periodOf(hours)\n return p ? m.plural(`interval.every.${p.unit}`, p.count) : null\n}\n\n/** \"/ 30 days\" */\nexport function perLabel(hours: number | null | undefined, m: Translator) {\n const p = periodOf(hours)\n return p ? m.plural(`interval.per.${p.unit}`, p.count) : null\n}\n\n/** \"30 days of access\", for a window that does not renew. */\nexport function accessLabel(hours: number | null | undefined, m: Translator) {\n const p = periodOf(hours)\n return p ? m.plural(`interval.access.${p.unit}`, p.count) : null\n}\n","import type {\n CardSummary,\n CurrencyScales,\n Order,\n Payment,\n Price,\n Subscription,\n} from \"../client/types\"\nimport type { Translator } from \"../i18n/messages\"\nimport { formatAmount } from \"../lib/money\"\nimport { accessLabel, everyLabel } from \"../lib/period\"\n\nexport function formatDate(\n value: string | null | undefined,\n locale?: string\n): string | null {\n if (!value) return null\n const date = new Date(value)\n if (Number.isNaN(date.getTime())) return null\n try {\n return new Intl.DateTimeFormat(locale, { dateStyle: \"medium\" }).format(date)\n } catch {\n return date.toISOString().slice(0, 10)\n }\n}\n\n/** Exact money, or null while the currency's scale is unknown. */\nexport function formatMoney(\n amount: string | null | undefined,\n currency: string,\n scales: CurrencyScales,\n locale?: string\n): string | null {\n if (!amount) return null\n const decimals = scales[currency.toUpperCase()]\n if (decimals === undefined) return null\n return formatAmount(amount, currency, decimals, locale)\n}\n\n/** \"every 30 days\", \"30 days of access\" or \"one-time\". */\nexport function intervalLabel(\n price:\n | Pick<Price, \"access_duration_hours\" | \"billing_interval_hours\">\n | null\n | undefined,\n m: Translator\n): string | null {\n if (!price) return null\n if (price.billing_interval_hours)\n return everyLabel(price.billing_interval_hours, m)\n return accessLabel(price.access_duration_hours, m) ?? m.t(\"interval.once\")\n}\n\nexport function subscriptionName(s: Subscription, { t }: Translator): string {\n return (\n s.product?.display_name?.trim() ||\n s.price?.key?.trim() ||\n t(\"subscriptions.fallbackName\")\n )\n}\n\n/**\n * What a payment bought, from the frozen lines of the order it settles: their\n * names and, for one recurring line, its cadence. Without its order, the kind.\n */\nexport function paymentItem(\n p: Payment,\n order: Order | undefined,\n m: Translator\n): { name: string; detail: string | null } {\n const names = [\n ...new Set(\n (order?.lines ?? []).map((l) => l.description.trim()).filter(Boolean)\n ),\n ]\n const line = order?.lines.length === 1 ? order.lines[0] : undefined\n return {\n name:\n names.join(\", \") ||\n m.t(p.subscription_id ? \"history.subscription\" : \"history.purchase\"),\n detail: line?.billing_interval_hours\n ? everyLabel(line.billing_interval_hours, m)\n : null,\n }\n}\n\nexport function brandName(brand: string | null | undefined, fallback: string) {\n const value = brand?.trim()\n if (!value) return fallback\n return value[0].toUpperCase() + value.slice(1).toLowerCase()\n}\n\n/** \"Visa •••• 4242 · 12/30\"; the brand alone when no digits are known. */\nexport function cardText(\n card: CardSummary | null | undefined,\n m: Translator\n): string {\n const brand = brandName(card?.brand, m.t(\"paymentMethods.fallbackBrand\"))\n if (!card?.last4) return brand\n const label = m.t(\"paymentMethods.cardLabel\", { brand, last4: card.last4 })\n const expires = expiry(card)\n return expires ? `${label} · ${expires}` : label\n}\n\nexport function expiry(card: CardSummary | null | undefined): string | null {\n if (!card?.exp_month || !card.exp_year) return null\n return `${String(card.exp_month).padStart(2, \"0\")}/${String(card.exp_year).slice(-2)}`\n}\n\nexport const LIVE_STATUSES = new Set([\n \"active\",\n \"pending\",\n \"past_due\",\n \"awaiting_method\",\n \"unverified\",\n])\n\nconst future = (at: string | null | undefined) =>\n !!at && new Date(at).getTime() > Date.now()\n\n/** A current subscription, or a canceled subscription retaining paid access. */\nexport const isLive = (s: Subscription) =>\n LIVE_STATUSES.has(s.status) ||\n (s.status === \"canceled\" &&\n !!s.access &&\n (!s.access.ends_at || future(s.access.ends_at)))\n\n/** Future billing has stopped or cancellation is scheduled. */\nexport const isEnding = (s: Subscription) =>\n isLive(s) && (!!s.cancel_scheduled || s.status === \"canceled\")\n\n/** A subscription OpenRails could move to another plan of its tier group. */\nexport const changeable = (s: Subscription) =>\n (s.status === \"active\" || s.status === \"past_due\") &&\n !s.cancel_scheduled &&\n !s.cancel_portal_url &&\n !!s.product?.tier_group\n\nexport type StatusTone = \"success\" | \"warning\" | \"destructive\" | \"neutral\"\n\nconst TONE: Record<string, StatusTone> = {\n active: \"success\",\n succeeded: \"success\",\n paid: \"success\",\n default: \"neutral\",\n pending: \"warning\",\n past_due: \"warning\",\n awaiting_method: \"warning\",\n cancel_scheduled: \"warning\",\n expiring_soon: \"warning\",\n needs_attention: \"warning\",\n partially_refunded: \"neutral\",\n failed: \"destructive\",\n expired: \"destructive\",\n canceled: \"neutral\",\n refunded: \"neutral\",\n}\n\nexport const statusTone = (status: string): StatusTone =>\n TONE[status] ?? \"neutral\"\n\n// The package ships no preflight, so account surfaces zero UA text margins.\nexport const RESET =\n \"[&_h2]:m-0 [&_p]:m-0 [&_ul]:m-0 [&_ul]:list-none [&_ul]:p-0 [&_table]:border-spacing-0\"\n","import * as React from \"react\"\nimport { cn } from \"cn\"\n\nfunction Card({\n className,\n size = \"default\",\n ...props\n}: React.ComponentProps<\"div\"> & { size?: \"default\" | \"sm\" }) {\n return (\n <div\n data-slot=\"card\"\n data-size={size}\n className={cn(\n \"group/card flex flex-col gap-(--card-spacing) overflow-hidden rounded-xl bg-card py-(--card-spacing) text-sm text-card-foreground shadow-xs ring-1 ring-foreground/10 [--card-spacing:--spacing(6)] has-[>img:first-child]:pt-0 data-[size=sm]:[--card-spacing:--spacing(4)] *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardHeader({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-header\"\n className={cn(\n \"group/card-header @container/card-header grid auto-rows-min items-start gap-1 rounded-t-xl px-(--card-spacing) has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] [.border-b]:pb-(--card-spacing)\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardTitle({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-title\"\n className={cn(\n \"text-base leading-normal font-medium group-data-[size=sm]/card:text-sm\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardDescription({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-description\"\n className={cn(\"text-sm text-muted-foreground\", className)}\n {...props}\n />\n )\n}\n\nfunction CardAction({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-action\"\n className={cn(\n \"col-start-2 row-span-2 row-start-1 self-start justify-self-end\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardContent({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-content\"\n className={cn(\"flex flex-col gap-3 px-(--card-spacing)\", className)}\n {...props}\n />\n )\n}\n\nfunction CardFooter({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-footer\"\n className={cn(\n \"flex items-center rounded-b-xl px-(--card-spacing) [.border-t]:pt-(--card-spacing)\",\n className\n )}\n {...props}\n />\n )\n}\n\nexport {\n Card,\n CardHeader,\n CardFooter,\n CardTitle,\n CardAction,\n CardDescription,\n CardContent,\n}\n","import { cn } from \"cn\"\n\nfunction Skeleton({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"skeleton\"\n className={cn(\"animate-pulse rounded-md bg-muted\", className)}\n {...props}\n />\n )\n}\n\nexport { Skeleton }\n","import * as React from \"react\"\nimport { cn } from \"cn\"\n\nimport type { BillingAppearance } from \"#orck/appearance\"\nimport type { BillingError } from \"#orck/client/errors\"\nimport { Button } from \"#orck/components/ui/button\"\nimport {\n Card,\n CardAction,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from \"#orck/components/ui/card\"\nimport { Skeleton } from \"#orck/components/ui/skeleton\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport { useScopeProps } from \"#orck/scope-context\"\nimport { RESET } from \"./format\"\n\nexport interface SectionProps {\n title: string\n description?: string\n action?: React.ReactNode\n appearance?: BillingAppearance\n className?: string\n children?: React.ReactNode\n \"data-testid\"?: string\n}\n\n// Styling root plus card. Each panel is usable alone, so each is a root.\nexport function Section({\n title,\n description,\n action,\n appearance,\n className,\n children,\n ...rest\n}: SectionProps) {\n const scope = useScopeProps(appearance)\n const id = React.useId()\n return (\n <section\n aria-labelledby={id}\n className={cn(scope.className, RESET, \"block\", className)}\n data-orck-theme={scope[\"data-orck-theme\"]}\n style={scope.style}\n data-testid={rest[\"data-testid\"]}\n >\n <Card className=\"gap-4 bg-card text-card-foreground\">\n <CardHeader>\n <CardTitle id={id} role=\"heading\" aria-level={2}>\n {title}\n </CardTitle>\n {description ? (\n <CardDescription>{description}</CardDescription>\n ) : null}\n {action ? <CardAction>{action}</CardAction> : null}\n </CardHeader>\n <CardContent className=\"gap-0\">{children}</CardContent>\n </Card>\n </section>\n )\n}\n\nexport function ListSkeleton({ rows = 2 }: { rows?: number }) {\n return (\n <div className=\"grid gap-4 py-2\" aria-hidden>\n {Array.from({ length: rows }, (_, i) => (\n <div key={i} className=\"flex items-center gap-3\">\n <Skeleton className=\"h-7 w-11 rounded-md\" />\n <div className=\"grid flex-1 gap-2\">\n <Skeleton className=\"h-3.5 w-40\" />\n <Skeleton className=\"h-3 w-28\" />\n </div>\n <Skeleton className=\"h-3.5 w-14\" />\n </div>\n ))}\n </div>\n )\n}\n\nexport function EmptyState({\n title,\n description,\n action,\n}: {\n title: string\n description?: string\n action?: React.ReactNode\n}) {\n return (\n <div className=\"grid justify-items-center gap-1 rounded-lg border border-dashed px-4 py-8 text-center\">\n <p className=\"text-sm font-medium\">{title}</p>\n {description ? (\n <p className=\"text-sm text-muted-foreground\">{description}</p>\n ) : null}\n {action ? <div className=\"mt-3\">{action}</div> : null}\n </div>\n )\n}\n\nexport function ErrorState({\n error,\n message,\n onRetry,\n}: {\n error: BillingError\n /** Replaces the error's own message. */\n message?: string\n onRetry: () => void\n}) {\n const m = useMessages()\n return (\n <div\n role=\"alert\"\n className=\"flex flex-wrap items-center justify-between gap-3 rounded-lg bg-destructive/5 px-4 py-3\"\n >\n <p className=\"text-sm text-destructive\">{message ?? m.error(error)}</p>\n <Button variant=\"outline\" size=\"sm\" onClick={onRetry}>\n {m.t(\"common.retry\")}\n </Button>\n </div>\n )\n}\n","import { mergeProps } from \"@base-ui/react/merge-props\"\nimport { useRender } from \"@base-ui/react/use-render\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\nimport { cn } from \"cn\"\n\nconst badgeVariants = cva(\n \"group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-4xl border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!\",\n {\n variants: {\n variant: {\n default: \"bg-primary text-primary-foreground [a]:hover:bg-primary/80\",\n secondary:\n \"bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80\",\n destructive:\n \"bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20\",\n outline:\n \"border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground\",\n ghost:\n \"hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50\",\n link: \"text-primary underline-offset-4 hover:underline\",\n },\n },\n defaultVariants: {\n variant: \"default\",\n },\n }\n)\n\nfunction Badge({\n className,\n variant = \"default\",\n render,\n ...props\n}: useRender.ComponentProps<\"span\"> & VariantProps<typeof badgeVariants>) {\n return useRender({\n defaultTagName: \"span\",\n props: mergeProps<\"span\">(\n {\n className: cn(badgeVariants({ variant }), className),\n },\n props\n ),\n render,\n state: {\n slot: \"badge\",\n variant,\n },\n })\n}\n\nexport { Badge, badgeVariants }\n","import { cn } from \"cn\"\n\nimport { Badge } from \"#orck/components/ui/badge\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport type { MessageKey } from \"#orck/i18n/messages\"\nimport { statusTone, type StatusTone } from \"./format\"\n\nconst TONE_CLASS: Record<StatusTone, string> = {\n success: \"bg-[color:var(--orck-success)]/12 text-[color:var(--orck-success)]\",\n warning: \"bg-[color:var(--orck-warning)]/14 text-[color:var(--orck-warning)]\",\n destructive: \"bg-destructive/10 text-destructive\",\n neutral: \"bg-muted text-muted-foreground\",\n}\n\nexport interface BillingStatusBadgeProps {\n /** Subscription, payment or card-health status. */\n status: string\n /** Overrides the translated label. */\n label?: string\n className?: string\n}\n\nexport function BillingStatusBadge({\n status,\n label,\n className,\n}: BillingStatusBadgeProps) {\n const { t, messages } = useMessages()\n const key = status\n const text =\n label ??\n (key in messages.status\n ? t(`status.${key}` as MessageKey)\n : status.replace(/_/g, \" \"))\n return (\n <Badge\n data-status={status}\n className={cn(TONE_CLASS[statusTone(status)], \"font-medium\", className)}\n >\n {text}\n </Badge>\n )\n}\n","import * as React from \"react\"\nimport { cn } from \"cn\"\n\nimport type { BillingAppearance } from \"#orck/appearance\"\nimport type { Payment } from \"#orck/client/types\"\nimport { Button } from \"#orck/components/ui/button\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport type { MessageKey, Translator } from \"#orck/i18n/messages\"\nimport { usePayments, type PaymentsOptions } from \"#orck/react/hooks\"\nimport { useCurrencyScales } from \"#orck/react/config\"\nimport { useUiSettings } from \"#orck/scope-context\"\nimport { cardText, formatDate, formatMoney, paymentItem } from \"./format\"\nimport { EmptyState, ErrorState, ListSkeleton, Section } from \"./section\"\nimport { BillingStatusBadge } from \"./status-badge\"\n\nexport interface PaymentHistoryProps extends PaymentsOptions {\n appearance?: BillingAppearance\n className?: string\n}\n\nfunction methodText(p: Payment, m: Translator): string {\n if (p.card?.last4) return cardText(p.card, m)\n const rail = p.rail ?? \"\"\n return rail in m.messages.history.rail\n ? m.t(`history.rail.${rail}` as MessageKey)\n : rail || m.t(\"common.notAvailable\")\n}\n\nexport function PaymentHistory({\n appearance,\n className,\n ...options\n}: PaymentHistoryProps) {\n const m = useMessages()\n const { t } = m\n const { locale } = useUiSettings()\n const state = usePayments(options)\n const scales = useCurrencyScales()\n\n let body: React.ReactNode\n const payments = state.payments\n if (payments === null && state.error) {\n body = <ErrorState error={state.error} onRetry={state.refetch} />\n } else if (payments === null) {\n body = <ListSkeleton rows={3} />\n } else if (payments.length === 0 && state.page === 0) {\n body = (\n <EmptyState\n title={t(\"history.empty\")}\n description={t(\"history.emptyDescription\")}\n />\n )\n } else {\n body = (\n <div className=\"-mx-1 overflow-x-auto px-1\">\n <table\n className={cn(\n \"w-full border-collapse text-sm\",\n state.loading && \"opacity-60 transition-opacity\"\n )}\n aria-busy={state.loading || undefined}\n >\n <thead>\n <tr className=\"border-b text-left text-xs text-muted-foreground\">\n <th\n scope=\"col\"\n className=\"hidden py-2 pr-3 font-medium @md:table-cell\"\n >\n {t(\"history.date\")}\n </th>\n <th scope=\"col\" className=\"py-2 pr-3 font-medium\">\n {t(\"history.item\")}\n </th>\n <th\n scope=\"col\"\n className=\"hidden py-2 pr-3 font-medium @md:table-cell\"\n >\n {t(\"history.method\")}\n </th>\n <th scope=\"col\" className=\"py-2 pr-3 font-medium\">\n {t(\"history.status\")}\n </th>\n <th scope=\"col\" className=\"py-2 text-right font-medium\">\n {t(\"history.amount\")}\n </th>\n </tr>\n </thead>\n <tbody className=\"divide-y divide-border\">\n {payments.map((p) => {\n const refund = p.kind === \"refund\"\n const status = p.status || (refund ? \"refunded\" : \"unknown\")\n const amount = formatMoney(p.amount, p.currency, scales, locale)\n const refunded =\n !refund && p.amount_refunded && p.amount_refunded !== \"0\"\n ? formatMoney(p.amount_refunded, p.currency, scales, locale)\n : null\n const date =\n formatDate(p.created_at, locale) ?? t(\"common.notAvailable\")\n const item = paymentItem(\n p,\n p.order_id ? state.orders[p.order_id] : undefined,\n m\n )\n return (\n <tr key={p.id} data-testid=\"payment-row\" data-payment-id={p.id}>\n <td className=\"hidden py-3 pr-3 align-top whitespace-nowrap tabular-nums @md:table-cell\">\n {date}\n </td>\n <td className=\"py-3 pr-3 align-top\">\n <div data-testid=\"payment-item\" className=\"font-medium\">\n {item.name}\n </div>\n {p.status === \"failed\" && p.failure?.message ? (\n <div\n data-testid=\"payment-failure\"\n className=\"text-xs text-destructive\"\n >\n {p.failure.message}\n </div>\n ) : null}\n {item.detail ? (\n <div\n data-testid=\"payment-period\"\n className=\"text-xs text-muted-foreground\"\n >\n {item.detail}\n </div>\n ) : null}\n <div className=\"text-xs text-muted-foreground tabular-nums @md:hidden\">\n {date} · {methodText(p, m)}\n </div>\n </td>\n <td className=\"hidden py-3 pr-3 align-top text-muted-foreground tabular-nums @md:table-cell\">\n {methodText(p, m)}\n </td>\n <td className=\"py-3 pr-3 align-top\">\n <BillingStatusBadge\n status={status}\n label={refund ? t(\"history.refund\") : undefined}\n />\n </td>\n <td className=\"py-3 text-right align-top font-medium whitespace-nowrap tabular-nums\">\n {amount ?? t(\"common.notAvailable\")}\n {refunded ? (\n <div className=\"text-xs font-normal text-muted-foreground\">\n {t(\"history.refundedAmount\", { amount: refunded })}\n </div>\n ) : null}\n </td>\n </tr>\n )\n })}\n </tbody>\n </table>\n </div>\n )\n }\n\n const paged = state.page > 0 || state.hasMore\n return (\n <Section\n title={t(\"history.title\")}\n description={t(\"history.description\")}\n appearance={appearance}\n className={className}\n data-testid=\"payment-history\"\n >\n {body}\n {payments !== null && state.error ? (\n <div className=\"pt-3\">\n <ErrorState error={state.error} onRetry={state.refetch} />\n </div>\n ) : null}\n {paged ? (\n <nav\n aria-label={t(\"history.title\")}\n className=\"flex items-center justify-between gap-3 pt-4\"\n >\n <span className=\"text-xs text-muted-foreground tabular-nums\">\n {t(\"history.page\", { page: state.page + 1 })}\n </span>\n <div className=\"flex gap-2\">\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={state.page === 0 || state.loading}\n onClick={state.previous}\n >\n {t(\"common.previous\")}\n </Button>\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={!state.hasMore || state.loading}\n onClick={state.next}\n >\n {t(\"common.next\")}\n </Button>\n </div>\n </nav>\n ) : null}\n </Section>\n )\n}\n","// Card-network identity: which marks we ship and how a rail's spelling maps\n// onto them.\nexport type CardBrand = \"visa\" | \"mastercard\" | \"amex\"\n\nconst BRAND_ALIASES: Record<string, CardBrand> = {\n visa: \"visa\",\n mastercard: \"mastercard\",\n mc: \"mastercard\",\n master: \"mastercard\",\n amex: \"amex\",\n americanexpress: \"amex\",\n \"american express\": \"amex\",\n}\n\n// Resolves the rail's spelling of a brand (\"Visa\", \"MASTERCARD\", \"amex\") onto\n// the marks we ship; anything unknown falls back to a text plate.\nexport function resolveCardBrand(brand?: string): CardBrand | undefined {\n const key = brand\n ?.trim()\n .toLowerCase()\n .replace(/[^a-z ]/g, \"\")\n return key ? BRAND_ALIASES[key] : undefined\n}\n","// Card network marks, inlined rather than fetched: this package is meant to\n// run inside someone else's app, where an asset URL of ours would 404. Artwork\n// is each network's own published symbol, unmodified in shape and color.\nimport * as React from \"react\"\n\nimport { resolveCardBrand } from \"#orck/lib/card-brands\"\nimport { cn } from \"cn\"\n\nfunction VisaMark() {\n return (\n <svg viewBox=\"0 0 1000 324.68\" className=\"h-2.5 w-auto\" role=\"presentation\">\n <path\n fill=\"#1434cb\"\n d=\"m651.19.5c-70.93,0-134.32,36.77-134.32,104.69,0,77.9,112.42,83.28,112.42,122.42,0,16.48-18.88,31.23-51.14,31.23-45.77,0-79.98-20.61-79.98-20.61l-14.64,68.55s39.41,17.41,91.73,17.41c77.55,0,138.58-38.57,138.58-107.66,0-82.32-112.89-87.54-112.89-123.86,0-12.91,15.5-27.05,47.66-27.05,36.29,0,65.89,14.99,65.89,14.99l14.33-66.2S696.61.5,651.18.5h0ZM2.22,5.5L.5,15.49s29.84,5.46,56.72,16.36c34.61,12.49,37.07,19.77,42.9,42.35l63.51,244.83h85.14L379.93,5.5h-84.94l-84.28,213.17-34.39-180.7c-3.15-20.68-19.13-32.48-38.68-32.48,0,0-135.41,0-135.41,0Zm411.87,0l-66.63,313.53h81L494.85,5.5h-80.76Zm451.76,0c-19.53,0-29.88,10.46-37.47,28.73l-118.67,284.8h84.94l16.43-47.47h103.48l9.99,47.47h74.95L934.12,5.5h-68.27Zm11.05,84.71l25.18,117.65h-67.45l42.28-117.65h0Z\"\n />\n </svg>\n )\n}\n\nfunction MastercardMark() {\n return (\n <svg viewBox=\"0 0 152.4 108\" className=\"h-4 w-auto\" role=\"presentation\">\n <g>\n <rect y=\"0\" fill=\"none\" width=\"152.4\" height=\"108\" />\n <g>\n <rect x=\"60.4\" y=\"25.7\" fill=\"#FF5F00\" width=\"31.5\" height=\"56.6\" />\n <path\n fill=\"#EB001B\"\n d=\"M62.4,54c0-11,5.1-21.5,13.7-28.3c-15.6-12.3-38.3-9.6-50.6,6.1C13.3,47.4,16,70,31.7,82.3\n\t\t\tc13.1,10.3,31.4,10.3,44.5,0C67.5,75.5,62.4,65,62.4,54z\"\n />\n <path\n fill=\"#F79E1B\"\n d=\"M134.4,54c0,19.9-16.1,36-36,36c-8.1,0-15.9-2.7-22.2-7.7c15.6-12.3,18.3-34.9,6-50.6c-1.8-2.2-3.8-4.3-6-6\n\t\t\tc15.6-12.3,38.3-9.6,50.5,6.1C131.7,38.1,134.4,45.9,134.4,54z\"\n />\n </g>\n </g>\n </svg>\n )\n}\n\nfunction AmexMark() {\n const gradientId = `orck-amex-${React.useId().replace(/[^a-zA-Z0-9-]/g, \"\")}`\n return (\n <svg viewBox=\"0 0 300 300\" className=\"h-full w-auto\" role=\"presentation\">\n <radialGradient\n id={gradientId}\n cx=\"57.3882\"\n cy=\"57.021\"\n r=\"264.5797\"\n gradientUnits=\"userSpaceOnUse\"\n >\n <stop offset=\"0\" stopColor=\"#9DD5F6\" />\n <stop offset=\"0.0711\" stopColor=\"#98D3F5\" />\n <stop offset=\"0.1575\" stopColor=\"#89CEF3\" />\n <stop offset=\"0.2516\" stopColor=\"#70C6EF\" />\n <stop offset=\"0.3514\" stopColor=\"#4EBBEA\" />\n <stop offset=\"0.4546\" stopColor=\"#23ADE3\" />\n <stop offset=\"0.5\" stopColor=\"#0DA6E0\" />\n <stop offset=\"1\" stopColor=\"#2E77BC\" />\n </radialGradient>\n <path\n fill={`url(#${gradientId})`}\n d=\"M289.584,7.598H7.639v282.966h281.945v-93.386c1.12-1.619,1.673-3.69,1.673-6.222\n\tc0-2.898-0.553-4.693-1.673-6.205\"\n />\n <g></g>\n <path\n fill=\"#FFFFFF\"\n d=\"M33.053,130.042l-5.424-13.217l-5.393,13.217 M152.543,124.779c-1.089,0.661-2.377,0.683-3.92,0.683h-9.627\n\tv-7.364h9.758c1.381,0,2.822,0.062,3.758,0.598c1.028,0.483,1.664,1.511,1.664,2.931\n\tC154.176,123.076,153.571,124.242,152.543,124.779z M221.221,130.042l-5.484-13.217l-5.454,13.217H221.221z M93.201,144.348h-8.124\n\tl-0.03-25.966l-11.491,25.966h-6.958l-11.521-25.989v25.989H38.959l-3.045-7.395h-16.5l-3.076,7.395H7.731l14.191-33.154h11.774\n\tl13.478,31.39v-31.39h12.934l10.371,22.491l9.527-22.491h13.194V144.348z M125.58,144.348H99.107v-33.154h26.473v6.904h-18.548\n\tv5.976h18.103v6.796h-18.103v6.621h18.548V144.348z M162.906,120.123c0,5.286-3.528,8.017-5.584,8.837\n\tc1.734,0.66,3.215,1.826,3.92,2.792c1.119,1.649,1.312,3.122,1.312,6.083v6.513h-7.993l-0.03-4.181c0-1.995,0.191-4.864-1.251-6.459\n\tc-1.158-1.166-2.923-1.419-5.776-1.419h-8.507v12.059h-7.924v-33.154h18.227c4.05,0,7.034,0.107,9.596,1.588\n\tC161.403,114.263,162.906,116.425,162.906,120.123z M175.588,144.348h-8.086v-33.154h8.086V144.348z M269.396,144.348h-11.23\n\tl-15.021-24.884v24.884h-16.139l-3.084-7.395H207.46l-2.992,7.395h-9.273c-3.852,0-8.729-0.852-11.491-3.667\n\tc-2.785-2.815-4.234-6.628-4.234-12.657c0-4.917,0.866-9.412,4.272-12.964c2.562-2.646,6.574-3.866,12.035-3.866h7.672v7.104h-7.511\n\tc-2.892,0-4.525,0.43-6.098,1.964c-1.351,1.396-2.278,4.035-2.278,7.51c0,3.552,0.706,6.113,2.179,7.786\n\tc1.22,1.312,3.437,1.71,5.523,1.71h3.559l11.169-26.073h11.874l13.417,31.359v-31.359h12.066l13.93,23.09v-23.09h8.117V144.348z\n\t M7.639,150.86h13.54l3.053-7.364h6.835l3.045,7.364h26.641v-5.63l2.378,5.654h13.83l2.378-5.738v5.714h66.208l-0.031-12.088h1.281\n\tc0.897,0.031,1.159,0.114,1.159,1.595v10.493h34.243v-2.814c2.762,1.48,7.058,2.814,12.711,2.814h14.406l3.083-7.364h6.835\n\tl3.015,7.364h27.761v-6.995l4.204,6.995h22.246v-46.24h-22.016v5.461l-3.083-5.461H228.77v5.461l-2.831-5.461h-30.515\n\tc-5.108,0-9.598,0.713-13.225,2.7v-2.7h-21.058v2.7c-2.308-2.048-5.453-2.7-8.95-2.7H75.258l-5.162,11.943l-5.301-11.943H40.563\n\tv5.461l-2.662-5.461H17.235l-9.597,21.985V150.86z\"\n />\n <path\n fill=\"#FFFFFF\"\n d=\"M289.584,175.315h-14.443c-1.442,0-2.4,0.054-3.207,0.599c-0.836,0.537-1.158,1.334-1.158,2.386\n\tc0,1.251,0.706,2.102,1.733,2.47c0.836,0.291,1.734,0.376,3.054,0.376l4.295,0.115c4.334,0.107,7.227,0.852,8.991,2.669\n\tc0.321,0.253,0.514,0.537,0.735,0.821 M289.584,197.178c-1.925,2.815-5.676,4.242-10.754,4.242h-15.304v-7.111h15.242\n\tc1.512,0,2.57-0.199,3.207-0.821c0.552-0.513,0.937-1.258,0.937-2.163c0-0.966-0.385-1.733-0.968-2.193\n\tc-0.575-0.506-1.412-0.736-2.792-0.736c-7.441-0.253-16.724,0.23-16.724-10.264c0-4.81,3.054-9.873,11.37-9.873h15.785v-6.598\n\th-14.666c-4.426,0-7.641,1.06-9.918,2.708v-2.708h-21.693c-3.469,0-7.541,0.86-9.467,2.708v-2.708h-38.738v2.708\n\tc-3.083-2.224-8.285-2.708-10.686-2.708h-25.552v2.708c-2.439-2.362-7.863-2.708-11.169-2.708h-28.597l-6.544,7.082l-6.129-7.082\n\tH63.706v46.272h41.914l6.743-7.194l6.352,7.194l25.836,0.023v-10.885h2.54c3.428,0.053,7.471-0.085,11.038-1.627v12.488h21.31\n\tv-12.06h1.028c1.312,0,1.441,0.054,1.441,1.365v10.694h64.736c4.11,0,8.406-1.052,10.785-2.961v2.961h20.534\n\tc4.273,0,8.446-0.599,11.621-2.133V197.178z M257.973,183.93c1.543,1.597,2.37,3.613,2.37,7.026c0,7.134-4.457,10.464-12.449,10.464\n\th-15.435v-7.111h15.373c1.503,0,2.569-0.199,3.237-0.821c0.545-0.513,0.936-1.258,0.936-2.163c0-0.966-0.423-1.733-0.967-2.193\n\tc-0.606-0.506-1.442-0.736-2.822-0.736c-7.411-0.253-16.692,0.23-16.692-10.264c0-4.81,3.022-9.873,11.33-9.873h15.887v7.058\n\th-14.537c-1.441,0-2.378,0.054-3.175,0.599c-0.868,0.537-1.19,1.334-1.19,2.386c0,1.251,0.737,2.102,1.734,2.47\n\tc0.836,0.291,1.734,0.376,3.084,0.376l4.266,0.115C253.225,181.368,256.178,182.112,257.973,183.93z M186.465,181.882\n\tc-1.06,0.629-2.371,0.683-3.913,0.683h-9.627v-7.448h9.758c1.411,0,2.823,0.03,3.782,0.599c1.027,0.537,1.641,1.564,1.641,2.983\n\tS187.492,181.261,186.465,181.882z M191.251,186.009c1.764,0.651,3.206,1.818,3.882,2.784c1.119,1.619,1.281,3.13,1.313,6.053v6.574\n\th-7.956v-4.149c0-1.995,0.192-4.949-1.281-6.491c-1.158-1.188-2.923-1.472-5.814-1.472h-8.469v12.112h-7.963v-33.162h18.296\n\tc4.012,0,6.934,0.177,9.535,1.565c2.501,1.511,4.074,3.581,4.074,7.364C196.867,182.48,193.337,185.181,191.251,186.009z\n\t M201.262,168.258h26.449v6.858h-18.557v6.029h18.104v6.766h-18.104v6.598l18.557,0.03v6.881h-26.449V168.258z M147.795,183.562\n\th-10.241v-8.445h10.333c2.861,0,4.847,1.166,4.847,4.066C152.734,182.051,150.84,183.562,147.795,183.562z M129.661,198.404\n\tl-12.167-13.508l12.167-13.079V198.404z M98.24,194.509H78.756v-6.598h17.398v-6.766H78.756v-6.029h19.868l8.668,9.664\n\tL98.24,194.509z M161.242,179.183c0,9.212-6.873,11.114-13.8,11.114h-9.888v11.123h-15.403l-9.758-10.978l-10.141,10.978h-31.39\n\tv-33.162h31.873l9.75,10.87l10.08-10.87h25.322C154.176,168.258,161.242,169.999,161.242,179.183z\"\n />\n </svg>\n )\n}\n\n// A fixed plate keeps every row's leading edge aligned whatever the mark's\n// aspect ratio.\nexport function CardBrandPlate({\n brand,\n fallback,\n className,\n}: {\n brand?: string\n fallback: string\n className?: string\n}) {\n const resolved = resolveCardBrand(brand)\n return (\n <span\n aria-hidden\n className={cn(\n \"grid h-7 w-11 shrink-0 place-items-center overflow-hidden rounded-md\",\n // White ground only because the marks are drawn for light surfaces —\n // on a light page it simply disappears and the mark stands alone.\n resolved\n ? \"bg-white\"\n : \"bg-muted text-[10px] font-semibold tracking-wide text-muted-foreground uppercase\",\n className\n )}\n >\n {resolved === \"visa\" ? (\n <VisaMark />\n ) : resolved === \"mastercard\" ? (\n <MastercardMark />\n ) : resolved === \"amex\" ? (\n <AmexMark />\n ) : (\n fallback\n )}\n </span>\n )\n}\n\nconst SUPPORTED_BRANDS = [\n { brand: \"visa\", Mark: VisaMark },\n { brand: \"mastercard\", Mark: MastercardMark },\n { brand: \"amex\", Mark: AmexMark },\n] as const\n\n// The accepted networks; once a number's brand is known, the others dim.\nexport function SupportedCardBrands({ active }: { active?: string }) {\n const resolved = resolveCardBrand(active)\n return (\n <span aria-hidden className=\"flex items-center gap-1\">\n {SUPPORTED_BRANDS.map(({ brand, Mark }) => (\n <span\n key={brand}\n className={cn(\n \"grid h-5 w-8 place-items-center rounded-[4px] bg-white ring-1 ring-[color:var(--border)] transition-opacity\",\n resolved && resolved !== brand && \"opacity-30\"\n )}\n >\n <Mark />\n </span>\n ))}\n </span>\n )\n}\n","\"use client\"\n\nimport * as React from \"react\"\nimport { AlertDialog as AlertDialogPrimitive } from \"@base-ui/react/alert-dialog\"\nimport { cn } from \"cn\"\n\nimport { Button } from \"#orck/components/ui/button\"\n\nfunction AlertDialog({ ...props }: AlertDialogPrimitive.Root.Props) {\n return <AlertDialogPrimitive.Root data-slot=\"alert-dialog\" {...props} />\n}\n\nfunction AlertDialogTrigger({ ...props }: AlertDialogPrimitive.Trigger.Props) {\n return (\n <AlertDialogPrimitive.Trigger data-slot=\"alert-dialog-trigger\" {...props} />\n )\n}\n\nfunction AlertDialogPortal({ ...props }: AlertDialogPrimitive.Portal.Props) {\n return (\n <AlertDialogPrimitive.Portal data-slot=\"alert-dialog-portal\" {...props} />\n )\n}\n\nfunction AlertDialogOverlay({\n className,\n ...props\n}: AlertDialogPrimitive.Backdrop.Props) {\n return (\n <AlertDialogPrimitive.Backdrop\n data-slot=\"alert-dialog-overlay\"\n className={cn(\n \"fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction AlertDialogContent({\n className,\n size = \"default\",\n ...props\n}: AlertDialogPrimitive.Popup.Props & {\n size?: \"default\" | \"sm\"\n}) {\n return (\n <AlertDialogPortal>\n <AlertDialogOverlay />\n <AlertDialogPrimitive.Popup\n data-slot=\"alert-dialog-content\"\n data-size={size}\n className={cn(\n \"group/alert-dialog-content fixed top-1/2 left-1/2 z-50 grid w-full -translate-x-1/2 -translate-y-1/2 gap-6 rounded-xl bg-popover p-6 text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none data-[size=default]:max-w-xs data-[size=sm]:max-w-xs data-[size=default]:sm:max-w-lg data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95\",\n className\n )}\n {...props}\n />\n </AlertDialogPortal>\n )\n}\n\nfunction AlertDialogHeader({\n className,\n ...props\n}: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"alert-dialog-header\"\n className={cn(\n \"grid grid-rows-[auto_1fr] place-items-center gap-1.5 text-center has-data-[slot=alert-dialog-media]:grid-rows-[auto_auto_1fr] has-data-[slot=alert-dialog-media]:gap-x-6 sm:group-data-[size=default]/alert-dialog-content:place-items-start sm:group-data-[size=default]/alert-dialog-content:text-left sm:group-data-[size=default]/alert-dialog-content:has-data-[slot=alert-dialog-media]:grid-rows-[auto_1fr]\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction AlertDialogFooter({\n className,\n ...props\n}: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"alert-dialog-footer\"\n className={cn(\n \"flex flex-col-reverse gap-2 group-data-[size=sm]/alert-dialog-content:grid group-data-[size=sm]/alert-dialog-content:grid-cols-2 sm:flex-row sm:justify-end\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction AlertDialogMedia({\n className,\n ...props\n}: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"alert-dialog-media\"\n className={cn(\n \"mb-2 inline-flex size-16 items-center justify-center rounded-md bg-muted sm:group-data-[size=default]/alert-dialog-content:row-span-2 *:[svg:not([class*='size-'])]:size-8\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction AlertDialogTitle({\n className,\n ...props\n}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {\n return (\n <AlertDialogPrimitive.Title\n data-slot=\"alert-dialog-title\"\n className={cn(\n \"text-lg font-medium sm:group-data-[size=default]/alert-dialog-content:group-has-data-[slot=alert-dialog-media]/alert-dialog-content:col-start-2\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction AlertDialogDescription({\n className,\n ...props\n}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {\n return (\n <AlertDialogPrimitive.Description\n data-slot=\"alert-dialog-description\"\n className={cn(\n \"text-sm text-balance text-muted-foreground md:text-pretty *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction AlertDialogAction({\n className,\n ...props\n}: React.ComponentProps<typeof Button>) {\n return (\n <Button\n data-slot=\"alert-dialog-action\"\n className={cn(className)}\n {...props}\n />\n )\n}\n\nfunction AlertDialogCancel({\n className,\n variant = \"outline\",\n size = \"default\",\n ...props\n}: AlertDialogPrimitive.Close.Props &\n Pick<React.ComponentProps<typeof Button>, \"variant\" | \"size\">) {\n return (\n <AlertDialogPrimitive.Close\n data-slot=\"alert-dialog-cancel\"\n className={cn(className)}\n render={<Button variant={variant} size={size} />}\n {...props}\n />\n )\n}\n\nexport {\n AlertDialog,\n AlertDialogAction,\n AlertDialogCancel,\n AlertDialogContent,\n AlertDialogDescription,\n AlertDialogFooter,\n AlertDialogHeader,\n AlertDialogMedia,\n AlertDialogOverlay,\n AlertDialogPortal,\n AlertDialogTitle,\n AlertDialogTrigger,\n}\n","import * as React from \"react\"\nimport { Dialog as DialogPrimitive } from \"@base-ui/react/dialog\"\nimport { cn } from \"cn\"\n\nimport { Button } from \"#orck/components/ui/button\"\nimport { HugeiconsIcon } from \"@hugeicons/react\"\nimport { Cancel01Icon } from \"@hugeicons/core-free-icons\"\n\nfunction Dialog({ ...props }: DialogPrimitive.Root.Props) {\n return <DialogPrimitive.Root data-slot=\"dialog\" {...props} />\n}\n\nfunction DialogTrigger({ ...props }: DialogPrimitive.Trigger.Props) {\n return <DialogPrimitive.Trigger data-slot=\"dialog-trigger\" {...props} />\n}\n\nfunction DialogPortal({ ...props }: DialogPrimitive.Portal.Props) {\n return <DialogPrimitive.Portal data-slot=\"dialog-portal\" {...props} />\n}\n\nfunction DialogClose({ ...props }: DialogPrimitive.Close.Props) {\n return <DialogPrimitive.Close data-slot=\"dialog-close\" {...props} />\n}\n\nfunction DialogOverlay({\n className,\n ...props\n}: DialogPrimitive.Backdrop.Props) {\n return (\n <DialogPrimitive.Backdrop\n data-slot=\"dialog-overlay\"\n className={cn(\n \"fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction DialogContent({\n className,\n children,\n showCloseButton = true,\n ...props\n}: DialogPrimitive.Popup.Props & {\n showCloseButton?: boolean\n}) {\n return (\n <DialogPortal>\n <DialogOverlay />\n <DialogPrimitive.Popup\n data-slot=\"dialog-content\"\n className={cn(\n \"fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-6 rounded-xl bg-popover p-6 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-md data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95\",\n className\n )}\n {...props}\n >\n {children}\n {showCloseButton && (\n <DialogPrimitive.Close\n data-slot=\"dialog-close\"\n render={\n <Button\n variant=\"ghost\"\n className=\"absolute top-4 right-4\"\n size=\"icon-sm\"\n />\n }\n >\n <HugeiconsIcon icon={Cancel01Icon} strokeWidth={2} />\n <span className=\"sr-only\">Close</span>\n </DialogPrimitive.Close>\n )}\n </DialogPrimitive.Popup>\n </DialogPortal>\n )\n}\n\nfunction DialogHeader({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"dialog-header\"\n className={cn(\"flex flex-col gap-2\", className)}\n {...props}\n />\n )\n}\n\nfunction DialogFooter({\n className,\n showCloseButton = false,\n children,\n ...props\n}: React.ComponentProps<\"div\"> & {\n showCloseButton?: boolean\n}) {\n return (\n <div\n data-slot=\"dialog-footer\"\n className={cn(\n \"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end\",\n className\n )}\n {...props}\n >\n {children}\n {showCloseButton && (\n <DialogPrimitive.Close render={<Button variant=\"outline\" />}>\n Close\n </DialogPrimitive.Close>\n )}\n </div>\n )\n}\n\nfunction DialogTitle({ className, ...props }: DialogPrimitive.Title.Props) {\n return (\n <DialogPrimitive.Title\n data-slot=\"dialog-title\"\n className={cn(\"leading-none font-medium\", className)}\n {...props}\n />\n )\n}\n\nfunction DialogDescription({\n className,\n ...props\n}: DialogPrimitive.Description.Props) {\n return (\n <DialogPrimitive.Description\n data-slot=\"dialog-description\"\n className={cn(\n \"text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground\",\n className\n )}\n {...props}\n />\n )\n}\n\nexport {\n Dialog,\n DialogClose,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogOverlay,\n DialogPortal,\n DialogTitle,\n DialogTrigger,\n}\n","import { cn } from \"cn\"\nimport { HugeiconsIcon } from \"@hugeicons/react\"\nimport { Loading03Icon } from \"@hugeicons/core-free-icons\"\n\nimport { useMessages } from \"#orck/i18n/context\"\n\n// Local: HugeiconsIcon props, since its strokeWidth rejects the svg string type.\nfunction Spinner({\n className,\n ...props\n}: Omit<React.ComponentProps<typeof HugeiconsIcon>, \"icon\">) {\n const { t } = useMessages() // Local: i18n \"Loading\" label.\n return (\n <HugeiconsIcon\n icon={Loading03Icon}\n strokeWidth={2}\n data-slot=\"spinner\"\n role=\"status\"\n aria-label={t(\"common.loading\")}\n className={cn(\"size-4 animate-spin\", className)}\n {...props}\n />\n )\n}\n\nexport { Spinner }\n","import * as React from \"react\"\nimport { Input as InputPrimitive } from \"@base-ui/react/input\"\nimport { cn } from \"cn\"\n\nfunction Input({ className, type, ...props }: React.ComponentProps<\"input\">) {\n return (\n <InputPrimitive\n type={type}\n data-slot=\"input\"\n className={cn(\n \"h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-2.5 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40\",\n className\n )}\n {...props}\n />\n )\n}\n\nexport { Input }\n","import * as React from \"react\"\nimport { cn } from \"cn\"\n\nfunction Label({ className, ...props }: React.ComponentProps<\"label\">) {\n return (\n <label\n data-slot=\"label\"\n className={cn(\n \"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50\",\n className\n )}\n {...props}\n />\n )\n}\n\nexport { Label }\n","import { z } from \"zod\"\n\nconst ISO_COUNTRY_CODES =\n \"AD AE AF AG AI AL AM AO AQ AR AS AT AU AW AX AZ BA BB BD BE BF BG BH BI BJ BL BM BN BO BQ BR BS BT BV BW BY BZ CA CC CD CF CG CH CI CK CL CM CN CO CR CU CV CW CX CY CZ DE DJ DK DM DO DZ EC EE EG EH ER ES ET FI FJ FK FM FO FR GA GB GD GE GF GG GH GI GL GM GN GP GQ GR GS GT GU GW GY HK HM HN HR HT HU ID IE IL IM IN IO IQ IR IS IT JE JM JO JP KE KG KH KI KM KN KP KR KW KY KZ LA LB LC LI LK LR LS LT LU LV LY MA MC MD ME MF MG MH MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ NA NC NE NF NG NI NL NO NP NR NU NZ OM PA PE PF PG PH PK PL PM PN PR PS PT PW PY QA RE RO RS RU RW SA SB SC SD SE SG SH SI SJ SK SL SM SN SO SR SS ST SV SX SY SZ TC TD TF TG TH TJ TK TL TM TN TO TR TT TV TW TZ UA UG UM US UY UZ VA VC VE VG VI VN VU WF WS YE YT ZA ZM ZW\".split(\n \" \"\n )\n\n// ISO-3166 alpha-2 projection of the UPU's \"List of countries which do not\n// require postal codes\" (Universal DataBase, September 2025). Keep a postal\n// code when a customer supplies one, but do not block tokenization when the\n// destination does not require it.\n// https://www.upu.int/UPU/media/upu/documents/PostCode/General-Addressing-Issues.pdf\nconst POSTAL_OPTIONAL_COUNTRIES = new Set([\n \"AE\",\n \"AG\",\n \"AO\",\n \"AQ\",\n \"AW\",\n \"BF\",\n \"BI\",\n \"BJ\",\n \"BO\",\n \"BQ\",\n \"BS\",\n \"BV\",\n \"BW\",\n \"BZ\",\n \"CF\",\n \"CG\",\n \"CI\",\n \"CK\",\n \"CM\",\n \"CW\",\n \"DM\",\n \"ER\",\n \"FJ\",\n \"GA\",\n \"GD\",\n \"GM\",\n \"GQ\",\n \"JM\",\n \"KM\",\n \"KP\",\n \"LY\",\n \"ML\",\n \"MR\",\n \"QA\",\n \"RW\",\n \"SB\",\n \"SC\",\n \"SL\",\n \"SO\",\n \"SR\",\n \"SS\",\n \"ST\",\n \"SX\",\n \"SY\",\n \"TD\",\n \"TG\",\n \"TK\",\n \"TO\",\n \"TV\",\n \"UM\",\n \"VU\",\n \"YE\",\n \"ZW\",\n])\n\nconst POSTAL_PLACEHOLDERS: Record<string, string> = {\n AR: \"C1000\",\n BR: \"01000-000\",\n CA: \"A1A 1A1\",\n CL: \"8320000\",\n CN: \"100000\",\n CO: \"110111\",\n DE: \"10115\",\n ES: \"28001\",\n JP: \"100-0001\",\n KR: \"04524\",\n MX: \"01000\",\n PE: \"15001\",\n US: \"12345\",\n}\n\nconst displayNames = new Intl.DisplayNames([\"en\"], { type: \"region\" })\n\nexport const COUNTRY_OPTIONS = ISO_COUNTRY_CODES.map((code) => ({\n code,\n name: displayNames.of(code) ?? code,\n})).sort((left, right) => left.name.localeCompare(right.name))\n\nexport const nameOnCardSchema = z\n .string()\n .trim()\n .min(1, \"Full name is required\")\n .max(200, \"Full name is too long\")\n\nexport const countryCodeSchema = z\n .string()\n .trim()\n .regex(/^[A-Za-z]{2}$/, \"Select a country\")\n .transform((value) => value.toUpperCase())\n\nexport function isPostalRequired(country: string): boolean {\n const code = country.trim().toUpperCase()\n return code === \"\" || !POSTAL_OPTIONAL_COUNTRIES.has(code)\n}\n\nexport function postalField(\n country: string,\n required: boolean\n): {\n label: string\n placeholder: string\n inputMode: \"numeric\" | \"text\"\n pattern?: string\n} {\n const code = country.trim().toUpperCase()\n const baseLabel =\n code === \"US\"\n ? \"ZIP code\"\n : code === \"GB\" || code === \"AU\" || code === \"NZ\"\n ? \"Postcode\"\n : \"Postal code\"\n return {\n label: required ? baseLabel : `${baseLabel} (optional)`,\n placeholder: POSTAL_PLACEHOLDERS[code] ?? baseLabel,\n inputMode: code === \"US\" ? \"numeric\" : \"text\",\n pattern: code === \"US\" ? \"[0-9]{5}(?:-[0-9]{4})?\" : undefined,\n }\n}\n\nexport const nmiBillingSchema = z\n .object({\n name_on_card: nameOnCardSchema,\n country: countryCodeSchema,\n zip: z.string().trim().max(32, \"Postal code is too long\"),\n })\n .superRefine((value, context) => {\n if (isPostalRequired(value.country) && !value.zip) {\n context.addIssue({\n code: \"custom\",\n message: `${postalField(value.country, true).label} is required`,\n path: [\"zip\"],\n })\n }\n if (\n value.country === \"US\" &&\n value.zip &&\n !/^\\d{5}(?:-\\d{4})?$/.test(value.zip)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"Enter a valid ZIP code\",\n path: [\"zip\"],\n })\n }\n })\n\nexport type NMIBilling = z.infer<typeof nmiBillingSchema>\n\n/** A card form's billing fields as a saved card's billing details. */\nexport function billingDetailsOf(billing: {\n name_on_card?: string\n email?: string\n zip?: string\n country?: string\n}) {\n const address = {\n ...(billing.zip ? { postal_code: billing.zip } : {}),\n ...(billing.country ? { country: billing.country } : {}),\n }\n return {\n ...(billing.name_on_card ? { name: billing.name_on_card } : {}),\n ...(billing.email ? { email: billing.email } : {}),\n ...(Object.keys(address).length > 0 ? { address } : {}),\n }\n}\n\nexport const emptyNMIBilling: NMIBilling = {\n name_on_card: \"\",\n country: \"\",\n zip: \"\",\n}\n\n/** The buyer's likely billing country from the browser locale, or \"\". */\nexport function browserCountry(): string {\n try {\n if (typeof navigator === \"undefined\" || !navigator.language) return \"\"\n const region = new Intl.Locale(navigator.language).maximize().region\n return region && /^[A-Z]{2}$/.test(region) ? region : \"\"\n } catch {\n return \"\"\n }\n}\n\n/** The host's country when it is a known code, else the browser's region. */\nexport function initialCountry(hostCountry?: string): string {\n const code = hostCountry?.trim().toUpperCase() ?? \"\"\n if (COUNTRY_OPTIONS.some((option) => option.code === code)) return code\n const region = browserCountry()\n return COUNTRY_OPTIONS.some((option) => option.code === region) ? region : \"\"\n}\n\n// The EEA and the UK, where keeping a card for later one-off purchases needs\n// the customer's unticked opt-in; mirrors OpenRails' mandates.optInCountries.\nconst REUSE_OPT_IN_COUNTRIES = new Set([\n \"AT\", \"BE\", \"BG\", \"CY\", \"CZ\", \"DE\", \"DK\", \"EE\", \"ES\", \"FI\", \"FR\", \"GR\", \"HR\",\n \"HU\", \"IE\", \"IT\", \"LT\", \"LU\", \"LV\", \"MT\", \"NL\", \"PL\", \"PT\", \"RO\", \"SE\", \"SI\",\n \"SK\", \"IS\", \"LI\", \"NO\", \"GB\",\n])\n\nexport function reuseNeedsOptIn(country: string): boolean {\n return REUSE_OPT_IN_COUNTRIES.has(country.trim().toUpperCase())\n}\n","import type * as React from \"react\"\n\nimport { Input } from \"#orck/components/ui/input\"\nimport { Label } from \"#orck/components/ui/label\"\nimport {\n COUNTRY_OPTIONS,\n isPostalRequired,\n postalField,\n type NMIBilling,\n} from \"#orck/lib/billing\"\n\nconst LABEL = \"text-[13px] font-medium text-foreground\"\nconst CONTROL =\n \"h-[38px] rounded-[9px] border border-input bg-card text-sm text-foreground\"\nconst INPUT = `${CONTROL} px-2.5`\n\nexport function BillingTextField({\n id,\n name,\n label,\n value,\n onChange,\n autoComplete,\n placeholder,\n disabled,\n maxLength,\n required,\n type,\n inputMode,\n pattern,\n}: {\n id: string\n name: string\n label: string\n value: string\n onChange: (value: string) => void\n autoComplete: string\n placeholder?: string\n disabled?: boolean\n maxLength?: number\n required?: boolean\n type?: React.HTMLInputTypeAttribute\n inputMode?: React.HTMLAttributes<HTMLInputElement>[\"inputMode\"]\n pattern?: string\n}) {\n return (\n <div className=\"grid gap-1.5\">\n <Label htmlFor={id} className={LABEL}>\n {label}\n </Label>\n <Input\n id={id}\n name={name}\n type={type}\n className={INPUT}\n value={value}\n autoComplete={autoComplete}\n placeholder={placeholder}\n disabled={disabled}\n maxLength={maxLength}\n required={required}\n inputMode={inputMode}\n pattern={pattern}\n onChange={(event) => onChange(event.target.value)}\n />\n </div>\n )\n}\n\nexport function CountryField({\n id,\n value,\n onChange,\n disabled,\n}: {\n id: string\n value: string\n onChange: (value: string) => void\n disabled?: boolean\n}) {\n return (\n <div className=\"grid gap-1.5\">\n <Label htmlFor={id} className={LABEL}>\n Country or region\n </Label>\n <select\n id={id}\n name=\"country\"\n className={`${CONTROL} w-full px-2.5`}\n value={value}\n autoComplete=\"billing country\"\n disabled={disabled}\n required\n onChange={(event) => onChange(event.target.value)}\n >\n <option value=\"\">Select country</option>\n {COUNTRY_OPTIONS.map((country) => (\n <option key={country.code} value={country.code}>\n {country.name}\n </option>\n ))}\n </select>\n </div>\n )\n}\n\nexport function PostalField({\n id,\n value,\n country,\n onChange,\n disabled,\n required,\n error,\n}: {\n id: string\n value: string\n country: string\n onChange: (value: string) => void\n disabled?: boolean\n required: boolean\n error?: string\n}) {\n const field = postalField(country, required)\n return (\n <div className=\"grid gap-1.5\">\n <BillingTextField\n id={id}\n name=\"zip\"\n label={field.label}\n value={value}\n onChange={onChange}\n autoComplete=\"billing postal-code\"\n placeholder={field.placeholder}\n disabled={disabled}\n maxLength={32}\n required={required}\n inputMode={field.inputMode}\n pattern={field.pattern}\n />\n {error ? (\n <p className=\"text-[12.5px] text-destructive\" role=\"alert\">\n {error}\n </p>\n ) : null}\n </div>\n )\n}\n\n// The card fields (children) sit between the cardholder name and the address.\nexport function CardBillingFields({\n idPrefix,\n value,\n onChange,\n disabled,\n postalError,\n children,\n}: {\n idPrefix: string\n value: NMIBilling\n onChange: (next: NMIBilling) => void\n disabled?: boolean\n postalError?: string\n children?: React.ReactNode\n}) {\n const set = (key: keyof NMIBilling) => (next: string) =>\n onChange({ ...value, [key]: next })\n const postalRequired = isPostalRequired(value.country)\n return (\n <div className=\"grid gap-3\">\n <BillingTextField\n id={`${idPrefix}-name-on-card`}\n name=\"name_on_card\"\n label=\"Full name\"\n value={value.name_on_card}\n onChange={set(\"name_on_card\")}\n autoComplete=\"cc-name\"\n disabled={disabled}\n maxLength={200}\n required\n />\n {children}\n <div className=\"grid grid-cols-2 gap-3\">\n <CountryField\n id={`${idPrefix}-country`}\n value={value.country}\n onChange={set(\"country\")}\n disabled={disabled}\n />\n <PostalField\n id={`${idPrefix}-postal-code`}\n value={value.zip}\n country={value.country}\n onChange={set(\"zip\")}\n disabled={disabled}\n required={postalRequired}\n error={postalError}\n />\n </div>\n </div>\n )\n}\n","// Card entry for the NMI rail. Live mode mounts Collect.js hosted iframes\n// into these containers (card data never touches our code); preview mode\n// (fixture tokenization keys) renders inert placeholders with the same\n// geometry so every state is designable without a gateway. A PSP that takes\n// cards on OpenRails itself gets NativeCardFields instead.\nimport type * as React from \"react\"\n\nimport { Label } from \"#orck/components/ui/label\"\nimport type { CardEntryState } from \"#orck/lib/card-entry\"\nimport type { CollectFieldErrors } from \"#orck/lib/collect\"\nimport { SupportedCardBrands } from \"#orck/components/card-brands\"\nimport { cn } from \"cn\"\n\nfunction FieldError({ id, message }: { id: string; message?: string }) {\n return message ? (\n <p id={id} className=\"text-[12.5px] text-destructive\" role=\"alert\">\n {message}\n </p>\n ) : null\n}\n\nconst FIELD =\n \"orck-collect-field h-[38px] overflow-hidden rounded-[9px] border border-[color:var(--border)] bg-card px-[3px]\"\nconst PREVIEW_FIELD =\n \"flex h-[38px] items-center rounded-[9px] border border-[color:var(--border)] bg-card px-[11px] text-sm text-[color:var(--orck-faint)] tabular-nums\"\n\nexport interface CardFieldIds {\n number: string\n expiry: string\n cvv: string\n}\n\nexport function CardFields({\n ids,\n preview,\n error,\n fieldErrors = {},\n hidden,\n brand,\n}: {\n ids: CardFieldIds\n preview: boolean\n /** The detected card brand, highlighted among the accepted ones. */\n brand?: string\n error?: string\n /** Inline per-field errors (gateway validation or a decline). */\n fieldErrors?: CollectFieldErrors\n // Kept mounted while hidden: the Collect.js iframes cannot be recreated\n // cheaply, so switching to a stored card must not unmount them.\n hidden?: boolean\n}) {\n return (\n <div\n className={cn(\"grid gap-3\", hidden && \"hidden\")}\n aria-hidden={hidden || undefined}\n >\n <div className=\"grid gap-1.5\">\n <div className=\"flex items-center justify-between\">\n <Label\n htmlFor={ids.number}\n className=\"text-[13px] font-medium text-foreground\"\n >\n Card number\n </Label>\n <SupportedCardBrands active={brand} />\n </div>\n {preview ? (\n <div id={ids.number} className={PREVIEW_FIELD}>\n 1234 1234 1234 1234\n </div>\n ) : (\n <div\n id={ids.number}\n className={cn(FIELD, fieldErrors.number && \"border-destructive\")}\n />\n )}\n <FieldError id={`${ids.number}-error`} message={fieldErrors.number} />\n </div>\n <div className=\"grid grid-cols-2 gap-3\">\n <div className=\"grid gap-1.5\">\n <Label\n htmlFor={ids.expiry}\n className=\"text-[13px] font-medium text-foreground\"\n >\n Expiry\n </Label>\n {preview ? (\n <div id={ids.expiry} className={PREVIEW_FIELD}>\n MM / YY\n </div>\n ) : (\n <div\n id={ids.expiry}\n className={cn(FIELD, fieldErrors.expiry && \"border-destructive\")}\n />\n )}\n <FieldError id={`${ids.expiry}-error`} message={fieldErrors.expiry} />\n </div>\n <div className=\"grid gap-1.5\">\n <Label\n htmlFor={ids.cvv}\n className=\"text-[13px] font-medium text-foreground\"\n >\n CVC\n </Label>\n {preview ? (\n <div id={ids.cvv} className={PREVIEW_FIELD}>\n CVC\n </div>\n ) : (\n <div\n id={ids.cvv}\n className={cn(FIELD, fieldErrors.cvv && \"border-destructive\")}\n />\n )}\n <FieldError id={`${ids.cvv}-error`} message={fieldErrors.cvv} />\n </div>\n </div>\n {error ? (\n <p className={cn(\"text-[13px] text-destructive\")} role=\"alert\">\n {error}\n </p>\n ) : null}\n </div>\n )\n}\n\nconst NATIVE_FIELD =\n \"h-[38px] w-full min-w-0 rounded-[9px] border border-[color:var(--border)] bg-card px-[11px] text-sm text-foreground tabular-nums outline-none placeholder:text-[color:var(--orck-faint)] focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:opacity-50\"\n\n/**\n * Card entry for a PSP that takes cards on OpenRails itself (driver \"card\"):\n * plain inputs in the same layout as the Collect.js containers. The card is\n * posted to OpenRails; no gateway script is loaded.\n */\nexport function NativeCardFields({\n ids,\n card,\n fieldErrors = {},\n disabled,\n hidden,\n}: {\n ids: CardFieldIds\n card: CardEntryState\n /** Inline errors beyond the form's own (a decline naming a field). */\n fieldErrors?: CollectFieldErrors\n disabled?: boolean\n hidden?: boolean\n}) {\n const errors = { ...card.fieldErrors, ...fieldErrors }\n const field = (\n id: string,\n name: \"number\" | \"expiry\" | \"cvc\",\n error: string | undefined,\n props: React.ComponentProps<\"input\">\n ) => (\n <>\n <input\n id={id}\n name={`card-${name}`}\n className={cn(NATIVE_FIELD, error && \"border-destructive\")}\n value={card.input[name]}\n onChange={(event) => card.change(name, event.target.value)}\n onBlur={() => card.leave(name)}\n inputMode=\"numeric\"\n spellCheck={false}\n disabled={disabled}\n required\n aria-invalid={error ? true : undefined}\n aria-describedby={error ? `${id}-error` : undefined}\n {...props}\n />\n <FieldError id={`${id}-error`} message={error} />\n </>\n )\n return (\n <div\n className={cn(\"grid gap-3\", hidden && \"hidden\")}\n aria-hidden={hidden || undefined}\n >\n <div className=\"grid gap-1.5\">\n <div className=\"flex items-center justify-between\">\n <Label\n htmlFor={ids.number}\n className=\"text-[13px] font-medium text-foreground\"\n >\n Card number\n </Label>\n <SupportedCardBrands />\n </div>\n {field(ids.number, \"number\", errors.number, {\n autoComplete: \"cc-number\",\n placeholder: \"1234 1234 1234 1234\",\n maxLength: 23,\n })}\n </div>\n <div className=\"grid grid-cols-2 gap-3\">\n <div className=\"grid gap-1.5\">\n <Label\n htmlFor={ids.expiry}\n className=\"text-[13px] font-medium text-foreground\"\n >\n Expiry\n </Label>\n {field(ids.expiry, \"expiry\", errors.expiry, {\n autoComplete: \"cc-exp\",\n placeholder: \"MM / YY\",\n maxLength: 7,\n })}\n </div>\n <div className=\"grid gap-1.5\">\n <Label\n htmlFor={ids.cvv}\n className=\"text-[13px] font-medium text-foreground\"\n >\n CVC\n </Label>\n {field(ids.cvv, \"cvc\", errors.cvv, {\n autoComplete: \"cc-csc\",\n placeholder: \"CVC\",\n maxLength: 4,\n })}\n </div>\n </div>\n </div>\n )\n}\n","// The one bold element on the surface: the ink button carrying the amount.\n// Redirect rails relabel it; Solana has no button at all.\nimport { Button } from \"#orck/components/ui/button\"\nimport { cn } from \"cn\"\n\nexport function PayButton({\n label,\n processing,\n disabled,\n}: {\n label: string\n processing: boolean\n disabled?: boolean\n}) {\n return (\n <Button\n type=\"submit\"\n className={cn(\n \"h-[42px] w-full rounded-[10px] text-sm font-semibold tabular-nums\",\n processing && \"opacity-75\"\n )}\n disabled={disabled || processing}\n >\n {processing ? (\n <>\n <span\n aria-hidden\n className=\"size-3.5 animate-spin rounded-full border-2 border-[color:var(--primary-foreground)]/35 border-t-[color:var(--primary-foreground)] motion-reduce:animate-none\"\n />\n Processing…\n </>\n ) : (\n label\n )}\n </Button>\n )\n}\n\nexport function TrustLine() {\n return (\n <div className=\"-mt-1 flex items-center justify-center gap-1.5 text-xs text-[color:var(--orck-faint)]\">\n <svg\n viewBox=\"0 0 16 16\"\n fill=\"currentColor\"\n aria-hidden\n className=\"size-[11px]\"\n >\n <path d=\"M8 1a3.5 3.5 0 0 0-3.5 3.5V6H4a1.5 1.5 0 0 0-1.5 1.5v5A1.5 1.5 0 0 0 4 14h8a1.5 1.5 0 0 0 1.5-1.5v-5A1.5 1.5 0 0 0 12 6h-.5V4.5A3.5 3.5 0 0 0 8 1Zm2 5H6V4.5a2 2 0 1 1 4 0V6Z\" />\n </svg>\n Secured by{\" \"}\n <a href=\"https://openrails.dev\" target=\"_blank\" rel=\"noreferrer\" className=\"underline-offset-2 hover:underline\">\n OpenRails\n </a>\n </div>\n )\n}\n","import * as React from \"react\"\nimport BasisTheory from \"@basis-theory/web-elements\"\nimport { CardBillingFields } from \"./billing-fields\"\nimport { CardFields } from \"./card-fields\"\nimport { PayButton, TrustLine } from \"./pay-button\"\nimport {\n emptyNMIBilling,\n initialCountry,\n nmiBillingSchema,\n} from \"../lib/billing\"\nimport type { TokenizedCardData } from \"../tokenized-card-form\"\n\n// Only the vendor's iframe handles PAN/CVC. An unconfirmed payment retains\n// exactly the same token and billing details so Retry replays its request.\nexport function PlatformCardForm({\n publicKey,\n submitLabel,\n disabled,\n onTokenized,\n purpose = \"payment\",\n defaultCountry,\n}: {\n purpose?: \"payment\" | \"setup\"\n defaultCountry?: string\n publicKey: string\n submitLabel: string\n disabled: boolean\n onTokenized: (card: TokenizedCardData) => Promise<boolean>\n}) {\n const uid = React.useId().replace(/[^a-zA-Z0-9-]/g, \"\")\n const ids = React.useMemo(\n () => ({\n number: `bt-${uid}-number`,\n expiry: `bt-${uid}-expiry`,\n cvv: `bt-${uid}-cvv`,\n }),\n [uid]\n )\n const [billing, setBilling] = React.useState(() => ({\n ...emptyNMIBilling,\n country: initialCountry(defaultCountry),\n }))\n const [ready, setReady] = React.useState(false)\n const [busy, setBusy] = React.useState(false)\n const [submitted, setSubmitted] = React.useState(false)\n const [retry, setRetry] = React.useState(false)\n const [error, setError] = React.useState<string>()\n const pending = React.useRef<TokenizedCardData>(undefined)\n const tokenize = React.useRef<() => Promise<string>>(undefined)\n const submitting = React.useRef(false)\n const authorization = React.useRef({ generation: 0, disabled })\n React.useLayoutEffect(() => {\n authorization.current = {\n generation: authorization.current.generation + 1,\n disabled,\n }\n }, [publicKey, disabled])\n React.useEffect(() => {\n let active = true\n const bt = BasisTheory(publicKey)\n const number = bt.createElement(\"cardNumber\")\n const expiry = bt.createElement(\"expiry\")\n const cvv = bt.createElement(\"cvv\")\n Promise.all([\n number.mount(`#${ids.number}`),\n expiry.mount(`#${ids.expiry}`),\n cvv.mount(`#${ids.cvv}`),\n ]).then(\n () => {\n if (!active) return\n tokenize.current = async () =>\n (\n await bt.tokenIntents.create({\n type: \"card\",\n data: {\n number,\n expiration_month: expiry,\n expiration_year: expiry,\n cvc: cvv,\n },\n })\n ).id\n setReady(true)\n },\n () => {\n if (active) setError(\"Secure card entry could not be loaded.\")\n }\n )\n return () => {\n active = false\n authorization.current.generation++\n tokenize.current = undefined\n void bt.destroy()\n }\n }, [publicKey, ids])\n const retryLabel = purpose === \"setup\" ? \"Retry saving card\" : \"Retry payment\"\n const unconfirmedMessage =\n purpose === \"setup\"\n ? \"The card save is not confirmed. Retry to check the same card.\"\n : \"The payment result is not confirmed. Retry to check the same payment.\"\n const submit = async (event: React.FormEvent) => {\n event.preventDefault()\n if (disabled || submitting.current || submitted || !tokenize.current) return\n const parsed = nmiBillingSchema.safeParse(billing)\n if (!parsed.success) {\n setError(parsed.error.issues[0]?.message ?? \"Check the billing details\")\n return\n }\n submitting.current = true\n setBusy(true)\n setError(undefined)\n const generation = authorization.current.generation\n try {\n const card = pending.current ?? {\n payment_token: await tokenize.current(),\n ...parsed.data,\n }\n if (\n authorization.current.generation !== generation ||\n authorization.current.disabled\n )\n return\n pending.current = card\n const accepted = await onTokenized(card)\n if (accepted) setSubmitted(true)\n else pending.current = undefined\n setRetry(false)\n } catch {\n const sent = !!pending.current\n setRetry(sent)\n setError(\n sent ? unconfirmedMessage : \"Check your card details and try again.\"\n )\n } finally {\n submitting.current = false\n setBusy(false)\n }\n }\n return (\n <form\n aria-label={\n purpose === \"setup\"\n ? \"Secure platform card setup\"\n : \"Secure platform card payment\"\n }\n className=\"grid gap-4\"\n onSubmit={(event) => void submit(event)}\n >\n <CardBillingFields\n idPrefix={`bt-${uid}`}\n value={billing}\n onChange={setBilling}\n disabled={disabled || busy || retry || submitted}\n >\n <CardFields ids={ids} preview={false} />\n </CardBillingFields>\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n ) : null}\n <PayButton\n label={retry ? retryLabel : submitLabel}\n processing={busy}\n disabled={disabled || submitted || !ready || !nmiBillingSchema.safeParse(billing).success}\n />\n <TrustLine />\n </form>\n )\n}\n","// Stripe.js for in-page card setup and payment authentication. Loaded on first\n// use, so hosts without a Stripe PSP never fetch it.\nimport type { Stripe } from \"@stripe/stripe-js\"\n\nconst loaded = new Map<string, Promise<Stripe>>()\n\nexport function loadStripeFor(publishableKey: string): Promise<Stripe> {\n let stripe = loaded.get(publishableKey)\n if (!stripe) {\n stripe = import(\"@stripe/stripe-js\")\n .then(({ loadStripe }) => loadStripe(publishableKey))\n .then((value) => {\n if (!value) throw new Error(\"Stripe could not be loaded.\")\n return value\n })\n stripe.catch(() => loaded.delete(publishableKey))\n loaded.set(publishableKey, stripe)\n }\n return stripe\n}\n","// Collect.js (NMI browser tokenization). The gateway script mounts hosted\n// iframes into our field containers, so card data never touches this code —\n// we receive a one-time token plus display metadata. Collect.js has no\n// teardown API: the script and configuration persist for the page lifetime;\n// reconfiguring re-mounts fields.\nimport * as React from \"react\"\n\nexport interface CollectCard {\n number?: string\n type?: string\n exp?: string\n}\n\nexport interface CollectResponse {\n token: string\n card?: CollectCard\n}\n\ndeclare global {\n interface Window {\n CollectJS?: {\n configure: (config: Record<string, unknown>) => void\n startPaymentRequest: () => void\n }\n }\n}\n\nconst SCRIPT_ID = \"openrails-collectjs\"\nconst TIMEOUT_MS = 30_000\nconst collectScriptStates = new WeakMap<\n HTMLScriptElement,\n \"loading\" | \"loaded\" | \"failed\"\n>()\n\nfunction safeCollectScriptURL(raw: string): string | undefined {\n try {\n const parsed = new URL(raw)\n if (\n parsed.protocol !== \"https:\" ||\n parsed.username ||\n parsed.password ||\n parsed.hash\n ) {\n return undefined\n }\n return parsed.toString()\n } catch {\n return undefined\n }\n}\n\n// toPlainColor normalizes a CSS color into rgb()/rgba() form, the least\n// common denominator the gateway's CSS sanitizer accepts. Chrome serializes\n// the theme tokens in their authored oklch space (canvas fillStyle keeps it\n// too), so oklch is converted numerically; everything else round-trips\n// through a canvas fillStyle. Unparseable input returns \"\".\nexport function toPlainColor(value: string | undefined): string {\n if (!value) return \"\"\n const oklch = oklchToRGB(value)\n if (oklch) return oklch\n try {\n const context = document.createElement(\"canvas\").getContext(\"2d\")\n if (!context) return \"\"\n context.fillStyle = \"#010203\"\n context.fillStyle = value\n const normalized = context.fillStyle\n if (normalized === \"#010203\" && value !== \"#010203\") return \"\"\n return normalized.startsWith(\"oklch\") ? \"\" : normalized\n } catch {\n return \"\"\n }\n}\n\n// oklchToRGB converts \"oklch(L C H)\" / \"oklch(L C H / A)\" (L as 0..1 or %)\n// to an rgb()/rgba() string via OKLab → linear sRGB (Ottosson's matrices).\nfunction oklchToRGB(value: string): string {\n const match =\n /^oklch\\(\\s*([\\d.]+%?)\\s+([\\d.]+)\\s+([\\d.]+)(?:deg)?\\s*(?:\\/\\s*([\\d.]+%?)\\s*)?\\)$/i.exec(\n value.trim()\n )\n if (!match) return \"\"\n const number = (raw: string) =>\n raw.endsWith(\"%\") ? parseFloat(raw) / 100 : parseFloat(raw)\n const L = number(match[1])\n const C = parseFloat(match[2])\n const H = (parseFloat(match[3]) * Math.PI) / 180\n const alpha = match[4] === undefined ? 1 : number(match[4])\n const a = C * Math.cos(H)\n const b = C * Math.sin(H)\n const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3\n const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3\n const s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3\n const channel = (linear: number) => {\n const gamma =\n linear <= 0.0031308\n ? 12.92 * linear\n : 1.055 * Math.max(linear, 0) ** (1 / 2.4) - 0.055\n return Math.round(Math.min(1, Math.max(0, gamma)) * 255)\n }\n const red = channel(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s)\n const green = channel(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s)\n const blue = channel(-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s)\n return alpha >= 1\n ? `rgb(${red}, ${green}, ${blue})`\n : `rgba(${red}, ${green}, ${blue}, ${alpha})`\n}\n\n// Preview keys skip the live script entirely so fixture-driven previews can\n// render the card fields without a real gateway.\nexport function isPreviewTokenizationKey(key: string): boolean {\n return key.startsWith(\"preview_\")\n}\n\n/** Inline field errors, keyed by our field names. */\nexport interface CollectFieldErrors {\n number?: string\n expiry?: string\n cvv?: string\n}\n\nconst FIELD_NAMES: Record<string, keyof CollectFieldErrors> = {\n ccnumber: \"number\",\n ccexp: \"expiry\",\n cvv: \"cvv\",\n}\n\nconst FIELD_MESSAGES: Record<keyof CollectFieldErrors, string> = {\n number: \"Enter a valid card number\",\n expiry: \"Enter a valid expiry date\",\n cvv: \"Enter a valid security code\",\n}\n\nexport interface CollectFieldSelectors {\n number: string\n expiry: string\n cvv: string\n}\n\nexport function useCollectJS(config: {\n enabled: boolean\n active: boolean\n tokenizationKey: string\n scriptURL: string\n selectors: CollectFieldSelectors\n}): {\n ready: boolean\n preview: boolean\n brand?: string\n loadError?: string\n /** Every field reported valid by the gateway. */\n valid: boolean\n fieldErrors: CollectFieldErrors\n tokenize: () => Promise<CollectResponse>\n} {\n const preview =\n config.enabled && isPreviewTokenizationKey(config.tokenizationKey)\n const [ready, setReady] = React.useState(false)\n const [loadError, setLoadError] = React.useState<string>()\n // The card brand Collect.js detects once the number is valid.\n const [brand, setBrand] = React.useState<string>()\n // Validity per field as Collect.js reports it on edit and blur.\n const [validity, setValidity] = React.useState<\n Partial<\n Record<keyof CollectFieldErrors, { valid: boolean; message?: string }>\n >\n >({})\n const pending = React.useRef<\n | {\n resolve: (r: CollectResponse) => void\n reject: (e: Error) => void\n timer: number\n }\n | undefined\n >(undefined)\n const configuredFor = React.useRef<string | undefined>(undefined)\n const { number, expiry, cvv } = config.selectors\n\n React.useEffect(() => {\n if (\n !config.enabled ||\n preview ||\n !config.tokenizationKey ||\n !config.scriptURL ||\n typeof document === \"undefined\"\n ) {\n return\n }\n const scriptURL = safeCollectScriptURL(config.scriptURL)\n if (!scriptURL) {\n void Promise.resolve().then(() => {\n setReady(false)\n setLoadError(\"Card fields failed to load\")\n })\n return\n }\n const configuration = [\n config.tokenizationKey,\n scriptURL,\n number,\n expiry,\n cvv,\n ].join(\"\\u0000\")\n const configurationChanged = configuredFor.current !== configuration\n if (!configurationChanged && !config.active) return\n configuredFor.current = configuration\n\n let canceled = false\n const settle = (fn: () => void) => {\n if (!canceled) fn()\n }\n const configure = () => {\n if (canceled) return\n const collect = window.CollectJS\n if (!collect) {\n settle(() => setLoadError(\"Card fields failed to load\"))\n return\n }\n settle(() => {\n // Replacing stale hosted iframes invalidates readiness until NMI\n // confirms that every new field is available.\n setReady(false)\n setLoadError(undefined)\n setValidity({})\n })\n // The hosted iframes cannot inherit the page theme: hand them the\n // container's resolved colors, normalized by toPlainColor for the\n // gateway's CSS sanitizer. Resolved once per configure.\n const probe = document.querySelector<HTMLElement>(number)\n const probeStyle = probe ? window.getComputedStyle(probe) : undefined\n const probeBackground = toPlainColor(probeStyle?.backgroundColor)\n const fieldBackground =\n probeBackground &&\n probeBackground !== \"transparent\" &&\n probeBackground !== \"rgba(0, 0, 0, 0)\"\n ? probeBackground\n : \"#ffffff\"\n const fieldColor = toPlainColor(probeStyle?.color) || \"#18181b\"\n const placeholderColor =\n toPlainColor(\n probeStyle?.getPropertyValue(\"--muted-foreground\").trim()\n ) || fieldColor\n try {\n collect.configure({\n variant: \"inline\",\n styleSniffer: true,\n customCss: {\n height: \"38px\",\n \"line-height\": \"38px\",\n padding: \"0 8px\",\n \"font-size\": \"14px\",\n \"font-family\": probeStyle?.fontFamily || \"inherit\",\n \"background-color\": fieldBackground,\n color: fieldColor,\n },\n placeholderCss: {\n color: placeholderColor,\n },\n invalidCss: {\n color:\n toPlainColor(\n probeStyle?.getPropertyValue(\"--destructive\").trim()\n ) || \"#dc2626\",\n },\n focusCss: {\n outline: \"none\",\n },\n // Collect.js owns the cross-origin inputs and therefore controls\n // their autocomplete behavior. Titles and placeholders are the\n // accessibility/browser hints its public field API supports.\n fields: {\n ccnumber: {\n selector: number,\n title: \"Card number\",\n placeholder: \"1234 1234 1234 1234\",\n },\n ccexp: {\n selector: expiry,\n title: \"Expiration date\",\n placeholder: \"MM / YY\",\n },\n cvv: {\n selector: cvv,\n title: \"Card security code\",\n placeholder: \"CVC\",\n },\n },\n fieldsAvailableCallback: () => settle(() => setReady(true)),\n lookUpCallback: (response: { type?: string }) =>\n settle(() => setBrand(response?.type || undefined)),\n validationCallback: (\n field: string,\n status: boolean,\n message: string\n ) => {\n const name = FIELD_NAMES[field]\n if (!name) return\n settle(() =>\n setValidity((current) => ({\n ...current,\n [name]: {\n valid: status,\n message: status\n ? undefined\n : message && message !== \"Field is empty\"\n ? `${FIELD_MESSAGES[name]}.`\n : FIELD_MESSAGES[name],\n },\n }))\n )\n },\n timeoutDuration: TIMEOUT_MS,\n timeoutCallback: () => {\n const request = pending.current\n pending.current = undefined\n if (request) {\n window.clearTimeout(request.timer)\n request.reject(new Error(\"Card entry timed out\"))\n }\n },\n callback: (response: CollectResponse) => {\n const request = pending.current\n pending.current = undefined\n if (request) {\n window.clearTimeout(request.timer)\n request.resolve(response)\n }\n },\n })\n } catch {\n settle(() => setLoadError(\"Card fields failed to load\"))\n }\n }\n let existing = document.getElementById(SCRIPT_ID)\n if (\n existing instanceof HTMLScriptElement &&\n (existing.src !== scriptURL ||\n collectScriptStates.get(existing) === \"failed\")\n ) {\n // A white-label merchant may use a different Collect.js distribution.\n // Never configure one merchant's key against another merchant's script,\n // and allow a later modal open to retry a failed network load.\n existing.remove()\n if (existing.src !== scriptURL) {\n Reflect.deleteProperty(window, \"CollectJS\")\n }\n existing = null\n }\n if (existing instanceof HTMLScriptElement) {\n if (window.CollectJS) {\n configure()\n return () => {\n canceled = true\n }\n }\n if (collectScriptStates.get(existing) === \"loaded\") {\n settle(() => setLoadError(\"Card fields failed to load\"))\n return () => {\n canceled = true\n }\n }\n const failed = () =>\n settle(() => setLoadError(\"Card fields failed to load\"))\n existing.addEventListener(\"load\", configure)\n existing.addEventListener(\"error\", failed)\n return () => {\n canceled = true\n existing.removeEventListener(\"load\", configure)\n existing.removeEventListener(\"error\", failed)\n }\n }\n const script = document.createElement(\"script\")\n script.id = SCRIPT_ID\n script.src = scriptURL\n script.async = true\n script.dataset.tokenizationKey = config.tokenizationKey\n collectScriptStates.set(script, \"loading\")\n script.onload = () => {\n collectScriptStates.set(script, \"loaded\")\n configure()\n }\n script.onerror = () => {\n collectScriptStates.set(script, \"failed\")\n settle(() => setLoadError(\"Card fields failed to load\"))\n }\n document.head.appendChild(script)\n return () => {\n canceled = true\n }\n }, [\n config.enabled,\n config.active,\n preview,\n config.tokenizationKey,\n config.scriptURL,\n number,\n expiry,\n cvv,\n ])\n\n const tokenize = React.useCallback(\n () =>\n new Promise<CollectResponse>((resolve, reject) => {\n if (preview) {\n // Preview sessions demo the full flow; a real backend rejects this\n // token, fixture sources accept it.\n resolve({\n token: \"preview_payment_token\",\n card: { number: \"4242424242424242\", type: \"visa\", exp: \"1227\" },\n })\n return\n }\n const collect = window.CollectJS\n if (!collect || !ready) {\n reject(new Error(\"Card fields are not ready\"))\n return\n }\n if (pending.current) {\n reject(new Error(\"Card entry is already in progress\"))\n return\n }\n const timer = window.setTimeout(() => {\n pending.current = undefined\n reject(new Error(\"Card entry timed out\"))\n }, TIMEOUT_MS + 5_000)\n pending.current = { resolve, reject, timer }\n collect.startPaymentRequest()\n }),\n [preview, ready]\n )\n\n const fieldErrors: CollectFieldErrors = {}\n for (const name of [\"number\", \"expiry\", \"cvv\"] as const) {\n const state = validity[name]\n if (state && !state.valid) fieldErrors[name] = state.message\n }\n const valid =\n preview ||\n ([\"number\", \"expiry\", \"cvv\"] as const).every(\n (name) => validity[name]?.valid === true\n )\n return {\n ready: ready || preview,\n preview,\n brand,\n loadError,\n valid,\n fieldErrors,\n tokenize,\n }\n}\n\n/** Display metadata of a tokenized card: never the PAN. */\nexport function collectCardDisplay(card?: CollectCard): {\n last_four?: string\n card_type?: string\n expiry_date?: string\n} {\n const digits = (card?.number ?? \"\").replace(/\\D/g, \"\")\n const exp = (card?.exp ?? \"\").replace(/\\D/g, \"\")\n return {\n ...(digits.length >= 4 ? { last_four: digits.slice(-4) } : {}),\n ...(card?.type ? { card_type: card.type } : {}),\n ...(exp.length === 4\n ? { expiry_date: `${exp.slice(0, 2)}/${exp.slice(2)}` }\n : {}),\n }\n}\n","// Stripe Elements appearance from the page's resolved theme tokens, so the\n// Payment Element matches our inputs (height, radius, type, colors).\nimport type { Appearance } from \"@stripe/stripe-js\"\n\nimport { toPlainColor } from \"#orck/lib/collect\"\n\nexport function stripeAppearance(host: HTMLElement): Appearance {\n const style = window.getComputedStyle(host)\n const token = (name: string) =>\n toPlainColor(style.getPropertyValue(name).trim()) || undefined\n const dark = !!host.closest(\".dark\")\n return {\n theme: dark ? \"night\" : \"stripe\",\n variables: {\n colorPrimary: token(\"--primary\"),\n colorBackground: token(\"--card\"),\n colorText: token(\"--foreground\"),\n colorTextSecondary: token(\"--muted-foreground\"),\n colorDanger: token(\"--destructive\"),\n fontFamily: style.fontFamily || undefined,\n fontSizeBase: \"14px\",\n borderRadius: \"9px\",\n spacingUnit: \"3px\",\n },\n rules: {\n \".Input\": {\n padding: \"9px 10px\",\n boxShadow: \"none\",\n borderColor: token(\"--border\") ?? \"\",\n },\n \".Input:focus\": {\n borderColor: token(\"--ring\") ?? \"\",\n boxShadow: \"none\",\n },\n \".Label\": { fontSize: \"13px\", fontWeight: \"500\", marginBottom: \"6px\" },\n \".Error\": { fontSize: \"12.5px\" },\n },\n }\n}\n","// Stripe Payment Element that saves a card in one call: Stripe's frames make\n// a payment method, and OpenRails saves it to the customer\n// (POST /v1/me/payment-methods). A bank that asks for 3-D Secure is answered\n// in the page (handleNextAction), then the save is confirmed.\nimport * as React from \"react\"\nimport type {\n Stripe,\n StripeElements,\n StripePaymentElementChangeEvent,\n} from \"@stripe/stripe-js\"\n\nimport type { BillingClient } from \"#orck/client/client\"\nimport { loadStripeFor } from \"#orck/lib/stripe\"\nimport { stripeAppearance } from \"#orck/lib/stripe-appearance\"\nimport type { PspConfig } from \"#orck/psp\"\n\nexport interface StripeCardHandle {\n /** Saves the entered card and returns its payment method id. */\n save(): Promise<string>\n /**\n * The entered card as Stripe's single-use payment method (`pm_`), for an\n * order to charge and save in one call.\n */\n tokenize(): Promise<string>\n /** Answers the bank's authentication of a payment or a card save. */\n handleNextAction(clientSecret: string): Promise<void>\n}\n\nexport const StripeCardEntry = React.forwardRef<\n StripeCardHandle,\n {\n psp: PspConfig\n client: BillingClient\n defaultCountry?: string\n /** Completeness of the entered card, from the element's change events. */\n onCompleteChange?: (complete: boolean) => void\n unavailableMessage: string\n verificationPendingMessage: string\n }\n>(function StripeCardEntry(\n {\n psp,\n client,\n defaultCountry,\n onCompleteChange,\n unavailableMessage,\n verificationPendingMessage,\n },\n ref\n) {\n const [error, setError] = React.useState<string>()\n const host = React.useRef<HTMLDivElement>(null)\n const mounted = React.useRef<{ stripe: Stripe; elements: StripeElements }>(\n null\n )\n const completeRef = React.useRef(onCompleteChange)\n React.useEffect(() => {\n completeRef.current = onCompleteChange\n })\n\n const publishable = psp.config?.publishable_key\n React.useEffect(() => {\n if (!publishable || !host.current) return\n let canceled = false\n let unmount: (() => void) | undefined\n void loadStripeFor(publishable).then(\n (stripe) => {\n if (canceled || !host.current) return\n const elements = stripe.elements({\n mode: \"setup\",\n paymentMethodTypes: [\"card\"],\n paymentMethodCreation: \"manual\",\n appearance: stripeAppearance(host.current),\n })\n // Cards only: the panel saves a card, so no Link bank or wallets.\n const element = elements.create(\"payment\", {\n wallets: { link: \"never\", applePay: \"never\", googlePay: \"never\" },\n ...(defaultCountry\n ? {\n defaultValues: {\n billingDetails: { address: { country: defaultCountry } },\n },\n }\n : {}),\n })\n element.on(\"change\", (event: StripePaymentElementChangeEvent) => {\n completeRef.current?.(event.complete)\n })\n element.mount(host.current)\n mounted.current = { stripe, elements }\n unmount = () => element.destroy()\n },\n (cause: unknown) => {\n if (!canceled)\n setError(cause instanceof Error ? cause.message : unavailableMessage)\n }\n )\n return () => {\n canceled = true\n mounted.current = null\n unmount?.()\n }\n }, [publishable, defaultCountry, unavailableMessage])\n\n React.useImperativeHandle(ref, () => {\n const tokenize = async () => {\n const current = mounted.current\n if (!current) throw new Error(unavailableMessage)\n setError(undefined)\n const validation = await current.elements.submit()\n if (validation.error)\n throw new Error(validation.error.message ?? unavailableMessage)\n const created = await current.stripe.createPaymentMethod({\n elements: current.elements,\n })\n if (created.error || !created.paymentMethod)\n throw new Error(created.error?.message ?? unavailableMessage)\n return created.paymentMethod.id\n }\n const handleNextAction = async (clientSecret: string) => {\n const current = mounted.current\n if (!current) throw new Error(unavailableMessage)\n const answered = await current.stripe.handleNextAction({ clientSecret })\n if (answered.error)\n throw new Error(answered.error.message ?? unavailableMessage)\n }\n return {\n tokenize,\n handleNextAction,\n async save() {\n let method = await client.addPaymentMethod({\n psp_id: psp.psp_id,\n token: await tokenize(),\n })\n const secret = method.next_action?.payload?.client_secret\n if (method.status === \"requires_action\" && secret) {\n await handleNextAction(secret)\n method = await client.confirmPaymentMethod(method.id)\n }\n if (method.status === \"requires_action\")\n throw new Error(verificationPendingMessage)\n return method.id\n },\n }\n }, [client, psp.psp_id, unavailableMessage, verificationPendingMessage])\n\n return (\n <div className=\"grid gap-2\">\n <div ref={host} data-testid=\"stripe-card-entry\" />\n {error ? (\n <p role=\"alert\" className=\"text-[13px] text-destructive\">\n {error}\n </p>\n ) : null}\n </div>\n )\n})\n","// Native card entry (driver \"card\"): the PSP declares card_entry: server, so\n// the page posts the card to OpenRails, which vaults it at the gateway. No\n// gateway script is loaded. The card lives in component state only until it\n// is submitted.\nimport * as React from \"react\"\n\nimport type { CollectFieldErrors } from \"#orck/lib/collect\"\n\n/** A card as OpenRails' `card` field takes it. */\nexport interface CardEntry {\n number: string\n exp_month: number\n exp_year: number\n cvc: string\n}\n\n/** What the buyer typed, as typed. */\nexport interface CardEntryInput {\n number: string\n expiry: string\n cvc: string\n}\n\nexport const FIELD_MESSAGES: Required<CollectFieldErrors> = {\n number: \"Enter a valid card number\",\n expiry: \"Enter a valid expiry date\",\n cvv: \"Enter a valid security code\",\n}\n\nconst digitsOf = (value: string) => value.replace(/\\D/g, \"\")\n\nfunction luhn(digits: string): boolean {\n let sum = 0\n for (let i = 0; i < digits.length; i++) {\n let d = digits.charCodeAt(digits.length - 1 - i) - 48\n if (i % 2 === 1) {\n d *= 2\n if (d > 9) d -= 9\n }\n sum += d\n }\n return sum % 10 === 0\n}\n\n/** The card network a number's leading digits name (\"\" when none). */\nexport function cardBrandOf(number: string): string {\n const d = digitsOf(number)\n const p = (n: number) => (d.length >= n ? Number(d.slice(0, n)) : -1)\n if (p(1) === 4) return \"visa\"\n if (p(2) === 34 || p(2) === 37) return \"amex\"\n if ((p(2) >= 51 && p(2) <= 55) || (p(4) >= 2221 && p(4) <= 2720))\n return \"mastercard\"\n if (p(4) === 6011 || p(2) === 65 || (p(3) >= 644 && p(3) <= 649))\n return \"discover\"\n if (p(2) === 35) return \"jcb\"\n if (p(2) === 36 || p(2) === 38 || (p(3) >= 300 && p(3) <= 305))\n return \"diners\"\n return \"\"\n}\n\n/** Groups a number as it is printed: 4-6-5 for Amex, fours otherwise. */\nexport function formatCardNumber(value: string): string {\n const d = digitsOf(value).slice(0, 19)\n if (cardBrandOf(d) === \"amex\")\n return [d.slice(0, 4), d.slice(4, 10), d.slice(10, 15)]\n .filter(Boolean)\n .join(\" \")\n return d.replace(/(\\d{4})(?=\\d)/g, \"$1 \")\n}\n\n/** MM / YY as it is typed. */\nexport function formatExpiry(value: string): string {\n const d = digitsOf(value).slice(0, 4)\n return d.length > 2 ? `${d.slice(0, 2)} / ${d.slice(2)}` : d\n}\n\nfunction parseExpiry(value: string, now: Date) {\n const d = digitsOf(value)\n if (d.length !== 4) return null\n const month = Number(d.slice(0, 2))\n const year = 2000 + Number(d.slice(2))\n if (month < 1 || month > 12) return null\n const lapsed =\n year < now.getFullYear() ||\n (year === now.getFullYear() && month < now.getMonth() + 1)\n return lapsed ? null : { month, year }\n}\n\n/** Every field's error; an empty object means the card is complete. */\nexport function cardEntryErrors(\n input: CardEntryInput,\n now = new Date()\n): CollectFieldErrors {\n const errors: CollectFieldErrors = {}\n const number = digitsOf(input.number)\n if (number.length < 12 || number.length > 19 || !luhn(number))\n errors.number = FIELD_MESSAGES.number\n if (!parseExpiry(input.expiry, now)) errors.expiry = FIELD_MESSAGES.expiry\n const cvc = digitsOf(input.cvc)\n const want = cardBrandOf(number) === \"amex\" ? 4 : 3\n if (cvc !== input.cvc.trim() || (cvc.length !== want && cvc.length !== 4))\n errors.cvv = FIELD_MESSAGES.cvv\n return errors\n}\n\n/** The card OpenRails takes, or null while any field is invalid. */\nexport function parseCardEntry(\n input: CardEntryInput,\n now = new Date()\n): CardEntry | null {\n if (Object.keys(cardEntryErrors(input, now)).length > 0) return null\n const expiry = parseExpiry(input.expiry, now)!\n return {\n number: digitsOf(input.number),\n exp_month: expiry.month,\n exp_year: expiry.year,\n cvc: digitsOf(input.cvc),\n }\n}\n\n/** A card's display facts, the ones a saved card is labelled with. */\nexport function cardEntryDisplay(card: CardEntry): {\n last_four: string\n card_type?: string\n expiry_date: string\n} {\n const brand = cardBrandOf(card.number)\n return {\n last_four: card.number.slice(-4),\n ...(brand ? { card_type: brand } : {}),\n expiry_date: `${String(card.exp_month).padStart(2, \"0\")}/${String(card.exp_year % 100).padStart(2, \"0\")}`,\n }\n}\n\nconst empty: CardEntryInput = { number: \"\", expiry: \"\", cvc: \"\" }\n\n/**\n * The state of one native card form. Errors show once a field was left;\n * `take` hands the card over and clears the form, so the page keeps it no\n * longer than the request that sends it.\n */\nexport function useCardEntry() {\n const [input, setInput] = React.useState<CardEntryInput>(empty)\n const [touched, setTouched] = React.useState<\n Partial<Record<keyof CardEntryInput, boolean>>\n >({})\n const errors = cardEntryErrors(input)\n const shown: CollectFieldErrors = {}\n if (touched.number && errors.number) shown.number = errors.number\n if (touched.expiry && errors.expiry) shown.expiry = errors.expiry\n if (touched.cvc && errors.cvv) shown.cvv = errors.cvv\n const clear = React.useCallback(() => {\n setInput(empty)\n setTouched({})\n }, [])\n return {\n input,\n fieldErrors: shown,\n valid: Object.keys(errors).length === 0,\n change: (field: keyof CardEntryInput, value: string) =>\n setInput((current) => ({\n ...current,\n [field]:\n field === \"number\"\n ? formatCardNumber(value)\n : field === \"expiry\"\n ? formatExpiry(value)\n : digitsOf(value).slice(0, 4),\n })),\n leave: (field: keyof CardEntryInput) =>\n setTouched((current) => ({ ...current, [field]: true })),\n take: (): CardEntry | null => {\n const card = parseCardEntry(input)\n if (!card) {\n setTouched({ number: true, expiry: true, cvc: true })\n return null\n }\n clear()\n return card\n },\n clear,\n }\n}\n\nexport type CardEntryState = ReturnType<typeof useCardEntry>\n","import * as React from \"react\"\nimport {\n appearanceStyle,\n appearanceTheme,\n type BillingAppearance,\n} from \"./appearance\"\nimport { CardBillingFields } from \"./components/billing-fields\"\nimport { CardFields } from \"./components/card-fields\"\nimport { PayButton, TrustLine } from \"./components/pay-button\"\nimport {\n emptyNMIBilling,\n initialCountry,\n nmiBillingSchema,\n reuseNeedsOptIn,\n} from \"./lib/billing\"\nimport { collectCardDisplay, useCollectJS } from \"./lib/collect\"\nimport { cn } from \"cn\"\n\n// Only tokenized billing details cross the iframe boundary. PAN/CVC are never\n// accepted by this component or handed to the host callback.\nexport interface TokenizedCardData {\n payment_token: string\n name_on_card: string\n country: string\n zip?: string\n /** Display metadata from the gateway: last four, brand, MM/YY. */\n last_four?: string\n card_type?: string\n expiry_date?: string\n /** The customer's opt-in to keep the card, when the form asked for it. */\n reusable?: boolean\n}\nexport interface TokenizedCardFormProps {\n tokenizationKey: string\n tokenizationURL: string\n /**\n * The host's use of the card. Resolving `false` says it was definitely\n * refused (a decline): the form takes another card.\n */\n onTokenized: (card: TokenizedCardData) => Promise<void | boolean>\n submitLabel?: string\n disabled?: boolean\n /** Billing country to preselect; default: the browser locale's region. */\n defaultCountry?: string\n /**\n * The merchant the card would be kept with, for a one-off purchase: where\n * keeping it needs an opt-in (EEA, UK) the form asks, unticked.\n */\n saveOptInMerchant?: string\n /** Shown above the button (the terms the customer accepts). */\n terms?: React.ReactNode\n /** The name the charge carries on the card statement. */\n statementDescriptor?: string\n appearance?: BillingAppearance\n className?: string\n}\n\n// The host supplies consent and performs its authorized save-card operation.\n// This component neither creates a purchase nor implies payment success.\nexport function TokenizedCardForm({\n tokenizationKey,\n tokenizationURL,\n onTokenized,\n submitLabel = \"Save card\",\n disabled = false,\n defaultCountry,\n saveOptInMerchant,\n terms,\n statementDescriptor,\n appearance,\n className,\n}: TokenizedCardFormProps) {\n const [keepCard, setKeepCard] = React.useState(false)\n const uid = React.useId().replace(/[^a-zA-Z0-9-]/g, \"\")\n const ids = React.useMemo(\n () => ({\n number: `orck-save-${uid}-number`,\n expiry: `orck-save-${uid}-expiry`,\n cvv: `orck-save-${uid}-cvv`,\n }),\n [uid]\n )\n const [billing, setBilling] = React.useState(() => ({\n ...emptyNMIBilling,\n country: initialCountry(defaultCountry),\n }))\n const [busy, setBusy] = React.useState(false)\n const [submitted, setSubmitted] = React.useState(false)\n const [error, setError] = React.useState<string>()\n const authorization = React.useRef({ generation: 0, disabled })\n React.useLayoutEffect(() => {\n authorization.current = {\n generation: authorization.current.generation + 1,\n disabled,\n }\n }, [tokenizationKey, tokenizationURL, disabled])\n const mounted = React.useRef(true)\n React.useEffect(() => {\n mounted.current = true\n return () => {\n mounted.current = false\n }\n }, [])\n const collect = useCollectJS({\n enabled: true,\n active: true,\n tokenizationKey,\n scriptURL: tokenizationURL,\n selectors: {\n number: `#${ids.number}`,\n expiry: `#${ids.expiry}`,\n cvv: `#${ids.cvv}`,\n },\n })\n // The button stays off until every required billing field is filled.\n const billingComplete = nmiBillingSchema.safeParse(billing).success\n const asksToKeep =\n saveOptInMerchant !== undefined && reuseNeedsOptIn(billing.country)\n const submit = async (event: React.FormEvent) => {\n event.preventDefault()\n if (disabled || busy || submitted) return\n const parsed = nmiBillingSchema.safeParse(billing)\n if (!parsed.success) {\n setError(parsed.error.issues[0]?.message ?? \"Check the billing details\")\n return\n }\n setBusy(true)\n setError(undefined)\n const generation = authorization.current.generation\n let sent = false\n try {\n const token = await collect.tokenize()\n if (\n !mounted.current ||\n authorization.current.generation !== generation ||\n authorization.current.disabled\n )\n return\n sent = true\n setSubmitted(true)\n const accepted = await onTokenized({\n payment_token: token.token,\n ...parsed.data,\n ...collectCardDisplay(token.card),\n ...(asksToKeep ? { reusable: keepCard } : {}),\n })\n if (accepted === false && mounted.current) setSubmitted(false)\n } catch (cause) {\n if (mounted.current)\n setError(\n sent\n ? \"The card-save result is not confirmed. Check your saved cards before starting another attempt.\"\n : cause instanceof Error\n ? cause.message\n : \"Card entry could not be completed.\"\n )\n } finally {\n if (mounted.current) setBusy(false)\n }\n }\n return (\n <div\n className={cn(\"orck\", className)}\n data-orck-theme={appearanceTheme(appearance)}\n style={appearanceStyle(appearance)}\n >\n <form\n aria-label=\"Secure card setup\"\n autoComplete=\"on\"\n className=\"grid gap-4\"\n onSubmit={(event) => void submit(event)}\n >\n <CardBillingFields\n idPrefix={`orck-save-${uid}`}\n value={billing}\n onChange={setBilling}\n disabled={disabled || busy || submitted}\n >\n <CardFields\n ids={ids}\n preview={collect.preview}\n brand={collect.brand}\n error={collect.loadError}\n fieldErrors={collect.fieldErrors}\n />\n </CardBillingFields>\n {asksToKeep ? (\n <label className=\"flex items-start gap-2 text-[13px] text-foreground\">\n <input\n type=\"checkbox\"\n className=\"mt-0.5\"\n checked={keepCard}\n onChange={(event) => setKeepCard(event.target.checked)}\n disabled={disabled || busy || submitted}\n />\n Save payment details to {saveOptInMerchant} for future purchases\n </label>\n ) : null}\n {terms ? (\n <p className=\"text-xs text-muted-foreground\">{terms}</p>\n ) : null}\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n ) : null}\n <PayButton\n label={submitLabel}\n processing={busy}\n disabled={\n disabled ||\n submitted ||\n !billingComplete ||\n !collect.ready ||\n !collect.valid ||\n Boolean(collect.loadError)\n }\n />\n {statementDescriptor ? (\n <p className=\"-mt-1 text-center text-xs text-muted-foreground\">\n The charge will appear as “{statementDescriptor}” on\n your card statement.\n </p>\n ) : (\n <TrustLine />\n )}\n </form>\n </div>\n )\n}\n","import * as React from \"react\"\n\nimport {\n appearanceStyle,\n appearanceTheme,\n type BillingAppearance,\n} from \"./appearance\"\nimport { isBillingError } from \"./client/errors\"\nimport { CardBillingFields } from \"./components/billing-fields\"\nimport { PlatformCardForm } from \"./components/platform-card-form\"\nimport { NativeCardFields } from \"./components/card-fields\"\nimport { PayButton, TrustLine } from \"./components/pay-button\"\nimport {\n StripeCardEntry,\n type StripeCardHandle,\n} from \"./components/stripe-card\"\nimport { useMessages } from \"./i18n/context\"\nimport {\n billingDetailsOf,\n emptyNMIBilling,\n initialCountry,\n nmiBillingSchema,\n} from \"./lib/billing\"\nimport { useCardEntry } from \"./lib/card-entry\"\nimport { cardSetupDriver, type PspConfig } from \"./psp\"\nimport { useBillingContext } from \"./react/context\"\nimport {\n TokenizedCardForm,\n type TokenizedCardData,\n} from \"./tokenized-card-form\"\nimport { cn } from \"cn\"\n\nexport interface SavePaymentMethodProps {\n /** The PSP to save the card with, from OpenRails's payment config. */\n psp: PspConfig\n onSaved: (paymentMethodId: string) => void\n /** Billing country to preselect; default: the browser locale's region. */\n defaultCountry?: string\n submitLabel?: string\n appearance?: BillingAppearance\n className?: string\n}\n\n/**\n * Saves a card to the customer's account with any PSP OpenRails serves, in\n * the page. The PSP's configuration picks the flow: card data enters the\n * provider's own frames, or, for a PSP whose card_entry is server, is posted\n * to OpenRails. Requires `BillingProvider`.\n */\nexport function SavePaymentMethod(props: SavePaymentMethodProps) {\n const { t } = useMessages()\n const driver = cardSetupDriver(props.psp)\n if (!driver)\n return (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {t(\"paymentMethods.unavailable\")}\n </p>\n )\n return (\n <div\n className={cn(\"orck grid gap-4\", props.className)}\n data-orck-theme={appearanceTheme(props.appearance)}\n style={appearanceStyle(props.appearance)}\n >\n <p className=\"text-sm text-muted-foreground\">\n {t(\"paymentMethods.saveNotice\")}\n </p>\n {driver === \"platform\" ? (\n <PlatformSetup {...props} />\n ) : driver === \"collect_js\" ? (\n <TokenizedSetup {...props} />\n ) : driver === \"card\" ? (\n <NativeCardSetup {...props} />\n ) : (\n <ElementsSetup {...props} />\n )}\n </div>\n )\n}\n\n// Provider SDK errors carry customer-facing text (\"Your card was declined.\").\nconst describe = (m: ReturnType<typeof useMessages>, cause: unknown) =>\n !isBillingError(cause) && cause instanceof Error && cause.message\n ? cause.message\n : m.error(cause)\n\nfunction TokenizedSetup({\n psp,\n onSaved,\n submitLabel,\n appearance,\n defaultCountry,\n}: SavePaymentMethodProps) {\n const m = useMessages()\n const { client, notify } = useBillingContext()\n const [formKey, setFormKey] = React.useState(0)\n const [error, setError] = React.useState<string>()\n const save = async (card: TokenizedCardData) => {\n setError(undefined)\n let method\n try {\n method = await client.addPaymentMethod({\n psp_id: psp.psp_id,\n token: card.payment_token,\n billing_details: billingDetailsOf(card),\n })\n } catch (cause) {\n setError(describe(m, cause))\n setFormKey((key) => key + 1)\n return\n }\n notify({ type: \"payment_method.added\", paymentMethodId: method.id })\n onSaved(method.id)\n }\n return (\n <>\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n ) : null}\n <TokenizedCardForm\n key={formKey}\n tokenizationKey={psp.config!.tokenization_key!}\n tokenizationURL={psp.config!.tokenization_url!}\n onTokenized={save}\n defaultCountry={defaultCountry}\n submitLabel={submitLabel ?? m.t(\"paymentMethods.save\")}\n appearance={appearance}\n />\n </>\n )\n}\n\nfunction NativeCardSetup({\n psp,\n onSaved,\n submitLabel,\n defaultCountry,\n}: SavePaymentMethodProps) {\n const m = useMessages()\n const { client, notify } = useBillingContext()\n const uid = React.useId().replace(/[^a-zA-Z0-9-]/g, \"\")\n const ids = React.useMemo(\n () => ({\n number: `orck-save-${uid}-number`,\n expiry: `orck-save-${uid}-expiry`,\n cvv: `orck-save-${uid}-cvv`,\n }),\n [uid]\n )\n const card = useCardEntry()\n const [billing, setBilling] = React.useState(() => ({\n ...emptyNMIBilling,\n country: initialCountry(defaultCountry),\n }))\n const [busy, setBusy] = React.useState(false)\n const [error, setError] = React.useState<string>()\n\n const submit = async (event: React.FormEvent) => {\n event.preventDefault()\n if (busy) return\n const parsed = nmiBillingSchema.safeParse(billing)\n if (!parsed.success) {\n setError(parsed.error.issues[0]?.message ?? \"Check the billing details\")\n return\n }\n const entered = card.take()\n if (!entered) return\n setBusy(true)\n setError(undefined)\n try {\n const method = await client.addPaymentMethod({\n psp_id: psp.psp_id,\n card: entered,\n billing_details: billingDetailsOf(parsed.data),\n })\n notify({ type: \"payment_method.added\", paymentMethodId: method.id })\n onSaved(method.id)\n } catch (cause) {\n setError(describe(m, cause))\n } finally {\n setBusy(false)\n }\n }\n\n return (\n <form\n aria-label=\"Secure card setup\"\n autoComplete=\"on\"\n className=\"grid gap-4\"\n noValidate\n onSubmit={(event) => void submit(event)}\n >\n <CardBillingFields\n idPrefix={`orck-save-${uid}`}\n value={billing}\n onChange={setBilling}\n disabled={busy}\n >\n <NativeCardFields ids={ids} card={card} disabled={busy} />\n </CardBillingFields>\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n ) : null}\n <PayButton\n label={submitLabel ?? m.t(\"paymentMethods.save\")}\n processing={busy}\n disabled={!card.valid || !nmiBillingSchema.safeParse(billing).success}\n />\n <TrustLine />\n </form>\n )\n}\n\nfunction ElementsSetup({\n psp,\n onSaved,\n submitLabel,\n defaultCountry,\n}: SavePaymentMethodProps) {\n const m = useMessages()\n const { t } = m\n const { client, notify } = useBillingContext()\n const card = React.useRef<StripeCardHandle>(null)\n const [complete, setComplete] = React.useState(false)\n const [busy, setBusy] = React.useState(false)\n const [error, setError] = React.useState<string>()\n const country = React.useMemo(\n () => initialCountry(defaultCountry),\n [defaultCountry]\n )\n\n const submit = async (event: React.FormEvent) => {\n event.preventDefault()\n if (!card.current || busy) return\n setBusy(true)\n setError(undefined)\n try {\n const id = await card.current.save()\n notify({ type: \"payment_method.added\", paymentMethodId: id })\n onSaved(id)\n } catch (cause) {\n setError(describe(m, cause))\n } finally {\n setBusy(false)\n }\n }\n\n return (\n <form className=\"grid gap-4\" onSubmit={(event) => void submit(event)}>\n <StripeCardEntry\n ref={card}\n psp={psp}\n client={client}\n defaultCountry={country || undefined}\n onCompleteChange={setComplete}\n unavailableMessage={t(\"paymentMethods.unavailable\")}\n verificationPendingMessage={t(\"paymentMethods.verificationPending\")}\n />\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n ) : null}\n <PayButton\n label={submitLabel ?? t(\"paymentMethods.save\")}\n processing={busy}\n disabled={!complete}\n />\n <TrustLine />\n </form>\n )\n}\n\nfunction PlatformSetup({\n psp,\n onSaved,\n submitLabel,\n defaultCountry,\n}: SavePaymentMethodProps) {\n const m = useMessages()\n const { client, notify } = useBillingContext()\n const [error, setError] = React.useState<string>()\n const save = async (card: TokenizedCardData) => {\n setError(undefined)\n let method\n try {\n method = await client.addPaymentMethod({\n psp_id: psp.psp_id,\n token: card.payment_token,\n billing_details: billingDetailsOf(card),\n })\n } catch (cause) {\n setError(describe(m, cause))\n // A definite refusal can collect a corrected card. A lost response\n // keeps the original collection so Retry recovers the same save.\n if (\n isBillingError(cause) &&\n (cause.status === 400 || cause.status === 402)\n )\n return false\n throw cause\n }\n notify({ type: \"payment_method.added\", paymentMethodId: method.id })\n onSaved(method.id)\n return true\n }\n return (\n <>\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n ) : null}\n <PlatformCardForm\n publicKey={psp.config!.public_api_key!}\n purpose=\"setup\"\n defaultCountry={defaultCountry}\n submitLabel={submitLabel ?? m.t(\"paymentMethods.save\")}\n disabled={false}\n onTokenized={save}\n />\n </>\n )\n}\n","import * as React from \"react\"\nimport { cn } from \"cn\"\n\n/** Polite confirmation line that clears itself. */\nexport function useNotice(): [React.ReactNode, (text: string) => void] {\n const [text, setText] = React.useState<string | null>(null)\n React.useEffect(() => {\n if (!text) return\n const timer = setTimeout(() => setText(null), 6000)\n return () => clearTimeout(timer)\n }, [text])\n const node = (\n <p\n role=\"status\"\n aria-live=\"polite\"\n className={cn(\"text-sm text-muted-foreground\", text ? \"pt-3\" : \"sr-only\")}\n >\n {text}\n </p>\n )\n return [node, setText]\n}\n","import * as React from \"react\"\nimport { HugeiconsIcon } from \"@hugeicons/react\"\nimport { Add01Icon, Delete02Icon } from \"@hugeicons/core-free-icons\"\n\nimport type { BillingAppearance } from \"#orck/appearance\"\nimport type { BillingError } from \"#orck/client/errors\"\nimport type { PaymentMethod } from \"#orck/client/types\"\nimport { CardBrandPlate } from \"#orck/components/card-brands\"\nimport {\n AlertDialog,\n AlertDialogCancel,\n AlertDialogContent,\n AlertDialogDescription,\n AlertDialogFooter,\n AlertDialogHeader,\n AlertDialogTitle,\n} from \"#orck/components/ui/alert-dialog\"\nimport { Button } from \"#orck/components/ui/button\"\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogHeader,\n DialogTitle,\n} from \"#orck/components/ui/dialog\"\nimport { Spinner } from \"#orck/components/ui/spinner\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport type { Translator } from \"#orck/i18n/messages\"\nimport { useCustomerConfig } from \"#orck/react/config\"\nimport { usePaymentMethods } from \"#orck/react/hooks\"\nimport { useScopeProps } from \"#orck/scope-context\"\nimport { canSavePaymentMethod, cardRetryAfter, routedPsps } from \"#orck/psp\"\nimport { SavePaymentMethod } from \"#orck/save-payment-method\"\nimport { cardText, RESET } from \"./format\"\nimport { EmptyState, ErrorState, ListSkeleton, Section } from \"./section\"\nimport { useNotice } from \"./notice\"\nimport { BillingStatusBadge } from \"./status-badge\"\n\nexport interface PaymentMethodsPanelProps {\n /**\n * Offers to make a card the default for this currency: it pays the\n * currency's usage orders and every subscription in it without its own card.\n */\n defaultCurrency?: string\n /** Billing country to preselect when adding a card. */\n defaultCountry?: string\n appearance?: BillingAppearance\n className?: string\n}\n\nfunction methodLabel(method: PaymentMethod, m: Translator): string {\n return cardText(method.card, m)\n}\n\nfunction removeMessage(error: BillingError, m: Translator): string {\n if (error.status === 409 && error.code === \"resource_conflict\")\n return m.t(\"paymentMethods.inUse\")\n if (error.status === 503 || error.code === \"invalid_response\")\n return m.t(\"paymentMethods.removeFailed\")\n return m.error(error)\n}\n\n/**\n * The customer's saved cards. \"Add card\" offers each PSP of the merchant's\n * payment setup (`GET /me/config`) that saves a card in the page.\n */\nexport function PaymentMethodsPanel({\n defaultCurrency,\n defaultCountry,\n appearance,\n className,\n}: PaymentMethodsPanelProps) {\n const m = useMessages()\n const { t } = m\n const scope = useScopeProps(appearance)\n const state = usePaymentMethods()\n const [removing, setRemoving] = React.useState<PaymentMethod | null>(null)\n const [removeError, setRemoveError] = React.useState<string | null>(null)\n const [rowError, setRowError] = React.useState<{\n id: string\n message: string\n } | null>(null)\n const [adding, setAdding] = React.useState(false)\n const config = useCustomerConfig()\n const psps = routedPsps(config.config?.payment.psps ?? [])\n const savable = psps.filter(canSavePaymentMethod)\n const retryAfter = savable.length > 0 ? null : cardRetryAfter(psps)\n const { refetch: refetchConfig } = config\n React.useEffect(() => {\n if (retryAfter === null) return\n const timer = setTimeout(refetchConfig, retryAfter * 1000)\n return () => clearTimeout(timer)\n }, [retryAfter, refetchConfig, config.config])\n const [pspId, setPspId] = React.useState<string>()\n const psp = savable.find((item) => item.psp_id === pspId) ?? savable[0]\n const [notice, announce] = useNotice()\n const currency = defaultCurrency?.toUpperCase()\n\n const confirmRemove = async () => {\n if (!removing) return\n setRemoveError(null)\n const result = await state.remove(removing.id)\n if (result) {\n setRemoveError(removeMessage(result, m))\n return\n }\n setRemoving(null)\n announce(t(\"paymentMethods.removed\"))\n }\n\n const makeDefault = async (method: PaymentMethod) => {\n if (!currency) return\n setRowError(null)\n const error = await state.setDefault(method.id, currency)\n if (error) setRowError({ id: method.id, message: m.error(error) })\n else announce(t(\"paymentMethods.defaultUpdated\"))\n }\n\n let body: React.ReactNode\n const methods = state.methods\n if (methods === null && state.error) {\n body = <ErrorState error={state.error} onRetry={state.refetch} />\n } else if (methods === null) {\n body = <ListSkeleton />\n } else if (methods.length === 0) {\n body = (\n <EmptyState\n title={t(\"paymentMethods.empty\")}\n description={t(\"paymentMethods.emptyDescription\")}\n />\n )\n } else {\n body = (\n <ul className=\"-my-1 divide-y divide-border\">\n {methods.map((method) => {\n const label = methodLabel(method, m)\n const users = (method.subscriptions ?? [])\n .map((s) => s.display_name)\n .filter(Boolean)\n const health = method.health?.expiry_status\n const defaults = method.default_currencies ?? []\n const pending = state.pending[method.id]\n const meta = [\n users.length > 0 &&\n t(\"paymentMethods.usedBy\", { names: users.join(\", \") }),\n ].filter(Boolean)\n return (\n <li\n key={method.id}\n data-testid=\"payment-method-row\"\n data-payment-method-id={method.id}\n className=\"flex flex-wrap items-center gap-x-3 gap-y-2 py-3.5\"\n >\n <CardBrandPlate\n brand={method.card?.brand ?? undefined}\n fallback={(method.card?.brand ?? \"card\").slice(0, 4)}\n />\n <div className=\"grid min-w-40 flex-1 gap-0.5\">\n <div className=\"flex flex-wrap items-center gap-x-2 gap-y-1\">\n <span className=\"text-sm font-medium tabular-nums\">\n {label}\n </span>\n {health === \"expired\" || health === \"expiring_soon\" ? (\n <BillingStatusBadge status={health} />\n ) : method.health?.active === false ? (\n <BillingStatusBadge status=\"needs_attention\" />\n ) : null}\n {defaults.length > 0 ? (\n <BillingStatusBadge\n status=\"default\"\n label={t(\"paymentMethods.defaultFor\", {\n currencies: defaults.join(\", \"),\n })}\n />\n ) : null}\n </div>\n {meta.length > 0 ? (\n <p className=\"text-sm text-muted-foreground tabular-nums\">\n {meta.join(\" · \")}\n </p>\n ) : null}\n {rowError?.id === method.id ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {rowError.message}\n </p>\n ) : null}\n </div>\n <div className=\"ml-auto flex items-center gap-1\">\n {currency && !defaults.includes(currency) ? (\n <Button\n variant=\"ghost\"\n size=\"sm\"\n className=\"text-muted-foreground\"\n disabled={!!pending}\n onClick={() => void makeDefault(method)}\n >\n {pending === \"default\" ? <Spinner /> : null}\n {t(\"paymentMethods.makeDefault\")}\n </Button>\n ) : null}\n <Button\n variant=\"destructive\"\n size=\"icon-sm\"\n className=\"bg-red-600 text-white hover:bg-red-700\"\n aria-label={t(\"paymentMethods.removeLabel\", { label })}\n title={t(\"paymentMethods.remove\")}\n disabled={!!pending}\n onClick={() => {\n setRemoveError(null)\n setRemoving(method)\n }}\n >\n {pending === \"remove\" ? (\n <Spinner />\n ) : (\n <HugeiconsIcon icon={Delete02Icon} aria-hidden />\n )}\n </Button>\n </div>\n </li>\n )\n })}\n </ul>\n )\n }\n\n const removingBusy = removing\n ? state.pending[removing.id] === \"remove\"\n : false\n const removingLabel = removing ? methodLabel(removing, m) : \"\"\n\n return (\n <Section\n title={t(\"paymentMethods.title\")}\n description={t(\"paymentMethods.description\")}\n appearance={appearance}\n className={className}\n data-testid=\"payment-methods-panel\"\n action={\n psp ? (\n <Button variant=\"outline\" size=\"sm\" onClick={() => setAdding(true)}>\n <HugeiconsIcon\n icon={Add01Icon}\n aria-hidden\n data-icon=\"inline-start\"\n />\n {t(\"paymentMethods.add\")}\n </Button>\n ) : null\n }\n >\n {body}\n {methods !== null && state.error ? (\n <div className=\"pt-3\">\n <ErrorState error={state.error} onRetry={state.refetch} />\n </div>\n ) : null}\n {config.error ? (\n <div className=\"pt-3\">\n <ErrorState\n error={config.error}\n message={t(\"paymentMethods.addUnavailable\")}\n onRetry={config.refetch}\n />\n </div>\n ) : retryAfter !== null ? (\n <p role=\"status\" className=\"pt-3 text-sm text-muted-foreground\">\n {t(\"paymentMethods.addUnavailable\")}\n </p>\n ) : null}\n {notice}\n\n <AlertDialog\n open={removing !== null}\n onOpenChange={(open) => {\n if (!open && !removingBusy) setRemoving(null)\n }}\n >\n <AlertDialogContent\n className={`${scope.className} ${RESET} bg-popover text-popover-foreground`}\n data-orck-theme={scope[\"data-orck-theme\"]}\n style={scope.style}\n >\n <AlertDialogHeader>\n <AlertDialogTitle>\n {t(\"paymentMethods.removeTitle\", { label: removingLabel })}\n </AlertDialogTitle>\n <AlertDialogDescription>\n {t(\"paymentMethods.removeDescription\")}\n </AlertDialogDescription>\n </AlertDialogHeader>\n {removeError ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {removeError}\n </p>\n ) : null}\n <AlertDialogFooter>\n <AlertDialogCancel disabled={removingBusy}>\n {t(\"common.cancel\")}\n </AlertDialogCancel>\n <Button\n variant=\"destructive\"\n disabled={removingBusy}\n onClick={() => void confirmRemove()}\n >\n {removingBusy ? <Spinner /> : null}\n {t(\"paymentMethods.removeConfirm\")}\n </Button>\n </AlertDialogFooter>\n </AlertDialogContent>\n </AlertDialog>\n\n {psp ? (\n <Dialog open={adding} onOpenChange={setAdding}>\n <DialogContent\n className={`${scope.className} ${RESET} max-h-[calc(100dvh-2rem)] overflow-y-auto bg-popover text-popover-foreground`}\n data-orck-theme={scope[\"data-orck-theme\"]}\n style={scope.style}\n >\n <DialogHeader>\n <DialogTitle>{t(\"paymentMethods.addTitle\")}</DialogTitle>\n <DialogDescription>\n {t(\"paymentMethods.addDescription\")}\n </DialogDescription>\n </DialogHeader>\n {savable.length > 1 ? (\n <label className=\"grid gap-1.5 text-sm\">\n {t(\"paymentMethods.provider\")}\n <select\n className=\"h-9 rounded-md border border-input bg-transparent px-2\"\n value={psp.psp_id}\n onChange={(event) => setPspId(event.target.value)}\n >\n {savable.map((item) => (\n <option key={item.psp_id} value={item.psp_id}>\n {item.display_name}\n </option>\n ))}\n </select>\n </label>\n ) : null}\n <SavePaymentMethod\n key={psp.psp_id}\n psp={psp}\n defaultCountry={defaultCountry}\n appearance={appearance}\n onSaved={() => {\n setAdding(false)\n announce(t(\"paymentMethods.added\"))\n }}\n />\n </DialogContent>\n </Dialog>\n ) : null}\n </Section>\n )\n}\n","import * as React from \"react\"\nimport { cn } from \"cn\"\n\nfunction Textarea({ className, ...props }: React.ComponentProps<\"textarea\">) {\n return (\n <textarea\n data-slot=\"textarea\"\n className={cn(\n \"flex field-sizing-content min-h-16 w-full rounded-md border border-input bg-transparent px-2.5 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40\",\n className\n )}\n {...props}\n />\n )\n}\n\nexport { Textarea }\n","import * as React from \"react\"\n\nimport type { BillingAppearance } from \"#orck/appearance\"\n\nimport {\n CANCEL_REASON_MAX,\n CANCEL_REASON_MIN,\n isWalletRejection,\n} from \"#orck/client/client\"\nimport type { BillingError } from \"#orck/client/errors\"\nimport {\n AlertDialog,\n AlertDialogCancel,\n AlertDialogContent,\n AlertDialogDescription,\n AlertDialogFooter,\n AlertDialogHeader,\n AlertDialogTitle,\n} from \"#orck/components/ui/alert-dialog\"\nimport { Button } from \"#orck/components/ui/button\"\nimport { Label } from \"#orck/components/ui/label\"\nimport { Spinner } from \"#orck/components/ui/spinner\"\nimport { Textarea } from \"#orck/components/ui/textarea\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport type { SubscriptionAction } from \"#orck/react/hooks\"\nimport { useScopeProps } from \"#orck/scope-context\"\nimport { RESET } from \"./format\"\n\n// Key it per subscription so each opening starts blank.\nexport interface CancelSubscriptionDialogProps {\n open: boolean\n onOpenChange: (open: boolean) => void\n /** Subscription display name. */\n name: string\n /** Offers an optional on-chain cancellation when a wallet is available. */\n onChain?: boolean\n /** In-flight stage, when cancelling. */\n pending?: SubscriptionAction\n /** Resolves null on success; the dialog then closes. */\n onConfirm: (reason: string, revokeOnChain: boolean) => Promise<BillingError | null>\n appearance?: BillingAppearance\n}\n\nexport function CancelSubscriptionDialog({\n open,\n onOpenChange,\n name,\n onChain = false,\n pending,\n onConfirm,\n appearance,\n}: CancelSubscriptionDialogProps) {\n const m = useMessages()\n const { t } = m\n const scope = useScopeProps(appearance)\n const reasonId = React.useId()\n const hintId = React.useId()\n const [reason, setReason] = React.useState(\"\")\n const [revokeOnChain, setRevokeOnChain] = React.useState(false)\n const [touched, setTouched] = React.useState(false)\n const [error, setError] = React.useState<BillingError | null>(null)\n const busy = pending !== undefined\n\n const length = reason.trim().length\n const tooShort = length < CANCEL_REASON_MIN\n const confirm = async () => {\n setTouched(true)\n if (tooShort || busy) return\n setError(null)\n const result = await onConfirm(reason, revokeOnChain)\n if (!result) onOpenChange(false)\n else if (!isWalletRejection(result)) setError(result)\n }\n\n const stageLabel =\n pending === \"cancel\" && revokeOnChain\n ? t(\"cancel.preparing\")\n : pending === \"signing\"\n ? t(\"cancel.signing\")\n : pending === \"confirming\"\n ? t(\"cancel.confirming\")\n : busy\n ? t(\"cancel.working\")\n : revokeOnChain\n ? t(\"cancel.confirmWallet\")\n : t(\"cancel.confirm\")\n\n return (\n <AlertDialog\n open={open}\n onOpenChange={(next) => {\n if (!next && busy) return\n onOpenChange(next)\n }}\n >\n <AlertDialogContent\n className={`${scope.className} ${RESET} bg-popover text-popover-foreground`}\n data-orck-theme={scope[\"data-orck-theme\"]}\n style={scope.style}\n >\n <form\n className=\"grid gap-5\"\n noValidate\n onSubmit={(event) => {\n event.preventDefault()\n void confirm()\n }}\n >\n <AlertDialogHeader>\n <AlertDialogTitle>{t(\"cancel.title\", { name })}</AlertDialogTitle>\n <AlertDialogDescription>\n {t(\"cancel.description\")}\n </AlertDialogDescription>\n </AlertDialogHeader>\n <div className=\"grid gap-2\">\n <Label htmlFor={reasonId}>{t(\"cancel.reasonLabel\")}</Label>\n <Textarea\n id={reasonId}\n value={reason}\n maxLength={CANCEL_REASON_MAX}\n placeholder={t(\"cancel.reasonPlaceholder\")}\n aria-describedby={hintId}\n aria-invalid={touched && tooShort ? true : undefined}\n disabled={busy}\n required\n rows={3}\n className=\"[font:inherit]\"\n onChange={(event) => setReason(event.target.value)}\n onBlur={() => length > 0 && setTouched(true)}\n />\n <div\n id={hintId}\n className=\"flex justify-between gap-3 text-xs text-muted-foreground\"\n >\n <span className={touched && tooShort ? \"text-destructive\" : \"\"}>\n {touched && tooShort\n ? t(\"cancel.reasonTooShort\", { min: CANCEL_REASON_MIN })\n : \"\"}\n </span>\n <span className=\"tabular-nums\">\n {t(\"cancel.reasonHint\", {\n count: reason.length,\n max: CANCEL_REASON_MAX,\n })}\n </span>\n </div>\n </div>\n {onChain ? (\n <label className=\"flex items-start gap-2 text-sm\">\n <input\n type=\"checkbox\"\n checked={revokeOnChain}\n disabled={busy}\n onChange={(event) => setRevokeOnChain(event.target.checked)}\n />\n <span>{t(\"cancel.revokeOnChain\")}</span>\n </label>\n ) : null}\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {m.error(error)}\n </p>\n ) : null}\n <AlertDialogFooter>\n <AlertDialogCancel disabled={busy}>\n {t(\"cancel.keep\")}\n </AlertDialogCancel>\n <Button type=\"submit\" variant=\"destructive\" disabled={busy}>\n {busy ? <Spinner /> : null}\n {stageLabel}\n </Button>\n </AlertDialogFooter>\n </form>\n </AlertDialogContent>\n </AlertDialog>\n )\n}\n","\"use client\"\n\nimport { Radio as RadioPrimitive } from \"@base-ui/react/radio\"\nimport { RadioGroup as RadioGroupPrimitive } from \"@base-ui/react/radio-group\"\nimport { cn } from \"cn\"\n\nfunction RadioGroup({ className, ...props }: RadioGroupPrimitive.Props) {\n return (\n <RadioGroupPrimitive\n data-slot=\"radio-group\"\n className={cn(\"grid w-full gap-3\", className)}\n {...props}\n />\n )\n}\n\nfunction RadioGroupItem({ className, ...props }: RadioPrimitive.Root.Props) {\n return (\n <RadioPrimitive.Root\n data-slot=\"radio-group-item\"\n className={cn(\n \"group/radio-group-item peer relative flex aspect-square size-4 shrink-0 rounded-full border border-input outline-none group-has-[:focus-visible]/field-label:ring-0 group-has-[:focus-visible]/field-label:not-data-checked:border-input after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground group-has-[:focus-visible]/field-label:data-checked:border-primary dark:data-checked:bg-primary\",\n className\n )}\n {...props}\n >\n <RadioPrimitive.Indicator\n data-slot=\"radio-group-indicator\"\n className=\"flex size-4 items-center justify-center\"\n >\n <span className=\"absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2 rounded-full bg-primary-foreground\" />\n </RadioPrimitive.Indicator>\n </RadioPrimitive.Root>\n )\n}\n\nexport { RadioGroup, RadioGroupItem }\n","import * as React from \"react\"\n\nimport type { BillingAppearance } from \"#orck/appearance\"\nimport { cn } from \"cn\"\n\nimport type { BillingError } from \"#orck/client/errors\"\nimport type { PaymentMethod, Subscription } from \"#orck/client/types\"\nimport { CardBrandPlate } from \"#orck/components/card-brands\"\nimport { Button } from \"#orck/components/ui/button\"\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from \"#orck/components/ui/dialog\"\nimport { Label } from \"#orck/components/ui/label\"\nimport { RadioGroup, RadioGroupItem } from \"#orck/components/ui/radio-group\"\nimport { Spinner } from \"#orck/components/ui/spinner\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport { usePaymentMethods } from \"#orck/react/hooks\"\nimport { useCustomerConfig } from \"#orck/react/config\"\nimport { canSavePaymentMethod, routedPsps } from \"#orck/psp\"\nimport { SavePaymentMethod } from \"#orck/save-payment-method\"\nimport { useScopeProps } from \"#orck/scope-context\"\nimport { cardText, RESET } from \"./format\"\nimport { ErrorState, ListSkeleton } from \"./section\"\n\n/** The choice that makes the subscription follow the default card. */\nconst FOLLOW_DEFAULT = \"default\"\n\n/** Cards the subscription's PSP can charge; expired cards are left out. */\nfunction eligibleCards(\n s: Subscription,\n methods: readonly PaymentMethod[]\n): PaymentMethod[] {\n return methods.filter(\n (m) =>\n m.health?.active !== false &&\n m.health?.expiry_status !== \"expired\" &&\n (!s.psp_id || !m.psp_id || m.psp_id === s.psp_id) &&\n (!s.rail || !m.rail || m.rail === s.rail)\n )\n}\n\nexport interface ChangeCardDialogProps {\n subscription: Subscription | null\n name: string\n onOpenChange: (open: boolean) => void\n pending: boolean\n /**\n * The subscription's own card, or null to follow the default card. Resolves\n * null on success; the dialog then closes.\n */\n onConfirm: (paymentMethodId: string | null) => Promise<BillingError | null>\n mode?: \"change\" | \"resume\"\n description?: string\n appearance?: BillingAppearance\n}\n\nexport function ChangeCardDialog({\n subscription,\n name,\n onOpenChange,\n pending,\n onConfirm,\n mode = \"change\",\n description,\n appearance,\n}: ChangeCardDialogProps) {\n const scope = useScopeProps(appearance)\n return (\n <Dialog\n open={subscription !== null}\n onOpenChange={(next) => {\n if (!next && pending) return\n onOpenChange(next)\n }}\n >\n <DialogContent\n showCloseButton={false}\n className={`${scope.className} ${RESET} max-h-[calc(100dvh-2rem)] overflow-y-auto bg-popover text-popover-foreground`}\n data-orck-theme={scope[\"data-orck-theme\"]}\n style={scope.style}\n >\n {subscription ? (\n <ChangeCardForm\n subscription={subscription}\n name={name}\n pending={pending}\n onCancel={() => onOpenChange(false)}\n onConfirm={onConfirm}\n mode={mode}\n description={description}\n appearance={appearance}\n />\n ) : null}\n </DialogContent>\n </Dialog>\n )\n}\n\n// Mounted only while open, so the card list loads on demand.\nfunction ChangeCardForm({\n subscription,\n name,\n pending,\n onCancel,\n onConfirm,\n mode,\n description,\n appearance,\n}: {\n subscription: Subscription\n name: string\n pending: boolean\n onCancel: () => void\n onConfirm: (paymentMethodId: string | null) => Promise<BillingError | null>\n mode: \"change\" | \"resume\"\n description?: string\n appearance?: BillingAppearance\n}) {\n const m = useMessages()\n const { t } = m\n const idPrefix = React.useId()\n const methods = usePaymentMethods()\n const current = subscription.payment_method_id ?? FOLLOW_DEFAULT\n const [selected, setSelected] = React.useState(current)\n const [error, setError] = React.useState<BillingError | null>(null)\n const [adding, setAdding] = React.useState(false)\n const [submitting, setSubmitting] = React.useState(false)\n const initialized = React.useRef(false)\n const busy = pending || submitting\n const cards = React.useMemo(\n () =>\n methods.methods ? eligibleCards(subscription, methods.methods) : null,\n [methods.methods, subscription]\n )\n React.useEffect(() => {\n if (mode !== \"resume\" || cards === null || initialized.current) return\n initialized.current = true\n setSelected(\n cards.some((card) => card.id === current) ? current : (cards[0]?.id ?? \"\")\n )\n setAdding(cards.length === 0)\n }, [cards, current, mode])\n const currency = subscription.price?.currency?.toUpperCase()\n const defaultCard = currency\n ? cards?.find((c) => (c.default_currencies ?? []).includes(currency))\n : undefined\n const choices = [\n ...(mode === \"change\" && defaultCard\n ? [{ id: FOLLOW_DEFAULT, card: defaultCard }]\n : []),\n ...(cards ?? []).map((card) => ({ id: card.id, card })),\n ]\n const canSwitch = choices.some((c) => c.id !== current)\n const selectable = choices.some((c) => c.id === selected)\n\n const confirm = async () => {\n if (!selectable || (mode === \"change\" && selected === current) || busy)\n return\n setError(null)\n setSubmitting(true)\n try {\n const result = await onConfirm(\n selected === FOLLOW_DEFAULT ? null : selected\n )\n if (result) setError(result)\n } finally {\n setSubmitting(false)\n }\n }\n\n let list: React.ReactNode\n if (cards === null && methods.error) {\n list = <ErrorState error={methods.error} onRetry={methods.refetch} />\n } else if (cards === null) {\n list = <ListSkeleton rows={2} />\n } else if (mode === \"resume\") {\n list = adding ? (\n <ResumeCardEntry\n subscription={subscription}\n appearance={appearance}\n onSaved={(id) => {\n setSelected(id)\n setAdding(false)\n methods.refetch()\n }}\n />\n ) : (\n <label className=\"grid gap-2 text-sm\">\n {t(\"changeCard.title\", { name })}\n <select\n aria-label={t(\"changeCard.title\", { name })}\n disabled={busy}\n value={selectable ? selected : \"\"}\n onChange={(event) => setSelected(event.target.value)}\n className=\"h-10 rounded-md border border-input bg-background px-3\"\n >\n {!selectable ? (\n <option value=\"\" disabled>\n {t(\"resume.chooseCard\")}\n </option>\n ) : null}\n {choices.map(({ id, card }) => (\n <option key={id} value={id}>\n {cardText(card.card, m)}\n </option>\n ))}\n </select>\n </label>\n )\n } else {\n list = (\n <RadioGroup\n value={selected}\n onValueChange={(next) => {\n if (typeof next === \"string\" && next) setSelected(next)\n }}\n disabled={busy}\n aria-label={t(\"changeCard.title\", { name })}\n className=\"grid gap-0\"\n >\n {choices.map(({ id: value, card }) => {\n const id = `${idPrefix}-${value}`\n const label = cardText(card.card, m)\n return (\n <Label\n key={value}\n htmlFor={id}\n data-testid=\"change-card-option\"\n className={cn(\n \"flex cursor-pointer items-center gap-3 py-1.5 select-none\",\n busy && \"cursor-default\"\n )}\n >\n <RadioGroupItem id={id} value={value} />\n <CardBrandPlate\n brand={card.card?.brand ?? undefined}\n fallback={(card.card?.brand ?? \"card\").slice(0, 4)}\n />\n <span className=\"min-w-0 flex-1 truncate text-sm font-medium tabular-nums\">\n {value === FOLLOW_DEFAULT\n ? t(\"changeCard.useDefault\", { card: label })\n : label}\n </span>\n {value === current ? (\n <span className=\"shrink-0 text-xs text-muted-foreground\">\n {t(\"changeCard.current\")}\n </span>\n ) : null}\n </Label>\n )\n })}\n </RadioGroup>\n )\n }\n\n return (\n <div className=\"grid gap-5\">\n <DialogHeader>\n <DialogTitle>\n {t(mode === \"resume\" ? \"resume.title\" : \"changeCard.title\", { name })}\n </DialogTitle>\n <DialogDescription>\n {description ??\n (cards !== null && !canSwitch\n ? t(\"changeCard.none\")\n : t(\"changeCard.description\"))}\n </DialogDescription>\n </DialogHeader>\n {list}\n {cards !== null && methods.error ? (\n <ErrorState error={methods.error} onRetry={methods.refetch} />\n ) : null}\n {mode === \"resume\" &&\n !adding &&\n cards !== null &&\n !selectable &&\n !methods.loading &&\n !methods.error ? (\n <p role=\"status\" className=\"text-sm text-muted-foreground\">\n {t(\"resume.savedCardUnavailable\")}\n </p>\n ) : null}\n {mode === \"resume\" && cards !== null ? (\n <Button\n type=\"button\"\n variant=\"link\"\n disabled={busy || (adding && cards.length === 0)}\n onClick={() => setAdding(!adding)}\n >\n {adding ? t(\"changeCard.title\", { name }) : t(\"paymentMethods.add\")}\n </Button>\n ) : null}\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {m.error(error)}\n </p>\n ) : null}\n <DialogFooter>\n <Button\n type=\"button\"\n variant=\"outline\"\n disabled={busy}\n onClick={onCancel}\n >\n {t(\"common.cancel\")}\n </Button>\n {!adding ? (\n <Button\n type=\"button\"\n onClick={() => void confirm()}\n disabled={\n busy || !selectable || (mode === \"change\" && selected === current)\n }\n >\n {busy ? <Spinner /> : null}\n {t(mode === \"resume\" ? \"resume.confirm\" : \"changeCard.confirm\")}\n </Button>\n ) : null}\n </DialogFooter>\n </div>\n )\n}\n\nfunction ResumeCardEntry({\n subscription,\n appearance,\n onSaved,\n}: {\n subscription: Subscription\n appearance?: BillingAppearance\n onSaved: (id: string) => void\n}) {\n const { t } = useMessages()\n const config = useCustomerConfig()\n const available = routedPsps(config.config?.payment.psps ?? []).filter(\n (psp) =>\n canSavePaymentMethod(psp) &&\n (!subscription.psp_id || psp.psp_id === subscription.psp_id) &&\n (!subscription.rail || psp.rail === subscription.rail)\n )\n const [selected, select] = React.useState<string>()\n const psp = available.find((item) => item.psp_id === selected) ?? available[0]\n if (config.error)\n return <ErrorState error={config.error} onRetry={config.refetch} />\n if (config.loading) return <ListSkeleton rows={2} />\n if (!psp)\n return (\n <p role=\"status\" className=\"text-sm text-muted-foreground\">\n {t(\"paymentMethods.addUnavailable\")}\n </p>\n )\n return (\n <div className=\"grid gap-4\">\n {available.length > 1 ? (\n <label className=\"grid gap-2 text-sm\">\n {t(\"paymentMethods.provider\")}\n <select\n value={psp.psp_id}\n onChange={(event) => select(event.target.value)}\n >\n {available.map((item) => (\n <option key={item.psp_id} value={item.psp_id}>\n {item.display_name}\n </option>\n ))}\n </select>\n </label>\n ) : null}\n <SavePaymentMethod\n key={psp.psp_id}\n psp={psp}\n appearance={appearance}\n onSaved={onSaved}\n />\n </div>\n )\n}\n","import type { BillingClient } from \"./client/client\"\nimport type { SubscriptionChange } from \"./client/types\"\nimport { loadStripeFor } from \"./lib/stripe\"\nimport { canAuthenticatePayment, type PspConfig } from \"./psp\"\n\n/**\n * Completes the issuer's authentication (3-D Secure) a subscription change\n * waits on, then confirms the change and answers it. A change with no\n * `authenticate` next action is answered as it is.\n */\nexport async function authenticateChange(\n client: BillingClient,\n subscriptionId: string,\n change: SubscriptionChange,\n psp: PspConfig\n): Promise<SubscriptionChange> {\n const next = change.next_action\n const secret = next?.payload?.client_secret\n if (\n change.status !== \"requires_action\" ||\n next?.type !== \"authenticate\" ||\n !secret ||\n !canAuthenticatePayment(psp)\n )\n return change\n const stripe = await loadStripeFor(psp.config!.publishable_key!)\n const answered = await stripe.handleNextAction({ clientSecret: secret })\n if (answered.error)\n throw new Error(answered.error.message ?? \"Authentication failed.\")\n return client.confirmSubscriptionChange(subscriptionId)\n}\n","import * as React from \"react\"\nimport { cn } from \"cn\"\n\nimport type { BillingAppearance } from \"#orck/appearance\"\nimport { authenticateChange } from \"#orck/authenticate\"\nimport type { SendSolanaTransaction } from \"#orck/client/client\"\nimport { isBillingError, type BillingError } from \"#orck/client/errors\"\nimport type {\n CurrencyScales,\n Subscription,\n SubscriptionChangeOption,\n} from \"#orck/client/types\"\nimport { Button } from \"#orck/components/ui/button\"\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from \"#orck/components/ui/dialog\"\nimport { Label } from \"#orck/components/ui/label\"\nimport { RadioGroup, RadioGroupItem } from \"#orck/components/ui/radio-group\"\nimport { Spinner } from \"#orck/components/ui/spinner\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport type { Translator } from \"#orck/i18n/messages\"\nimport { useCurrencyScales, useCustomerConfig } from \"#orck/react/config\"\nimport { useBillingContext } from \"#orck/react/context\"\nimport {\n useChangeOptions,\n type ChangeOptionsState,\n type SubscriptionAction,\n type SubscriptionsState,\n} from \"#orck/react/hooks\"\nimport { useScopeProps, useUiSettings } from \"#orck/scope-context\"\nimport { formatDate, formatMoney, intervalLabel, RESET } from \"./format\"\nimport { ErrorState, ListSkeleton } from \"./section\"\n\n// A plan change is a money write: its Idempotency-Key is reused until the\n// change has a definitive answer, so retrying a lost answer replays it.\nconst keys = new Map<string, string>()\nconst slot = (subscriptionId: string, priceId: string) =>\n JSON.stringify([subscriptionId, priceId])\n\nfunction changeKey(subscriptionId: string, priceId: string): string {\n const id = slot(subscriptionId, priceId)\n const key = keys.get(id) ?? crypto.randomUUID()\n keys.set(id, key)\n return key\n}\n\n// The change may have landed: the next attempt must replay the same key.\nconst uncertain = (error: BillingError) =>\n error.code === \"subscription_change_in_flight\" ||\n error.status === 0 ||\n error.status >= 500\n\nexport interface ChangePlanProps {\n subscription: Subscription\n name: string\n pending: SubscriptionAction | undefined\n changeSubscription: SubscriptionsState[\"changeSubscription\"]\n sendSolanaTransaction?: SendSolanaTransaction\n /** Announces the outcome once the dialog closes. */\n onChanged: (text: string) => void\n appearance?: BillingAppearance\n}\n\n/** The row's Change plan button and dialog, when another plan is open to it. */\nexport function ChangePlan({\n subscription,\n name,\n pending,\n changeSubscription,\n sendSolanaTransaction,\n onChanged,\n appearance,\n}: ChangePlanProps) {\n const m = useMessages()\n const { t } = m\n const { locale } = useUiSettings()\n const { client, notify } = useBillingContext()\n const { config: merchant } = useCustomerConfig()\n const options = useChangeOptions(subscription.id)\n const [open, setOpen] = React.useState(false)\n const [working, setWorking] = React.useState(false)\n\n if (!open && !options.options?.length) return null\n\n const confirm = async (\n option: SubscriptionChangeOption\n ): Promise<string | null> => {\n const id = subscription.id\n const priceId = option.price.id\n let result = await changeSubscription(\n id,\n { priceId, idempotencyKey: changeKey(id, priceId) },\n sendSolanaTransaction\n )\n if (isBillingError(result)) {\n if (!uncertain(result)) keys.delete(slot(id, priceId))\n return m.error(result)\n }\n const next = result.next_action\n if (next?.type === \"redirect_to_url\" && next.url) {\n window.location.assign(next.url)\n return null\n }\n if (result.status === \"requires_action\" && next?.type === \"authenticate\") {\n const psp = merchant?.payment.psps.find((p) => p.psp_id === next.psp_id)\n if (!psp) return m.t(\"paymentMethods.unavailable\")\n try {\n result = await authenticateChange(client, id, result, psp)\n } catch (err) {\n if (isBillingError(err)) return m.error(err)\n return (err instanceof Error && err.message) || m.t(\"errors.generic\")\n }\n notify({\n type: \"subscription.changed\",\n subscriptionId: id,\n change: result,\n })\n }\n if (result.status === \"requires_action\")\n return m.t(\"changePlan.actionRequired\")\n if (result.status !== \"processing\") keys.delete(slot(id, priceId))\n if (result.status === \"blocked\")\n return result.message || m.t(\"errors.generic\")\n setOpen(false)\n const product = option.product.display_name || name\n const date = formatDate(\n result.delayed_start ?? result.next_charge_date,\n locale\n )\n onChanged(\n result.status === \"processing\"\n ? t(\"changePlan.processing\")\n : result.effective === \"period_end\" && date\n ? t(\"changePlan.scheduled\", { name: product, date })\n : t(\"changePlan.done\", { name: product })\n )\n return null\n }\n\n return (\n <>\n <Button\n variant=\"ghost\"\n size=\"sm\"\n disabled={!!pending}\n aria-label={t(\"subscriptions.changePlanLabel\", { name })}\n onClick={() => {\n options.refetch()\n setOpen(true)\n }}\n >\n {t(\"subscriptions.changePlan\")}\n </Button>\n <ChangePlanDialog\n open={open}\n onOpenChange={setOpen}\n name={name}\n options={options}\n busy={working || !!pending}\n stage={pending}\n onConfirm={async (option) => {\n setWorking(true)\n try {\n return await confirm(option)\n } finally {\n setWorking(false)\n }\n }}\n appearance={appearance}\n />\n </>\n )\n}\n\nfunction ChangePlanDialog({\n open,\n onOpenChange,\n appearance,\n busy,\n ...form\n}: {\n open: boolean\n onOpenChange: (open: boolean) => void\n appearance?: BillingAppearance\n} & ChangePlanFormProps) {\n const scope = useScopeProps(appearance)\n return (\n <Dialog\n open={open}\n onOpenChange={(next) => {\n if (!next && busy) return\n onOpenChange(next)\n }}\n >\n <DialogContent\n showCloseButton={false}\n className={`${scope.className} ${RESET} bg-popover text-popover-foreground`}\n data-orck-theme={scope[\"data-orck-theme\"]}\n style={scope.style}\n >\n {open ? (\n <ChangePlanForm\n {...form}\n busy={busy}\n onCancel={() => onOpenChange(false)}\n />\n ) : null}\n </DialogContent>\n </Dialog>\n )\n}\n\ninterface ChangePlanFormProps {\n name: string\n options: ChangeOptionsState\n busy: boolean\n stage: SubscriptionAction | undefined\n /** Resolves null on success, else the message to show. */\n onConfirm: (option: SubscriptionChangeOption) => Promise<string | null>\n onCancel?: () => void\n}\n\nfunction ChangePlanForm({\n name,\n options,\n busy,\n stage,\n onConfirm,\n onCancel,\n}: ChangePlanFormProps) {\n const m = useMessages()\n const { t } = m\n const { locale } = useUiSettings()\n const scales = useCurrencyScales()\n const idPrefix = React.useId()\n const [selected, setSelected] = React.useState(\"\")\n const [error, setError] = React.useState<string | null>(null)\n const list = options.options\n const chosen = list?.find((o) => o.price.id === selected)\n\n let body: React.ReactNode\n if (list === null && options.error) {\n body = <ErrorState error={options.error} onRetry={options.refetch} />\n } else if (list === null) {\n body = <ListSkeleton rows={2} />\n } else {\n body = (\n <RadioGroup\n value={selected}\n onValueChange={(next) => {\n if (typeof next === \"string\" && next) setSelected(next)\n }}\n disabled={busy}\n aria-label={t(\"changePlan.title\", { name })}\n className=\"grid gap-0\"\n >\n {list.map((option) => {\n const id = `${idPrefix}-${option.price.id}`\n const price = formatMoney(\n option.price.unit_amount,\n option.price.currency,\n scales,\n locale\n )\n const interval = intervalLabel(option.price, m)\n return (\n <Label\n key={option.price.id}\n htmlFor={id}\n data-testid=\"change-plan-option\"\n className={cn(\n \"flex cursor-pointer items-start gap-3 py-2 select-none\",\n busy && \"cursor-default\"\n )}\n >\n <RadioGroupItem\n id={id}\n value={option.price.id}\n className=\"mt-0.5\"\n />\n <span className=\"grid min-w-0 flex-1 gap-0.5\">\n <span className=\"text-sm font-medium\">\n {option.product.display_name}\n {price ? (\n <span className=\"font-normal text-muted-foreground tabular-nums\">\n {\" · \"}\n {price}\n {interval ? ` ${interval}` : null}\n </span>\n ) : null}\n </span>\n <span className=\"text-xs font-normal text-muted-foreground tabular-nums\">\n {optionTerms(option, m, scales, locale)}\n </span>\n </span>\n </Label>\n )\n })}\n </RadioGroup>\n )\n }\n\n return (\n <form\n className=\"grid gap-5\"\n noValidate\n onSubmit={(event) => {\n event.preventDefault()\n if (!chosen || busy) return\n setError(null)\n void onConfirm(chosen).then(setError)\n }}\n >\n <DialogHeader>\n <DialogTitle>{t(\"changePlan.title\", { name })}</DialogTitle>\n <DialogDescription>\n {list?.length === 0\n ? t(\"changePlan.none\")\n : t(\"changePlan.description\")}\n </DialogDescription>\n </DialogHeader>\n {body}\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n ) : null}\n <DialogFooter>\n <Button\n type=\"button\"\n variant=\"outline\"\n disabled={busy}\n onClick={onCancel}\n >\n {t(\"common.cancel\")}\n </Button>\n <Button type=\"submit\" disabled={busy || !chosen}>\n {busy ? <Spinner /> : null}\n {stage === \"signing\"\n ? t(\"changePlan.signing\")\n : stage === \"confirming\"\n ? t(\"changePlan.confirming\")\n : t(\"changePlan.confirm\")}\n </Button>\n </DialogFooter>\n </form>\n )\n}\n\n/** What the change charges and when, from its preview. */\nfunction optionTerms(\n option: SubscriptionChangeOption,\n m: Translator,\n scales: CurrencyScales,\n locale?: string\n): string {\n const p = option.preview\n const next = formatMoney(p.next_charge_amount, p.currency, scales, locale)\n const date = formatDate(p.next_charge_date, locale)\n if (!next || !date) return p.message ?? \"\"\n if (p.effective !== \"now\")\n return m.t(\"changePlan.atPeriodEnd\", { next, date })\n const amount = formatMoney(p.amount_due_now, p.currency, scales, locale)\n if (!amount) return p.message ?? \"\"\n return m.t(\n p.is_estimate ? \"changePlan.chargeNowEstimate\" : \"changePlan.chargeNow\",\n {\n amount,\n next,\n date,\n }\n )\n}\n","import type { BillingAppearance } from \"#orck/appearance\"\nimport {\n AlertDialog,\n AlertDialogCancel,\n AlertDialogContent,\n AlertDialogDescription,\n AlertDialogFooter,\n AlertDialogHeader,\n AlertDialogTitle,\n} from \"#orck/components/ui/alert-dialog\"\nimport { Button } from \"#orck/components/ui/button\"\nimport { Spinner } from \"#orck/components/ui/spinner\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport { useScopeProps } from \"#orck/scope-context\"\nimport { RESET } from \"./format\"\n\n// Resuming re-arms renewals: the customer confirms they'll be charged again.\nexport function ResumeSubscriptionDialog({\n open,\n onOpenChange,\n name,\n price,\n date,\n busy,\n onConfirm,\n appearance,\n}: {\n open: boolean\n onOpenChange: (open: boolean) => void\n name: string\n /** The renewal amount, formatted. */\n price: string | null\n /** The next renewal date, formatted. */\n date: string | null\n busy: boolean\n onConfirm: () => void\n appearance?: BillingAppearance\n}) {\n const m = useMessages()\n const t = m.t\n const scope = useScopeProps(appearance)\n return (\n <AlertDialog\n open={open}\n onOpenChange={(next) => {\n if (!next && busy) return\n onOpenChange(next)\n }}\n >\n <AlertDialogContent\n className={`${scope.className} ${RESET} bg-popover text-popover-foreground`}\n data-orck-theme={scope[\"data-orck-theme\"]}\n style={scope.style}\n >\n <AlertDialogHeader>\n <AlertDialogTitle>{t(\"resume.title\", { name })}</AlertDialogTitle>\n <AlertDialogDescription>\n {price && date\n ? t(\"resume.description\", { price, date })\n : t(\"resume.descriptionNoDate\")}\n </AlertDialogDescription>\n </AlertDialogHeader>\n <AlertDialogFooter>\n <AlertDialogCancel disabled={busy}>{t(\"resume.keepCanceled\")}</AlertDialogCancel>\n <Button type=\"button\" disabled={busy} onClick={onConfirm}>\n {busy ? <Spinner /> : null}\n {t(\"resume.confirm\")}\n </Button>\n </AlertDialogFooter>\n </AlertDialogContent>\n </AlertDialog>\n )\n}\n","import * as React from \"react\"\nimport { HugeiconsIcon } from \"@hugeicons/react\"\nimport { ArrowUpRight01Icon } from \"@hugeicons/core-free-icons\"\nimport { cn } from \"cn\"\n\nimport type { BillingAppearance } from \"#orck/appearance\"\nimport type { SendSolanaTransaction } from \"#orck/client/client\"\nimport type { Subscription } from \"#orck/client/types\"\nimport { Button, buttonVariants } from \"#orck/components/ui/button\"\nimport { Spinner } from \"#orck/components/ui/spinner\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport { useSubscriptions, type SubscriptionsOptions } from \"#orck/react/hooks\"\nimport { useCurrencyScales } from \"#orck/react/config\"\nimport { useUiSettings } from \"#orck/scope-context\"\nimport { CancelSubscriptionDialog } from \"./cancel-dialog\"\nimport { ChangeCardDialog } from \"./change-card-dialog\"\nimport { ChangePlan } from \"./change-plan\"\nimport { ResumeSubscriptionDialog } from \"./resume-dialog\"\nimport {\n brandName,\n changeable,\n formatDate,\n formatMoney,\n intervalLabel,\n isEnding,\n isLive,\n LIVE_STATUSES,\n subscriptionName,\n} from \"./format\"\nimport { EmptyState, ErrorState, ListSkeleton, Section } from \"./section\"\nimport { useNotice } from \"./notice\"\nimport { BillingStatusBadge } from \"./status-badge\"\n\nexport interface SubscriptionsPanelProps extends SubscriptionsOptions {\n /**\n * Wallet for Solana subscriptions: plan changes and the optional on-chain\n * cancellation.\n */\n sendSolanaTransaction?: SendSolanaTransaction\n /** Empty-state link to the host's plans page (uses `navigate` if set). */\n plansHref?: string\n /** Host content under a row, e.g. a plan-change control. */\n renderSubscriptionFooter?: (subscription: Subscription) => React.ReactNode\n appearance?: BillingAppearance\n className?: string\n}\n\n// Canceled engine subscriptions support choosing a new card before resume.\n// Provider-managed and wallet subscriptions retain their own resume flow.\nconst resumesWithCard = (s: Subscription) =>\n (s.rail === \"nmi\" || s.rail === \"stripe\") && s.collection_policy === \"engine\"\n\nexport function SubscriptionsPanel({\n sendSolanaTransaction,\n plansHref,\n renderSubscriptionFooter,\n appearance,\n className,\n ...options\n}: SubscriptionsPanelProps) {\n const m = useMessages()\n const { t } = m\n const { locale, navigate } = useUiSettings()\n const state = useSubscriptions(options)\n const scales = useCurrencyScales()\n const [cancelling, setCancelling] = React.useState<Subscription | null>(null)\n const [resuming, setResuming] = React.useState<Subscription | null>(null)\n const [changingCard, setChangingCard] = React.useState<Subscription | null>(\n null\n )\n const [rowError, setRowError] = React.useState<{\n id: string\n message: string\n } | null>(null)\n const [notice, announce] = useNotice()\n\n const rows = React.useMemo(() => {\n const list = state.subscriptions ?? []\n return [...list.filter(isLive), ...list.filter((s) => !isLive(s))]\n }, [state.subscriptions])\n\n const resume = async (s: Subscription, paymentMethodId: string | null) => {\n setRowError(null)\n if (resumesWithCard(s) && paymentMethodId !== s.payment_method_id) {\n const error = await state.setPaymentMethod(s.id, paymentMethodId)\n if (error) return error\n }\n const error = await state.resume(s.id)\n if (!error) {\n setResuming(null)\n announce(t(\"subscriptions.resumed\"))\n }\n return error\n }\n\n const onChain = cancelling?.rail === \"solana\"\n\n let body: React.ReactNode\n if (state.subscriptions === null && state.error) {\n body = <ErrorState error={state.error} onRetry={state.refetch} />\n } else if (state.subscriptions === null) {\n body = <ListSkeleton />\n } else if (rows.length === 0) {\n body = (\n <EmptyState\n title={t(\"subscriptions.empty\")}\n description={t(\"subscriptions.emptyDescription\")}\n action={\n plansHref ? (\n <a\n href={plansHref}\n className={buttonVariants({ variant: \"outline\", size: \"sm\" })}\n onClick={(event) => {\n if (!navigate) return\n event.preventDefault()\n navigate(plansHref)\n }}\n >\n {t(\"subscriptions.browsePlans\")}\n </a>\n ) : null\n }\n />\n )\n } else {\n body = (\n <ul className=\"-my-1 divide-y divide-border\">\n {rows.map((s) => {\n const live = isLive(s)\n const pending = state.pending[s.id]\n const name = subscriptionName(s, m)\n const price = s.price\n ? formatMoney(s.price.unit_amount, s.price.currency, scales, locale)\n : null\n const interval = intervalLabel(s.price, m)\n const periodEnd = formatDate(s.current_period_ends_at, locale)\n const accessEnd = formatDate(s.access?.ends_at, locale)\n const endedAt = formatDate(\n s.ended_at ?? s.canceled_at ?? s.current_period_ends_at,\n locale\n )\n const scheduled = isEnding(s)\n const renews = live && !scheduled && !!s.price?.billing_interval_hours\n const when = !live\n ? s.status === \"canceled\"\n ? t(\"subscriptions.noMorePayments\")\n : endedAt && t(\"subscriptions.endedOn\", { date: endedAt })\n : renews && periodEnd\n ? t(\"subscriptions.renews\", { date: periodEnd })\n : accessEnd\n ? t(\"subscriptions.endsOn\", { date: accessEnd })\n : t(\"subscriptions.noMorePayments\")\n const paidWith = !renews\n ? null\n : s.rail === \"solana\"\n ? t(\"subscriptions.wallet\")\n : s.card?.last4\n ? t(\"subscriptions.paidWith\", {\n brand: brandName(\n s.card.brand,\n t(\"paymentMethods.fallbackBrand\")\n ),\n last4: s.card.last4,\n })\n : null\n const portal = live && !scheduled ? s.cancel_portal_url : null\n const canCancel = LIVE_STATUSES.has(s.status) && !scheduled && !portal\n const canChangeCard =\n ((s.resumable && s.collection_policy === \"engine\") ||\n ((s.status === \"active\" ||\n s.status === \"past_due\" ||\n s.status === \"awaiting_method\" ||\n s.status === \"unverified\") &&\n !scheduled)) &&\n !portal &&\n s.rail !== \"solana\" &&\n (s.collection_policy === \"engine\" ||\n s.collection_policy === \"nmi_schedule\")\n const status = s.cancel_scheduled ? \"cancel_scheduled\" : s.status\n const footer = renderSubscriptionFooter?.(s)\n return (\n <li\n key={s.id}\n data-testid=\"subscription-row\"\n data-subscription-id={s.id}\n className=\"grid gap-3 py-4 @md:grid-cols-[1fr_auto] @md:items-center\"\n >\n <div className=\"grid min-w-0 gap-1\">\n <div className=\"flex flex-wrap items-center gap-x-2 gap-y-1\">\n <span\n className={cn(\n \"truncate text-sm font-semibold\",\n !live && \"text-muted-foreground\"\n )}\n >\n {name}\n </span>\n <BillingStatusBadge status={status} />\n </div>\n <p className=\"text-sm text-muted-foreground tabular-nums\">\n {[when, paidWith].filter(Boolean).join(\" · \") ||\n t(\"common.notAvailable\")}\n </p>\n {price ? (\n <p\n className={cn(\n \"text-sm tabular-nums\",\n !live && \"text-muted-foreground\"\n )}\n >\n <span className=\"font-medium\">{price}</span>\n {interval ? (\n <span className=\"text-muted-foreground\"> {interval}</span>\n ) : null}\n </p>\n ) : null}\n {s.status === \"past_due\" || s.status === \"awaiting_method\" ? (\n <p className=\"text-sm text-destructive\">\n {t(\"subscriptions.pastDue\")}\n </p>\n ) : null}\n {rowError?.id === s.id ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {rowError.message}\n </p>\n ) : null}\n </div>\n <div className=\"flex flex-wrap gap-2 @md:justify-end\">\n {s.resumable ? (\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={!!pending}\n onClick={() => {\n setRowError(null)\n setResuming(s)\n }}\n >\n {pending === \"resume\" ? <Spinner /> : null}\n {pending === \"resume\"\n ? t(\"subscriptions.updating\")\n : t(\"subscriptions.resume\")}\n </Button>\n ) : null}\n {portal ? (\n <a\n href={portal}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className={buttonVariants({\n variant: \"outline\",\n size: \"sm\",\n })}\n >\n {t(\"subscriptions.manageAtProvider\")}\n <HugeiconsIcon icon={ArrowUpRight01Icon} aria-hidden />\n </a>\n ) : null}\n {changeable(s) &&\n (s.rail !== \"solana\" || sendSolanaTransaction) ? (\n <ChangePlan\n subscription={s}\n name={name}\n pending={pending}\n changeSubscription={state.changeSubscription}\n sendSolanaTransaction={sendSolanaTransaction}\n onChanged={announce}\n appearance={appearance}\n />\n ) : null}\n {canChangeCard ? (\n <Button\n variant=\"ghost\"\n size=\"sm\"\n disabled={!!pending}\n aria-label={t(\"subscriptions.changeCardLabel\", { name })}\n onClick={() => {\n setRowError(null)\n setChangingCard(s)\n }}\n >\n {pending === \"payment_method\" ? <Spinner /> : null}\n {t(\"subscriptions.changeCard\")}\n </Button>\n ) : null}\n {canCancel ? (\n <Button\n size=\"sm\"\n className=\"bg-red-600 text-white hover:bg-red-700\"\n disabled={!!pending}\n aria-label={t(\"subscriptions.cancelLabel\", { name })}\n onClick={() => {\n setRowError(null)\n setCancelling(s)\n }}\n >\n {pending === \"cancel\" ||\n (cancelling?.id === s.id && !!pending) ? (\n <Spinner />\n ) : null}\n {t(\"subscriptions.cancel\")}\n </Button>\n ) : null}\n </div>\n {footer ? (\n <div\n data-testid=\"subscription-footer\"\n className=\"border-t border-border/60 pt-3 @md:col-span-2\"\n >\n {footer}\n </div>\n ) : null}\n </li>\n )\n })}\n </ul>\n )\n }\n\n return (\n <Section\n title={t(\"subscriptions.title\")}\n description={t(\"subscriptions.description\")}\n appearance={appearance}\n className={className}\n data-testid=\"subscriptions-panel\"\n >\n {body}\n {state.subscriptions !== null && state.error ? (\n <div className=\"pt-3\">\n <ErrorState error={state.error} onRetry={state.refetch} />\n </div>\n ) : null}\n {notice}\n <ChangeCardDialog\n key={`card-${changingCard?.id ?? \"closed\"}`}\n subscription={changingCard}\n name={changingCard ? subscriptionName(changingCard, m) : \"\"}\n onOpenChange={(open) => !open && setChangingCard(null)}\n appearance={appearance}\n pending={\n !!changingCard && state.pending[changingCard.id] === \"payment_method\"\n }\n onConfirm={async (paymentMethodId) => {\n if (!changingCard) return null\n const error = await state.setPaymentMethod(\n changingCard.id,\n paymentMethodId\n )\n if (!error) {\n setChangingCard(null)\n announce(t(\"changeCard.done\"))\n }\n return error\n }}\n />\n <ChangeCardDialog\n key={`resume-${resuming?.id ?? \"closed\"}`}\n subscription={resuming && resumesWithCard(resuming) ? resuming : null}\n mode=\"resume\"\n onOpenChange={(open) => !open && setResuming(null)}\n name={resuming ? subscriptionName(resuming, m) : \"\"}\n description={\n resuming?.price && resuming.current_period_ends_at\n ? t(\"resume.description\", {\n price:\n formatMoney(\n resuming.price.unit_amount,\n resuming.price.currency,\n scales,\n locale\n ) ?? \"\",\n date: formatDate(resuming.current_period_ends_at, locale) ?? \"\",\n })\n : t(\"resume.descriptionNoDate\")\n }\n pending={resuming ? !!state.pending[resuming.id] : false}\n onConfirm={(paymentMethodId) =>\n resuming ? resume(resuming, paymentMethodId) : Promise.resolve(null)\n }\n appearance={appearance}\n />\n <ResumeSubscriptionDialog\n open={!!resuming && !resumesWithCard(resuming)}\n onOpenChange={(open) => !open && setResuming(null)}\n name={resuming ? subscriptionName(resuming, m) : \"\"}\n price={\n resuming?.price\n ? formatMoney(\n resuming.price.unit_amount,\n resuming.price.currency,\n scales,\n locale\n )\n : null\n }\n date={formatDate(resuming?.current_period_ends_at, locale)}\n busy={resuming ? !!state.pending[resuming.id] : false}\n onConfirm={async () => {\n if (!resuming) return\n const error = await resume(resuming, null)\n if (error) {\n setRowError({ id: resuming.id, message: m.error(error) })\n setResuming(null)\n }\n }}\n appearance={appearance}\n />\n <CancelSubscriptionDialog\n key={cancelling?.id ?? \"closed\"}\n open={cancelling !== null}\n onOpenChange={(open) => !open && setCancelling(null)}\n name={cancelling ? subscriptionName(cancelling, m) : \"\"}\n onChain={onChain && !!sendSolanaTransaction}\n appearance={appearance}\n pending={cancelling ? state.pending[cancelling.id] : undefined}\n onConfirm={async (reason, revokeOnChain) => {\n if (!cancelling) return null\n const error = await state.cancel(\n cancelling.id,\n reason,\n sendSolanaTransaction,\n revokeOnChain\n )\n if (!error) announce(t(\"cancel.done\"))\n return error\n }}\n />\n </Section>\n )\n}\n","import { cn } from \"cn\"\n\nimport type { BillingAppearance } from \"#orck/appearance\"\nimport type { SendSolanaTransaction } from \"#orck/client/client\"\nimport { BillingUiRoot } from \"#orck/scope\"\nimport { PaymentHistory } from \"./payment-history\"\nimport { PaymentMethodsPanel } from \"./payment-methods-panel\"\nimport {\n SubscriptionsPanel,\n type SubscriptionsPanelProps,\n} from \"./subscriptions-panel\"\n\nexport interface AccountBillingProps {\n /**\n * Offers to make a card the default for this currency: it pays the\n * currency's usage orders and every subscription in it without its own card.\n */\n defaultCurrency?: string\n /** Billing country to preselect when adding a card. */\n defaultCountry?: string\n sendSolanaTransaction?: SendSolanaTransaction\n plansHref?: string\n renderSubscriptionFooter?: SubscriptionsPanelProps[\"renderSubscriptionFooter\"]\n historyPageSize?: number\n appearance?: BillingAppearance\n className?: string\n}\n\n/** Subscriptions, payment methods and history in one column. */\nexport function AccountBilling({\n defaultCurrency,\n defaultCountry,\n sendSolanaTransaction,\n plansHref,\n renderSubscriptionFooter,\n historyPageSize,\n appearance,\n className,\n}: AccountBillingProps) {\n return (\n <BillingUiRoot\n appearance={appearance}\n className={cn(\"grid gap-6\", className)}\n data-testid=\"account-billing\"\n >\n <SubscriptionsPanel\n sendSolanaTransaction={sendSolanaTransaction}\n plansHref={plansHref}\n renderSubscriptionFooter={renderSubscriptionFooter}\n appearance={appearance}\n />\n <PaymentMethodsPanel\n defaultCurrency={defaultCurrency}\n defaultCountry={defaultCountry}\n appearance={appearance}\n />\n <PaymentHistory pageSize={historyPageSize} appearance={appearance} />\n </BillingUiRoot>\n )\n}\n","import { cn } from \"cn\"\n\nimport type { BillingAppearance } from \"#orck/appearance\"\nimport { buttonVariants } from \"#orck/components/ui/button\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport { useSubscriptions } from \"#orck/react/hooks\"\nimport { useScopeProps, useUiSettings } from \"#orck/scope-context\"\nimport { isLive, RESET } from \"./format\"\n\nexport interface RenewalPromptProps {\n /** The host's plans page (uses `navigate` if set). */\n plansHref: string\n appearance?: BillingAppearance\n className?: string\n}\n\n/**\n * Invites a customer whose subscriptions have all ended back to the plans\n * page; renders nothing otherwise. A host that grants access some other way\n * leaves it out for customers who have that access.\n */\nexport function RenewalPrompt({\n plansHref,\n appearance,\n className,\n}: RenewalPromptProps) {\n const { t } = useMessages()\n const { navigate } = useUiSettings()\n const scope = useScopeProps(appearance)\n const { subscriptions } = useSubscriptions()\n if (!subscriptions?.length || subscriptions.some(isLive)) return null\n return (\n <div\n data-testid=\"renewal-prompt\"\n data-orck-theme={scope[\"data-orck-theme\"]}\n style={scope.style}\n className={cn(\n scope.className,\n RESET,\n \"flex flex-wrap items-center justify-between gap-3 rounded-xl border border-border bg-card p-4 text-card-foreground\",\n className\n )}\n >\n <div className=\"grid min-w-0 gap-1\">\n <p className=\"text-sm font-semibold\">{t(\"renewal.title\")}</p>\n <p className=\"text-sm text-muted-foreground\">\n {t(\"renewal.description\")}\n </p>\n </div>\n <a\n href={plansHref}\n className={buttonVariants({ size: \"sm\" })}\n onClick={(event) => {\n if (!navigate) return\n event.preventDefault()\n navigate(plansHref)\n }}\n >\n {t(\"renewal.action\")}\n </a>\n </div>\n )\n}\n","// Solana Pay transfer request: the official SDK owns QR rendering while the\n// purchase owns lifecycle copy and the same-device wallet link.\nimport * as React from \"react\"\n\nimport { buttonVariants } from \"#orck/components/ui/button\"\nimport { cn } from \"cn\"\n\n// Keep the official renderer's full quiet zone. Cropping it makes the tile\n// denser but materially reduces scan reliability on lower-quality cameras.\nconst QR_SIZE = 208\n\nexport function SolanaBody({\n amountLabel,\n payload,\n statusLine,\n}: {\n amountLabel: string\n payload?: string\n statusLine: string\n}) {\n const qrRef = React.useRef<HTMLDivElement | null>(null)\n const [qrState, setQrState] = React.useState<\"loading\" | \"ready\" | \"failed\">(\n \"loading\"\n )\n\n React.useEffect(() => {\n const container = qrRef.current\n if (!container || !payload) return\n\n let canceled = false\n container.replaceChildren()\n setQrState(\"loading\")\n void import(\"@solana/pay\")\n .then(({ createQR }) => {\n if (canceled) return\n createQR(payload, QR_SIZE, \"#ffffff\", \"#18181b\").append(container)\n setQrState(\"ready\")\n })\n .catch(() => {\n if (!canceled) setQrState(\"failed\")\n })\n return () => {\n canceled = true\n container.replaceChildren()\n }\n }, [payload])\n\n return (\n <div className=\"grid justify-items-center gap-3 py-1\">\n <div className=\"grid place-items-center rounded-xl bg-white p-1 shadow-sm ring-1 ring-black/10\">\n {payload ? (\n <div\n role=\"img\"\n aria-label=\"Solana Pay QR code\"\n className=\"relative overflow-hidden rounded-lg\"\n style={{ width: QR_SIZE, height: QR_SIZE }}\n >\n <div ref={qrRef} className=\"absolute inset-0\" />\n {qrState === \"loading\" ? (\n <div\n aria-hidden\n className=\"absolute inset-0 animate-pulse rounded-lg bg-zinc-100\"\n />\n ) : null}\n {qrState === \"failed\" ? (\n <div className=\"absolute inset-0 grid place-items-center text-center text-xs text-zinc-600\">\n QR code unavailable\n </div>\n ) : null}\n </div>\n ) : (\n <div\n aria-hidden\n className=\"animate-pulse rounded-lg bg-zinc-100\"\n style={{ width: QR_SIZE, height: QR_SIZE }}\n />\n )}\n </div>\n <div className=\"text-[13px] font-medium text-balance\">\n Scan with a Solana wallet\n </div>\n <div\n className=\"text-center text-[12.5px] text-pretty text-muted-foreground tabular-nums\"\n aria-live=\"polite\"\n >\n {amountLabel} · {statusLine}\n </div>\n {payload ? (\n <a\n href={payload}\n className={cn(\n buttonVariants({ variant: \"secondary\" }),\n \"h-9 w-full max-w-56\"\n )}\n >\n Open in wallet\n </a>\n ) : null}\n </div>\n )\n}\n","// Cards the customer already stored with this merchant. Selecting one skips\n// gateway tokenization: the pay request carries the stored method's id. Rows\n// stay surfaceless like the rail list; the brand plate and ink carry selection.\nimport { HugeiconsIcon } from \"@hugeicons/react\"\nimport { Add01Icon } from \"@hugeicons/core-free-icons\"\nimport { CardBrandPlate } from \"#orck/components/card-brands\"\n\nimport { Label } from \"#orck/components/ui/label\"\nimport { RadioGroup, RadioGroupItem } from \"#orck/components/ui/radio-group\"\nimport { cn } from \"cn\"\nimport type { SavedPaymentMethod } from \"#orck/types\"\n\nexport const NEW_CARD_VALUE = \"new\"\n\n// Text plates for brands CardBrandPlate has no mark for.\nconst BRAND_PLATE: Record<string, string> = {\n visa: \"VISA\",\n mastercard: \"MC\",\n amex: \"AMEX\",\n discover: \"DISC\",\n jcb: \"JCB\",\n diners: \"DINERS\",\n}\n\nfunction brandPlate(brand?: string | null): string {\n const key = brand?.trim().toLowerCase() ?? \"\"\n return BRAND_PLATE[key] ?? \"CARD\"\n}\n\n// The plate is decorative; assistive tech gets the spoken brand instead.\nfunction brandName(brand?: string | null): string {\n const value = brand?.trim()\n if (!value) return \"Card\"\n return value[0].toUpperCase() + value.slice(1)\n}\n\nfunction expiryLabel(method: SavedPaymentMethod): string | undefined {\n const card = method.card\n if (!card?.exp_month || !card.exp_year) return undefined\n const month = String(card.exp_month).padStart(2, \"0\")\n return `${month}/${String(card.exp_year).slice(-2)}`\n}\n\nexport function SavedMethods({\n methods,\n value,\n onChange,\n disabled,\n idPrefix,\n}: {\n methods: SavedPaymentMethod[]\n value: string\n onChange: (value: string) => void\n disabled?: boolean\n idPrefix: string\n}) {\n return (\n <RadioGroup\n value={value}\n onValueChange={(next) => {\n if (typeof next === \"string\" && next) onChange(next)\n }}\n disabled={disabled}\n aria-label=\"Saved cards\"\n className=\"grid gap-0\"\n >\n {methods.map((method) => {\n const id = `${idPrefix}-${method.id}`\n const active = value === method.id\n const expires = expiryLabel(method)\n const brand = method.card?.brand\n const last4 = method.card?.last4\n return (\n <Label\n key={method.id}\n htmlFor={id}\n className={cn(\n \"flex cursor-pointer items-center gap-3 py-1.5 select-none\",\n disabled && \"cursor-default\"\n )}\n >\n <RadioGroupItem id={id} value={method.id} />\n <CardBrandPlate\n brand={brand ?? undefined}\n fallback={brandPlate(brand)}\n />\n <span\n className={cn(\n \"min-w-0 flex-1 truncate text-sm font-medium text-muted-foreground tabular-nums transition-colors\",\n active && \"font-semibold text-foreground\"\n )}\n >\n <span className=\"sr-only\">\n {brandName(brand)} card ending {last4}\n {expires ? `, expires ${expires}` : \"\"}\n </span>\n <span aria-hidden>\n {brandName(brand)} •••• {last4 ?? \"····\"}\n {expires ? (\n <span className=\"font-normal text-muted-foreground\">\n {\" \"}\n · {expires}\n </span>\n ) : null}\n </span>\n </span>\n </Label>\n )\n })}\n <Label\n htmlFor={`${idPrefix}-new`}\n className={cn(\n \"flex cursor-pointer items-center gap-3 py-1.5 text-sm font-medium text-muted-foreground select-none\",\n value === NEW_CARD_VALUE && \"font-semibold text-foreground\",\n disabled && \"cursor-default\"\n )}\n >\n <RadioGroupItem id={`${idPrefix}-new`} value={NEW_CARD_VALUE} />\n <span\n aria-hidden\n className={cn(\n \"grid h-7 w-11 shrink-0 place-items-center rounded-md border border-dashed border-border text-muted-foreground transition-colors\",\n value === NEW_CARD_VALUE &&\n \"border-solid border-transparent bg-foreground text-background\"\n )}\n >\n <HugeiconsIcon icon={Add01Icon} className=\"size-3.5\" />\n </span>\n Use a new card\n </Label>\n </RadioGroup>\n )\n}\n","// Terminal and transitional views. Each is quiet: one fact, one instruction,\n// no dead controls.\nimport { Skeleton } from \"#orck/components/ui/skeleton\"\nimport { Eyebrow } from \"#orck/components/eyebrow\"\n\nexport function LoadingSkeleton() {\n return (\n <div className=\"grid gap-4\" aria-hidden>\n <Skeleton className=\"h-3 w-24\" />\n <Skeleton className=\"h-6 w-52\" />\n <Skeleton className=\"mt-1.5 h-11 w-full\" />\n <Skeleton className=\"h-28 w-full\" />\n <Skeleton className=\"h-11 w-full\" />\n <Skeleton className=\"mt-1 h-[42px] w-full\" />\n </div>\n )\n}\n\nexport function SucceededView({\n merchantName,\n embedded,\n}: {\n merchantName: string\n embedded: boolean\n}) {\n return (\n <div className=\"grid gap-4\">\n <Eyebrow>{merchantName}</Eyebrow>\n <div className=\"grid justify-items-center gap-2.5 px-2 py-7 text-center\">\n <div className=\"grid size-11 place-items-center rounded-full bg-[color:var(--orck-success)]/12 text-[color:var(--orck-success)]\">\n <svg\n width=\"20\"\n height=\"20\"\n viewBox=\"0 0 20 20\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2.2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden\n >\n <path d=\"M4 10.5l4 4 8-9\" />\n </svg>\n </div>\n <div className=\"text-[15px] font-semibold\">Payment complete</div>\n <div className=\"text-[13px] text-muted-foreground\">\n {embedded ? \"You're all set.\" : `Returning to ${merchantName}…`}\n </div>\n </div>\n </div>\n )\n}\n\nexport function TerminalView({\n merchantName,\n headline,\n sub,\n}: {\n merchantName: string\n headline: string\n sub?: string\n}) {\n return (\n <div className=\"grid gap-4\">\n <Eyebrow>{merchantName}</Eyebrow>\n <div className=\"grid justify-items-center gap-2 px-2 py-7 text-center\">\n <div className=\"text-[15px] font-semibold\">{headline}</div>\n {sub ? (\n <div className=\"text-[13px] text-muted-foreground\">{sub}</div>\n ) : null}\n </div>\n </div>\n )\n}\n","// Apple Pay and Google Pay through Stripe's Express Checkout Element: the\n// wallet makes a payment method (`pm_`) the order charges as it does a new\n// card's. Stripe shows a wallet only on a registered payment-method domain,\n// in a browser that supports it, with a card in the wallet.\nimport * as React from \"react\"\nimport type {\n StripeExpressCheckoutElementConfirmEvent,\n StripeExpressCheckoutElementReadyEvent,\n} from \"@stripe/stripe-js\"\n\nimport { loadStripeFor } from \"#orck/lib/stripe\"\nimport { stripeAppearance } from \"#orck/lib/stripe-appearance\"\n\nexport interface StripeWalletsProps {\n publishableKey: string\n /** The total in the currency's minor units (Stripe's `amount`). */\n amount: number\n currency: string\n /** Pays with the wallet's payment method; false when the payment failed. */\n onPaymentMethod: (paymentMethod: string) => Promise<boolean>\n /** Whether a wallet button shows. */\n onAvailable?: (available: boolean) => void\n}\n\nexport function StripeWallets({\n publishableKey,\n amount,\n currency,\n onPaymentMethod,\n onAvailable,\n}: StripeWalletsProps) {\n const host = React.useRef<HTMLDivElement>(null)\n const pay = React.useRef(onPaymentMethod)\n const available = React.useRef(onAvailable)\n React.useEffect(() => {\n pay.current = onPaymentMethod\n available.current = onAvailable\n })\n const [shown, setShown] = React.useState(false)\n\n React.useEffect(() => {\n if (!host.current) return\n let canceled = false\n let unmount: (() => void) | undefined\n const show = (value: boolean) => {\n if (canceled) return\n setShown(value)\n available.current?.(value)\n }\n void loadStripeFor(publishableKey).then(\n (stripe) => {\n if (canceled || !host.current) return\n const elements = stripe.elements({\n mode: \"payment\",\n amount,\n currency: currency.toLowerCase(),\n paymentMethodCreation: \"manual\",\n paymentMethodTypes: [\"card\"],\n appearance: stripeAppearance(host.current),\n })\n const element = elements.create(\"expressCheckout\", {\n paymentMethods: {\n applePay: \"auto\",\n googlePay: \"auto\",\n link: \"never\",\n paypal: \"never\",\n amazonPay: \"never\",\n klarna: \"never\",\n },\n })\n element.on(\"ready\", (event: StripeExpressCheckoutElementReadyEvent) => {\n const methods = event.availablePaymentMethods\n show(!!methods && (methods.applePay || methods.googlePay))\n })\n element.on(\n \"confirm\",\n (event: StripeExpressCheckoutElementConfirmEvent) => {\n void (async () => {\n const submitted = await elements.submit()\n const created = submitted.error\n ? undefined\n : await stripe.createPaymentMethod({ elements })\n const method = created?.paymentMethod?.id\n if (!method || !(await pay.current(method)))\n event.paymentFailed({ reason: \"fail\" })\n })()\n }\n )\n element.mount(host.current)\n unmount = () => element.destroy()\n },\n () => show(false)\n )\n return () => {\n canceled = true\n unmount?.()\n }\n }, [publishableKey, amount, currency])\n\n return (\n <div\n ref={host}\n data-testid=\"stripe-wallets\"\n style={{ visibility: shown ? \"visible\" : \"hidden\" }}\n />\n )\n}\n","// A checkout's fallback PSPs: one kept back until the PSPs it stands in for\n// are not offered, or have failed often enough on the order. The checkout\n// decides this, never the merchant's PSP configuration.\nimport { z } from \"zod\"\n\nimport type { Order } from \"./client/types\"\nimport type { PspConfig } from \"./psp\"\n\n/** A PSP kept back for others, named by key. */\nexport interface PaymentFallback {\n /** The PSP keys it stands in for, e.g. `[\"mobius\"]`. */\n for: string[]\n /** Failed attempts through them on the order, combined, that reveal it. */\n afterFailures: number\n}\n\n/** Fallback PSPs by key: `{ ccbill: { for: [\"mobius\"], afterFailures: 2 } }`. */\nexport type PaymentFallbacks = Record<string, PaymentFallback>\n\ntype Option = Order[\"payment_options\"][number]\n\n/**\n * The psp_ids of the options a fallback keeps back: one of its `for` PSPs is\n * offered here and they have failed fewer than `afterFailures` times.\n */\nexport function hiddenFallbacks(\n fallbacks: PaymentFallbacks | undefined,\n options: Option[],\n psps: PspConfig[]\n): Set<string> {\n const hidden = new Set<string>()\n if (!fallbacks) return hidden\n const keyOf = new Map(psps.map((psp) => [psp.psp_id, psp.key.toLowerCase()]))\n const named = new Map(\n Object.entries(fallbacks).map(([key, f]) => [key.toLowerCase(), f])\n )\n for (const option of options) {\n const fallback = named.get(keyOf.get(option.psp_id) ?? \"\")\n if (!fallback) continue\n const primaries = new Set(fallback.for.map((key) => key.toLowerCase()))\n const offered = options.filter((o) =>\n primaries.has(keyOf.get(o.psp_id) ?? \"\")\n )\n const failed = offered.reduce((n, o) => n + o.failed_attempts, 0)\n if (offered.length > 0 && failed < fallback.afterFailures)\n hidden.add(option.psp_id)\n }\n return hidden\n}\n\n// The pay page reads fallbacks from its URL fragment, after the secret:\n// #pus_…&fallbacks=<JSON>. It accepts only small, well-formed values.\nconst FRAGMENT_PARAM = \"fallbacks\"\nconst MAX_FRAGMENT = 4096\nconst MAX_FALLBACKS_JSON = 1024\nconst MAX_ENTRIES = 8\nconst pspKey = z.string().regex(/^[a-z0-9][a-z0-9_-]{0,62}$/)\nconst fallbacksSchema = z\n .record(\n pspKey,\n z.strictObject({\n for: z.array(pspKey).min(1).max(MAX_ENTRIES),\n afterFailures: z.number().int().min(1).max(100),\n })\n )\n .refine((value) => {\n const n = Object.keys(value).length\n return n >= 1 && n <= MAX_ENTRIES\n })\n\n/** The pay URL carrying fallbacks to the pay page in its fragment. */\nexport function withPaymentFallbacks(\n url: string,\n fallbacks?: PaymentFallbacks\n): string {\n if (!fallbacks || Object.keys(fallbacks).length === 0) return url\n const at = url.indexOf(\"#\")\n const base = at < 0 ? url : url.slice(0, at)\n const fragment = at < 0 ? \"\" : url.slice(at + 1)\n const param = `${FRAGMENT_PARAM}=${encodeURIComponent(JSON.stringify(fallbacks))}`\n return `${base}#${fragment ? `${fragment}&` : \"\"}${param}`\n}\n\n/** A pay URL fragment's secret and fallbacks; invalid fallbacks are dropped. */\nexport function readPaymentFragment(hash: string): {\n secret: string | null\n fallbacks?: PaymentFallbacks\n} {\n const [secret = \"\", ...rest] = hash.replace(/^#/, \"\").split(\"&\")\n const out = { secret: secret.startsWith(\"pus_\") ? secret : null }\n if (hash.length > MAX_FRAGMENT) return out\n const raw = new URLSearchParams(rest.join(\"&\")).get(FRAGMENT_PARAM)\n if (!raw || raw.length > MAX_FALLBACKS_JSON) return out\n try {\n const parsed = fallbacksSchema.safeParse(JSON.parse(raw))\n return parsed.success ? { ...out, fallbacks: parsed.data } : out\n } catch {\n return out\n }\n}\n","// Shows an order and pays it, on the host's own page: a saved card, a new card\n// in the PSP's own fields (charged and saved in one call), Apple Pay or Google\n// Pay through a Stripe PSP (when asked), a Solana wallet through a Solana\n// Pay QR, or a PSP's own page. A bank challenge runs in the page, then\n// confirm. A fallback PSP (`fallbacks`) waits until the PSPs it stands in for\n// fail, then is offered as the way out of a failing card.\n// Driven only by the order API (GET, pay, confirm), GET /config and GET\n// /me/config; never cancels.\nimport * as React from \"react\"\n\nimport {\n appearanceStyle,\n appearanceTheme,\n type BillingAppearance,\n} from \"./appearance\"\nimport type { BillingClient, OrderResult } from \"./client/client\"\nimport { isBillingError } from \"./client/errors\"\nimport type { Order, OrderPaymentInput, PaymentMethod } from \"./client/types\"\nimport { PayButton, TrustLine } from \"./components/pay-button\"\nimport { Button } from \"./components/ui/button\"\nimport { SolanaBody } from \"./components/qr\"\nimport { SavedMethods, NEW_CARD_VALUE } from \"./components/saved-methods\"\nimport { LoadingSkeleton } from \"./components/states\"\nimport {\n StripeCardEntry,\n type StripeCardHandle,\n} from \"./components/stripe-card\"\nimport { StripeWallets } from \"./components/stripe-wallets\"\nimport { useMessages } from \"./i18n/context\"\nimport { hiddenFallbacks, type PaymentFallbacks } from \"./fallbacks\"\nimport { billingDetailsOf } from \"./lib/billing\"\nimport { amountToMinorUnits, formatAmount } from \"./lib/money\"\nimport { loadStripeFor } from \"./lib/stripe\"\nimport { cardSetupDriver, type PspConfig } from \"./psp\"\nimport { useConfig, useCurrencyScales, useCustomerConfig } from \"./react/config\"\nimport { useBillingContext } from \"./react/context\"\nimport {\n TokenizedCardForm,\n type TokenizedCardData,\n} from \"./tokenized-card-form\"\nimport { PlatformCardForm } from \"./components/platform-card-form\"\nimport type { SavedPaymentMethod } from \"./types\"\nimport { cn } from \"cn\"\n\nexport interface OrderPaymentProps {\n orderId: string\n /** The client to pay through; default: the provider's. */\n client?: BillingClient\n /** Where a redirect PSP will return to; card PSPs need none. */\n returnUrl?: string\n /** Offer the customer's saved cards (GET /me/payment-methods). Default true. */\n savedPaymentMethods?: boolean\n /**\n * Offer a PSP whose card entry is server. Default true; orders take\n * tokens only, so such a PSP is offered for saved cards alone.\n */\n serverCardEntry?: boolean\n /**\n * Offer Apple Pay and Google Pay through a Stripe PSP's Express Checkout\n * Element. The page's host must be a payment-method domain registered on\n * that Stripe account. Default false.\n */\n wallets?: boolean\n /**\n * PSPs kept back until the PSPs they stand in for are not offered, or have\n * failed `afterFailures` times on the order; then offered under \"Card\n * payment isn't working?\". `{ ccbill: { for: [\"mobius\"], afterFailures: 2 } }`.\n */\n fallbacks?: PaymentFallbacks\n /** Once the order is complete, or processing on an asynchronous rail. */\n onSettled?: (order: Order) => void\n appearance?: BillingAppearance\n className?: string\n}\n\nconst platformCard = (psp: PspConfig) =>\n psp.custodian === \"platform\" && psp.rail === \"nmi\" &&\n psp.flow === \"tokenize\" && !psp.status && !!psp.config?.public_api_key\n\nconst settled = (order: Order) =>\n order.status === \"complete\" || order.status === \"processing\"\n\n// How often a Solana order awaiting its wallet is read again.\nconst SOLANA_POLL_MS = 3000\n\n/** Pays one order. Requires `BillingProvider`. */\nexport function OrderPayment({\n orderId,\n client: given,\n returnUrl,\n savedPaymentMethods = true,\n serverCardEntry = true,\n wallets = false,\n fallbacks,\n onSettled,\n appearance,\n className,\n}: OrderPaymentProps) {\n const m = useMessages()\n const context = useBillingContext()\n const client = given ?? context.client\n const { config } = useConfig()\n const {\n config: merchant,\n error: merchantError,\n refetch: refetchMerchant,\n } = useCustomerConfig()\n const scales = useCurrencyScales()\n const [order, setOrder] = React.useState<Order>()\n const [methods, setMethods] = React.useState<PaymentMethod[]>([])\n const [choice, setChoice] = React.useState<string>(NEW_CARD_VALUE)\n const [pspID, setPspID] = React.useState<string>()\n const [error, setError] = React.useState<string>()\n const [busy, setBusy] = React.useState(false)\n const [pendingSaved, setPendingSaved] = React.useState<string>()\n const [walletShown, setWalletShown] = React.useState(false)\n // One key per pay attempt, minted at render: a retry of the same request\n // answers what the first did. A failed answer mints the next.\n const [key, setKey] = React.useState(() => crypto.randomUUID())\n const stripeCard = React.useRef<StripeCardHandle>(null)\n const settledRef = React.useRef(onSettled)\n React.useEffect(() => {\n settledRef.current = onSettled\n })\n\n React.useEffect(() => {\n const abort = new AbortController()\n client.getOrder(orderId, abort.signal).then(setOrder, (cause: unknown) => {\n if (!abort.signal.aborted) setError(m.error(cause))\n })\n return () => abort.abort()\n }, [client, orderId, m])\n\n React.useEffect(() => {\n if (!savedPaymentMethods || order?.collection_owner !== \"engine\") return\n const abort = new AbortController()\n client.listPaymentMethods({ signal: abort.signal }).then(\n (page) => setMethods(page.data),\n () => undefined\n )\n return () => abort.abort()\n }, [client, savedPaymentMethods, order?.collection_owner])\n\n React.useEffect(() => {\n if (order && settled(order)) settledRef.current?.(order)\n }, [order])\n\n // A Solana order awaits its wallet: confirm asks OpenRails to read the\n // chain, until the transfer lands.\n const awaitingWallet =\n order?.collection_owner === \"engine\" &&\n order?.payment.status === \"requires_action\" &&\n order.payment.next_action?.type === \"solana_pay\"\n React.useEffect(() => {\n if (!awaitingWallet || !order) return\n const timer = window.setInterval(() => {\n client.confirmOrder(order.id).then(\n (result) => setOrder(result.order),\n () => undefined\n )\n }, SOLANA_POLL_MS)\n return () => window.clearInterval(timer)\n }, [awaitingWallet, client, order])\n\n // What the order offers here, less the fallbacks still kept back.\n const offered = React.useMemo(\n () => (order?.collection_owner === \"engine\" ? order.payment_options : []),\n [order]\n )\n const known = React.useMemo(\n () =>\n (merchant?.payment.psps ?? []).filter((psp) =>\n offered.some((option) => option.psp_id === psp.psp_id)\n ),\n [merchant, offered]\n )\n const hidden = hiddenFallbacks(fallbacks, offered, known)\n const options = offered.filter((option) => !hidden.has(option.psp_id))\n const psps = known.filter((psp) => !hidden.has(psp.psp_id))\n // New cards: PSPs whose own fields make a token, where the order takes\n // one (a renewal takes saved cards only).\n const cardPsps = psps.filter((psp) => {\n const driver = cardSetupDriver(psp)\n return (\n (driver === \"collect_js\" || driver === \"stripe_elements\" || platformCard(psp)) &&\n options.some(\n (option) =>\n option.psp_id === psp.psp_id && option.accepts.includes(\"new_card\")\n )\n )\n })\n const usable = psps.filter(\n (psp) => serverCardEntry || cardSetupDriver(psp) !== \"card\"\n )\n const saved: SavedPaymentMethod[] = methods\n .filter(\n (method) =>\n (method.status ?? \"active\") === \"active\" &&\n method.reusable !== false &&\n method.health?.active !== false &&\n usable.some((psp) =>\n psp.psp_id === method.psp_id || options.some((option) =>\n option.psp_id === psp.psp_id &&\n option.saved_payment_method_ids?.includes(method.id)\n )\n )\n )\n .map((method) => ({\n id: method.id,\n psp_id: method.psp_id ?? \"\",\n rail: method.rail ?? \"\",\n card: method.card ?? undefined,\n }))\n const psp: PspConfig | undefined =\n cardPsps.find((item) => item.psp_id === pspID) ?? cardPsps[0]\n const solana = options.find((option) => option.accepts.includes(\"solana_pay\"))\n // A PSP with no fields in this page takes the order on its hosted page.\n const redirects = psps.filter(\n (item) =>\n cardSetupDriver(item) === null &&\n options.some(\n (option) =>\n option.psp_id === item.psp_id && option.accepts.includes(\"redirect\")\n )\n )\n const fallsBack = (item: PspConfig) =>\n !!fallbacks &&\n Object.keys(fallbacks).some(\n (key) => key.toLowerCase() === item.key.toLowerCase()\n )\n const hosted = redirects.filter((item) => !fallsBack(item))\n const revealed = redirects.filter(fallsBack)\n const recurring = order?.lines.some((line) => line.billing_interval_hours !== null) ?? false\n const tokens = solana\n ? (merchant?.payment.solana?.tokens ?? []).filter(\n (token) => !recurring || token.recurring_eligible === true\n )\n : []\n const walletPsp = wallets\n ? cardPsps.find(\n (item) =>\n cardSetupDriver(item) === \"stripe_elements\" &&\n !!item.config?.publishable_key\n )\n : undefined\n\n if (!order)\n return error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n ) : (\n <LoadingSkeleton />\n )\n\n const decimals = scales[order.currency.toUpperCase()] ?? 2\n const money = (amount: string) =>\n formatAmount(amount, order.currency, decimals)\n const currency = config?.currencies?.find(\n (item) => item.code.toUpperCase() === order.currency.toUpperCase()\n )\n // Stripe takes the total in minor units; a total that is not a whole\n // number of them is offered no wallet.\n const walletAmount =\n walletPsp && currency?.minor_decimals != null\n ? amountToMinorUnits(\n order.total,\n currency.decimals,\n currency.minor_decimals\n )\n : null\n\n // answer applies an order request's answer: settle, run the bank's\n // challenge, or show why the payment failed.\n const answer = async (result: OrderResult): Promise<boolean> => {\n setOrder(result.order)\n if (result.error) {\n setError(\n result.order.payment.last_payment_error?.message ?? result.error.message\n )\n setKey(crypto.randomUUID())\n return false\n }\n const next = result.order.payment.next_action\n if (result.order.collection_owner !== \"engine\" || result.order.payment.status !== \"requires_action\" || !next) return true\n if (next.type === \"redirect_to_url\" && next.url) {\n window.location.assign(next.url)\n return true\n }\n const secret = next.payload?.client_secret\n const challenger = merchant?.payment.psps.find(\n (item) => item.psp_id === next.psp_id\n )\n const publishable = challenger?.config?.publishable_key\n if (next.type !== \"authenticate\" || !secret || !publishable) {\n setError(m.t(\"paymentMethods.unavailable\"))\n return false\n }\n if (stripeCard.current && next.psp_id === psp?.psp_id)\n await stripeCard.current.handleNextAction(secret)\n else {\n const stripe = await loadStripeFor(publishable)\n const answered = await stripe.handleNextAction({ clientSecret: secret })\n if (answered.error) throw new Error(answered.error.message)\n }\n return answer(await client.confirmOrder(order.id))\n }\n\n // pay answers whether the payment went through (or awaits its rail).\n const pay = async (\n payment: () => Promise<OrderPaymentInput>,\n preserveUnconfirmed = false,\n reusable?: boolean\n ): Promise<boolean> => {\n if (\n busy ||\n order.collection_owner !== \"engine\" ||\n (pendingSaved && !preserveUnconfirmed)\n )\n return false\n setBusy(true)\n setError(undefined)\n try {\n return await answer(\n await client.payOrder(order.id, {\n payment: await payment(),\n expectedTotal: order.total,\n idempotencyKey: key,\n ...(reusable === undefined ? {} : { reusable }),\n })\n )\n } catch (cause) {\n setError(\n !isBillingError(cause) && cause instanceof Error && cause.message\n ? cause.message\n : m.error(cause)\n )\n // Validation rejected the request before a charge; let the customer\n // correct it. Network, server and in-flight errors keep the same attempt.\n const rejected = isBillingError(cause) && cause.status === 400 &&\n cause.type === \"invalid_request_error\"\n if (preserveUnconfirmed && !rejected) throw cause\n setKey(crypto.randomUUID())\n return false\n } finally {\n setBusy(false)\n }\n }\n\n // A payment the bank asks the customer to authenticate before they came\n // here (a renewal charged while they were away).\n const authenticate = async () => {\n if (busy || order.collection_owner !== \"engine\") return\n setBusy(true)\n setError(undefined)\n try {\n await answer({ order })\n } catch (cause) {\n setError(\n !isBillingError(cause) && cause instanceof Error && cause.message\n ? cause.message\n : m.error(cause)\n )\n } finally {\n setBusy(false)\n }\n }\n const awaitingAuthentication =\n order.collection_owner === \"engine\" &&\n order.status === \"open\" &&\n order.payment.status === \"requires_action\" &&\n order.payment.next_action?.type === \"authenticate\"\n // Back from a PSP's page before it reported the payment.\n const awaitingRedirect =\n order.collection_owner === \"engine\" &&\n order.status === \"open\" &&\n order.payment.status === \"requires_action\" &&\n order.payment.next_action?.type === \"redirect_to_url\" &&\n !!order.payment.next_action.url\n const redirectPsp = merchant?.payment.psps.find(\n (item) => item.psp_id === order.payment.next_action?.psp_id\n )\n\n // A usage order is paid for what it still owes; a written-off one too.\n const payLabel = recurring ? \"Subscribe\" : \"Pay\"\n const profile = merchant?.merchant\n const terms =\n profile?.terms_url || profile?.privacy_url ? (\n <>\n By {recurring ? \"subscribing\" : \"paying\"}, you agree to our{\" \"}\n {profile.terms_url ? (\n <a href={profile.terms_url} target=\"_blank\" rel=\"noreferrer\" className=\"underline\">\n Terms of Service\n </a>\n ) : null}\n {profile.terms_url && profile.privacy_url ? \" and \" : null}\n {profile.privacy_url ? (\n <a href={profile.privacy_url} target=\"_blank\" rel=\"noreferrer\" className=\"underline\">\n Privacy Policy\n </a>\n ) : null}\n .\n </>\n ) : undefined\n const open =\n order.collection_owner === \"engine\" &&\n (order.status === \"open\" ||\n (order.status === \"uncollectible\" && !!order.usage)) &&\n order.payment.status === \"requires_payment_method\"\n\n return (\n <div\n className={cn(\"orck grid gap-5\", className)}\n data-orck-theme={appearanceTheme(appearance)}\n style={appearanceStyle(appearance)}\n >\n <div className=\"grid\">\n {order.lines.map((line) => (\n <div\n key={line.id}\n className=\"flex items-start justify-between gap-4 py-2 text-[13.5px]\"\n >\n <span>\n {line.description}\n {line.quantity && line.quantity > 1 ? ` × ${line.quantity}` : \"\"}\n </span>\n <span className=\"whitespace-nowrap tabular-nums\">\n {money(line.amount)}\n </span>\n </div>\n ))}\n <div className=\"flex items-start justify-between gap-4 border-t border-border pt-3 text-[13.5px] font-semibold\">\n <span>Total</span>\n <span className=\"whitespace-nowrap tabular-nums\">\n {money(order.total)}\n </span>\n </div>\n {order.usage && order.usage.amount_paid !== \"0\" && (\n <div className=\"flex items-start justify-between gap-4 pt-1 text-[13.5px]\">\n <span>Due</span>\n <span className=\"whitespace-nowrap tabular-nums\">\n {money(order.usage.amount_due)}\n </span>\n </div>\n )}\n </div>\n\n {awaitingWallet ? (\n <SolanaBody\n amountLabel={`${order.payment.next_action?.payload?.token_amount ?? \"\"} ${order.payment.next_action?.payload?.token_symbol ?? \"\"}`.trim()}\n payload={order.payment.next_action?.url ?? undefined}\n statusLine=\"Waiting for your wallet's payment\"\n />\n ) : order.status === \"complete\" ? (\n <p role=\"status\" className=\"text-sm font-semibold\">\n Payment complete\n </p>\n ) : order.collection_owner !== \"engine\" ? (\n <p role=\"status\" className=\"text-sm text-muted-foreground\">\n This bill is collected by the payment provider. No payment is needed here.\n </p>\n ) : order.status === \"processing\" ? (\n <p role=\"status\" className=\"text-sm text-muted-foreground\">\n Your payment is processing.\n </p>\n ) : order.status !== \"open\" ? (\n <p role=\"status\" className=\"text-sm text-muted-foreground\">\n This order can no longer be paid.\n </p>\n ) : awaitingRedirect ? (\n <form\n className=\"grid gap-4\"\n onSubmit={(event) => {\n event.preventDefault()\n window.location.assign(order.payment.next_action!.url!)\n }}\n >\n <p className=\"text-sm text-muted-foreground\">\n Your payment is waiting on{\" \"}\n {redirectPsp?.display_name ?? \"the payment page\"}.\n </p>\n <PayButton\n label={`Continue to ${redirectPsp?.display_name ?? \"the payment page\"}`}\n processing={false}\n />\n </form>\n ) : awaitingAuthentication ? (\n <form\n className=\"grid gap-4\"\n onSubmit={(event) => {\n event.preventDefault()\n void authenticate()\n }}\n >\n <p className=\"text-sm text-muted-foreground\">\n Your bank asks you to confirm this payment.\n </p>\n <PayButton label=\"Confirm payment\" processing={busy} />\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n ) : null}\n </form>\n ) : (\n <div className=\"grid gap-4\">\n {!pendingSaved && walletPsp && walletAmount ? (\n <StripeWallets\n publishableKey={walletPsp.config!.publishable_key!}\n amount={walletAmount}\n currency={order.currency}\n onAvailable={setWalletShown}\n onPaymentMethod={(method) =>\n pay(async () => ({ token: method, psp_id: walletPsp.psp_id }))\n }\n />\n ) : null}\n {!pendingSaved && walletShown && walletPsp && walletAmount ? (\n <p className=\"text-center text-[13px] text-muted-foreground\">\n or pay another way\n </p>\n ) : null}\n {saved.length > 0 ? (\n <SavedMethods\n methods={saved}\n value={choice}\n onChange={setChoice}\n disabled={busy || !open || !!pendingSaved}\n idPrefix={`orck-order-${order.id}`}\n />\n ) : null}\n {choice !== NEW_CARD_VALUE ? (\n <form\n className=\"grid gap-4\"\n onSubmit={(event) => {\n event.preventDefault()\n const method = pendingSaved ?? choice\n const platform = options.some((option) =>\n option.saved_payment_method_ids?.includes(method)\n )\n void pay(async () => ({ payment_method_id: method }), platform)\n .then(() => setPendingSaved(undefined))\n .catch(() => setPendingSaved(method))\n }}\n >\n <PayButton\n label={pendingSaved ? \"Retry payment\" : payLabel}\n processing={busy}\n disabled={!open}\n />\n </form>\n ) : psp ? (\n <>\n {cardPsps.length > 1 ? (\n <select\n aria-label=\"Pay with\"\n className=\"h-9 rounded-md border border-border bg-transparent px-2 text-sm\"\n value={psp.psp_id}\n onChange={(event) => setPspID(event.target.value)}\n >\n {cardPsps.map((item) => (\n <option key={item.psp_id} value={item.psp_id}>\n {item.display_name}\n </option>\n ))}\n </select>\n ) : null}\n {platformCard(psp) ? (\n <PlatformCardForm\n key={psp.psp_id}\n publicKey={psp.config!.public_api_key!}\n submitLabel={payLabel}\n disabled={busy || !open}\n onTokenized={(card) => pay(async () => ({\n token: card.payment_token,\n psp_id: psp.psp_id,\n billing_details: billingDetailsOf(card),\n }), true)}\n />\n ) : cardSetupDriver(psp) === \"collect_js\" ? (\n <TokenizedCardForm\n key={psp.psp_id}\n tokenizationKey={psp.config!.tokenization_key!}\n tokenizationURL={psp.config!.tokenization_url!}\n submitLabel={payLabel}\n disabled={busy || !open}\n appearance={appearance}\n defaultCountry={merchant?.client_country || undefined}\n saveOptInMerchant={recurring ? undefined : profile?.display_name}\n terms={terms}\n statementDescriptor={profile?.statement_descriptor ?? undefined}\n // A refused payment leaves the form open for another card.\n onTokenized={(card: TokenizedCardData) =>\n pay(\n async () => ({\n token: card.payment_token,\n psp_id: psp.psp_id,\n billing_details: billingDetailsOf(card),\n }),\n false,\n card.reusable\n )\n }\n />\n ) : (\n <form\n className=\"grid gap-4\"\n onSubmit={(event) => {\n event.preventDefault()\n void pay(async () => ({\n token: await stripeCard.current!.tokenize(),\n psp_id: psp.psp_id,\n }))\n }}\n >\n <StripeCardEntry\n key={psp.psp_id}\n ref={stripeCard}\n psp={psp}\n client={client}\n unavailableMessage={m.t(\"paymentMethods.unavailable\")}\n verificationPendingMessage={m.t(\n \"paymentMethods.verificationPending\"\n )}\n />\n <PayButton\n label={payLabel}\n processing={busy}\n disabled={!open}\n />\n <TrustLine />\n </form>\n )}\n </>\n ) : solana || hosted.length > 0 || revealed.length > 0 ? null : !merchant ? (\n // The merchant's payment setup is still loading, or failed to:\n // never read that as card entry being unavailable.\n merchantError ? (\n <div role=\"alert\" className=\"grid gap-2 text-sm\">\n <p className=\"text-destructive\">{m.error(merchantError)}</p>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" onClick={refetchMerchant}>\n {m.t(\"common.retry\")}\n </Button>\n </div>\n ) : (\n <p className=\"text-sm text-muted-foreground\">{m.t(\"common.loading\")}</p>\n )\n ) : (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {m.t(\"paymentMethods.unavailable\")}\n </p>\n )}\n {hosted.map((item) => (\n <form\n key={item.psp_id}\n onSubmit={(event) => {\n event.preventDefault()\n void pay(async () => ({\n return_url: returnUrl ?? window.location.href,\n psp_id: item.psp_id,\n }))\n }}\n >\n <PayButton\n label={`${payLabel} with ${item.display_name}`}\n processing={busy}\n disabled={!open || !!pendingSaved}\n />\n </form>\n ))}\n {revealed.length > 0 ? (\n <div className=\"grid gap-2 border-t border-border pt-4\">\n <p className=\"text-[13px] text-muted-foreground\">\n Card payment isn't working?\n </p>\n {revealed.map((item) => (\n <button\n key={item.psp_id}\n type=\"button\"\n className=\"h-9 rounded-md border border-border text-sm\"\n disabled={busy || !open || !!pendingSaved}\n onClick={() =>\n void pay(async () => ({\n return_url: returnUrl ?? window.location.href,\n psp_id: item.psp_id,\n }))\n }\n >\n Pay with {item.display_name}\n </button>\n ))}\n </div>\n ) : null}\n {solana && tokens.length > 0 ? (\n <div className=\"grid gap-2 border-t border-border pt-4\">\n {tokens.map((token) => (\n <button\n key={token.symbol}\n type=\"button\"\n className=\"h-9 rounded-md border border-border text-sm\"\n disabled={busy || !open || !!pendingSaved}\n onClick={() =>\n void pay(async () => ({\n token_symbol: token.symbol,\n psp_id: solana.psp_id,\n }))\n }\n >\n Pay with {token.symbol} on Solana\n </button>\n ))}\n </div>\n ) : null}\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n ) : null}\n </div>\n )}\n </div>\n )\n}\n","// An order's pay URL framed on the merchant's own page, as Stripe's\n// embedded Checkout: the order's pay URL (embedded) in an\n// iframe the checkout origin allows only on the merchant's registered origins.\n// The framed page reports its height and the order's completion, and only\n// messages from the pay URL's origin and this iframe are heard. Fulfil\n// on order.completed, never on the completion message. Fallbacks reach the\n// framed page in the URL fragment, never through the server.\nimport * as React from \"react\"\n\nimport { withPaymentFallbacks, type PaymentFallbacks } from \"./fallbacks\"\n\n/** The framed page's message once the order completes. */\nexport const PAYMENT_COMPLETE_MESSAGE = \"openrails.payment.complete\"\n/** The framed page's message when its height changes. */\nexport const PAYMENT_RESIZE_MESSAGE = \"openrails.payment.resize\"\n\nexport interface EmbeddedPaymentCompletion {\n orderId: string\n /**\n * The order's success_url, with the order id filled in; \"\" for a\n * customer's own pay URL, which returns nowhere (the frame says it is paid).\n */\n successUrl: string\n}\n\nexport interface EmbeddedPaymentProps {\n /** The order's pay_url, secret and all. */\n url: string\n /**\n * Called once the order completes. Without it the page goes to the\n * order's success_url, if it has one.\n */\n onComplete?: (completion: EmbeddedPaymentCompletion) => void\n /** As OrderPayment's: the framed page keeps these PSPs back the same way. */\n fallbacks?: PaymentFallbacks\n /** Called once when the pay page never loads (no message from the frame). */\n onLoadFailure?: () => void\n title?: string\n className?: string\n}\n\n// The pay page posts its height on mount; silence this long means it failed.\nconst LOAD_TIMEOUT_MS = 12_000\n\nexport function EmbeddedPayment(props: EmbeddedPaymentProps) {\n return <PaymentFrame key={props.url} {...props} />\n}\n\nfunction PaymentFrame({\n url,\n onComplete,\n fallbacks,\n onLoadFailure,\n title = \"Payment\",\n className,\n}: EmbeddedPaymentProps) {\n const frame = React.useRef<HTMLIFrameElement>(null)\n const [height, setHeight] = React.useState<number>()\n const [attempt, setAttempt] = React.useState(0)\n const [loaded, setLoaded] = React.useState(false)\n const [failed, setFailed] = React.useState(false)\n const reported = React.useRef(false)\n const failure = React.useRef(onLoadFailure)\n React.useEffect(() => {\n failure.current = onLoadFailure\n })\n const completed = React.useRef(onComplete)\n React.useEffect(() => {\n completed.current = onComplete\n })\n const destination = React.useMemo(() => {\n try {\n const parsed = new URL(url)\n const orderId = /^\\/pay\\/([^/]+)$/.exec(parsed.pathname)?.[1]\n return (parsed.protocol === \"https:\" || parsed.protocol === \"http:\") &&\n orderId\n ? { origin: parsed.origin, orderId }\n : null\n } catch {\n return null\n }\n }, [url])\n const origin = destination?.origin\n const orderId = destination?.orderId\n\n React.useEffect(() => {\n if (!origin) return\n let done = false\n const heard = (event: MessageEvent) => {\n if (\n event.origin !== origin ||\n !frame.current ||\n event.source !== frame.current.contentWindow\n )\n return\n const data: unknown = event.data\n if (!data || typeof data !== \"object\") return\n setLoaded(true)\n const message = data as Record<string, unknown>\n if (\n message.type === PAYMENT_RESIZE_MESSAGE &&\n typeof message.height === \"number\" &&\n message.height > 0 &&\n message.height < 20_000\n ) {\n setHeight(Math.ceil(message.height))\n return\n }\n if (\n message.type !== PAYMENT_COMPLETE_MESSAGE ||\n typeof message.order_id !== \"string\" ||\n message.order_id !== orderId ||\n done\n )\n return\n done = true\n const successUrl =\n typeof message.success_url === \"string\" ? message.success_url : \"\"\n if (completed.current)\n completed.current({ orderId: message.order_id, successUrl })\n else if (/^https?:\\/\\//i.test(successUrl))\n window.location.assign(successUrl)\n }\n window.addEventListener(\"message\", heard)\n return () => window.removeEventListener(\"message\", heard)\n }, [origin, orderId])\n\n React.useEffect(() => {\n if (!origin || loaded || failed) return\n const timer = window.setTimeout(() => {\n setFailed(true)\n if (!reported.current) {\n reported.current = true\n failure.current?.()\n }\n }, LOAD_TIMEOUT_MS)\n return () => window.clearTimeout(timer)\n }, [origin, loaded, failed, attempt])\n\n if (!origin) return null\n if (failed)\n return (\n <div role=\"alert\" className=\"grid gap-3 p-6 text-center\">\n <p className=\"text-sm font-medium text-foreground\">\n The secure payment page didn't load.\n </p>\n <p className=\"text-sm text-muted-foreground\">\n Please try again in a moment.\n </p>\n <button\n type=\"button\"\n className=\"mx-auto rounded-md border border-input px-4 py-2 text-sm\"\n onClick={() => {\n setFailed(false)\n setAttempt((n) => n + 1)\n }}\n >\n Try again\n </button>\n </div>\n )\n return (\n <>\n {loaded ? null : (\n <p className=\"p-6 text-center text-sm text-muted-foreground\">\n Loading secure payment page…\n </p>\n )}\n <iframe\n key={attempt}\n ref={frame}\n src={withPaymentFallbacks(url, fallbacks)}\n title={title}\n className={className}\n scrolling=\"no\"\n allow=\"payment *; publickey-credentials-get *; publickey-credentials-create *\"\n style={{\n border: 0,\n width: \"100%\",\n height: loaded ? (height ?? 640) : 0,\n visibility: loaded ? \"visible\" : \"hidden\",\n }}\n />\n </>\n )\n}\n","// Shows the customer's cart, priced live, removes lines and checks it out:\n// one order made from the cart (cart: true, at the total shown), then paid\n// here with OrderPayment unless the host takes the order itself. Hosts add\n// and change lines with client.setCartLine.\nimport * as React from \"react\"\n\nimport {\n appearanceStyle,\n appearanceTheme,\n type BillingAppearance,\n} from \"./appearance\"\nimport type { BillingClient } from \"./client/client\"\nimport type { Cart as CartData, Order } from \"./client/types\"\nimport { PayButton } from \"./components/pay-button\"\nimport type { PaymentFallbacks } from \"./fallbacks\"\nimport { LoadingSkeleton } from \"./components/states\"\nimport { useMessages } from \"./i18n/context\"\nimport { formatAmount } from \"./lib/money\"\nimport { OrderPayment } from \"./order-payment\"\nimport { useCurrencyScales } from \"./react/config\"\nimport { useBillingContext } from \"./react/context\"\nimport { cn } from \"cn\"\n\nexport interface CartProps {\n /** The client to read and buy through; default: the provider's. */\n client?: BillingClient\n /**\n * The order made from the cart. Default: pay it here with OrderPayment.\n */\n onOrder?: (order: Order) => void\n /** Passed to OrderPayment: the order is complete, or processing. */\n onSettled?: (order: Order) => void\n /** Passed to OrderPayment: PSPs kept back until others fail on the order. */\n fallbacks?: PaymentFallbacks\n appearance?: BillingAppearance\n className?: string\n}\n\n/** The customer's cart. Requires `BillingProvider`. */\nexport function Cart({\n client: given,\n onOrder,\n onSettled,\n fallbacks,\n appearance,\n className,\n}: CartProps) {\n const m = useMessages()\n const context = useBillingContext()\n const client = given ?? context.client\n const scales = useCurrencyScales()\n const [cart, setCart] = React.useState<CartData>()\n const [order, setOrder] = React.useState<Order>()\n const [error, setError] = React.useState<string>()\n const [busy, setBusy] = React.useState(false)\n // One key per order attempt: a retry answers the same order.\n const [key, setKey] = React.useState(() => crypto.randomUUID())\n\n React.useEffect(() => {\n const abort = new AbortController()\n client.getCart(abort.signal).then(setCart, (cause: unknown) => {\n if (!abort.signal.aborted) setError(m.error(cause))\n })\n return () => abort.abort()\n }, [client, m])\n\n const act = async (work: () => Promise<void>) => {\n if (busy) return\n setBusy(true)\n setError(undefined)\n try {\n await work()\n } catch (cause) {\n setError(m.error(cause))\n } finally {\n setBusy(false)\n }\n }\n\n if (order && !onOrder)\n return (\n <OrderPayment\n orderId={order.id}\n client={client}\n onSettled={onSettled}\n fallbacks={fallbacks}\n appearance={appearance}\n className={className}\n />\n )\n if (!cart)\n return error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n ) : (\n <LoadingSkeleton />\n )\n\n const decimals = scales[cart.currency.toUpperCase()] ?? 2\n const money = (amount: string) =>\n formatAmount(amount, cart.currency, decimals)\n const buyable =\n cart.lines.length > 0 && cart.lines.every((line) => !line.refusal)\n\n const remove = (priceId: string) =>\n act(async () => {\n setCart(await client.setCartLine(priceId, { quantity: 0 }))\n setKey(crypto.randomUUID())\n })\n\n const purchase = () =>\n act(async () => {\n const result = await client.createOrder({\n cart: true,\n expectedTotal: cart.total,\n idempotencyKey: key,\n })\n if (result.error) throw result.error\n setOrder(result.order)\n onOrder?.(result.order)\n })\n\n return (\n <div\n className={cn(\"orck grid gap-5\", className)}\n data-orck-theme={appearanceTheme(appearance)}\n style={appearanceStyle(appearance)}\n >\n {cart.lines.length === 0 ? (\n <p role=\"status\" className=\"text-sm text-muted-foreground\">\n Your cart is empty.\n </p>\n ) : (\n <div className=\"grid\">\n {cart.lines.map((line) => (\n <div\n key={line.price_id}\n className=\"grid gap-1 border-b border-border py-2 text-[13.5px]\"\n >\n <div className=\"flex items-start justify-between gap-4\">\n <span>{line.description || line.price_id}</span>\n <span className=\"whitespace-nowrap tabular-nums\">\n {money(line.amount)}\n </span>\n </div>\n <div className=\"flex items-center gap-2\">\n {line.quantity != null && line.quantity > 1 ? (\n <span className=\"text-[13px] text-muted-foreground\">\n Quantity {line.quantity}\n </span>\n ) : null}\n <button\n type=\"button\"\n className=\"text-[13px] text-muted-foreground underline\"\n disabled={busy}\n onClick={() => void remove(line.price_id)}\n >\n Remove\n </button>\n </div>\n {line.refusal ? (\n <p className=\"text-[13px] text-destructive\">\n {line.refusal.message}\n </p>\n ) : null}\n </div>\n ))}\n <div className=\"flex items-start justify-between gap-4 pt-3 text-[13.5px] font-semibold\">\n <span>Total</span>\n <span className=\"whitespace-nowrap tabular-nums\">\n {money(cart.total)}\n </span>\n </div>\n </div>\n )}\n {cart.lines.length > 0 ? (\n <form\n className=\"grid gap-2\"\n onSubmit={(event) => {\n event.preventDefault()\n void purchase()\n }}\n >\n <PayButton label=\"Check out\" processing={busy} disabled={!buyable} />\n <button\n type=\"button\"\n className=\"text-[13px] text-muted-foreground underline\"\n disabled={busy}\n onClick={() =>\n void act(async () => {\n await client.clearCart()\n setCart(await client.getCart())\n })\n }\n >\n Empty cart\n </button>\n </form>\n ) : null}\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n ) : null}\n </div>\n )\n}\n","import { formatMoney } from \"../account/format\"\nimport type { CurrencyScales, Price } from \"../client/types\"\nimport type { Translator } from \"../i18n/messages\"\nimport { periodOf } from \"./period\"\n\n/** \"$4.99\", \"Rent for 3 days, $1.99\" or \"$10.00 every 30 days\". */\nexport function priceLabel(\n price: Pick<\n Price,\n | \"unit_amount\"\n | \"currency\"\n | \"billing_interval_hours\"\n | \"access_duration_hours\"\n >,\n scales: CurrencyScales,\n m: Translator,\n locale?: string\n): string {\n const amount =\n formatMoney(price.unit_amount, price.currency, scales, locale) ??\n `${price.unit_amount} ${price.currency}`\n const every = periodOf(price.billing_interval_hours)\n if (every)\n return m.t(\"products.recurring\", {\n amount,\n every: m.plural(`interval.every.${every.unit}`, every.count),\n })\n const access = periodOf(price.access_duration_hours)\n if (access)\n return m.t(\"products.rent\", {\n amount,\n period: m.plural(`interval.duration.${access.unit}`, access.count),\n })\n return m.t(\"products.once\", { amount })\n}\n","// The payment dialogs — hosts, not flows: one Dialog around OrderPayment, or\n// around the order's embedded payment page on the checkout origin. Closing is always\n// possible; an accepted payment settles on the server whether or not the\n// dialog stays open, and the order stays the customer's to pay.\nimport type { ReactNode } from \"react\"\n\nimport {\n appearanceStyle,\n appearanceTheme,\n type BillingAppearance,\n} from \"#orck/appearance\"\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogTitle,\n} from \"#orck/components/ui/dialog\"\nimport {\n EmbeddedPayment,\n type EmbeddedPaymentProps,\n} from \"#orck/embedded-payment\"\nimport { OrderPayment, type OrderPaymentProps } from \"#orck/order-payment\"\n\ninterface DialogProps {\n open: boolean\n onOpenChange: (open: boolean) => void\n}\n\nfunction PayDialog({\n open,\n onOpenChange,\n appearance,\n children,\n}: DialogProps & { appearance?: BillingAppearance; children: ReactNode }) {\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent\n className=\"orck max-h-[calc(100dvh-2rem)] w-[460px] max-w-[calc(100vw-2rem)] gap-0 overflow-hidden bg-background p-6 text-foreground ring-0 [&>[data-slot=dialog-close]]:top-5 [&>[data-slot=dialog-close]]:right-5 [&>[data-slot=dialog-close]]:text-foreground\"\n data-orck-theme={appearanceTheme(appearance)}\n style={appearanceStyle(appearance)}\n showCloseButton\n >\n <DialogTitle className=\"sr-only\">Payment</DialogTitle>\n <DialogDescription className=\"sr-only\">\n Complete your payment\n </DialogDescription>\n <div className=\"max-h-[calc(100dvh-5rem)] min-h-0 touch-pan-y [scrollbar-width:none] overflow-y-auto overscroll-contain pt-7 pr-6 [-webkit-overflow-scrolling:touch] [&::-webkit-scrollbar]:hidden\">\n {children}\n </div>\n </DialogContent>\n </Dialog>\n )\n}\n\nexport interface OrderModalProps extends OrderPaymentProps, DialogProps {}\n\nexport function OrderModal({\n open,\n onOpenChange,\n ...payment\n}: OrderModalProps) {\n return (\n <PayDialog\n open={open}\n onOpenChange={onOpenChange}\n appearance={payment.appearance}\n >\n <OrderPayment {...payment} />\n </PayDialog>\n )\n}\n\nexport interface EmbeddedModalProps extends EmbeddedPaymentProps, DialogProps {\n appearance?: BillingAppearance\n}\n\nexport function EmbeddedModal({\n open,\n onOpenChange,\n appearance,\n ...payment\n}: EmbeddedModalProps) {\n return (\n <PayDialog open={open} onOpenChange={onOpenChange} appearance={appearance}>\n <EmbeddedPayment {...payment} />\n </PayDialog>\n )\n}\n","// BuyButton buys one price the host's page carries: it creates the signed-in\n// customer's order and pays it, in OrderPayment on the page, or, on a site\n// the merchant registered to frame its pay URLs, in the order's embedded\n// pay URL on the checkout origin. The app never handles the order itself.\nimport * as React from \"react\"\nimport { cn } from \"cn\"\n\nimport type { BillingAppearance } from \"#orck/appearance\"\nimport { isBillingError, localError, toBillingError } from \"#orck/client/errors\"\nimport type { Order, Price } from \"#orck/client/types\"\nimport type { PaymentFallbacks } from \"#orck/fallbacks\"\nimport { Button } from \"#orck/components/ui/button\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport { priceLabel } from \"#orck/lib/price-label\"\nimport { EmbeddedModal, OrderModal } from \"#orck/modal\"\nimport { useCurrencyScales } from \"#orck/react/config\"\nimport { useBillingContext } from \"#orck/react/context\"\nimport { useScopeProps, useUiSettings } from \"#orck/scope-context\"\n\nexport interface BuyButtonProps {\n /**\n * The price to buy, from a product the host's server put in its page (the\n * Go Client's ListProducts, its prices as a buyer sees them:\n * `billing.BuyerPrices`). The browser never reads the catalog.\n */\n price: Price\n /** The button's text; by default the price's amount and terms. */\n label?: string\n /**\n * A customer-chosen deposit, in the price currency's native units, for a\n * price with `customer_amount`; the order charges exactly this.\n */\n amount?: string\n /** Where a redirect PSP (Stripe's hosted page) returns the buyer: one of the app's return origins. */\n returnUrl?: string\n /** PSPs kept back until others fail on the order; see OrderPayment. */\n fallbacks?: PaymentFallbacks\n /**\n * The order is paid. A hint: the host's own gate decides access, so send\n * the buyer to the content it guards.\n */\n onPaid: (order: Order) => void\n /**\n * Buying needs a signed-in customer: called instead of paying when\n * `signedIn` is false or OpenRails answers 401.\n */\n onSignInRequired: () => void\n /** false when the host knows the visitor is signed out. */\n signedIn?: boolean\n appearance?: BillingAppearance\n className?: string\n}\n\n// An unpaid order of the customer's that holds what is being bought: the\n// refusal names it, and the customer pays that one instead.\nfunction heldBy(err: unknown): string | undefined {\n if (!isBillingError(err) || err.code !== \"already_owned\") return undefined\n const owner = err.metadata.owned_by\n return typeof owner === \"string\" && owner.startsWith(\"ord_\")\n ? owner\n : undefined\n}\n\n// Where the order is paid: on this page, or framed from the checkout origin.\ntype Paying =\n | { kind: \"inline\"; orderId: string }\n | { kind: \"embedded\"; orderId: string; url: string }\n\n// A page on an origin the merchant registered to frame its pay URLs pays\n// there; any other pays on the page.\nconst framesCheckout = (origins: string[]) =>\n typeof window !== \"undefined\" && origins.includes(window.location.origin)\n\n/** One price's button and its order. Requires `BillingProvider`. */\nexport function BuyButton({\n price,\n label,\n amount,\n returnUrl,\n fallbacks,\n onPaid,\n onSignInRequired,\n signedIn,\n appearance,\n className,\n}: BuyButtonProps) {\n const m = useMessages()\n const { locale } = useUiSettings()\n const scales = useCurrencyScales()\n const scope = useScopeProps(appearance)\n const { client } = useBillingContext()\n const [paying, setPaying] = React.useState<Paying>()\n const [starting, setStarting] = React.useState(false)\n const [failure, setFailure] = React.useState<string>()\n const paid = (order: Order) => {\n if (order.status !== \"complete\") return\n setPaying(undefined)\n onPaid(order)\n }\n\n const buy = async () => {\n if (signedIn === false) return onSignInRequired()\n setFailure(undefined)\n setStarting(true)\n try {\n const { merchant } = await client.getCustomerConfig()\n const embedded = framesCheckout(merchant.embed_origins)\n let order: Order\n try {\n // No key: OpenRails answers the customer's open order of these lines,\n // so a second click, a reopened dialog or a reload pays the same one.\n ;({ order } = await client.createOrder({\n lines: [{ price_id: price.id, ...(amount ? { amount } : {}) }],\n ...(embedded ? { payUrl: { embedded: true } } : {}),\n }))\n } catch (err) {\n const held = heldBy(err)\n // Only an order made with a pay URL answers its URL.\n if (!held || embedded) throw err\n setPaying({ kind: \"inline\", orderId: held })\n return\n }\n if (order.status === \"complete\") return paid(order)\n if (!embedded) {\n setPaying({ kind: \"inline\", orderId: order.id })\n return\n }\n const url = order.pay_url\n if (!url)\n throw localError(\n \"invalid_response\",\n \"the order answered no pay URL\"\n )\n setPaying({ kind: \"embedded\", orderId: order.id, url })\n } catch (err) {\n if (isBillingError(err) && err.status === 401) onSignInRequired()\n else setFailure(m.error(toBillingError(err)))\n } finally {\n setStarting(false)\n }\n }\n\n const close = (open: boolean) => !open && setPaying(undefined)\n return (\n <span\n className={cn(scope.className, \"inline-flex flex-col gap-1\", className)}\n data-orck-theme={scope[\"data-orck-theme\"]}\n // A styling root is a size container; a button sizes to its label.\n style={{ ...scope.style, containerType: \"normal\" }}\n >\n <Button disabled={starting} onClick={() => void buy()}>\n {label ?? priceLabel(price, scales, m, locale)}\n </Button>\n {failure ? (\n <span role=\"alert\" className=\"text-sm text-destructive\">\n {failure}\n </span>\n ) : null}\n {paying?.kind === \"inline\" ? (\n <OrderModal\n open\n onOpenChange={close}\n orderId={paying.orderId}\n returnUrl={returnUrl}\n fallbacks={fallbacks}\n appearance={appearance}\n onSettled={paid}\n />\n ) : null}\n {paying?.kind === \"embedded\" ? (\n <EmbeddedModal\n open\n onOpenChange={close}\n url={paying.url}\n fallbacks={fallbacks}\n appearance={appearance}\n // The frame's word is a hint: the order says whether it is paid.\n onComplete={() =>\n void client.getOrder(paying.orderId).then(paid, () => undefined)\n }\n onLoadFailure={() =>\n void client\n .reportPayURLFailure(paying.orderId)\n .catch(() => undefined)\n }\n />\n ) : null}\n </span>\n )\n}\n","// ProductList sells the products the host's page carries: each one on sale,\n// one buy button per price. The host's server decides what to sell (say from\n// its gate's 402) and puts the products in its page; the browser never reads\n// the catalog. The host decides what happens once it's paid.\nimport * as React from \"react\"\nimport { cn } from \"cn\"\n\nimport { RESET } from \"#orck/account/format\"\nimport { EmptyState } from \"#orck/account/section\"\nimport type { BillingAppearance } from \"#orck/appearance\"\nimport { BuyButton } from \"#orck/buy-button\"\nimport type { Order, Product } from \"#orck/client/types\"\nimport type { PaymentFallbacks } from \"#orck/fallbacks\"\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from \"#orck/components/ui/card\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport { useScopeProps } from \"#orck/scope-context\"\n\nexport interface ProductListProps {\n /**\n * What to sell, from the host's own server: the Go Client's ListProducts\n * (by product key or entitlement), their prices as a buyer sees them\n * (`billing.BuyerPrices`).\n */\n products: Product[]\n /**\n * The order is paid. A hint: the host's own gate decides access, so send\n * the buyer back to the content it guards.\n */\n onPaid: (order: Order) => void\n /**\n * Buying needs a signed-in customer: called instead of the purchase when\n * `signedIn` is false or OpenRails answers 401.\n */\n onSignInRequired: () => void\n /** false when the host knows the visitor is signed out. */\n signedIn?: boolean\n /** Where a redirect PSP (Stripe's hosted page) returns the buyer: one of the app's return origins. */\n returnUrl?: string\n /** PSPs kept back until others fail on the order; see OrderPayment. */\n fallbacks?: PaymentFallbacks\n appearance?: BillingAppearance\n className?: string\n}\n\ntype ListedPrice = ProductListProps[\"products\"][number][\"prices\"][number]\n\nconst sameTerms = (a: ListedPrice, b: ListedPrice) =>\n a.unit_amount === b.unit_amount &&\n a.currency === b.currency &&\n a.billing_interval_hours === b.billing_interval_hours &&\n a.access_duration_hours === (b.provider?.access_duration_default ? b.billing_interval_hours : b.access_duration_hours) &&\n !a.trial_unit_amount && !b.trial_unit_amount &&\n !a.trial_duration_hours && !b.trial_duration_hours &&\n !a.quantity && !b.quantity\n\nexport function ProductList({\n products: given,\n onPaid,\n onSignInRequired,\n signedIn,\n returnUrl,\n fallbacks,\n appearance,\n className,\n}: ProductListProps) {\n const m = useMessages()\n const scope = useScopeProps(appearance)\n\n // A deposit's amount is chosen before purchase; ProductList sells fixed\n // prices. A provider's price on the terms of one of ours is that price's\n // fallback on the order, not a price of its own.\n const products = given\n .filter((product) => !product.archived)\n .map((product) => {\n const live = product.prices.filter(\n (p) => !p.archived && !p.customer_amount && (!p.provider || p.provider.rail === \"ccbill\")\n )\n return {\n product,\n prices: live.filter(\n (p) => !p.provider || !live.some((o) => !o.provider && (!o.sell_via?.length || o.sell_via.includes(\"card\")) && sameTerms(o, p))\n ),\n }\n })\n .filter((entry) => entry.prices.length > 0)\n\n let body: React.ReactNode\n if (products.length === 0) {\n body = <EmptyState title={m.t(\"products.empty\")} />\n } else {\n body = products.map(({ product, prices }) => (\n <Card key={product.id} className=\"gap-4\" data-testid=\"product\">\n <CardHeader>\n <CardTitle role=\"heading\" aria-level={2}>\n {product.display_name}\n </CardTitle>\n {product.description ? (\n <CardDescription>{product.description}</CardDescription>\n ) : null}\n </CardHeader>\n <CardContent className=\"flex flex-wrap gap-2\">\n {prices.map((price) => (\n <BuyButton\n key={price.id}\n price={price}\n onPaid={onPaid}\n onSignInRequired={onSignInRequired}\n signedIn={signedIn}\n returnUrl={returnUrl}\n fallbacks={fallbacks}\n appearance={appearance}\n />\n ))}\n </CardContent>\n </Card>\n ))\n }\n\n return (\n <div\n className={cn(scope.className, RESET, \"grid gap-4\", className)}\n data-orck-theme={scope[\"data-orck-theme\"]}\n style={scope.style}\n >\n {body}\n </div>\n )\n}\n","export interface BillingNotificationItem {\n kind: string\n data?: unknown\n}\nexport type BillingNotificationAction =\n | \"update_payment_method\"\n | \"resubscribe\"\n | \"authenticate_payment\"\n | \"contact_support\"\n | \"manage_billing\"\nexport type BillingNotificationActions = Partial<\n Record<BillingNotificationAction, string>\n>\n\nexport function dataOf(item: BillingNotificationItem): Record<string, unknown> {\n return item.data && typeof item.data === \"object\" && !Array.isArray(item.data)\n ? (item.data as Record<string, unknown>)\n : {}\n}\n\n/** The selected billing lifecycle outcomes, rather than signup/cancel confirmations. */\nexport function isPaymentFailure(kind: string): boolean {\n return [\n \"payment_method_failed\",\n \"payment_method_update_required\",\n \"payment_authentication_required\",\n \"order_collection_stopped\",\n ].includes(kind)\n}\n\nexport function isBillingNotification(item: BillingNotificationItem): boolean {\n return (\n isPaymentFailure(item.kind) ||\n item.kind === \"premium_ended\" ||\n (item.kind === \"premium_renewed\" && dataOf(item).downgrade_applied === true)\n )\n}\n\n/** The immutable event's guidance; it is not a claim that a debt remains open. */\nexport function billingNotificationAction(\n item: BillingNotificationItem\n): BillingNotificationAction {\n const action =\n dataOf(item).recovery_action ??\n (item.kind === \"payment_method_update_required\"\n ? \"update_payment_method\"\n : item.kind === \"payment_authentication_required\"\n ? \"authenticate_payment\"\n : undefined)\n return action === \"update_payment_method\" ||\n action === \"resubscribe\" ||\n action === \"authenticate_payment\" ||\n action === \"contact_support\"\n ? action\n : \"manage_billing\"\n}\n","import { useMessages } from \"../i18n/context\"\nimport {\n createTranslator,\n resolveMessages,\n type Translator,\n type BillingUiMessageBundle,\n} from \"../i18n/messages\"\nimport { BillingUiRoot } from \"../scope\"\nimport type { BillingAppearance } from \"../appearance\"\n\nimport {\n dataOf,\n isPaymentFailure,\n isBillingNotification,\n billingNotificationAction,\n type BillingNotificationItem,\n type BillingNotificationActions,\n} from \"../lib/billing-notification\"\n\n/** Shared billing wording. Hosts supply only their authorized destination URLs. */\nexport function BillingNotification({\n item,\n actions = {},\n language,\n messages,\n appearance,\n}: {\n item: BillingNotificationItem\n actions?: BillingNotificationActions\n language?: string\n messages?: BillingUiMessageBundle\n appearance?: BillingAppearance\n}) {\n const inherited = useMessages()\n const translator =\n language || messages\n ? createTranslator(\n messages ? resolveMessages(messages) : inherited.messages,\n undefined,\n language ?? inherited.locale\n )\n : inherited\n const { t } = translator\n if (!isBillingNotification(item)) return null\n const data = dataOf(item)\n const title =\n item.kind === \"payment_method_update_required\"\n ? t(\"billingNotifications.paymentMethodRequiredTitle\")\n : item.kind === \"payment_authentication_required\"\n ? t(\"billingNotifications.authenticationRequiredTitle\")\n : item.kind === \"order_collection_stopped\"\n ? t(\"billingNotifications.collectionStoppedTitle\")\n : isPaymentFailure(item.kind)\n ? t(\"billingNotifications.paymentFailed\")\n : item.kind === \"premium_ended\"\n ? t(\"billingNotifications.membershipEnded\")\n : t(\"billingNotifications.membershipDowngraded\")\n let detail: string\n if (isPaymentFailure(item.kind)) {\n const attempt = date(data.next_attempt_at, translator)\n detail =\n data.retry_status === \"scheduled\" && attempt\n ? t(\"billingNotifications.retryScheduled\", { date: attempt })\n : data.retry_status === \"payment_method_required\"\n ? t(\"billingNotifications.paymentMethodRequired\")\n : data.retry_status === \"stopped\"\n ? t(\"billingNotifications.retryStopped\")\n : t(\"billingNotifications.retryUnknown\")\n } else if (item.kind === \"premium_ended\") {\n const ended = date(data.ended_at, translator)\n detail = ended\n ? t(\"billingNotifications.endedAt\", { date: ended })\n : t(\"billingNotifications.ended\")\n } else {\n detail =\n typeof data.from_product_name === \"string\" &&\n typeof data.to_product_name === \"string\" &&\n data.from_product_name &&\n data.to_product_name\n ? t(\"billingNotifications.downgradedTo\", {\n from: data.from_product_name,\n to: data.to_product_name,\n })\n : t(\"billingNotifications.downgraded\")\n }\n const action = billingNotificationAction(item)\n const href = actions[action] ?? actions.manage_billing\n const label = actions[action] ? action : \"manage_billing\"\n return (\n <BillingUiRoot\n appearance={appearance}\n className=\"grid gap-2\"\n data-orck=\"billing-notification\"\n >\n <p className=\"font-medium\">{title}</p>\n <p className=\"text-muted-foreground\">{detail}</p>\n {isPaymentFailure(item.kind) && (\n <p className=\"text-muted-foreground\">\n {t(`billingNotifications.instructions.${action}`)}\n </p>\n )}\n {href && (\n <a href={href} className=\"font-medium underline underline-offset-4\">\n {t(`billingNotifications.actions.${label}`)}\n </a>\n )}\n </BillingUiRoot>\n )\n}\n\nfunction date(value: unknown, translator: Translator): string | undefined {\n if (typeof value !== \"string\" || !Number.isFinite(Date.parse(value)))\n return undefined\n return new Intl.DateTimeFormat(translator.locale, {\n dateStyle: \"medium\",\n timeStyle: \"short\",\n }).format(new Date(value))\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAOA,SAAgB,GAAc,EAC5B,eACA,cACA,UACA,GAAG,KAC0D;CAC7D,IAAM,IAAQ,EAAc,CAAU;CACtC,OACE,kBAAC,OAAD;EACE,mBAAiB,EAAM;EACvB,WAAW,EAAG,EAAM,WAAW,CAAS;EACxC,OAAO;GAAE,GAAG,EAAM;GAAO,GAAG;EAAM;EAClC,GAAI;CACL,CAAA;AAEL;;;AClBA,IAAM,KAAiB,GACrB,8lBACA;CACE,UAAU;EACR,SAAS;GACP,SAAS;GACT,SACE;GACF,WACE;GACF,OACE;GACF,aACE;GACF,MAAM;EACR;EACA,MAAM;GACJ,SACE;GACF,IAAI;GACJ,IAAI;GACJ,IAAI;GACJ,MAAM;GACN,WACE;GACF,WACE;GACF,WAAW;EACb;CACF;CACA,iBAAiB;EACf,SAAS;EACT,MAAM;CACR;AACF,CACF;AAEA,SAAS,EAAO,EACd,cACA,aAAU,WACV,UAAO,WACP,GAAG,KAC2D;CAC9D,OACE,kBAAC,GAAD;EACE,aAAU;EACV,WAAW,EAAG,GAAe;GAAE;GAAS;GAAM;EAAU,CAAC,CAAC;EAC1D,GAAI;CACL,CAAA;AAEL;;;AC3CA,SAAgB,GAAS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AAO,IAAI,KAAK,eAAe,EAAW,QAAQ;EAChD,WAAW;EACX,WAAW;CACb,CAAC,CAAC,CAAC,OAAO,IAAI,KAAK,CAAK,CAAC;AAC3B"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/scope.tsx","../src/components/ui/button.tsx","../src/lib/card-brands.ts","../src/lib/period.ts","../src/account/format.ts","../src/components/ui/card.tsx","../src/components/ui/skeleton.tsx","../src/account/section.tsx","../src/components/ui/badge.tsx","../src/account/status-badge.tsx","../src/account/payment-history.tsx","../src/components/card-brands.tsx","../src/components/ui/alert-dialog.tsx","../src/components/ui/dialog.tsx","../src/components/ui/spinner.tsx","../src/components/ui/input.tsx","../src/components/ui/label.tsx","../src/lib/billing.ts","../src/components/billing-fields.tsx","../src/components/card-fields.tsx","../src/components/pay-button.tsx","../src/components/platform-card-form.tsx","../src/lib/stripe.ts","../src/lib/collect.ts","../src/lib/stripe-appearance.ts","../src/components/stripe-card.tsx","../src/lib/card-entry.ts","../src/tokenized-card-form.tsx","../src/save-payment-method.tsx","../src/account/notice.tsx","../src/account/payment-methods-panel.tsx","../src/components/ui/textarea.tsx","../src/account/cancel-dialog.tsx","../src/components/ui/radio-group.tsx","../src/account/change-card-dialog.tsx","../src/authenticate.ts","../src/account/change-plan.tsx","../src/account/resume-dialog.tsx","../src/account/subscriptions-panel.tsx","../src/account/account-billing.tsx","../src/account/renewal-prompt.tsx","../src/components/qr.tsx","../src/components/saved-methods.tsx","../src/components/states.tsx","../src/components/stripe-wallets.tsx","../src/fallbacks.ts","../src/order-payment.tsx","../src/embedded-payment.tsx","../src/cart.tsx","../src/lib/price-label.ts","../src/modal.tsx","../src/buy-button.tsx","../src/product-list.tsx","../src/lib/billing-notification.ts","../src/components/billing-notification.tsx"],"sourcesContent":["import type { ComponentProps } from \"react\"\n\nimport type { BillingAppearance } from \"./appearance\"\nimport { cn } from \"cn\"\nimport { useScopeProps } from \"./scope-context\"\n\n/** Styling root for in-page billing surfaces. */\nexport function BillingUiRoot({\n appearance,\n className,\n style,\n ...props\n}: ComponentProps<\"div\"> & { appearance?: BillingAppearance }) {\n const scope = useScopeProps(appearance)\n return (\n <div\n data-orck-theme={scope[\"data-orck-theme\"]}\n className={cn(scope.className, className)}\n style={{ ...scope.style, ...style }}\n {...props}\n />\n )\n}\n","import { Button as ButtonPrimitive } from \"@base-ui/react/button\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\nimport { cn } from \"cn\"\n\nconst buttonVariants = cva(\n \"group/button inline-flex shrink-0 items-center justify-center rounded-md border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\",\n {\n variants: {\n variant: {\n default: \"bg-primary text-primary-foreground hover:bg-primary/80\",\n outline:\n \"border-border bg-background shadow-xs hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50\",\n secondary:\n \"bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground\",\n ghost:\n \"hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50\",\n destructive:\n \"bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40\",\n link: \"text-primary underline-offset-4 hover:underline\",\n },\n size: {\n default:\n \"h-9 gap-1.5 px-2.5 in-data-[slot=button-group]:rounded-md has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2\",\n xs: \"h-6 gap-1 rounded-[min(var(--radius-md),8px)] px-2 text-xs in-data-[slot=button-group]:rounded-md has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3\",\n sm: \"h-8 gap-1 rounded-[min(var(--radius-md),10px)] px-2.5 in-data-[slot=button-group]:rounded-md has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5\",\n lg: \"h-10 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2\",\n icon: \"size-9\",\n \"icon-xs\":\n \"size-6 rounded-[min(var(--radius-md),8px)] in-data-[slot=button-group]:rounded-md [&_svg:not([class*='size-'])]:size-3\",\n \"icon-sm\":\n \"size-8 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-md\",\n \"icon-lg\": \"size-10\",\n },\n },\n defaultVariants: {\n variant: \"default\",\n size: \"default\",\n },\n }\n)\n\nfunction Button({\n className,\n variant = \"default\",\n size = \"default\",\n ...props\n}: ButtonPrimitive.Props & VariantProps<typeof buttonVariants>) {\n return (\n <ButtonPrimitive\n data-slot=\"button\"\n className={cn(buttonVariants({ variant, size, className }))}\n {...props}\n />\n )\n}\n\nexport { Button, buttonVariants }\n","// Card-network identity: which marks we ship and how a rail's spelling maps\n// onto them.\nexport type CardBrand = \"visa\" | \"mastercard\" | \"amex\"\n\nconst BRAND_ALIASES: Record<string, CardBrand> = {\n visa: \"visa\",\n mastercard: \"mastercard\",\n mc: \"mastercard\",\n master: \"mastercard\",\n amex: \"amex\",\n americanexpress: \"amex\",\n \"american express\": \"amex\",\n}\n\n// How people write each brand; a brand not here is shown capitalized.\nconst BRAND_LABELS: Record<string, string> = {\n visa: \"Visa\",\n mastercard: \"Mastercard\",\n amex: \"Amex\",\n discover: \"Discover\",\n jcb: \"JCB\",\n diners: \"Diners Club\",\n unionpay: \"UnionPay\",\n}\n\n// cardBrandLabel is the rail's spelling of a brand (\"VISA\", \"mc\",\n// \"american_express\") as people read it; undefined when there is none.\nexport function cardBrandLabel(brand?: string | null): string | undefined {\n const value = brand?.trim()\n if (!value) return undefined\n const key = value.toLowerCase().replace(/[^a-z]/g, \"\")\n return (\n BRAND_LABELS[resolveCardBrand(value) ?? key] ??\n value[0].toUpperCase() + value.slice(1).toLowerCase()\n )\n}\n\n// Resolves the rail's spelling of a brand (\"Visa\", \"MASTERCARD\", \"amex\") onto\n// the marks we ship; anything unknown falls back to a text plate.\nexport function resolveCardBrand(brand?: string): CardBrand | undefined {\n const key = brand\n ?.trim()\n .toLowerCase()\n .replace(/[^a-z ]/g, \"\")\n return key ? BRAND_ALIASES[key] : undefined\n}\n","import type { Translator } from \"../i18n/messages\"\n\n// OpenRails durations are exact hours (720h is 30 days, never \"a month\"), so\n// labels name only units that divide the window exactly.\nexport type PeriodUnit = \"hour\" | \"day\" | \"week\"\n\nexport interface Period {\n unit: PeriodUnit\n count: number\n}\n\nexport function periodOf(hours: number | null | undefined): Period | null {\n if (!hours || !Number.isSafeInteger(hours) || hours <= 0) return null\n if (hours % 168 === 0) return { unit: \"week\", count: hours / 168 }\n if (hours % 24 === 0) return { unit: \"day\", count: hours / 24 }\n return { unit: \"hour\", count: hours }\n}\n\n/** \"every 30 days\" */\nexport function everyLabel(hours: number | null | undefined, m: Translator) {\n const p = periodOf(hours)\n return p ? m.plural(`interval.every.${p.unit}`, p.count) : null\n}\n\n/** \"/ 30 days\" */\nexport function perLabel(hours: number | null | undefined, m: Translator) {\n const p = periodOf(hours)\n return p ? m.plural(`interval.per.${p.unit}`, p.count) : null\n}\n\n/** \"30 days of access\", for a window that does not renew. */\nexport function accessLabel(hours: number | null | undefined, m: Translator) {\n const p = periodOf(hours)\n return p ? m.plural(`interval.access.${p.unit}`, p.count) : null\n}\n","import type {\n CardSummary,\n CurrencyScales,\n Order,\n Payment,\n Price,\n Subscription,\n} from \"../client/types\"\nimport type { Translator } from \"../i18n/messages\"\nimport { cardBrandLabel } from \"../lib/card-brands\"\nimport { formatAmount } from \"../lib/money\"\nimport { accessLabel, everyLabel } from \"../lib/period\"\n\nexport function formatDate(\n value: string | null | undefined,\n locale?: string\n): string | null {\n if (!value) return null\n const date = new Date(value)\n if (Number.isNaN(date.getTime())) return null\n try {\n return new Intl.DateTimeFormat(locale, { dateStyle: \"medium\" }).format(date)\n } catch {\n return date.toISOString().slice(0, 10)\n }\n}\n\n/** Exact money, or null while the currency's scale is unknown. */\nexport function formatMoney(\n amount: string | null | undefined,\n currency: string,\n scales: CurrencyScales,\n locale?: string\n): string | null {\n if (!amount) return null\n const decimals = scales[currency.toUpperCase()]\n if (decimals === undefined) return null\n return formatAmount(amount, currency, decimals, locale)\n}\n\n/** \"every 30 days\", \"30 days of access\" or \"one-time\". */\nexport function intervalLabel(\n price:\n | Pick<Price, \"access_duration_hours\" | \"billing_interval_hours\">\n | null\n | undefined,\n m: Translator\n): string | null {\n if (!price) return null\n if (price.billing_interval_hours)\n return everyLabel(price.billing_interval_hours, m)\n return accessLabel(price.access_duration_hours, m) ?? m.t(\"interval.once\")\n}\n\nexport function subscriptionName(s: Subscription, { t }: Translator): string {\n return (\n s.product?.display_name?.trim() ||\n s.price?.key?.trim() ||\n t(\"subscriptions.fallbackName\")\n )\n}\n\n/**\n * What a payment bought, from the frozen lines of the order it settles: their\n * names and, for one recurring line, its cadence. Without its order, the kind.\n */\nexport function paymentItem(\n p: Payment,\n order: Order | undefined,\n m: Translator\n): { name: string; detail: string | null } {\n const names = [\n ...new Set(\n (order?.lines ?? []).map((l) => l.description.trim()).filter(Boolean)\n ),\n ]\n const line = order?.lines.length === 1 ? order.lines[0] : undefined\n return {\n name:\n names.join(\", \") ||\n m.t(p.subscription_id ? \"history.subscription\" : \"history.purchase\"),\n detail: line?.billing_interval_hours\n ? everyLabel(line.billing_interval_hours, m)\n : null,\n }\n}\n\nexport function brandName(brand: string | null | undefined, fallback: string) {\n return cardBrandLabel(brand) ?? fallback\n}\n\n/** \"Visa •••• 4242 · 12/30\"; the brand alone when no digits are known. */\nexport function cardText(\n card: CardSummary | null | undefined,\n m: Translator\n): string {\n const brand = brandName(card?.brand, m.t(\"paymentMethods.fallbackBrand\"))\n if (!card?.last4) return brand\n const label = m.t(\"paymentMethods.cardLabel\", { brand, last4: card.last4 })\n const expires = expiry(card)\n return expires ? `${label} · ${expires}` : label\n}\n\nexport function expiry(card: CardSummary | null | undefined): string | null {\n if (!card?.exp_month || !card.exp_year) return null\n return `${String(card.exp_month).padStart(2, \"0\")}/${String(card.exp_year).slice(-2)}`\n}\n\nexport const LIVE_STATUSES = new Set([\n \"active\",\n \"pending\",\n \"past_due\",\n \"awaiting_method\",\n \"unverified\",\n])\n\nconst future = (at: string | null | undefined) =>\n !!at && new Date(at).getTime() > Date.now()\n\n/** A current subscription, or a canceled subscription retaining paid access. */\nexport const isLive = (s: Subscription) =>\n LIVE_STATUSES.has(s.status) ||\n (s.status === \"canceled\" &&\n !!s.access &&\n (!s.access.ends_at || future(s.access.ends_at)))\n\n/** Future billing has stopped or cancellation is scheduled. */\nexport const isEnding = (s: Subscription) =>\n isLive(s) && (!!s.cancel_scheduled || s.status === \"canceled\")\n\n/** A subscription OpenRails could move to another plan of its tier group. */\nexport const changeable = (s: Subscription) =>\n (s.status === \"active\" || s.status === \"past_due\") &&\n !s.cancel_scheduled &&\n !s.cancel_portal_url &&\n !!s.product?.tier_group\n\nexport type StatusTone = \"success\" | \"warning\" | \"destructive\" | \"neutral\"\n\nconst TONE: Record<string, StatusTone> = {\n active: \"success\",\n succeeded: \"success\",\n paid: \"success\",\n default: \"neutral\",\n pending: \"warning\",\n past_due: \"warning\",\n awaiting_method: \"warning\",\n cancel_scheduled: \"warning\",\n expiring_soon: \"warning\",\n needs_attention: \"warning\",\n partially_refunded: \"neutral\",\n failed: \"destructive\",\n expired: \"destructive\",\n canceled: \"neutral\",\n refunded: \"neutral\",\n}\n\nexport const statusTone = (status: string): StatusTone =>\n TONE[status] ?? \"neutral\"\n\n// The package ships no preflight, so account surfaces zero UA text margins.\nexport const RESET =\n \"[&_h2]:m-0 [&_p]:m-0 [&_ul]:m-0 [&_ul]:list-none [&_ul]:p-0 [&_table]:border-spacing-0\"\n","import * as React from \"react\"\nimport { cn } from \"cn\"\n\nfunction Card({\n className,\n size = \"default\",\n ...props\n}: React.ComponentProps<\"div\"> & { size?: \"default\" | \"sm\" }) {\n return (\n <div\n data-slot=\"card\"\n data-size={size}\n className={cn(\n \"group/card flex flex-col gap-(--card-spacing) overflow-hidden rounded-xl bg-card py-(--card-spacing) text-sm text-card-foreground shadow-xs ring-1 ring-foreground/10 [--card-spacing:--spacing(6)] has-[>img:first-child]:pt-0 data-[size=sm]:[--card-spacing:--spacing(4)] *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardHeader({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-header\"\n className={cn(\n \"group/card-header @container/card-header grid auto-rows-min items-start gap-1 rounded-t-xl px-(--card-spacing) has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] [.border-b]:pb-(--card-spacing)\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardTitle({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-title\"\n className={cn(\n \"text-base leading-normal font-medium group-data-[size=sm]/card:text-sm\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardDescription({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-description\"\n className={cn(\"text-sm text-muted-foreground\", className)}\n {...props}\n />\n )\n}\n\nfunction CardAction({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-action\"\n className={cn(\n \"col-start-2 row-span-2 row-start-1 self-start justify-self-end\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardContent({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-content\"\n className={cn(\"flex flex-col gap-3 px-(--card-spacing)\", className)}\n {...props}\n />\n )\n}\n\nfunction CardFooter({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-footer\"\n className={cn(\n \"flex items-center rounded-b-xl px-(--card-spacing) [.border-t]:pt-(--card-spacing)\",\n className\n )}\n {...props}\n />\n )\n}\n\nexport {\n Card,\n CardHeader,\n CardFooter,\n CardTitle,\n CardAction,\n CardDescription,\n CardContent,\n}\n","import { cn } from \"cn\"\n\nfunction Skeleton({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"skeleton\"\n className={cn(\"animate-pulse rounded-md bg-muted\", className)}\n {...props}\n />\n )\n}\n\nexport { Skeleton }\n","import * as React from \"react\"\nimport { cn } from \"cn\"\n\nimport type { BillingAppearance } from \"#orck/appearance\"\nimport type { BillingError } from \"#orck/client/errors\"\nimport { Button } from \"#orck/components/ui/button\"\nimport {\n Card,\n CardAction,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from \"#orck/components/ui/card\"\nimport { Skeleton } from \"#orck/components/ui/skeleton\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport { useScopeProps } from \"#orck/scope-context\"\nimport { RESET } from \"./format\"\n\nexport interface SectionProps {\n title: string\n description?: string\n action?: React.ReactNode\n appearance?: BillingAppearance\n className?: string\n children?: React.ReactNode\n \"data-testid\"?: string\n}\n\n// Styling root plus card. Each panel is usable alone, so each is a root.\nexport function Section({\n title,\n description,\n action,\n appearance,\n className,\n children,\n ...rest\n}: SectionProps) {\n const scope = useScopeProps(appearance)\n const id = React.useId()\n return (\n <section\n aria-labelledby={id}\n className={cn(scope.className, RESET, \"block\", className)}\n data-orck-theme={scope[\"data-orck-theme\"]}\n style={scope.style}\n data-testid={rest[\"data-testid\"]}\n >\n <Card className=\"gap-4 bg-card text-card-foreground\">\n <CardHeader>\n <CardTitle id={id} role=\"heading\" aria-level={2}>\n {title}\n </CardTitle>\n {description ? (\n <CardDescription>{description}</CardDescription>\n ) : null}\n {action ? <CardAction>{action}</CardAction> : null}\n </CardHeader>\n <CardContent className=\"gap-0\">{children}</CardContent>\n </Card>\n </section>\n )\n}\n\nexport function ListSkeleton({ rows = 2 }: { rows?: number }) {\n return (\n <div className=\"grid gap-4 py-2\" aria-hidden>\n {Array.from({ length: rows }, (_, i) => (\n <div key={i} className=\"flex items-center gap-3\">\n <Skeleton className=\"h-7 w-11 rounded-md\" />\n <div className=\"grid flex-1 gap-2\">\n <Skeleton className=\"h-3.5 w-40\" />\n <Skeleton className=\"h-3 w-28\" />\n </div>\n <Skeleton className=\"h-3.5 w-14\" />\n </div>\n ))}\n </div>\n )\n}\n\nexport function EmptyState({\n title,\n description,\n action,\n}: {\n title: string\n description?: string\n action?: React.ReactNode\n}) {\n return (\n <div className=\"grid justify-items-center gap-1 rounded-lg border border-dashed px-4 py-8 text-center\">\n <p className=\"text-sm font-medium\">{title}</p>\n {description ? (\n <p className=\"text-sm text-muted-foreground\">{description}</p>\n ) : null}\n {action ? <div className=\"mt-3\">{action}</div> : null}\n </div>\n )\n}\n\nexport function ErrorState({\n error,\n message,\n onRetry,\n}: {\n error: BillingError\n /** Replaces the error's own message. */\n message?: string\n onRetry: () => void\n}) {\n const m = useMessages()\n return (\n <div\n role=\"alert\"\n className=\"flex flex-wrap items-center justify-between gap-3 rounded-lg bg-destructive/5 px-4 py-3\"\n >\n <p className=\"text-sm text-destructive\">{message ?? m.error(error)}</p>\n <Button variant=\"outline\" size=\"sm\" onClick={onRetry}>\n {m.t(\"common.retry\")}\n </Button>\n </div>\n )\n}\n","import { mergeProps } from \"@base-ui/react/merge-props\"\nimport { useRender } from \"@base-ui/react/use-render\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\nimport { cn } from \"cn\"\n\nconst badgeVariants = cva(\n \"group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-4xl border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!\",\n {\n variants: {\n variant: {\n default: \"bg-primary text-primary-foreground [a]:hover:bg-primary/80\",\n secondary:\n \"bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80\",\n destructive:\n \"bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20\",\n outline:\n \"border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground\",\n ghost:\n \"hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50\",\n link: \"text-primary underline-offset-4 hover:underline\",\n },\n },\n defaultVariants: {\n variant: \"default\",\n },\n }\n)\n\nfunction Badge({\n className,\n variant = \"default\",\n render,\n ...props\n}: useRender.ComponentProps<\"span\"> & VariantProps<typeof badgeVariants>) {\n return useRender({\n defaultTagName: \"span\",\n props: mergeProps<\"span\">(\n {\n className: cn(badgeVariants({ variant }), className),\n },\n props\n ),\n render,\n state: {\n slot: \"badge\",\n variant,\n },\n })\n}\n\nexport { Badge, badgeVariants }\n","import { cn } from \"cn\"\n\nimport { Badge } from \"#orck/components/ui/badge\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport type { MessageKey } from \"#orck/i18n/messages\"\nimport { statusTone, type StatusTone } from \"./format\"\n\nconst TONE_CLASS: Record<StatusTone, string> = {\n success: \"bg-[color:var(--orck-success)]/12 text-[color:var(--orck-success)]\",\n warning: \"bg-[color:var(--orck-warning)]/14 text-[color:var(--orck-warning)]\",\n destructive: \"bg-destructive/10 text-destructive\",\n neutral: \"bg-muted text-muted-foreground\",\n}\n\nexport interface BillingStatusBadgeProps {\n /** Subscription, payment or card-health status. */\n status: string\n /** Overrides the translated label. */\n label?: string\n className?: string\n}\n\nexport function BillingStatusBadge({\n status,\n label,\n className,\n}: BillingStatusBadgeProps) {\n const { t, messages } = useMessages()\n const key = status\n const text =\n label ??\n (key in messages.status\n ? t(`status.${key}` as MessageKey)\n : status.replace(/_/g, \" \"))\n return (\n <Badge\n data-status={status}\n className={cn(TONE_CLASS[statusTone(status)], \"font-medium\", className)}\n >\n {text}\n </Badge>\n )\n}\n","import * as React from \"react\"\nimport { cn } from \"cn\"\n\nimport type { BillingAppearance } from \"#orck/appearance\"\nimport type { Payment } from \"#orck/client/types\"\nimport { Button } from \"#orck/components/ui/button\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport type { MessageKey, Translator } from \"#orck/i18n/messages\"\nimport { usePayments, type PaymentsOptions } from \"#orck/react/hooks\"\nimport { useCurrencyScales } from \"#orck/react/config\"\nimport { useUiSettings } from \"#orck/scope-context\"\nimport { cardText, formatDate, formatMoney, paymentItem } from \"./format\"\nimport { EmptyState, ErrorState, ListSkeleton, Section } from \"./section\"\nimport { BillingStatusBadge } from \"./status-badge\"\n\nexport interface PaymentHistoryProps extends PaymentsOptions {\n appearance?: BillingAppearance\n className?: string\n}\n\nfunction methodText(p: Payment, m: Translator): string {\n if (p.card?.last4) return cardText(p.card, m)\n const rail = p.rail ?? \"\"\n return rail in m.messages.history.rail\n ? m.t(`history.rail.${rail}` as MessageKey)\n : rail || m.t(\"common.notAvailable\")\n}\n\nexport function PaymentHistory({\n appearance,\n className,\n ...options\n}: PaymentHistoryProps) {\n const m = useMessages()\n const { t } = m\n const { locale } = useUiSettings()\n const state = usePayments(options)\n const scales = useCurrencyScales()\n\n let body: React.ReactNode\n const payments = state.payments\n if (payments === null && state.error) {\n body = <ErrorState error={state.error} onRetry={state.refetch} />\n } else if (payments === null) {\n body = <ListSkeleton rows={3} />\n } else if (payments.length === 0 && state.page === 0) {\n body = (\n <EmptyState\n title={t(\"history.empty\")}\n description={t(\"history.emptyDescription\")}\n />\n )\n } else {\n body = (\n <div className=\"-mx-1 overflow-x-auto px-1\">\n <table\n className={cn(\n \"w-full border-collapse text-sm\",\n state.loading && \"opacity-60 transition-opacity\"\n )}\n aria-busy={state.loading || undefined}\n >\n <thead>\n <tr className=\"border-b text-left text-xs text-muted-foreground\">\n <th\n scope=\"col\"\n className=\"hidden py-2 pr-3 font-medium @md:table-cell\"\n >\n {t(\"history.date\")}\n </th>\n <th scope=\"col\" className=\"py-2 pr-3 font-medium\">\n {t(\"history.item\")}\n </th>\n <th\n scope=\"col\"\n className=\"hidden py-2 pr-3 font-medium @md:table-cell\"\n >\n {t(\"history.method\")}\n </th>\n <th scope=\"col\" className=\"py-2 pr-3 font-medium\">\n {t(\"history.status\")}\n </th>\n <th scope=\"col\" className=\"py-2 text-right font-medium\">\n {t(\"history.amount\")}\n </th>\n </tr>\n </thead>\n <tbody className=\"divide-y divide-border\">\n {payments.map((p) => {\n const refund = p.kind === \"refund\"\n const status = p.status || (refund ? \"refunded\" : \"unknown\")\n const amount = formatMoney(p.amount, p.currency, scales, locale)\n const refunded =\n !refund && p.amount_refunded && p.amount_refunded !== \"0\"\n ? formatMoney(p.amount_refunded, p.currency, scales, locale)\n : null\n const date =\n formatDate(p.created_at, locale) ?? t(\"common.notAvailable\")\n const item = paymentItem(\n p,\n p.order_id ? state.orders[p.order_id] : undefined,\n m\n )\n return (\n <tr key={p.id} data-testid=\"payment-row\" data-payment-id={p.id}>\n <td className=\"hidden py-3 pr-3 align-top whitespace-nowrap tabular-nums @md:table-cell\">\n {date}\n </td>\n <td className=\"py-3 pr-3 align-top\">\n <div data-testid=\"payment-item\" className=\"font-medium\">\n {item.name}\n </div>\n {p.status === \"failed\" && p.failure?.message ? (\n <div\n data-testid=\"payment-failure\"\n className=\"text-xs text-destructive\"\n >\n {p.failure.message}\n </div>\n ) : null}\n {item.detail ? (\n <div\n data-testid=\"payment-period\"\n className=\"text-xs text-muted-foreground\"\n >\n {item.detail}\n </div>\n ) : null}\n <div className=\"text-xs text-muted-foreground tabular-nums @md:hidden\">\n {date} · {methodText(p, m)}\n </div>\n </td>\n <td className=\"hidden py-3 pr-3 align-top text-muted-foreground tabular-nums @md:table-cell\">\n {methodText(p, m)}\n </td>\n <td className=\"py-3 pr-3 align-top\">\n <BillingStatusBadge\n status={status}\n label={refund ? t(\"history.refund\") : undefined}\n />\n </td>\n <td className=\"py-3 text-right align-top font-medium whitespace-nowrap tabular-nums\">\n {amount ?? t(\"common.notAvailable\")}\n {refunded ? (\n <div className=\"text-xs font-normal text-muted-foreground\">\n {t(\"history.refundedAmount\", { amount: refunded })}\n </div>\n ) : null}\n </td>\n </tr>\n )\n })}\n </tbody>\n </table>\n </div>\n )\n }\n\n const paged = state.page > 0 || state.hasMore\n return (\n <Section\n title={t(\"history.title\")}\n description={t(\"history.description\")}\n appearance={appearance}\n className={className}\n data-testid=\"payment-history\"\n >\n {body}\n {payments !== null && state.error ? (\n <div className=\"pt-3\">\n <ErrorState error={state.error} onRetry={state.refetch} />\n </div>\n ) : null}\n {paged ? (\n <nav\n aria-label={t(\"history.title\")}\n className=\"flex items-center justify-between gap-3 pt-4\"\n >\n <span className=\"text-xs text-muted-foreground tabular-nums\">\n {t(\"history.page\", { page: state.page + 1 })}\n </span>\n <div className=\"flex gap-2\">\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={state.page === 0 || state.loading}\n onClick={state.previous}\n >\n {t(\"common.previous\")}\n </Button>\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={!state.hasMore || state.loading}\n onClick={state.next}\n >\n {t(\"common.next\")}\n </Button>\n </div>\n </nav>\n ) : null}\n </Section>\n )\n}\n","// Card network marks, inlined rather than fetched: this package is meant to\n// run inside someone else's app, where an asset URL of ours would 404. Artwork\n// is each network's own published symbol, unmodified in shape and color.\nimport * as React from \"react\"\n\nimport { resolveCardBrand } from \"#orck/lib/card-brands\"\nimport { cn } from \"cn\"\n\nfunction VisaMark() {\n return (\n <svg viewBox=\"0 0 1000 324.68\" className=\"h-2.5 w-auto\" role=\"presentation\">\n <path\n fill=\"#1434cb\"\n d=\"m651.19.5c-70.93,0-134.32,36.77-134.32,104.69,0,77.9,112.42,83.28,112.42,122.42,0,16.48-18.88,31.23-51.14,31.23-45.77,0-79.98-20.61-79.98-20.61l-14.64,68.55s39.41,17.41,91.73,17.41c77.55,0,138.58-38.57,138.58-107.66,0-82.32-112.89-87.54-112.89-123.86,0-12.91,15.5-27.05,47.66-27.05,36.29,0,65.89,14.99,65.89,14.99l14.33-66.2S696.61.5,651.18.5h0ZM2.22,5.5L.5,15.49s29.84,5.46,56.72,16.36c34.61,12.49,37.07,19.77,42.9,42.35l63.51,244.83h85.14L379.93,5.5h-84.94l-84.28,213.17-34.39-180.7c-3.15-20.68-19.13-32.48-38.68-32.48,0,0-135.41,0-135.41,0Zm411.87,0l-66.63,313.53h81L494.85,5.5h-80.76Zm451.76,0c-19.53,0-29.88,10.46-37.47,28.73l-118.67,284.8h84.94l16.43-47.47h103.48l9.99,47.47h74.95L934.12,5.5h-68.27Zm11.05,84.71l25.18,117.65h-67.45l42.28-117.65h0Z\"\n />\n </svg>\n )\n}\n\nfunction MastercardMark() {\n return (\n <svg viewBox=\"0 0 152.4 108\" className=\"h-4 w-auto\" role=\"presentation\">\n <g>\n <rect y=\"0\" fill=\"none\" width=\"152.4\" height=\"108\" />\n <g>\n <rect x=\"60.4\" y=\"25.7\" fill=\"#FF5F00\" width=\"31.5\" height=\"56.6\" />\n <path\n fill=\"#EB001B\"\n d=\"M62.4,54c0-11,5.1-21.5,13.7-28.3c-15.6-12.3-38.3-9.6-50.6,6.1C13.3,47.4,16,70,31.7,82.3\n\t\t\tc13.1,10.3,31.4,10.3,44.5,0C67.5,75.5,62.4,65,62.4,54z\"\n />\n <path\n fill=\"#F79E1B\"\n d=\"M134.4,54c0,19.9-16.1,36-36,36c-8.1,0-15.9-2.7-22.2-7.7c15.6-12.3,18.3-34.9,6-50.6c-1.8-2.2-3.8-4.3-6-6\n\t\t\tc15.6-12.3,38.3-9.6,50.5,6.1C131.7,38.1,134.4,45.9,134.4,54z\"\n />\n </g>\n </g>\n </svg>\n )\n}\n\nfunction AmexMark() {\n const gradientId = `orck-amex-${React.useId().replace(/[^a-zA-Z0-9-]/g, \"\")}`\n return (\n <svg viewBox=\"0 0 300 300\" className=\"h-full w-auto\" role=\"presentation\">\n <radialGradient\n id={gradientId}\n cx=\"57.3882\"\n cy=\"57.021\"\n r=\"264.5797\"\n gradientUnits=\"userSpaceOnUse\"\n >\n <stop offset=\"0\" stopColor=\"#9DD5F6\" />\n <stop offset=\"0.0711\" stopColor=\"#98D3F5\" />\n <stop offset=\"0.1575\" stopColor=\"#89CEF3\" />\n <stop offset=\"0.2516\" stopColor=\"#70C6EF\" />\n <stop offset=\"0.3514\" stopColor=\"#4EBBEA\" />\n <stop offset=\"0.4546\" stopColor=\"#23ADE3\" />\n <stop offset=\"0.5\" stopColor=\"#0DA6E0\" />\n <stop offset=\"1\" stopColor=\"#2E77BC\" />\n </radialGradient>\n <path\n fill={`url(#${gradientId})`}\n d=\"M289.584,7.598H7.639v282.966h281.945v-93.386c1.12-1.619,1.673-3.69,1.673-6.222\n\tc0-2.898-0.553-4.693-1.673-6.205\"\n />\n <g></g>\n <path\n fill=\"#FFFFFF\"\n d=\"M33.053,130.042l-5.424-13.217l-5.393,13.217 M152.543,124.779c-1.089,0.661-2.377,0.683-3.92,0.683h-9.627\n\tv-7.364h9.758c1.381,0,2.822,0.062,3.758,0.598c1.028,0.483,1.664,1.511,1.664,2.931\n\tC154.176,123.076,153.571,124.242,152.543,124.779z M221.221,130.042l-5.484-13.217l-5.454,13.217H221.221z M93.201,144.348h-8.124\n\tl-0.03-25.966l-11.491,25.966h-6.958l-11.521-25.989v25.989H38.959l-3.045-7.395h-16.5l-3.076,7.395H7.731l14.191-33.154h11.774\n\tl13.478,31.39v-31.39h12.934l10.371,22.491l9.527-22.491h13.194V144.348z M125.58,144.348H99.107v-33.154h26.473v6.904h-18.548\n\tv5.976h18.103v6.796h-18.103v6.621h18.548V144.348z M162.906,120.123c0,5.286-3.528,8.017-5.584,8.837\n\tc1.734,0.66,3.215,1.826,3.92,2.792c1.119,1.649,1.312,3.122,1.312,6.083v6.513h-7.993l-0.03-4.181c0-1.995,0.191-4.864-1.251-6.459\n\tc-1.158-1.166-2.923-1.419-5.776-1.419h-8.507v12.059h-7.924v-33.154h18.227c4.05,0,7.034,0.107,9.596,1.588\n\tC161.403,114.263,162.906,116.425,162.906,120.123z M175.588,144.348h-8.086v-33.154h8.086V144.348z M269.396,144.348h-11.23\n\tl-15.021-24.884v24.884h-16.139l-3.084-7.395H207.46l-2.992,7.395h-9.273c-3.852,0-8.729-0.852-11.491-3.667\n\tc-2.785-2.815-4.234-6.628-4.234-12.657c0-4.917,0.866-9.412,4.272-12.964c2.562-2.646,6.574-3.866,12.035-3.866h7.672v7.104h-7.511\n\tc-2.892,0-4.525,0.43-6.098,1.964c-1.351,1.396-2.278,4.035-2.278,7.51c0,3.552,0.706,6.113,2.179,7.786\n\tc1.22,1.312,3.437,1.71,5.523,1.71h3.559l11.169-26.073h11.874l13.417,31.359v-31.359h12.066l13.93,23.09v-23.09h8.117V144.348z\n\t M7.639,150.86h13.54l3.053-7.364h6.835l3.045,7.364h26.641v-5.63l2.378,5.654h13.83l2.378-5.738v5.714h66.208l-0.031-12.088h1.281\n\tc0.897,0.031,1.159,0.114,1.159,1.595v10.493h34.243v-2.814c2.762,1.48,7.058,2.814,12.711,2.814h14.406l3.083-7.364h6.835\n\tl3.015,7.364h27.761v-6.995l4.204,6.995h22.246v-46.24h-22.016v5.461l-3.083-5.461H228.77v5.461l-2.831-5.461h-30.515\n\tc-5.108,0-9.598,0.713-13.225,2.7v-2.7h-21.058v2.7c-2.308-2.048-5.453-2.7-8.95-2.7H75.258l-5.162,11.943l-5.301-11.943H40.563\n\tv5.461l-2.662-5.461H17.235l-9.597,21.985V150.86z\"\n />\n <path\n fill=\"#FFFFFF\"\n d=\"M289.584,175.315h-14.443c-1.442,0-2.4,0.054-3.207,0.599c-0.836,0.537-1.158,1.334-1.158,2.386\n\tc0,1.251,0.706,2.102,1.733,2.47c0.836,0.291,1.734,0.376,3.054,0.376l4.295,0.115c4.334,0.107,7.227,0.852,8.991,2.669\n\tc0.321,0.253,0.514,0.537,0.735,0.821 M289.584,197.178c-1.925,2.815-5.676,4.242-10.754,4.242h-15.304v-7.111h15.242\n\tc1.512,0,2.57-0.199,3.207-0.821c0.552-0.513,0.937-1.258,0.937-2.163c0-0.966-0.385-1.733-0.968-2.193\n\tc-0.575-0.506-1.412-0.736-2.792-0.736c-7.441-0.253-16.724,0.23-16.724-10.264c0-4.81,3.054-9.873,11.37-9.873h15.785v-6.598\n\th-14.666c-4.426,0-7.641,1.06-9.918,2.708v-2.708h-21.693c-3.469,0-7.541,0.86-9.467,2.708v-2.708h-38.738v2.708\n\tc-3.083-2.224-8.285-2.708-10.686-2.708h-25.552v2.708c-2.439-2.362-7.863-2.708-11.169-2.708h-28.597l-6.544,7.082l-6.129-7.082\n\tH63.706v46.272h41.914l6.743-7.194l6.352,7.194l25.836,0.023v-10.885h2.54c3.428,0.053,7.471-0.085,11.038-1.627v12.488h21.31\n\tv-12.06h1.028c1.312,0,1.441,0.054,1.441,1.365v10.694h64.736c4.11,0,8.406-1.052,10.785-2.961v2.961h20.534\n\tc4.273,0,8.446-0.599,11.621-2.133V197.178z M257.973,183.93c1.543,1.597,2.37,3.613,2.37,7.026c0,7.134-4.457,10.464-12.449,10.464\n\th-15.435v-7.111h15.373c1.503,0,2.569-0.199,3.237-0.821c0.545-0.513,0.936-1.258,0.936-2.163c0-0.966-0.423-1.733-0.967-2.193\n\tc-0.606-0.506-1.442-0.736-2.822-0.736c-7.411-0.253-16.692,0.23-16.692-10.264c0-4.81,3.022-9.873,11.33-9.873h15.887v7.058\n\th-14.537c-1.441,0-2.378,0.054-3.175,0.599c-0.868,0.537-1.19,1.334-1.19,2.386c0,1.251,0.737,2.102,1.734,2.47\n\tc0.836,0.291,1.734,0.376,3.084,0.376l4.266,0.115C253.225,181.368,256.178,182.112,257.973,183.93z M186.465,181.882\n\tc-1.06,0.629-2.371,0.683-3.913,0.683h-9.627v-7.448h9.758c1.411,0,2.823,0.03,3.782,0.599c1.027,0.537,1.641,1.564,1.641,2.983\n\tS187.492,181.261,186.465,181.882z M191.251,186.009c1.764,0.651,3.206,1.818,3.882,2.784c1.119,1.619,1.281,3.13,1.313,6.053v6.574\n\th-7.956v-4.149c0-1.995,0.192-4.949-1.281-6.491c-1.158-1.188-2.923-1.472-5.814-1.472h-8.469v12.112h-7.963v-33.162h18.296\n\tc4.012,0,6.934,0.177,9.535,1.565c2.501,1.511,4.074,3.581,4.074,7.364C196.867,182.48,193.337,185.181,191.251,186.009z\n\t M201.262,168.258h26.449v6.858h-18.557v6.029h18.104v6.766h-18.104v6.598l18.557,0.03v6.881h-26.449V168.258z M147.795,183.562\n\th-10.241v-8.445h10.333c2.861,0,4.847,1.166,4.847,4.066C152.734,182.051,150.84,183.562,147.795,183.562z M129.661,198.404\n\tl-12.167-13.508l12.167-13.079V198.404z M98.24,194.509H78.756v-6.598h17.398v-6.766H78.756v-6.029h19.868l8.668,9.664\n\tL98.24,194.509z M161.242,179.183c0,9.212-6.873,11.114-13.8,11.114h-9.888v11.123h-15.403l-9.758-10.978l-10.141,10.978h-31.39\n\tv-33.162h31.873l9.75,10.87l10.08-10.87h25.322C154.176,168.258,161.242,169.999,161.242,179.183z\"\n />\n </svg>\n )\n}\n\n// A fixed plate keeps every row's leading edge aligned whatever the mark's\n// aspect ratio.\nexport function CardBrandPlate({\n brand,\n fallback,\n className,\n}: {\n brand?: string\n fallback: string\n className?: string\n}) {\n const resolved = resolveCardBrand(brand)\n return (\n <span\n aria-hidden\n className={cn(\n \"grid h-7 w-11 shrink-0 place-items-center overflow-hidden rounded-md\",\n // White ground only because the marks are drawn for light surfaces —\n // on a light page it simply disappears and the mark stands alone.\n resolved\n ? \"bg-white\"\n : \"bg-muted text-[10px] font-semibold tracking-wide text-muted-foreground uppercase\",\n className\n )}\n >\n {resolved === \"visa\" ? (\n <VisaMark />\n ) : resolved === \"mastercard\" ? (\n <MastercardMark />\n ) : resolved === \"amex\" ? (\n <AmexMark />\n ) : (\n fallback\n )}\n </span>\n )\n}\n\nconst SUPPORTED_BRANDS = [\n { brand: \"visa\", Mark: VisaMark },\n { brand: \"mastercard\", Mark: MastercardMark },\n { brand: \"amex\", Mark: AmexMark },\n] as const\n\n// The accepted networks; once a number's brand is known, the others dim.\nexport function SupportedCardBrands({ active }: { active?: string }) {\n const resolved = resolveCardBrand(active)\n return (\n <span aria-hidden className=\"flex items-center gap-1\">\n {SUPPORTED_BRANDS.map(({ brand, Mark }) => (\n <span\n key={brand}\n className={cn(\n \"grid h-5 w-8 place-items-center rounded-[4px] bg-white ring-1 ring-[color:var(--border)] transition-opacity\",\n resolved && resolved !== brand && \"opacity-30\"\n )}\n >\n <Mark />\n </span>\n ))}\n </span>\n )\n}\n","\"use client\"\n\nimport * as React from \"react\"\nimport { AlertDialog as AlertDialogPrimitive } from \"@base-ui/react/alert-dialog\"\nimport { cn } from \"cn\"\n\nimport { Button } from \"#orck/components/ui/button\"\n\nfunction AlertDialog({ ...props }: AlertDialogPrimitive.Root.Props) {\n return <AlertDialogPrimitive.Root data-slot=\"alert-dialog\" {...props} />\n}\n\nfunction AlertDialogTrigger({ ...props }: AlertDialogPrimitive.Trigger.Props) {\n return (\n <AlertDialogPrimitive.Trigger data-slot=\"alert-dialog-trigger\" {...props} />\n )\n}\n\nfunction AlertDialogPortal({ ...props }: AlertDialogPrimitive.Portal.Props) {\n return (\n <AlertDialogPrimitive.Portal data-slot=\"alert-dialog-portal\" {...props} />\n )\n}\n\nfunction AlertDialogOverlay({\n className,\n ...props\n}: AlertDialogPrimitive.Backdrop.Props) {\n return (\n <AlertDialogPrimitive.Backdrop\n data-slot=\"alert-dialog-overlay\"\n className={cn(\n \"fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction AlertDialogContent({\n className,\n size = \"default\",\n ...props\n}: AlertDialogPrimitive.Popup.Props & {\n size?: \"default\" | \"sm\"\n}) {\n return (\n <AlertDialogPortal>\n <AlertDialogOverlay />\n <AlertDialogPrimitive.Popup\n data-slot=\"alert-dialog-content\"\n data-size={size}\n className={cn(\n \"group/alert-dialog-content fixed top-1/2 left-1/2 z-50 grid w-full -translate-x-1/2 -translate-y-1/2 gap-6 rounded-xl bg-popover p-6 text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none data-[size=default]:max-w-xs data-[size=sm]:max-w-xs data-[size=default]:sm:max-w-lg data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95\",\n className\n )}\n {...props}\n />\n </AlertDialogPortal>\n )\n}\n\nfunction AlertDialogHeader({\n className,\n ...props\n}: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"alert-dialog-header\"\n className={cn(\n \"grid grid-rows-[auto_1fr] place-items-center gap-1.5 text-center has-data-[slot=alert-dialog-media]:grid-rows-[auto_auto_1fr] has-data-[slot=alert-dialog-media]:gap-x-6 sm:group-data-[size=default]/alert-dialog-content:place-items-start sm:group-data-[size=default]/alert-dialog-content:text-left sm:group-data-[size=default]/alert-dialog-content:has-data-[slot=alert-dialog-media]:grid-rows-[auto_1fr]\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction AlertDialogFooter({\n className,\n ...props\n}: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"alert-dialog-footer\"\n className={cn(\n \"flex flex-col-reverse gap-2 group-data-[size=sm]/alert-dialog-content:grid group-data-[size=sm]/alert-dialog-content:grid-cols-2 sm:flex-row sm:justify-end\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction AlertDialogMedia({\n className,\n ...props\n}: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"alert-dialog-media\"\n className={cn(\n \"mb-2 inline-flex size-16 items-center justify-center rounded-md bg-muted sm:group-data-[size=default]/alert-dialog-content:row-span-2 *:[svg:not([class*='size-'])]:size-8\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction AlertDialogTitle({\n className,\n ...props\n}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {\n return (\n <AlertDialogPrimitive.Title\n data-slot=\"alert-dialog-title\"\n className={cn(\n \"text-lg font-medium sm:group-data-[size=default]/alert-dialog-content:group-has-data-[slot=alert-dialog-media]/alert-dialog-content:col-start-2\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction AlertDialogDescription({\n className,\n ...props\n}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {\n return (\n <AlertDialogPrimitive.Description\n data-slot=\"alert-dialog-description\"\n className={cn(\n \"text-sm text-balance text-muted-foreground md:text-pretty *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction AlertDialogAction({\n className,\n ...props\n}: React.ComponentProps<typeof Button>) {\n return (\n <Button\n data-slot=\"alert-dialog-action\"\n className={cn(className)}\n {...props}\n />\n )\n}\n\nfunction AlertDialogCancel({\n className,\n variant = \"outline\",\n size = \"default\",\n ...props\n}: AlertDialogPrimitive.Close.Props &\n Pick<React.ComponentProps<typeof Button>, \"variant\" | \"size\">) {\n return (\n <AlertDialogPrimitive.Close\n data-slot=\"alert-dialog-cancel\"\n className={cn(className)}\n render={<Button variant={variant} size={size} />}\n {...props}\n />\n )\n}\n\nexport {\n AlertDialog,\n AlertDialogAction,\n AlertDialogCancel,\n AlertDialogContent,\n AlertDialogDescription,\n AlertDialogFooter,\n AlertDialogHeader,\n AlertDialogMedia,\n AlertDialogOverlay,\n AlertDialogPortal,\n AlertDialogTitle,\n AlertDialogTrigger,\n}\n","import * as React from \"react\"\nimport { Dialog as DialogPrimitive } from \"@base-ui/react/dialog\"\nimport { cn } from \"cn\"\n\nimport { Button } from \"#orck/components/ui/button\"\nimport { HugeiconsIcon } from \"@hugeicons/react\"\nimport { Cancel01Icon } from \"@hugeicons/core-free-icons\"\n\nfunction Dialog({ ...props }: DialogPrimitive.Root.Props) {\n return <DialogPrimitive.Root data-slot=\"dialog\" {...props} />\n}\n\nfunction DialogTrigger({ ...props }: DialogPrimitive.Trigger.Props) {\n return <DialogPrimitive.Trigger data-slot=\"dialog-trigger\" {...props} />\n}\n\nfunction DialogPortal({ ...props }: DialogPrimitive.Portal.Props) {\n return <DialogPrimitive.Portal data-slot=\"dialog-portal\" {...props} />\n}\n\nfunction DialogClose({ ...props }: DialogPrimitive.Close.Props) {\n return <DialogPrimitive.Close data-slot=\"dialog-close\" {...props} />\n}\n\nfunction DialogOverlay({\n className,\n ...props\n}: DialogPrimitive.Backdrop.Props) {\n return (\n <DialogPrimitive.Backdrop\n data-slot=\"dialog-overlay\"\n className={cn(\n \"fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction DialogContent({\n className,\n children,\n showCloseButton = true,\n ...props\n}: DialogPrimitive.Popup.Props & {\n showCloseButton?: boolean\n}) {\n return (\n <DialogPortal>\n <DialogOverlay />\n <DialogPrimitive.Popup\n data-slot=\"dialog-content\"\n className={cn(\n \"fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-6 rounded-xl bg-popover p-6 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-md data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95\",\n className\n )}\n {...props}\n >\n {children}\n {showCloseButton && (\n <DialogPrimitive.Close\n data-slot=\"dialog-close\"\n render={\n <Button\n variant=\"ghost\"\n className=\"absolute top-4 right-4\"\n size=\"icon-sm\"\n />\n }\n >\n <HugeiconsIcon icon={Cancel01Icon} strokeWidth={2} />\n <span className=\"sr-only\">Close</span>\n </DialogPrimitive.Close>\n )}\n </DialogPrimitive.Popup>\n </DialogPortal>\n )\n}\n\nfunction DialogHeader({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"dialog-header\"\n className={cn(\"flex flex-col gap-2\", className)}\n {...props}\n />\n )\n}\n\nfunction DialogFooter({\n className,\n showCloseButton = false,\n children,\n ...props\n}: React.ComponentProps<\"div\"> & {\n showCloseButton?: boolean\n}) {\n return (\n <div\n data-slot=\"dialog-footer\"\n className={cn(\n \"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end\",\n className\n )}\n {...props}\n >\n {children}\n {showCloseButton && (\n <DialogPrimitive.Close render={<Button variant=\"outline\" />}>\n Close\n </DialogPrimitive.Close>\n )}\n </div>\n )\n}\n\nfunction DialogTitle({ className, ...props }: DialogPrimitive.Title.Props) {\n return (\n <DialogPrimitive.Title\n data-slot=\"dialog-title\"\n className={cn(\"leading-none font-medium\", className)}\n {...props}\n />\n )\n}\n\nfunction DialogDescription({\n className,\n ...props\n}: DialogPrimitive.Description.Props) {\n return (\n <DialogPrimitive.Description\n data-slot=\"dialog-description\"\n className={cn(\n \"text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground\",\n className\n )}\n {...props}\n />\n )\n}\n\nexport {\n Dialog,\n DialogClose,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogOverlay,\n DialogPortal,\n DialogTitle,\n DialogTrigger,\n}\n","import { cn } from \"cn\"\nimport { HugeiconsIcon } from \"@hugeicons/react\"\nimport { Loading03Icon } from \"@hugeicons/core-free-icons\"\n\nimport { useMessages } from \"#orck/i18n/context\"\n\n// Local: HugeiconsIcon props, since its strokeWidth rejects the svg string type.\nfunction Spinner({\n className,\n ...props\n}: Omit<React.ComponentProps<typeof HugeiconsIcon>, \"icon\">) {\n const { t } = useMessages() // Local: i18n \"Loading\" label.\n return (\n <HugeiconsIcon\n icon={Loading03Icon}\n strokeWidth={2}\n data-slot=\"spinner\"\n role=\"status\"\n aria-label={t(\"common.loading\")}\n className={cn(\"size-4 animate-spin\", className)}\n {...props}\n />\n )\n}\n\nexport { Spinner }\n","import * as React from \"react\"\nimport { Input as InputPrimitive } from \"@base-ui/react/input\"\nimport { cn } from \"cn\"\n\nfunction Input({ className, type, ...props }: React.ComponentProps<\"input\">) {\n return (\n <InputPrimitive\n type={type}\n data-slot=\"input\"\n className={cn(\n \"h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-2.5 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40\",\n className\n )}\n {...props}\n />\n )\n}\n\nexport { Input }\n","import * as React from \"react\"\nimport { cn } from \"cn\"\n\nfunction Label({ className, ...props }: React.ComponentProps<\"label\">) {\n return (\n <label\n data-slot=\"label\"\n className={cn(\n \"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50\",\n className\n )}\n {...props}\n />\n )\n}\n\nexport { Label }\n","import { z } from \"zod\"\n\nconst ISO_COUNTRY_CODES =\n \"AD AE AF AG AI AL AM AO AQ AR AS AT AU AW AX AZ BA BB BD BE BF BG BH BI BJ BL BM BN BO BQ BR BS BT BV BW BY BZ CA CC CD CF CG CH CI CK CL CM CN CO CR CU CV CW CX CY CZ DE DJ DK DM DO DZ EC EE EG EH ER ES ET FI FJ FK FM FO FR GA GB GD GE GF GG GH GI GL GM GN GP GQ GR GS GT GU GW GY HK HM HN HR HT HU ID IE IL IM IN IO IQ IR IS IT JE JM JO JP KE KG KH KI KM KN KP KR KW KY KZ LA LB LC LI LK LR LS LT LU LV LY MA MC MD ME MF MG MH MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ NA NC NE NF NG NI NL NO NP NR NU NZ OM PA PE PF PG PH PK PL PM PN PR PS PT PW PY QA RE RO RS RU RW SA SB SC SD SE SG SH SI SJ SK SL SM SN SO SR SS ST SV SX SY SZ TC TD TF TG TH TJ TK TL TM TN TO TR TT TV TW TZ UA UG UM US UY UZ VA VC VE VG VI VN VU WF WS YE YT ZA ZM ZW\".split(\n \" \"\n )\n\n// ISO-3166 alpha-2 projection of the UPU's \"List of countries which do not\n// require postal codes\" (Universal DataBase, September 2025). Keep a postal\n// code when a customer supplies one, but do not block tokenization when the\n// destination does not require it.\n// https://www.upu.int/UPU/media/upu/documents/PostCode/General-Addressing-Issues.pdf\nconst POSTAL_OPTIONAL_COUNTRIES = new Set([\n \"AE\",\n \"AG\",\n \"AO\",\n \"AQ\",\n \"AW\",\n \"BF\",\n \"BI\",\n \"BJ\",\n \"BO\",\n \"BQ\",\n \"BS\",\n \"BV\",\n \"BW\",\n \"BZ\",\n \"CF\",\n \"CG\",\n \"CI\",\n \"CK\",\n \"CM\",\n \"CW\",\n \"DM\",\n \"ER\",\n \"FJ\",\n \"GA\",\n \"GD\",\n \"GM\",\n \"GQ\",\n \"JM\",\n \"KM\",\n \"KP\",\n \"LY\",\n \"ML\",\n \"MR\",\n \"QA\",\n \"RW\",\n \"SB\",\n \"SC\",\n \"SL\",\n \"SO\",\n \"SR\",\n \"SS\",\n \"ST\",\n \"SX\",\n \"SY\",\n \"TD\",\n \"TG\",\n \"TK\",\n \"TO\",\n \"TV\",\n \"UM\",\n \"VU\",\n \"YE\",\n \"ZW\",\n])\n\nconst POSTAL_PLACEHOLDERS: Record<string, string> = {\n AR: \"C1000\",\n BR: \"01000-000\",\n CA: \"A1A 1A1\",\n CL: \"8320000\",\n CN: \"100000\",\n CO: \"110111\",\n DE: \"10115\",\n ES: \"28001\",\n JP: \"100-0001\",\n KR: \"04524\",\n MX: \"01000\",\n PE: \"15001\",\n US: \"12345\",\n}\n\nconst displayNames = new Intl.DisplayNames([\"en\"], { type: \"region\" })\n\nexport const COUNTRY_OPTIONS = ISO_COUNTRY_CODES.map((code) => ({\n code,\n name: displayNames.of(code) ?? code,\n})).sort((left, right) => left.name.localeCompare(right.name))\n\nexport const nameOnCardSchema = z\n .string()\n .trim()\n .min(1, \"Full name is required\")\n .max(200, \"Full name is too long\")\n\nexport const countryCodeSchema = z\n .string()\n .trim()\n .regex(/^[A-Za-z]{2}$/, \"Select a country\")\n .transform((value) => value.toUpperCase())\n\nexport function isPostalRequired(country: string): boolean {\n const code = country.trim().toUpperCase()\n return code === \"\" || !POSTAL_OPTIONAL_COUNTRIES.has(code)\n}\n\nexport function postalField(\n country: string,\n required: boolean\n): {\n label: string\n placeholder: string\n inputMode: \"numeric\" | \"text\"\n pattern?: string\n} {\n const code = country.trim().toUpperCase()\n const baseLabel =\n code === \"US\"\n ? \"ZIP code\"\n : code === \"GB\" || code === \"AU\" || code === \"NZ\"\n ? \"Postcode\"\n : \"Postal code\"\n return {\n label: required ? baseLabel : `${baseLabel} (optional)`,\n placeholder: POSTAL_PLACEHOLDERS[code] ?? baseLabel,\n inputMode: code === \"US\" ? \"numeric\" : \"text\",\n pattern: code === \"US\" ? \"[0-9]{5}(?:-[0-9]{4})?\" : undefined,\n }\n}\n\nexport const nmiBillingSchema = z\n .object({\n name_on_card: nameOnCardSchema,\n country: countryCodeSchema,\n zip: z.string().trim().max(32, \"Postal code is too long\"),\n })\n .superRefine((value, context) => {\n if (isPostalRequired(value.country) && !value.zip) {\n context.addIssue({\n code: \"custom\",\n message: `${postalField(value.country, true).label} is required`,\n path: [\"zip\"],\n })\n }\n if (\n value.country === \"US\" &&\n value.zip &&\n !/^\\d{5}(?:-\\d{4})?$/.test(value.zip)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"Enter a valid ZIP code\",\n path: [\"zip\"],\n })\n }\n })\n\nexport type NMIBilling = z.infer<typeof nmiBillingSchema>\n\n/** A card form's billing fields as a saved card's billing details. */\nexport function billingDetailsOf(billing: {\n name_on_card?: string\n email?: string\n zip?: string\n country?: string\n}) {\n const address = {\n ...(billing.zip ? { postal_code: billing.zip } : {}),\n ...(billing.country ? { country: billing.country } : {}),\n }\n return {\n ...(billing.name_on_card ? { name: billing.name_on_card } : {}),\n ...(billing.email ? { email: billing.email } : {}),\n ...(Object.keys(address).length > 0 ? { address } : {}),\n }\n}\n\nexport const emptyNMIBilling: NMIBilling = {\n name_on_card: \"\",\n country: \"\",\n zip: \"\",\n}\n\n/** The buyer's likely billing country from the browser locale, or \"\". */\nexport function browserCountry(): string {\n try {\n if (typeof navigator === \"undefined\" || !navigator.language) return \"\"\n const region = new Intl.Locale(navigator.language).maximize().region\n return region && /^[A-Z]{2}$/.test(region) ? region : \"\"\n } catch {\n return \"\"\n }\n}\n\n/** The host's country when it is a known code, else the browser's region. */\nexport function initialCountry(hostCountry?: string): string {\n const code = hostCountry?.trim().toUpperCase() ?? \"\"\n if (COUNTRY_OPTIONS.some((option) => option.code === code)) return code\n const region = browserCountry()\n return COUNTRY_OPTIONS.some((option) => option.code === region) ? region : \"\"\n}\n\n// The EEA and the UK, where keeping a card for later one-off purchases needs\n// the customer's unticked opt-in; mirrors OpenRails' mandates.optInCountries.\nconst REUSE_OPT_IN_COUNTRIES = new Set([\n \"AT\", \"BE\", \"BG\", \"CY\", \"CZ\", \"DE\", \"DK\", \"EE\", \"ES\", \"FI\", \"FR\", \"GR\", \"HR\",\n \"HU\", \"IE\", \"IT\", \"LT\", \"LU\", \"LV\", \"MT\", \"NL\", \"PL\", \"PT\", \"RO\", \"SE\", \"SI\",\n \"SK\", \"IS\", \"LI\", \"NO\", \"GB\",\n])\n\nexport function reuseNeedsOptIn(country: string): boolean {\n return REUSE_OPT_IN_COUNTRIES.has(country.trim().toUpperCase())\n}\n","import type * as React from \"react\"\n\nimport { Input } from \"#orck/components/ui/input\"\nimport { Label } from \"#orck/components/ui/label\"\nimport {\n COUNTRY_OPTIONS,\n isPostalRequired,\n postalField,\n type NMIBilling,\n} from \"#orck/lib/billing\"\n\nconst LABEL = \"text-[13px] font-medium text-foreground\"\nconst CONTROL =\n \"h-[38px] rounded-[9px] border border-input bg-card text-sm text-foreground\"\nconst INPUT = `${CONTROL} px-2.5`\n\nexport function BillingTextField({\n id,\n name,\n label,\n value,\n onChange,\n autoComplete,\n placeholder,\n disabled,\n maxLength,\n required,\n type,\n inputMode,\n pattern,\n}: {\n id: string\n name: string\n label: string\n value: string\n onChange: (value: string) => void\n autoComplete: string\n placeholder?: string\n disabled?: boolean\n maxLength?: number\n required?: boolean\n type?: React.HTMLInputTypeAttribute\n inputMode?: React.HTMLAttributes<HTMLInputElement>[\"inputMode\"]\n pattern?: string\n}) {\n return (\n <div className=\"grid gap-1.5\">\n <Label htmlFor={id} className={LABEL}>\n {label}\n </Label>\n <Input\n id={id}\n name={name}\n type={type}\n className={INPUT}\n value={value}\n autoComplete={autoComplete}\n placeholder={placeholder}\n disabled={disabled}\n maxLength={maxLength}\n required={required}\n inputMode={inputMode}\n pattern={pattern}\n onChange={(event) => onChange(event.target.value)}\n />\n </div>\n )\n}\n\nexport function CountryField({\n id,\n value,\n onChange,\n disabled,\n}: {\n id: string\n value: string\n onChange: (value: string) => void\n disabled?: boolean\n}) {\n return (\n <div className=\"grid gap-1.5\">\n <Label htmlFor={id} className={LABEL}>\n Country or region\n </Label>\n <select\n id={id}\n name=\"country\"\n className={`${CONTROL} w-full px-2.5`}\n value={value}\n autoComplete=\"billing country\"\n disabled={disabled}\n required\n onChange={(event) => onChange(event.target.value)}\n >\n <option value=\"\">Select country</option>\n {COUNTRY_OPTIONS.map((country) => (\n <option key={country.code} value={country.code}>\n {country.name}\n </option>\n ))}\n </select>\n </div>\n )\n}\n\nexport function PostalField({\n id,\n value,\n country,\n onChange,\n disabled,\n required,\n error,\n}: {\n id: string\n value: string\n country: string\n onChange: (value: string) => void\n disabled?: boolean\n required: boolean\n error?: string\n}) {\n const field = postalField(country, required)\n return (\n <div className=\"grid gap-1.5\">\n <BillingTextField\n id={id}\n name=\"zip\"\n label={field.label}\n value={value}\n onChange={onChange}\n autoComplete=\"billing postal-code\"\n placeholder={field.placeholder}\n disabled={disabled}\n maxLength={32}\n required={required}\n inputMode={field.inputMode}\n pattern={field.pattern}\n />\n {error ? (\n <p className=\"text-[12.5px] text-destructive\" role=\"alert\">\n {error}\n </p>\n ) : null}\n </div>\n )\n}\n\n// The card fields (children) sit between the cardholder name and the address.\nexport function CardBillingFields({\n idPrefix,\n value,\n onChange,\n disabled,\n postalError,\n children,\n}: {\n idPrefix: string\n value: NMIBilling\n onChange: (next: NMIBilling) => void\n disabled?: boolean\n postalError?: string\n children?: React.ReactNode\n}) {\n const set = (key: keyof NMIBilling) => (next: string) =>\n onChange({ ...value, [key]: next })\n const postalRequired = isPostalRequired(value.country)\n return (\n <div className=\"grid gap-3\">\n <BillingTextField\n id={`${idPrefix}-name-on-card`}\n name=\"name_on_card\"\n label=\"Full name\"\n value={value.name_on_card}\n onChange={set(\"name_on_card\")}\n autoComplete=\"cc-name\"\n disabled={disabled}\n maxLength={200}\n required\n />\n {children}\n <div className=\"grid grid-cols-2 gap-3\">\n <CountryField\n id={`${idPrefix}-country`}\n value={value.country}\n onChange={set(\"country\")}\n disabled={disabled}\n />\n <PostalField\n id={`${idPrefix}-postal-code`}\n value={value.zip}\n country={value.country}\n onChange={set(\"zip\")}\n disabled={disabled}\n required={postalRequired}\n error={postalError}\n />\n </div>\n </div>\n )\n}\n","// Card entry for the NMI rail. Live mode mounts Collect.js hosted iframes\n// into these containers (card data never touches our code); preview mode\n// (fixture tokenization keys) renders inert placeholders with the same\n// geometry so every state is designable without a gateway. A PSP that takes\n// cards on OpenRails itself gets NativeCardFields instead.\nimport type * as React from \"react\"\n\nimport { Label } from \"#orck/components/ui/label\"\nimport type { CardEntryState } from \"#orck/lib/card-entry\"\nimport type { CollectFieldErrors } from \"#orck/lib/collect\"\nimport { SupportedCardBrands } from \"#orck/components/card-brands\"\nimport { cn } from \"cn\"\n\nfunction FieldError({ id, message }: { id: string; message?: string }) {\n return message ? (\n <p id={id} className=\"text-[12.5px] text-destructive\" role=\"alert\">\n {message}\n </p>\n ) : null\n}\n\nconst FIELD =\n \"orck-collect-field h-[38px] overflow-hidden rounded-[9px] border border-[color:var(--border)] bg-card px-[3px]\"\nconst PREVIEW_FIELD =\n \"flex h-[38px] items-center rounded-[9px] border border-[color:var(--border)] bg-card px-[11px] text-sm text-[color:var(--orck-faint)] tabular-nums\"\n\nexport interface CardFieldIds {\n number: string\n expiry: string\n cvv: string\n}\n\nexport function CardFields({\n ids,\n preview,\n error,\n fieldErrors = {},\n hidden,\n brand,\n}: {\n ids: CardFieldIds\n preview: boolean\n /** The detected card brand, highlighted among the accepted ones. */\n brand?: string\n error?: string\n /** Inline per-field errors (gateway validation or a decline). */\n fieldErrors?: CollectFieldErrors\n // Kept mounted while hidden: the Collect.js iframes cannot be recreated\n // cheaply, so switching to a stored card must not unmount them.\n hidden?: boolean\n}) {\n return (\n <div\n className={cn(\"grid gap-3\", hidden && \"hidden\")}\n aria-hidden={hidden || undefined}\n >\n <div className=\"grid gap-1.5\">\n <div className=\"flex items-center justify-between\">\n <Label\n htmlFor={ids.number}\n className=\"text-[13px] font-medium text-foreground\"\n >\n Card number\n </Label>\n <SupportedCardBrands active={brand} />\n </div>\n {preview ? (\n <div id={ids.number} className={PREVIEW_FIELD}>\n 1234 1234 1234 1234\n </div>\n ) : (\n <div\n id={ids.number}\n className={cn(FIELD, fieldErrors.number && \"border-destructive\")}\n />\n )}\n <FieldError id={`${ids.number}-error`} message={fieldErrors.number} />\n </div>\n <div className=\"grid grid-cols-2 gap-3\">\n <div className=\"grid gap-1.5\">\n <Label\n htmlFor={ids.expiry}\n className=\"text-[13px] font-medium text-foreground\"\n >\n Expiry\n </Label>\n {preview ? (\n <div id={ids.expiry} className={PREVIEW_FIELD}>\n MM / YY\n </div>\n ) : (\n <div\n id={ids.expiry}\n className={cn(FIELD, fieldErrors.expiry && \"border-destructive\")}\n />\n )}\n <FieldError id={`${ids.expiry}-error`} message={fieldErrors.expiry} />\n </div>\n <div className=\"grid gap-1.5\">\n <Label\n htmlFor={ids.cvv}\n className=\"text-[13px] font-medium text-foreground\"\n >\n CVC\n </Label>\n {preview ? (\n <div id={ids.cvv} className={PREVIEW_FIELD}>\n CVC\n </div>\n ) : (\n <div\n id={ids.cvv}\n className={cn(FIELD, fieldErrors.cvv && \"border-destructive\")}\n />\n )}\n <FieldError id={`${ids.cvv}-error`} message={fieldErrors.cvv} />\n </div>\n </div>\n {error ? (\n <p className={cn(\"text-[13px] text-destructive\")} role=\"alert\">\n {error}\n </p>\n ) : null}\n </div>\n )\n}\n\nconst NATIVE_FIELD =\n \"h-[38px] w-full min-w-0 rounded-[9px] border border-[color:var(--border)] bg-card px-[11px] text-sm text-foreground tabular-nums outline-none placeholder:text-[color:var(--orck-faint)] focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:opacity-50\"\n\n/**\n * Card entry for a PSP that takes cards on OpenRails itself (driver \"card\"):\n * plain inputs in the same layout as the Collect.js containers. The card is\n * posted to OpenRails; no gateway script is loaded.\n */\nexport function NativeCardFields({\n ids,\n card,\n fieldErrors = {},\n disabled,\n hidden,\n}: {\n ids: CardFieldIds\n card: CardEntryState\n /** Inline errors beyond the form's own (a decline naming a field). */\n fieldErrors?: CollectFieldErrors\n disabled?: boolean\n hidden?: boolean\n}) {\n const errors = { ...card.fieldErrors, ...fieldErrors }\n const field = (\n id: string,\n name: \"number\" | \"expiry\" | \"cvc\",\n error: string | undefined,\n props: React.ComponentProps<\"input\">\n ) => (\n <>\n <input\n id={id}\n name={`card-${name}`}\n className={cn(NATIVE_FIELD, error && \"border-destructive\")}\n value={card.input[name]}\n onChange={(event) => card.change(name, event.target.value)}\n onBlur={() => card.leave(name)}\n inputMode=\"numeric\"\n spellCheck={false}\n disabled={disabled}\n required\n aria-invalid={error ? true : undefined}\n aria-describedby={error ? `${id}-error` : undefined}\n {...props}\n />\n <FieldError id={`${id}-error`} message={error} />\n </>\n )\n return (\n <div\n className={cn(\"grid gap-3\", hidden && \"hidden\")}\n aria-hidden={hidden || undefined}\n >\n <div className=\"grid gap-1.5\">\n <div className=\"flex items-center justify-between\">\n <Label\n htmlFor={ids.number}\n className=\"text-[13px] font-medium text-foreground\"\n >\n Card number\n </Label>\n <SupportedCardBrands />\n </div>\n {field(ids.number, \"number\", errors.number, {\n autoComplete: \"cc-number\",\n placeholder: \"1234 1234 1234 1234\",\n maxLength: 23,\n })}\n </div>\n <div className=\"grid grid-cols-2 gap-3\">\n <div className=\"grid gap-1.5\">\n <Label\n htmlFor={ids.expiry}\n className=\"text-[13px] font-medium text-foreground\"\n >\n Expiry\n </Label>\n {field(ids.expiry, \"expiry\", errors.expiry, {\n autoComplete: \"cc-exp\",\n placeholder: \"MM / YY\",\n maxLength: 7,\n })}\n </div>\n <div className=\"grid gap-1.5\">\n <Label\n htmlFor={ids.cvv}\n className=\"text-[13px] font-medium text-foreground\"\n >\n CVC\n </Label>\n {field(ids.cvv, \"cvc\", errors.cvv, {\n autoComplete: \"cc-csc\",\n placeholder: \"CVC\",\n maxLength: 4,\n })}\n </div>\n </div>\n </div>\n )\n}\n","// The one bold element on the surface: the ink button carrying the amount.\n// Redirect rails relabel it; Solana has no button at all.\nimport { Button } from \"#orck/components/ui/button\"\nimport { cn } from \"cn\"\n\nexport function PayButton({\n label,\n processing,\n disabled,\n}: {\n label: string\n processing: boolean\n disabled?: boolean\n}) {\n return (\n <Button\n type=\"submit\"\n className={cn(\n \"h-[42px] w-full rounded-[10px] text-sm font-semibold tabular-nums\",\n processing && \"opacity-75\"\n )}\n disabled={disabled || processing}\n >\n {processing ? (\n <>\n <span\n aria-hidden\n className=\"size-3.5 animate-spin rounded-full border-2 border-[color:var(--primary-foreground)]/35 border-t-[color:var(--primary-foreground)] motion-reduce:animate-none\"\n />\n Processing…\n </>\n ) : (\n label\n )}\n </Button>\n )\n}\n\nexport function TrustLine() {\n return (\n <div className=\"-mt-1 flex items-center justify-center gap-1.5 text-xs text-[color:var(--orck-faint)]\">\n <svg\n viewBox=\"0 0 16 16\"\n fill=\"currentColor\"\n aria-hidden\n className=\"size-[11px]\"\n >\n <path d=\"M8 1a3.5 3.5 0 0 0-3.5 3.5V6H4a1.5 1.5 0 0 0-1.5 1.5v5A1.5 1.5 0 0 0 4 14h8a1.5 1.5 0 0 0 1.5-1.5v-5A1.5 1.5 0 0 0 12 6h-.5V4.5A3.5 3.5 0 0 0 8 1Zm2 5H6V4.5a2 2 0 1 1 4 0V6Z\" />\n </svg>\n Secured by{\" \"}\n <a href=\"https://openrails.dev\" target=\"_blank\" rel=\"noreferrer\" className=\"underline-offset-2 hover:underline\">\n OpenRails\n </a>\n </div>\n )\n}\n","import * as React from \"react\"\nimport BasisTheory from \"@basis-theory/web-elements\"\nimport { CardBillingFields } from \"./billing-fields\"\nimport { CardFields } from \"./card-fields\"\nimport { PayButton, TrustLine } from \"./pay-button\"\nimport {\n emptyNMIBilling,\n initialCountry,\n nmiBillingSchema,\n} from \"../lib/billing\"\nimport type { TokenizedCardData } from \"../tokenized-card-form\"\n\n// Only the vendor's iframe handles PAN/CVC. An unconfirmed payment retains\n// exactly the same token and billing details so Retry replays its request.\nexport function PlatformCardForm({\n publicKey,\n submitLabel,\n disabled,\n onTokenized,\n purpose = \"payment\",\n defaultCountry,\n}: {\n purpose?: \"payment\" | \"setup\"\n defaultCountry?: string\n publicKey: string\n submitLabel: string\n disabled: boolean\n onTokenized: (card: TokenizedCardData) => Promise<boolean>\n}) {\n const uid = React.useId().replace(/[^a-zA-Z0-9-]/g, \"\")\n const ids = React.useMemo(\n () => ({\n number: `bt-${uid}-number`,\n expiry: `bt-${uid}-expiry`,\n cvv: `bt-${uid}-cvv`,\n }),\n [uid]\n )\n const [billing, setBilling] = React.useState(() => ({\n ...emptyNMIBilling,\n country: initialCountry(defaultCountry),\n }))\n const [ready, setReady] = React.useState(false)\n const [busy, setBusy] = React.useState(false)\n const [submitted, setSubmitted] = React.useState(false)\n const [retry, setRetry] = React.useState(false)\n const [error, setError] = React.useState<string>()\n const pending = React.useRef<TokenizedCardData>(undefined)\n const tokenize = React.useRef<() => Promise<string>>(undefined)\n const submitting = React.useRef(false)\n const authorization = React.useRef({ generation: 0, disabled })\n React.useLayoutEffect(() => {\n authorization.current = {\n generation: authorization.current.generation + 1,\n disabled,\n }\n }, [publicKey, disabled])\n React.useEffect(() => {\n let active = true\n const bt = BasisTheory(publicKey)\n const number = bt.createElement(\"cardNumber\")\n const expiry = bt.createElement(\"expiry\")\n const cvv = bt.createElement(\"cvv\")\n Promise.all([\n number.mount(`#${ids.number}`),\n expiry.mount(`#${ids.expiry}`),\n cvv.mount(`#${ids.cvv}`),\n ]).then(\n () => {\n if (!active) return\n tokenize.current = async () =>\n (\n await bt.tokenIntents.create({\n type: \"card\",\n data: {\n number,\n expiration_month: expiry,\n expiration_year: expiry,\n cvc: cvv,\n },\n })\n ).id\n setReady(true)\n },\n () => {\n if (active) setError(\"Secure card entry could not be loaded.\")\n }\n )\n return () => {\n active = false\n authorization.current.generation++\n tokenize.current = undefined\n void bt.destroy()\n }\n }, [publicKey, ids])\n const retryLabel = purpose === \"setup\" ? \"Retry saving card\" : \"Retry payment\"\n const unconfirmedMessage =\n purpose === \"setup\"\n ? \"The card save is not confirmed. Retry to check the same card.\"\n : \"The payment result is not confirmed. Retry to check the same payment.\"\n const submit = async (event: React.FormEvent) => {\n event.preventDefault()\n if (disabled || submitting.current || submitted || !tokenize.current) return\n const parsed = nmiBillingSchema.safeParse(billing)\n if (!parsed.success) {\n setError(parsed.error.issues[0]?.message ?? \"Check the billing details\")\n return\n }\n submitting.current = true\n setBusy(true)\n setError(undefined)\n const generation = authorization.current.generation\n try {\n const card = pending.current ?? {\n payment_token: await tokenize.current(),\n ...parsed.data,\n }\n if (\n authorization.current.generation !== generation ||\n authorization.current.disabled\n )\n return\n pending.current = card\n const accepted = await onTokenized(card)\n if (accepted) setSubmitted(true)\n else pending.current = undefined\n setRetry(false)\n } catch {\n const sent = !!pending.current\n setRetry(sent)\n setError(\n sent ? unconfirmedMessage : \"Check your card details and try again.\"\n )\n } finally {\n submitting.current = false\n setBusy(false)\n }\n }\n return (\n <form\n aria-label={\n purpose === \"setup\"\n ? \"Secure platform card setup\"\n : \"Secure platform card payment\"\n }\n className=\"grid gap-4\"\n onSubmit={(event) => void submit(event)}\n >\n <CardBillingFields\n idPrefix={`bt-${uid}`}\n value={billing}\n onChange={setBilling}\n disabled={disabled || busy || retry || submitted}\n >\n <CardFields ids={ids} preview={false} />\n </CardBillingFields>\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n ) : null}\n <PayButton\n label={retry ? retryLabel : submitLabel}\n processing={busy}\n disabled={disabled || submitted || !ready || !nmiBillingSchema.safeParse(billing).success}\n />\n <TrustLine />\n </form>\n )\n}\n","// Stripe.js for in-page card setup and payment authentication. Loaded on first\n// use, so hosts without a Stripe PSP never fetch it.\nimport type { Stripe } from \"@stripe/stripe-js\"\n\nconst loaded = new Map<string, Promise<Stripe>>()\n\nexport function loadStripeFor(publishableKey: string): Promise<Stripe> {\n let stripe = loaded.get(publishableKey)\n if (!stripe) {\n stripe = import(\"@stripe/stripe-js\")\n .then(({ loadStripe }) => loadStripe(publishableKey))\n .then((value) => {\n if (!value) throw new Error(\"Stripe could not be loaded.\")\n return value\n })\n stripe.catch(() => loaded.delete(publishableKey))\n loaded.set(publishableKey, stripe)\n }\n return stripe\n}\n","// Collect.js (NMI browser tokenization). The gateway script mounts hosted\n// iframes into our field containers, so card data never touches this code —\n// we receive a one-time token plus display metadata. Collect.js has no\n// teardown API: the script and configuration persist for the page lifetime;\n// reconfiguring re-mounts fields.\nimport * as React from \"react\"\n\nexport interface CollectCard {\n number?: string\n type?: string\n exp?: string\n}\n\nexport interface CollectResponse {\n token: string\n card?: CollectCard\n}\n\ndeclare global {\n interface Window {\n CollectJS?: {\n configure: (config: Record<string, unknown>) => void\n startPaymentRequest: () => void\n }\n }\n}\n\nconst SCRIPT_ID = \"openrails-collectjs\"\nconst TIMEOUT_MS = 30_000\nconst collectScriptStates = new WeakMap<\n HTMLScriptElement,\n \"loading\" | \"loaded\" | \"failed\"\n>()\n\nfunction safeCollectScriptURL(raw: string): string | undefined {\n try {\n const parsed = new URL(raw)\n if (\n parsed.protocol !== \"https:\" ||\n parsed.username ||\n parsed.password ||\n parsed.hash\n ) {\n return undefined\n }\n return parsed.toString()\n } catch {\n return undefined\n }\n}\n\n// toPlainColor normalizes a CSS color into rgb()/rgba() form, the least\n// common denominator the gateway's CSS sanitizer accepts. Chrome serializes\n// the theme tokens in their authored oklch space (canvas fillStyle keeps it\n// too), so oklch is converted numerically; everything else round-trips\n// through a canvas fillStyle. Unparseable input returns \"\".\nexport function toPlainColor(value: string | undefined): string {\n if (!value) return \"\"\n const oklch = oklchToRGB(value)\n if (oklch) return oklch\n try {\n const context = document.createElement(\"canvas\").getContext(\"2d\")\n if (!context) return \"\"\n context.fillStyle = \"#010203\"\n context.fillStyle = value\n const normalized = context.fillStyle\n if (normalized === \"#010203\" && value !== \"#010203\") return \"\"\n return normalized.startsWith(\"oklch\") ? \"\" : normalized\n } catch {\n return \"\"\n }\n}\n\n// oklchToRGB converts \"oklch(L C H)\" / \"oklch(L C H / A)\" (L as 0..1 or %)\n// to an rgb()/rgba() string via OKLab → linear sRGB (Ottosson's matrices).\nfunction oklchToRGB(value: string): string {\n const match =\n /^oklch\\(\\s*([\\d.]+%?)\\s+([\\d.]+)\\s+([\\d.]+)(?:deg)?\\s*(?:\\/\\s*([\\d.]+%?)\\s*)?\\)$/i.exec(\n value.trim()\n )\n if (!match) return \"\"\n const number = (raw: string) =>\n raw.endsWith(\"%\") ? parseFloat(raw) / 100 : parseFloat(raw)\n const L = number(match[1])\n const C = parseFloat(match[2])\n const H = (parseFloat(match[3]) * Math.PI) / 180\n const alpha = match[4] === undefined ? 1 : number(match[4])\n const a = C * Math.cos(H)\n const b = C * Math.sin(H)\n const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3\n const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3\n const s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3\n const channel = (linear: number) => {\n const gamma =\n linear <= 0.0031308\n ? 12.92 * linear\n : 1.055 * Math.max(linear, 0) ** (1 / 2.4) - 0.055\n return Math.round(Math.min(1, Math.max(0, gamma)) * 255)\n }\n const red = channel(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s)\n const green = channel(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s)\n const blue = channel(-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s)\n return alpha >= 1\n ? `rgb(${red}, ${green}, ${blue})`\n : `rgba(${red}, ${green}, ${blue}, ${alpha})`\n}\n\n// Preview keys skip the live script entirely so fixture-driven previews can\n// render the card fields without a real gateway.\nexport function isPreviewTokenizationKey(key: string): boolean {\n return key.startsWith(\"preview_\")\n}\n\n/** Inline field errors, keyed by our field names. */\nexport interface CollectFieldErrors {\n number?: string\n expiry?: string\n cvv?: string\n}\n\nconst FIELD_NAMES: Record<string, keyof CollectFieldErrors> = {\n ccnumber: \"number\",\n ccexp: \"expiry\",\n cvv: \"cvv\",\n}\n\nconst FIELD_MESSAGES: Record<keyof CollectFieldErrors, string> = {\n number: \"Enter a valid card number\",\n expiry: \"Enter a valid expiry date\",\n cvv: \"Enter a valid security code\",\n}\n\nexport interface CollectFieldSelectors {\n number: string\n expiry: string\n cvv: string\n}\n\nexport function useCollectJS(config: {\n enabled: boolean\n active: boolean\n tokenizationKey: string\n scriptURL: string\n selectors: CollectFieldSelectors\n}): {\n ready: boolean\n preview: boolean\n brand?: string\n loadError?: string\n /** Every field reported valid by the gateway. */\n valid: boolean\n fieldErrors: CollectFieldErrors\n tokenize: () => Promise<CollectResponse>\n} {\n const preview =\n config.enabled && isPreviewTokenizationKey(config.tokenizationKey)\n const [ready, setReady] = React.useState(false)\n const [loadError, setLoadError] = React.useState<string>()\n // The card brand Collect.js detects once the number is valid.\n const [brand, setBrand] = React.useState<string>()\n // Validity per field as Collect.js reports it on edit and blur.\n const [validity, setValidity] = React.useState<\n Partial<\n Record<keyof CollectFieldErrors, { valid: boolean; message?: string }>\n >\n >({})\n const pending = React.useRef<\n | {\n resolve: (r: CollectResponse) => void\n reject: (e: Error) => void\n timer: number\n }\n | undefined\n >(undefined)\n const configuredFor = React.useRef<string | undefined>(undefined)\n const { number, expiry, cvv } = config.selectors\n\n React.useEffect(() => {\n if (\n !config.enabled ||\n preview ||\n !config.tokenizationKey ||\n !config.scriptURL ||\n typeof document === \"undefined\"\n ) {\n return\n }\n const scriptURL = safeCollectScriptURL(config.scriptURL)\n if (!scriptURL) {\n void Promise.resolve().then(() => {\n setReady(false)\n setLoadError(\"Card fields failed to load\")\n })\n return\n }\n const configuration = [\n config.tokenizationKey,\n scriptURL,\n number,\n expiry,\n cvv,\n ].join(\"\\u0000\")\n const configurationChanged = configuredFor.current !== configuration\n if (!configurationChanged && !config.active) return\n configuredFor.current = configuration\n\n let canceled = false\n const settle = (fn: () => void) => {\n if (!canceled) fn()\n }\n const configure = () => {\n if (canceled) return\n const collect = window.CollectJS\n if (!collect) {\n settle(() => setLoadError(\"Card fields failed to load\"))\n return\n }\n settle(() => {\n // Replacing stale hosted iframes invalidates readiness until NMI\n // confirms that every new field is available.\n setReady(false)\n setLoadError(undefined)\n setValidity({})\n })\n // The hosted iframes cannot inherit the page theme: hand them the\n // container's resolved colors, normalized by toPlainColor for the\n // gateway's CSS sanitizer. Resolved once per configure.\n const probe = document.querySelector<HTMLElement>(number)\n const probeStyle = probe ? window.getComputedStyle(probe) : undefined\n const probeBackground = toPlainColor(probeStyle?.backgroundColor)\n const fieldBackground =\n probeBackground &&\n probeBackground !== \"transparent\" &&\n probeBackground !== \"rgba(0, 0, 0, 0)\"\n ? probeBackground\n : \"#ffffff\"\n const fieldColor = toPlainColor(probeStyle?.color) || \"#18181b\"\n const placeholderColor =\n toPlainColor(\n probeStyle?.getPropertyValue(\"--muted-foreground\").trim()\n ) || fieldColor\n try {\n collect.configure({\n variant: \"inline\",\n styleSniffer: true,\n customCss: {\n height: \"38px\",\n \"line-height\": \"38px\",\n padding: \"0 8px\",\n \"font-size\": \"14px\",\n \"font-family\": probeStyle?.fontFamily || \"inherit\",\n \"background-color\": fieldBackground,\n color: fieldColor,\n },\n placeholderCss: {\n color: placeholderColor,\n },\n invalidCss: {\n color:\n toPlainColor(\n probeStyle?.getPropertyValue(\"--destructive\").trim()\n ) || \"#dc2626\",\n },\n focusCss: {\n outline: \"none\",\n },\n // Collect.js owns the cross-origin inputs and therefore controls\n // their autocomplete behavior. Titles and placeholders are the\n // accessibility/browser hints its public field API supports.\n fields: {\n ccnumber: {\n selector: number,\n title: \"Card number\",\n placeholder: \"1234 1234 1234 1234\",\n },\n ccexp: {\n selector: expiry,\n title: \"Expiration date\",\n placeholder: \"MM / YY\",\n },\n cvv: {\n selector: cvv,\n title: \"Card security code\",\n placeholder: \"CVC\",\n },\n },\n fieldsAvailableCallback: () => settle(() => setReady(true)),\n lookUpCallback: (response: { type?: string }) =>\n settle(() => setBrand(response?.type || undefined)),\n validationCallback: (\n field: string,\n status: boolean,\n message: string\n ) => {\n const name = FIELD_NAMES[field]\n if (!name) return\n settle(() =>\n setValidity((current) => ({\n ...current,\n [name]: {\n valid: status,\n message: status\n ? undefined\n : message && message !== \"Field is empty\"\n ? `${FIELD_MESSAGES[name]}.`\n : FIELD_MESSAGES[name],\n },\n }))\n )\n },\n timeoutDuration: TIMEOUT_MS,\n timeoutCallback: () => {\n const request = pending.current\n pending.current = undefined\n if (request) {\n window.clearTimeout(request.timer)\n request.reject(new Error(\"Card entry timed out\"))\n }\n },\n callback: (response: CollectResponse) => {\n const request = pending.current\n pending.current = undefined\n if (request) {\n window.clearTimeout(request.timer)\n request.resolve(response)\n }\n },\n })\n } catch {\n settle(() => setLoadError(\"Card fields failed to load\"))\n }\n }\n let existing = document.getElementById(SCRIPT_ID)\n if (\n existing instanceof HTMLScriptElement &&\n (existing.src !== scriptURL ||\n collectScriptStates.get(existing) === \"failed\")\n ) {\n // A white-label merchant may use a different Collect.js distribution.\n // Never configure one merchant's key against another merchant's script,\n // and allow a later modal open to retry a failed network load.\n existing.remove()\n if (existing.src !== scriptURL) {\n Reflect.deleteProperty(window, \"CollectJS\")\n }\n existing = null\n }\n if (existing instanceof HTMLScriptElement) {\n if (window.CollectJS) {\n configure()\n return () => {\n canceled = true\n }\n }\n if (collectScriptStates.get(existing) === \"loaded\") {\n settle(() => setLoadError(\"Card fields failed to load\"))\n return () => {\n canceled = true\n }\n }\n const failed = () =>\n settle(() => setLoadError(\"Card fields failed to load\"))\n existing.addEventListener(\"load\", configure)\n existing.addEventListener(\"error\", failed)\n return () => {\n canceled = true\n existing.removeEventListener(\"load\", configure)\n existing.removeEventListener(\"error\", failed)\n }\n }\n const script = document.createElement(\"script\")\n script.id = SCRIPT_ID\n script.src = scriptURL\n script.async = true\n script.dataset.tokenizationKey = config.tokenizationKey\n collectScriptStates.set(script, \"loading\")\n script.onload = () => {\n collectScriptStates.set(script, \"loaded\")\n configure()\n }\n script.onerror = () => {\n collectScriptStates.set(script, \"failed\")\n settle(() => setLoadError(\"Card fields failed to load\"))\n }\n document.head.appendChild(script)\n return () => {\n canceled = true\n }\n }, [\n config.enabled,\n config.active,\n preview,\n config.tokenizationKey,\n config.scriptURL,\n number,\n expiry,\n cvv,\n ])\n\n const tokenize = React.useCallback(\n () =>\n new Promise<CollectResponse>((resolve, reject) => {\n if (preview) {\n // Preview sessions demo the full flow; a real backend rejects this\n // token, fixture sources accept it.\n resolve({\n token: \"preview_payment_token\",\n card: { number: \"4242424242424242\", type: \"visa\", exp: \"1227\" },\n })\n return\n }\n const collect = window.CollectJS\n if (!collect || !ready) {\n reject(new Error(\"Card fields are not ready\"))\n return\n }\n if (pending.current) {\n reject(new Error(\"Card entry is already in progress\"))\n return\n }\n const timer = window.setTimeout(() => {\n pending.current = undefined\n reject(new Error(\"Card entry timed out\"))\n }, TIMEOUT_MS + 5_000)\n pending.current = { resolve, reject, timer }\n collect.startPaymentRequest()\n }),\n [preview, ready]\n )\n\n const fieldErrors: CollectFieldErrors = {}\n for (const name of [\"number\", \"expiry\", \"cvv\"] as const) {\n const state = validity[name]\n if (state && !state.valid) fieldErrors[name] = state.message\n }\n const valid =\n preview ||\n ([\"number\", \"expiry\", \"cvv\"] as const).every(\n (name) => validity[name]?.valid === true\n )\n return {\n ready: ready || preview,\n preview,\n brand,\n loadError,\n valid,\n fieldErrors,\n tokenize,\n }\n}\n\n/** Display metadata of a tokenized card: never the PAN. */\nexport function collectCardDisplay(card?: CollectCard): {\n last_four?: string\n card_type?: string\n expiry_date?: string\n} {\n const digits = (card?.number ?? \"\").replace(/\\D/g, \"\")\n const exp = (card?.exp ?? \"\").replace(/\\D/g, \"\")\n return {\n ...(digits.length >= 4 ? { last_four: digits.slice(-4) } : {}),\n ...(card?.type ? { card_type: card.type } : {}),\n ...(exp.length === 4\n ? { expiry_date: `${exp.slice(0, 2)}/${exp.slice(2)}` }\n : {}),\n }\n}\n","// Stripe Elements appearance from the page's resolved theme tokens, so the\n// Payment Element matches our inputs (height, radius, type, colors).\nimport type { Appearance } from \"@stripe/stripe-js\"\n\nimport { toPlainColor } from \"#orck/lib/collect\"\n\nexport function stripeAppearance(host: HTMLElement): Appearance {\n const style = window.getComputedStyle(host)\n const token = (name: string) =>\n toPlainColor(style.getPropertyValue(name).trim()) || undefined\n const dark = !!host.closest(\".dark\")\n return {\n theme: dark ? \"night\" : \"stripe\",\n variables: {\n colorPrimary: token(\"--primary\"),\n colorBackground: token(\"--card\"),\n colorText: token(\"--foreground\"),\n colorTextSecondary: token(\"--muted-foreground\"),\n colorDanger: token(\"--destructive\"),\n fontFamily: style.fontFamily || undefined,\n fontSizeBase: \"14px\",\n borderRadius: \"9px\",\n spacingUnit: \"3px\",\n },\n rules: {\n \".Input\": {\n padding: \"9px 10px\",\n boxShadow: \"none\",\n borderColor: token(\"--border\") ?? \"\",\n },\n \".Input:focus\": {\n borderColor: token(\"--ring\") ?? \"\",\n boxShadow: \"none\",\n },\n \".Label\": { fontSize: \"13px\", fontWeight: \"500\", marginBottom: \"6px\" },\n \".Error\": { fontSize: \"12.5px\" },\n },\n }\n}\n","// Stripe Payment Element that saves a card in one call: Stripe's frames make\n// a payment method, and OpenRails saves it to the customer\n// (POST /v1/me/payment-methods). A bank that asks for 3-D Secure is answered\n// in the page (handleNextAction), then the save is confirmed.\nimport * as React from \"react\"\nimport type {\n Stripe,\n StripeElements,\n StripePaymentElementChangeEvent,\n} from \"@stripe/stripe-js\"\n\nimport type { BillingClient } from \"#orck/client/client\"\nimport { loadStripeFor } from \"#orck/lib/stripe\"\nimport { stripeAppearance } from \"#orck/lib/stripe-appearance\"\nimport type { PspConfig } from \"#orck/psp\"\n\nexport interface StripeCardHandle {\n /** Saves the entered card and returns its payment method id. */\n save(): Promise<string>\n /**\n * The entered card as Stripe's single-use payment method (`pm_`), for an\n * order to charge and save in one call.\n */\n tokenize(): Promise<string>\n /** Answers the bank's authentication of a payment or a card save. */\n handleNextAction(clientSecret: string): Promise<void>\n}\n\nexport const StripeCardEntry = React.forwardRef<\n StripeCardHandle,\n {\n psp: PspConfig\n client: BillingClient\n defaultCountry?: string\n /** Completeness of the entered card, from the element's change events. */\n onCompleteChange?: (complete: boolean) => void\n unavailableMessage: string\n verificationPendingMessage: string\n }\n>(function StripeCardEntry(\n {\n psp,\n client,\n defaultCountry,\n onCompleteChange,\n unavailableMessage,\n verificationPendingMessage,\n },\n ref\n) {\n const [error, setError] = React.useState<string>()\n const host = React.useRef<HTMLDivElement>(null)\n const mounted = React.useRef<{ stripe: Stripe; elements: StripeElements }>(\n null\n )\n const completeRef = React.useRef(onCompleteChange)\n React.useEffect(() => {\n completeRef.current = onCompleteChange\n })\n\n const publishable = psp.config?.publishable_key\n React.useEffect(() => {\n if (!publishable || !host.current) return\n let canceled = false\n let unmount: (() => void) | undefined\n void loadStripeFor(publishable).then(\n (stripe) => {\n if (canceled || !host.current) return\n const elements = stripe.elements({\n mode: \"setup\",\n paymentMethodTypes: [\"card\"],\n paymentMethodCreation: \"manual\",\n appearance: stripeAppearance(host.current),\n })\n // Cards only: the panel saves a card, so no Link bank or wallets.\n const element = elements.create(\"payment\", {\n wallets: { link: \"never\", applePay: \"never\", googlePay: \"never\" },\n ...(defaultCountry\n ? {\n defaultValues: {\n billingDetails: { address: { country: defaultCountry } },\n },\n }\n : {}),\n })\n element.on(\"change\", (event: StripePaymentElementChangeEvent) => {\n completeRef.current?.(event.complete)\n })\n element.mount(host.current)\n mounted.current = { stripe, elements }\n unmount = () => element.destroy()\n },\n (cause: unknown) => {\n if (!canceled)\n setError(cause instanceof Error ? cause.message : unavailableMessage)\n }\n )\n return () => {\n canceled = true\n mounted.current = null\n unmount?.()\n }\n }, [publishable, defaultCountry, unavailableMessage])\n\n React.useImperativeHandle(ref, () => {\n const tokenize = async () => {\n const current = mounted.current\n if (!current) throw new Error(unavailableMessage)\n setError(undefined)\n const validation = await current.elements.submit()\n if (validation.error)\n throw new Error(validation.error.message ?? unavailableMessage)\n const created = await current.stripe.createPaymentMethod({\n elements: current.elements,\n })\n if (created.error || !created.paymentMethod)\n throw new Error(created.error?.message ?? unavailableMessage)\n return created.paymentMethod.id\n }\n const handleNextAction = async (clientSecret: string) => {\n const current = mounted.current\n if (!current) throw new Error(unavailableMessage)\n const answered = await current.stripe.handleNextAction({ clientSecret })\n if (answered.error)\n throw new Error(answered.error.message ?? unavailableMessage)\n }\n return {\n tokenize,\n handleNextAction,\n async save() {\n let method = await client.addPaymentMethod({\n psp_id: psp.psp_id,\n token: await tokenize(),\n })\n const secret = method.next_action?.payload?.client_secret\n if (method.status === \"requires_action\" && secret) {\n await handleNextAction(secret)\n method = await client.confirmPaymentMethod(method.id)\n }\n if (method.status === \"requires_action\")\n throw new Error(verificationPendingMessage)\n return method.id\n },\n }\n }, [client, psp.psp_id, unavailableMessage, verificationPendingMessage])\n\n return (\n <div className=\"grid gap-2\">\n <div ref={host} data-testid=\"stripe-card-entry\" />\n {error ? (\n <p role=\"alert\" className=\"text-[13px] text-destructive\">\n {error}\n </p>\n ) : null}\n </div>\n )\n})\n","// Native card entry (driver \"card\"): the PSP declares card_entry: server, so\n// the page posts the card to OpenRails, which vaults it at the gateway. No\n// gateway script is loaded. The card lives in component state only until it\n// is submitted.\nimport * as React from \"react\"\n\nimport type { CollectFieldErrors } from \"#orck/lib/collect\"\n\n/** A card as OpenRails' `card` field takes it. */\nexport interface CardEntry {\n number: string\n exp_month: number\n exp_year: number\n cvc: string\n}\n\n/** What the buyer typed, as typed. */\nexport interface CardEntryInput {\n number: string\n expiry: string\n cvc: string\n}\n\nexport const FIELD_MESSAGES: Required<CollectFieldErrors> = {\n number: \"Enter a valid card number\",\n expiry: \"Enter a valid expiry date\",\n cvv: \"Enter a valid security code\",\n}\n\nconst digitsOf = (value: string) => value.replace(/\\D/g, \"\")\n\nfunction luhn(digits: string): boolean {\n let sum = 0\n for (let i = 0; i < digits.length; i++) {\n let d = digits.charCodeAt(digits.length - 1 - i) - 48\n if (i % 2 === 1) {\n d *= 2\n if (d > 9) d -= 9\n }\n sum += d\n }\n return sum % 10 === 0\n}\n\n/** The card network a number's leading digits name (\"\" when none). */\nexport function cardBrandOf(number: string): string {\n const d = digitsOf(number)\n const p = (n: number) => (d.length >= n ? Number(d.slice(0, n)) : -1)\n if (p(1) === 4) return \"visa\"\n if (p(2) === 34 || p(2) === 37) return \"amex\"\n if ((p(2) >= 51 && p(2) <= 55) || (p(4) >= 2221 && p(4) <= 2720))\n return \"mastercard\"\n if (p(4) === 6011 || p(2) === 65 || (p(3) >= 644 && p(3) <= 649))\n return \"discover\"\n if (p(2) === 35) return \"jcb\"\n if (p(2) === 36 || p(2) === 38 || (p(3) >= 300 && p(3) <= 305))\n return \"diners\"\n return \"\"\n}\n\n/** Groups a number as it is printed: 4-6-5 for Amex, fours otherwise. */\nexport function formatCardNumber(value: string): string {\n const d = digitsOf(value).slice(0, 19)\n if (cardBrandOf(d) === \"amex\")\n return [d.slice(0, 4), d.slice(4, 10), d.slice(10, 15)]\n .filter(Boolean)\n .join(\" \")\n return d.replace(/(\\d{4})(?=\\d)/g, \"$1 \")\n}\n\n/** MM / YY as it is typed. */\nexport function formatExpiry(value: string): string {\n const d = digitsOf(value).slice(0, 4)\n return d.length > 2 ? `${d.slice(0, 2)} / ${d.slice(2)}` : d\n}\n\nfunction parseExpiry(value: string, now: Date) {\n const d = digitsOf(value)\n if (d.length !== 4) return null\n const month = Number(d.slice(0, 2))\n const year = 2000 + Number(d.slice(2))\n if (month < 1 || month > 12) return null\n const lapsed =\n year < now.getFullYear() ||\n (year === now.getFullYear() && month < now.getMonth() + 1)\n return lapsed ? null : { month, year }\n}\n\n/** Every field's error; an empty object means the card is complete. */\nexport function cardEntryErrors(\n input: CardEntryInput,\n now = new Date()\n): CollectFieldErrors {\n const errors: CollectFieldErrors = {}\n const number = digitsOf(input.number)\n if (number.length < 12 || number.length > 19 || !luhn(number))\n errors.number = FIELD_MESSAGES.number\n if (!parseExpiry(input.expiry, now)) errors.expiry = FIELD_MESSAGES.expiry\n const cvc = digitsOf(input.cvc)\n const want = cardBrandOf(number) === \"amex\" ? 4 : 3\n if (cvc !== input.cvc.trim() || (cvc.length !== want && cvc.length !== 4))\n errors.cvv = FIELD_MESSAGES.cvv\n return errors\n}\n\n/** The card OpenRails takes, or null while any field is invalid. */\nexport function parseCardEntry(\n input: CardEntryInput,\n now = new Date()\n): CardEntry | null {\n if (Object.keys(cardEntryErrors(input, now)).length > 0) return null\n const expiry = parseExpiry(input.expiry, now)!\n return {\n number: digitsOf(input.number),\n exp_month: expiry.month,\n exp_year: expiry.year,\n cvc: digitsOf(input.cvc),\n }\n}\n\n/** A card's display facts, the ones a saved card is labelled with. */\nexport function cardEntryDisplay(card: CardEntry): {\n last_four: string\n card_type?: string\n expiry_date: string\n} {\n const brand = cardBrandOf(card.number)\n return {\n last_four: card.number.slice(-4),\n ...(brand ? { card_type: brand } : {}),\n expiry_date: `${String(card.exp_month).padStart(2, \"0\")}/${String(card.exp_year % 100).padStart(2, \"0\")}`,\n }\n}\n\nconst empty: CardEntryInput = { number: \"\", expiry: \"\", cvc: \"\" }\n\n/**\n * The state of one native card form. Errors show once a field was left;\n * `take` hands the card over and clears the form, so the page keeps it no\n * longer than the request that sends it.\n */\nexport function useCardEntry() {\n const [input, setInput] = React.useState<CardEntryInput>(empty)\n const [touched, setTouched] = React.useState<\n Partial<Record<keyof CardEntryInput, boolean>>\n >({})\n const errors = cardEntryErrors(input)\n const shown: CollectFieldErrors = {}\n if (touched.number && errors.number) shown.number = errors.number\n if (touched.expiry && errors.expiry) shown.expiry = errors.expiry\n if (touched.cvc && errors.cvv) shown.cvv = errors.cvv\n const clear = React.useCallback(() => {\n setInput(empty)\n setTouched({})\n }, [])\n return {\n input,\n fieldErrors: shown,\n valid: Object.keys(errors).length === 0,\n change: (field: keyof CardEntryInput, value: string) =>\n setInput((current) => ({\n ...current,\n [field]:\n field === \"number\"\n ? formatCardNumber(value)\n : field === \"expiry\"\n ? formatExpiry(value)\n : digitsOf(value).slice(0, 4),\n })),\n leave: (field: keyof CardEntryInput) =>\n setTouched((current) => ({ ...current, [field]: true })),\n take: (): CardEntry | null => {\n const card = parseCardEntry(input)\n if (!card) {\n setTouched({ number: true, expiry: true, cvc: true })\n return null\n }\n clear()\n return card\n },\n clear,\n }\n}\n\nexport type CardEntryState = ReturnType<typeof useCardEntry>\n","import * as React from \"react\"\nimport type { BillingAppearance } from \"./appearance\"\nimport { CardBillingFields } from \"./components/billing-fields\"\nimport { CardFields } from \"./components/card-fields\"\nimport { PayButton, TrustLine } from \"./components/pay-button\"\nimport {\n emptyNMIBilling,\n initialCountry,\n nmiBillingSchema,\n reuseNeedsOptIn,\n} from \"./lib/billing\"\nimport { collectCardDisplay, useCollectJS } from \"./lib/collect\"\nimport { cn } from \"cn\"\nimport { useScopeProps } from \"./scope-context\"\n\n// Only tokenized billing details cross the iframe boundary. PAN/CVC are never\n// accepted by this component or handed to the host callback.\nexport interface TokenizedCardData {\n payment_token: string\n name_on_card: string\n country: string\n zip?: string\n /** Display metadata from the gateway: last four, brand, MM/YY. */\n last_four?: string\n card_type?: string\n expiry_date?: string\n /** The customer's opt-in to keep the card, when the form asked for it. */\n reusable?: boolean\n}\nexport interface TokenizedCardFormProps {\n tokenizationKey: string\n tokenizationURL: string\n /**\n * The host's use of the card. Resolving `false` says it was definitely\n * refused (a decline): the form takes another card.\n */\n onTokenized: (card: TokenizedCardData) => Promise<void | boolean>\n submitLabel?: string\n disabled?: boolean\n /** Billing country to preselect; default: the browser locale's region. */\n defaultCountry?: string\n /**\n * The merchant the card would be kept with, for a one-off purchase: where\n * keeping it needs an opt-in (EEA, UK) the form asks, unticked.\n */\n saveOptInMerchant?: string\n /** Shown above the button (the terms the customer accepts). */\n terms?: React.ReactNode\n /** The name the charge carries on the card statement. */\n statementDescriptor?: string\n appearance?: BillingAppearance\n className?: string\n}\n\n// The host supplies consent and performs its authorized save-card operation.\n// This component neither creates a purchase nor implies payment success.\nexport function TokenizedCardForm({\n tokenizationKey,\n tokenizationURL,\n onTokenized,\n submitLabel = \"Save card\",\n disabled = false,\n defaultCountry,\n saveOptInMerchant,\n terms,\n statementDescriptor,\n appearance,\n className,\n}: TokenizedCardFormProps) {\n // Without its own appearance the form takes the provider's: the card\n // fields' colors are read from this scope.\n const scope = useScopeProps(appearance)\n const [keepCard, setKeepCard] = React.useState(false)\n const uid = React.useId().replace(/[^a-zA-Z0-9-]/g, \"\")\n const ids = React.useMemo(\n () => ({\n number: `orck-save-${uid}-number`,\n expiry: `orck-save-${uid}-expiry`,\n cvv: `orck-save-${uid}-cvv`,\n }),\n [uid]\n )\n const [billing, setBilling] = React.useState(() => ({\n ...emptyNMIBilling,\n country: initialCountry(defaultCountry),\n }))\n const [busy, setBusy] = React.useState(false)\n const [submitted, setSubmitted] = React.useState(false)\n const [error, setError] = React.useState<string>()\n const authorization = React.useRef({ generation: 0, disabled })\n React.useLayoutEffect(() => {\n authorization.current = {\n generation: authorization.current.generation + 1,\n disabled,\n }\n }, [tokenizationKey, tokenizationURL, disabled])\n const mounted = React.useRef(true)\n React.useEffect(() => {\n mounted.current = true\n return () => {\n mounted.current = false\n }\n }, [])\n const collect = useCollectJS({\n enabled: true,\n active: true,\n tokenizationKey,\n scriptURL: tokenizationURL,\n selectors: {\n number: `#${ids.number}`,\n expiry: `#${ids.expiry}`,\n cvv: `#${ids.cvv}`,\n },\n })\n // The button stays off until every required billing field is filled.\n const billingComplete = nmiBillingSchema.safeParse(billing).success\n const asksToKeep =\n saveOptInMerchant !== undefined && reuseNeedsOptIn(billing.country)\n const submit = async (event: React.FormEvent) => {\n event.preventDefault()\n if (disabled || busy || submitted) return\n const parsed = nmiBillingSchema.safeParse(billing)\n if (!parsed.success) {\n setError(parsed.error.issues[0]?.message ?? \"Check the billing details\")\n return\n }\n setBusy(true)\n setError(undefined)\n const generation = authorization.current.generation\n let sent = false\n try {\n const token = await collect.tokenize()\n if (\n !mounted.current ||\n authorization.current.generation !== generation ||\n authorization.current.disabled\n )\n return\n sent = true\n setSubmitted(true)\n const accepted = await onTokenized({\n payment_token: token.token,\n ...parsed.data,\n ...collectCardDisplay(token.card),\n ...(asksToKeep ? { reusable: keepCard } : {}),\n })\n if (accepted === false && mounted.current) setSubmitted(false)\n } catch (cause) {\n if (mounted.current)\n setError(\n sent\n ? \"The card-save result is not confirmed. Check your saved cards before starting another attempt.\"\n : cause instanceof Error\n ? cause.message\n : \"Card entry could not be completed.\"\n )\n } finally {\n if (mounted.current) setBusy(false)\n }\n }\n return (\n <div\n className={cn(scope.className, className)}\n data-orck-theme={scope[\"data-orck-theme\"]}\n style={scope.style}\n >\n <form\n aria-label=\"Secure card setup\"\n autoComplete=\"on\"\n className=\"grid gap-4\"\n onSubmit={(event) => void submit(event)}\n >\n <CardBillingFields\n idPrefix={`orck-save-${uid}`}\n value={billing}\n onChange={setBilling}\n disabled={disabled || busy || submitted}\n >\n <CardFields\n ids={ids}\n preview={collect.preview}\n brand={collect.brand}\n error={collect.loadError}\n fieldErrors={collect.fieldErrors}\n />\n </CardBillingFields>\n {asksToKeep ? (\n <label className=\"flex items-start gap-2 text-[13px] text-foreground\">\n <input\n type=\"checkbox\"\n className=\"mt-0.5\"\n checked={keepCard}\n onChange={(event) => setKeepCard(event.target.checked)}\n disabled={disabled || busy || submitted}\n />\n Save payment details to {saveOptInMerchant} for future purchases\n </label>\n ) : null}\n {terms ? (\n <p className=\"text-xs text-muted-foreground\">{terms}</p>\n ) : null}\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n ) : null}\n <PayButton\n label={submitLabel}\n processing={busy}\n disabled={\n disabled ||\n submitted ||\n !billingComplete ||\n !collect.ready ||\n !collect.valid ||\n Boolean(collect.loadError)\n }\n />\n {statementDescriptor ? (\n <p className=\"-mt-1 text-center text-xs text-muted-foreground\">\n The charge will appear as “{statementDescriptor}” on\n your card statement.\n </p>\n ) : (\n <TrustLine />\n )}\n </form>\n </div>\n )\n}\n","import * as React from \"react\"\n\nimport type { BillingAppearance } from \"./appearance\"\nimport { isBillingError } from \"./client/errors\"\nimport { CardBillingFields } from \"./components/billing-fields\"\nimport { PlatformCardForm } from \"./components/platform-card-form\"\nimport { NativeCardFields } from \"./components/card-fields\"\nimport { PayButton, TrustLine } from \"./components/pay-button\"\nimport {\n StripeCardEntry,\n type StripeCardHandle,\n} from \"./components/stripe-card\"\nimport { useMessages } from \"./i18n/context\"\nimport {\n billingDetailsOf,\n emptyNMIBilling,\n initialCountry,\n nmiBillingSchema,\n} from \"./lib/billing\"\nimport { useCardEntry } from \"./lib/card-entry\"\nimport { cardSetupDriver, type PspConfig } from \"./psp\"\nimport { useBillingContext } from \"./react/context\"\nimport {\n TokenizedCardForm,\n type TokenizedCardData,\n} from \"./tokenized-card-form\"\nimport { cn } from \"cn\"\nimport { useScopeProps } from \"./scope-context\"\n\nexport interface SavePaymentMethodProps {\n /** The PSP to save the card with, from OpenRails's payment config. */\n psp: PspConfig\n onSaved: (paymentMethodId: string) => void\n /** Billing country to preselect; default: the browser locale's region. */\n defaultCountry?: string\n submitLabel?: string\n appearance?: BillingAppearance\n className?: string\n}\n\n/**\n * Saves a card to the customer's account with any PSP OpenRails serves, in\n * the page. The PSP's configuration picks the flow: card data enters the\n * provider's own frames, or, for a PSP whose card_entry is server, is posted\n * to OpenRails. Requires `BillingProvider`.\n */\nexport function SavePaymentMethod(props: SavePaymentMethodProps) {\n const { t } = useMessages()\n // Without its own appearance the form takes the provider's, like the\n // panel around it.\n const scope = useScopeProps(props.appearance)\n const driver = cardSetupDriver(props.psp)\n if (!driver)\n return (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {t(\"paymentMethods.unavailable\")}\n </p>\n )\n return (\n <div\n className={cn(scope.className, \"grid gap-4\", props.className)}\n data-orck-theme={scope[\"data-orck-theme\"]}\n style={scope.style}\n >\n <p className=\"text-sm text-muted-foreground\">\n {t(\"paymentMethods.saveNotice\")}\n </p>\n {driver === \"platform\" ? (\n <PlatformSetup {...props} />\n ) : driver === \"collect_js\" ? (\n <TokenizedSetup {...props} />\n ) : driver === \"card\" ? (\n <NativeCardSetup {...props} />\n ) : (\n <ElementsSetup {...props} />\n )}\n </div>\n )\n}\n\n// Provider SDK errors carry customer-facing text (\"Your card was declined.\").\nconst describe = (m: ReturnType<typeof useMessages>, cause: unknown) =>\n !isBillingError(cause) && cause instanceof Error && cause.message\n ? cause.message\n : m.error(cause)\n\nfunction TokenizedSetup({\n psp,\n onSaved,\n submitLabel,\n appearance,\n defaultCountry,\n}: SavePaymentMethodProps) {\n const m = useMessages()\n const { client, notify } = useBillingContext()\n const [formKey, setFormKey] = React.useState(0)\n const [error, setError] = React.useState<string>()\n const save = async (card: TokenizedCardData) => {\n setError(undefined)\n let method\n try {\n method = await client.addPaymentMethod({\n psp_id: psp.psp_id,\n token: card.payment_token,\n billing_details: billingDetailsOf(card),\n })\n } catch (cause) {\n setError(describe(m, cause))\n setFormKey((key) => key + 1)\n return\n }\n notify({ type: \"payment_method.added\", paymentMethodId: method.id })\n onSaved(method.id)\n }\n return (\n <>\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n ) : null}\n <TokenizedCardForm\n key={formKey}\n tokenizationKey={psp.config!.tokenization_key!}\n tokenizationURL={psp.config!.tokenization_url!}\n onTokenized={save}\n defaultCountry={defaultCountry}\n submitLabel={submitLabel ?? m.t(\"paymentMethods.save\")}\n appearance={appearance}\n />\n </>\n )\n}\n\nfunction NativeCardSetup({\n psp,\n onSaved,\n submitLabel,\n defaultCountry,\n}: SavePaymentMethodProps) {\n const m = useMessages()\n const { client, notify } = useBillingContext()\n const uid = React.useId().replace(/[^a-zA-Z0-9-]/g, \"\")\n const ids = React.useMemo(\n () => ({\n number: `orck-save-${uid}-number`,\n expiry: `orck-save-${uid}-expiry`,\n cvv: `orck-save-${uid}-cvv`,\n }),\n [uid]\n )\n const card = useCardEntry()\n const [billing, setBilling] = React.useState(() => ({\n ...emptyNMIBilling,\n country: initialCountry(defaultCountry),\n }))\n const [busy, setBusy] = React.useState(false)\n const [error, setError] = React.useState<string>()\n\n const submit = async (event: React.FormEvent) => {\n event.preventDefault()\n if (busy) return\n const parsed = nmiBillingSchema.safeParse(billing)\n if (!parsed.success) {\n setError(parsed.error.issues[0]?.message ?? \"Check the billing details\")\n return\n }\n const entered = card.take()\n if (!entered) return\n setBusy(true)\n setError(undefined)\n try {\n const method = await client.addPaymentMethod({\n psp_id: psp.psp_id,\n card: entered,\n billing_details: billingDetailsOf(parsed.data),\n })\n notify({ type: \"payment_method.added\", paymentMethodId: method.id })\n onSaved(method.id)\n } catch (cause) {\n setError(describe(m, cause))\n } finally {\n setBusy(false)\n }\n }\n\n return (\n <form\n aria-label=\"Secure card setup\"\n autoComplete=\"on\"\n className=\"grid gap-4\"\n noValidate\n onSubmit={(event) => void submit(event)}\n >\n <CardBillingFields\n idPrefix={`orck-save-${uid}`}\n value={billing}\n onChange={setBilling}\n disabled={busy}\n >\n <NativeCardFields ids={ids} card={card} disabled={busy} />\n </CardBillingFields>\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n ) : null}\n <PayButton\n label={submitLabel ?? m.t(\"paymentMethods.save\")}\n processing={busy}\n disabled={!card.valid || !nmiBillingSchema.safeParse(billing).success}\n />\n <TrustLine />\n </form>\n )\n}\n\nfunction ElementsSetup({\n psp,\n onSaved,\n submitLabel,\n defaultCountry,\n}: SavePaymentMethodProps) {\n const m = useMessages()\n const { t } = m\n const { client, notify } = useBillingContext()\n const card = React.useRef<StripeCardHandle>(null)\n const [complete, setComplete] = React.useState(false)\n const [busy, setBusy] = React.useState(false)\n const [error, setError] = React.useState<string>()\n const country = React.useMemo(\n () => initialCountry(defaultCountry),\n [defaultCountry]\n )\n\n const submit = async (event: React.FormEvent) => {\n event.preventDefault()\n if (!card.current || busy) return\n setBusy(true)\n setError(undefined)\n try {\n const id = await card.current.save()\n notify({ type: \"payment_method.added\", paymentMethodId: id })\n onSaved(id)\n } catch (cause) {\n setError(describe(m, cause))\n } finally {\n setBusy(false)\n }\n }\n\n return (\n <form className=\"grid gap-4\" onSubmit={(event) => void submit(event)}>\n <StripeCardEntry\n ref={card}\n psp={psp}\n client={client}\n defaultCountry={country || undefined}\n onCompleteChange={setComplete}\n unavailableMessage={t(\"paymentMethods.unavailable\")}\n verificationPendingMessage={t(\"paymentMethods.verificationPending\")}\n />\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n ) : null}\n <PayButton\n label={submitLabel ?? t(\"paymentMethods.save\")}\n processing={busy}\n disabled={!complete}\n />\n <TrustLine />\n </form>\n )\n}\n\nfunction PlatformSetup({\n psp,\n onSaved,\n submitLabel,\n defaultCountry,\n}: SavePaymentMethodProps) {\n const m = useMessages()\n const { client, notify } = useBillingContext()\n const [error, setError] = React.useState<string>()\n const save = async (card: TokenizedCardData) => {\n setError(undefined)\n let method\n try {\n method = await client.addPaymentMethod({\n psp_id: psp.psp_id,\n token: card.payment_token,\n billing_details: billingDetailsOf(card),\n })\n } catch (cause) {\n setError(describe(m, cause))\n // A definite refusal can collect a corrected card. A lost response\n // keeps the original collection so Retry recovers the same save.\n if (\n isBillingError(cause) &&\n (cause.status === 400 || cause.status === 402)\n )\n return false\n throw cause\n }\n notify({ type: \"payment_method.added\", paymentMethodId: method.id })\n onSaved(method.id)\n return true\n }\n return (\n <>\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n ) : null}\n <PlatformCardForm\n publicKey={psp.config!.public_api_key!}\n purpose=\"setup\"\n defaultCountry={defaultCountry}\n submitLabel={submitLabel ?? m.t(\"paymentMethods.save\")}\n disabled={false}\n onTokenized={save}\n />\n </>\n )\n}\n","import * as React from \"react\"\nimport { cn } from \"cn\"\n\n/** Polite confirmation line that clears itself. */\nexport function useNotice(): [React.ReactNode, (text: string) => void] {\n const [text, setText] = React.useState<string | null>(null)\n React.useEffect(() => {\n if (!text) return\n const timer = setTimeout(() => setText(null), 6000)\n return () => clearTimeout(timer)\n }, [text])\n const node = (\n <p\n role=\"status\"\n aria-live=\"polite\"\n className={cn(\"text-sm text-muted-foreground\", text ? \"pt-3\" : \"sr-only\")}\n >\n {text}\n </p>\n )\n return [node, setText]\n}\n","import * as React from \"react\"\nimport { HugeiconsIcon } from \"@hugeicons/react\"\nimport { Add01Icon, Delete02Icon } from \"@hugeicons/core-free-icons\"\n\nimport type { BillingAppearance } from \"#orck/appearance\"\nimport type { BillingError } from \"#orck/client/errors\"\nimport type { PaymentMethod } from \"#orck/client/types\"\nimport { CardBrandPlate } from \"#orck/components/card-brands\"\nimport {\n AlertDialog,\n AlertDialogCancel,\n AlertDialogContent,\n AlertDialogDescription,\n AlertDialogFooter,\n AlertDialogHeader,\n AlertDialogTitle,\n} from \"#orck/components/ui/alert-dialog\"\nimport { Button } from \"#orck/components/ui/button\"\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogHeader,\n DialogTitle,\n} from \"#orck/components/ui/dialog\"\nimport { Spinner } from \"#orck/components/ui/spinner\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport type { Translator } from \"#orck/i18n/messages\"\nimport { useCustomerConfig } from \"#orck/react/config\"\nimport { usePaymentMethods } from \"#orck/react/hooks\"\nimport { useScopeProps } from \"#orck/scope-context\"\nimport { canSavePaymentMethod, cardRetryAfter, routedPsps } from \"#orck/psp\"\nimport { SavePaymentMethod } from \"#orck/save-payment-method\"\nimport { cardText, RESET } from \"./format\"\nimport { EmptyState, ErrorState, ListSkeleton, Section } from \"./section\"\nimport { useNotice } from \"./notice\"\nimport { BillingStatusBadge } from \"./status-badge\"\n\nexport interface PaymentMethodsPanelProps {\n /**\n * Offers to make a card the default for this currency: it pays the\n * currency's usage orders and every subscription in it without its own card.\n */\n defaultCurrency?: string\n /** Billing country to preselect when adding a card. */\n defaultCountry?: string\n appearance?: BillingAppearance\n className?: string\n}\n\nfunction methodLabel(method: PaymentMethod, m: Translator): string {\n return cardText(method.card, m)\n}\n\nfunction removeMessage(error: BillingError, m: Translator): string {\n if (error.status === 409 && error.code === \"resource_conflict\")\n return m.t(\"paymentMethods.inUse\")\n if (error.status === 503 || error.code === \"invalid_response\")\n return m.t(\"paymentMethods.removeFailed\")\n return m.error(error)\n}\n\n/**\n * The customer's saved cards. \"Add card\" offers each PSP of the merchant's\n * payment setup (`GET /me/config`) that saves a card in the page.\n */\nexport function PaymentMethodsPanel({\n defaultCurrency,\n defaultCountry,\n appearance,\n className,\n}: PaymentMethodsPanelProps) {\n const m = useMessages()\n const { t } = m\n const scope = useScopeProps(appearance)\n const state = usePaymentMethods()\n const [removing, setRemoving] = React.useState<PaymentMethod | null>(null)\n const [removeError, setRemoveError] = React.useState<string | null>(null)\n const [rowError, setRowError] = React.useState<{\n id: string\n message: string\n } | null>(null)\n const [adding, setAdding] = React.useState(false)\n const config = useCustomerConfig()\n const psps = routedPsps(config.config?.payment.psps ?? [])\n const savable = psps.filter(canSavePaymentMethod)\n const retryAfter = savable.length > 0 ? null : cardRetryAfter(psps)\n const { refetch: refetchConfig } = config\n React.useEffect(() => {\n if (retryAfter === null) return\n const timer = setTimeout(refetchConfig, retryAfter * 1000)\n return () => clearTimeout(timer)\n }, [retryAfter, refetchConfig, config.config])\n const [pspId, setPspId] = React.useState<string>()\n const psp = savable.find((item) => item.psp_id === pspId) ?? savable[0]\n const [notice, announce] = useNotice()\n const currency = defaultCurrency?.toUpperCase()\n\n const confirmRemove = async () => {\n if (!removing) return\n setRemoveError(null)\n const result = await state.remove(removing.id)\n if (result) {\n setRemoveError(removeMessage(result, m))\n return\n }\n setRemoving(null)\n announce(t(\"paymentMethods.removed\"))\n }\n\n const makeDefault = async (method: PaymentMethod) => {\n if (!currency) return\n setRowError(null)\n const error = await state.setDefault(method.id, currency)\n if (error) setRowError({ id: method.id, message: m.error(error) })\n else announce(t(\"paymentMethods.defaultUpdated\"))\n }\n\n let body: React.ReactNode\n const methods = state.methods\n if (methods === null && state.error) {\n body = <ErrorState error={state.error} onRetry={state.refetch} />\n } else if (methods === null) {\n body = <ListSkeleton />\n } else if (methods.length === 0) {\n body = (\n <EmptyState\n title={t(\"paymentMethods.empty\")}\n description={t(\"paymentMethods.emptyDescription\")}\n />\n )\n } else {\n body = (\n <ul className=\"-my-1 divide-y divide-border\">\n {methods.map((method) => {\n const label = methodLabel(method, m)\n const users = (method.subscriptions ?? [])\n .map((s) => s.display_name)\n .filter(Boolean)\n const health = method.health?.expiry_status\n const defaults = method.default_currencies ?? []\n const pending = state.pending[method.id]\n const meta = [\n users.length > 0 &&\n t(\"paymentMethods.usedBy\", { names: users.join(\", \") }),\n ].filter(Boolean)\n return (\n <li\n key={method.id}\n data-testid=\"payment-method-row\"\n data-payment-method-id={method.id}\n className=\"flex flex-wrap items-center gap-x-3 gap-y-2 py-3.5\"\n >\n <CardBrandPlate\n brand={method.card?.brand ?? undefined}\n fallback={(method.card?.brand ?? \"card\").slice(0, 4)}\n />\n <div className=\"grid min-w-40 flex-1 gap-0.5\">\n <div className=\"flex flex-wrap items-center gap-x-2 gap-y-1\">\n <span className=\"text-sm font-medium tabular-nums\">\n {label}\n </span>\n {health === \"expired\" || health === \"expiring_soon\" ? (\n <BillingStatusBadge status={health} />\n ) : method.health?.active === false ? (\n <BillingStatusBadge status=\"needs_attention\" />\n ) : null}\n {defaults.length > 0 ? (\n <BillingStatusBadge\n status=\"default\"\n label={t(\"paymentMethods.defaultFor\", {\n currencies: defaults.join(\", \"),\n })}\n />\n ) : null}\n </div>\n {meta.length > 0 ? (\n <p className=\"text-sm text-muted-foreground tabular-nums\">\n {meta.join(\" · \")}\n </p>\n ) : null}\n {rowError?.id === method.id ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {rowError.message}\n </p>\n ) : null}\n </div>\n <div className=\"ml-auto flex items-center gap-1\">\n {currency && !defaults.includes(currency) ? (\n <Button\n variant=\"ghost\"\n size=\"sm\"\n className=\"text-muted-foreground\"\n disabled={!!pending}\n onClick={() => void makeDefault(method)}\n >\n {pending === \"default\" ? <Spinner /> : null}\n {t(\"paymentMethods.makeDefault\")}\n </Button>\n ) : null}\n <Button\n variant=\"destructive\"\n size=\"icon-sm\"\n className=\"bg-red-600 text-white hover:bg-red-700\"\n aria-label={t(\"paymentMethods.removeLabel\", { label })}\n title={t(\"paymentMethods.remove\")}\n disabled={!!pending}\n onClick={() => {\n setRemoveError(null)\n setRemoving(method)\n }}\n >\n {pending === \"remove\" ? (\n <Spinner />\n ) : (\n <HugeiconsIcon icon={Delete02Icon} aria-hidden />\n )}\n </Button>\n </div>\n </li>\n )\n })}\n </ul>\n )\n }\n\n const removingBusy = removing\n ? state.pending[removing.id] === \"remove\"\n : false\n const removingLabel = removing ? methodLabel(removing, m) : \"\"\n\n return (\n <Section\n title={t(\"paymentMethods.title\")}\n description={t(\"paymentMethods.description\")}\n appearance={appearance}\n className={className}\n data-testid=\"payment-methods-panel\"\n action={\n psp ? (\n <Button variant=\"outline\" size=\"sm\" onClick={() => setAdding(true)}>\n <HugeiconsIcon\n icon={Add01Icon}\n aria-hidden\n data-icon=\"inline-start\"\n />\n {t(\"paymentMethods.add\")}\n </Button>\n ) : null\n }\n >\n {body}\n {methods !== null && state.error ? (\n <div className=\"pt-3\">\n <ErrorState error={state.error} onRetry={state.refetch} />\n </div>\n ) : null}\n {config.error ? (\n <div className=\"pt-3\">\n <ErrorState\n error={config.error}\n message={t(\"paymentMethods.addUnavailable\")}\n onRetry={config.refetch}\n />\n </div>\n ) : retryAfter !== null ? (\n <p role=\"status\" className=\"pt-3 text-sm text-muted-foreground\">\n {t(\"paymentMethods.addUnavailable\")}\n </p>\n ) : null}\n {notice}\n\n <AlertDialog\n open={removing !== null}\n onOpenChange={(open) => {\n if (!open && !removingBusy) setRemoving(null)\n }}\n >\n <AlertDialogContent\n className={`${scope.className} ${RESET} bg-popover text-popover-foreground`}\n data-orck-theme={scope[\"data-orck-theme\"]}\n style={scope.style}\n >\n <AlertDialogHeader>\n <AlertDialogTitle>\n {t(\"paymentMethods.removeTitle\", { label: removingLabel })}\n </AlertDialogTitle>\n <AlertDialogDescription>\n {t(\"paymentMethods.removeDescription\")}\n </AlertDialogDescription>\n </AlertDialogHeader>\n {removeError ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {removeError}\n </p>\n ) : null}\n <AlertDialogFooter>\n <AlertDialogCancel disabled={removingBusy}>\n {t(\"common.cancel\")}\n </AlertDialogCancel>\n <Button\n variant=\"destructive\"\n disabled={removingBusy}\n onClick={() => void confirmRemove()}\n >\n {removingBusy ? <Spinner /> : null}\n {t(\"paymentMethods.removeConfirm\")}\n </Button>\n </AlertDialogFooter>\n </AlertDialogContent>\n </AlertDialog>\n\n {psp ? (\n <Dialog open={adding} onOpenChange={setAdding}>\n <DialogContent\n className={`${scope.className} ${RESET} max-h-[calc(100dvh-2rem)] overflow-y-auto bg-popover text-popover-foreground`}\n data-orck-theme={scope[\"data-orck-theme\"]}\n style={scope.style}\n >\n <DialogHeader>\n <DialogTitle>{t(\"paymentMethods.addTitle\")}</DialogTitle>\n <DialogDescription>\n {t(\"paymentMethods.addDescription\")}\n </DialogDescription>\n </DialogHeader>\n {savable.length > 1 ? (\n <label className=\"grid gap-1.5 text-sm\">\n {t(\"paymentMethods.provider\")}\n <select\n className=\"h-9 rounded-md border border-input bg-transparent px-2\"\n value={psp.psp_id}\n onChange={(event) => setPspId(event.target.value)}\n >\n {savable.map((item) => (\n <option key={item.psp_id} value={item.psp_id}>\n {item.display_name}\n </option>\n ))}\n </select>\n </label>\n ) : null}\n <SavePaymentMethod\n key={psp.psp_id}\n psp={psp}\n defaultCountry={defaultCountry}\n appearance={appearance}\n onSaved={() => {\n setAdding(false)\n announce(t(\"paymentMethods.added\"))\n }}\n />\n </DialogContent>\n </Dialog>\n ) : null}\n </Section>\n )\n}\n","import * as React from \"react\"\nimport { cn } from \"cn\"\n\nfunction Textarea({ className, ...props }: React.ComponentProps<\"textarea\">) {\n return (\n <textarea\n data-slot=\"textarea\"\n className={cn(\n \"flex field-sizing-content min-h-16 w-full rounded-md border border-input bg-transparent px-2.5 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40\",\n className\n )}\n {...props}\n />\n )\n}\n\nexport { Textarea }\n","import * as React from \"react\"\n\nimport type { BillingAppearance } from \"#orck/appearance\"\n\nimport {\n CANCEL_REASON_MAX,\n CANCEL_REASON_MIN,\n isWalletRejection,\n} from \"#orck/client/client\"\nimport type { BillingError } from \"#orck/client/errors\"\nimport {\n AlertDialog,\n AlertDialogCancel,\n AlertDialogContent,\n AlertDialogDescription,\n AlertDialogFooter,\n AlertDialogHeader,\n AlertDialogTitle,\n} from \"#orck/components/ui/alert-dialog\"\nimport { Button } from \"#orck/components/ui/button\"\nimport { Label } from \"#orck/components/ui/label\"\nimport { Spinner } from \"#orck/components/ui/spinner\"\nimport { Textarea } from \"#orck/components/ui/textarea\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport type { SubscriptionAction } from \"#orck/react/hooks\"\nimport { useScopeProps } from \"#orck/scope-context\"\nimport { RESET } from \"./format\"\n\n// Key it per subscription so each opening starts blank.\nexport interface CancelSubscriptionDialogProps {\n open: boolean\n onOpenChange: (open: boolean) => void\n /** Subscription display name. */\n name: string\n /** Offers an optional on-chain cancellation when a wallet is available. */\n onChain?: boolean\n /** In-flight stage, when cancelling. */\n pending?: SubscriptionAction\n /** Resolves null on success; the dialog then closes. */\n onConfirm: (reason: string, revokeOnChain: boolean) => Promise<BillingError | null>\n appearance?: BillingAppearance\n}\n\nexport function CancelSubscriptionDialog({\n open,\n onOpenChange,\n name,\n onChain = false,\n pending,\n onConfirm,\n appearance,\n}: CancelSubscriptionDialogProps) {\n const m = useMessages()\n const { t } = m\n const scope = useScopeProps(appearance)\n const reasonId = React.useId()\n const hintId = React.useId()\n const [reason, setReason] = React.useState(\"\")\n const [revokeOnChain, setRevokeOnChain] = React.useState(false)\n const [touched, setTouched] = React.useState(false)\n const [error, setError] = React.useState<BillingError | null>(null)\n const busy = pending !== undefined\n\n const length = reason.trim().length\n const tooShort = length < CANCEL_REASON_MIN\n const confirm = async () => {\n setTouched(true)\n if (tooShort || busy) return\n setError(null)\n const result = await onConfirm(reason, revokeOnChain)\n if (!result) onOpenChange(false)\n else if (!isWalletRejection(result)) setError(result)\n }\n\n const stageLabel =\n pending === \"cancel\" && revokeOnChain\n ? t(\"cancel.preparing\")\n : pending === \"signing\"\n ? t(\"cancel.signing\")\n : pending === \"confirming\"\n ? t(\"cancel.confirming\")\n : busy\n ? t(\"cancel.working\")\n : revokeOnChain\n ? t(\"cancel.confirmWallet\")\n : t(\"cancel.confirm\")\n\n return (\n <AlertDialog\n open={open}\n onOpenChange={(next) => {\n if (!next && busy) return\n onOpenChange(next)\n }}\n >\n <AlertDialogContent\n className={`${scope.className} ${RESET} bg-popover text-popover-foreground`}\n data-orck-theme={scope[\"data-orck-theme\"]}\n style={scope.style}\n >\n <form\n className=\"grid gap-5\"\n noValidate\n onSubmit={(event) => {\n event.preventDefault()\n void confirm()\n }}\n >\n <AlertDialogHeader>\n <AlertDialogTitle>{t(\"cancel.title\", { name })}</AlertDialogTitle>\n <AlertDialogDescription>\n {t(\"cancel.description\")}\n </AlertDialogDescription>\n </AlertDialogHeader>\n <div className=\"grid gap-2\">\n <Label htmlFor={reasonId}>{t(\"cancel.reasonLabel\")}</Label>\n <Textarea\n id={reasonId}\n value={reason}\n maxLength={CANCEL_REASON_MAX}\n placeholder={t(\"cancel.reasonPlaceholder\")}\n aria-describedby={hintId}\n aria-invalid={touched && tooShort ? true : undefined}\n disabled={busy}\n required\n rows={3}\n className=\"[font:inherit]\"\n onChange={(event) => setReason(event.target.value)}\n onBlur={() => length > 0 && setTouched(true)}\n />\n <div\n id={hintId}\n className=\"flex justify-between gap-3 text-xs text-muted-foreground\"\n >\n <span className={touched && tooShort ? \"text-destructive\" : \"\"}>\n {touched && tooShort\n ? t(\"cancel.reasonTooShort\", { min: CANCEL_REASON_MIN })\n : \"\"}\n </span>\n <span className=\"tabular-nums\">\n {t(\"cancel.reasonHint\", {\n count: reason.length,\n max: CANCEL_REASON_MAX,\n })}\n </span>\n </div>\n </div>\n {onChain ? (\n <label className=\"flex items-start gap-2 text-sm\">\n <input\n type=\"checkbox\"\n checked={revokeOnChain}\n disabled={busy}\n onChange={(event) => setRevokeOnChain(event.target.checked)}\n />\n <span>{t(\"cancel.revokeOnChain\")}</span>\n </label>\n ) : null}\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {m.error(error)}\n </p>\n ) : null}\n <AlertDialogFooter>\n <AlertDialogCancel disabled={busy}>\n {t(\"cancel.keep\")}\n </AlertDialogCancel>\n <Button type=\"submit\" variant=\"destructive\" disabled={busy}>\n {busy ? <Spinner /> : null}\n {stageLabel}\n </Button>\n </AlertDialogFooter>\n </form>\n </AlertDialogContent>\n </AlertDialog>\n )\n}\n","\"use client\"\n\nimport { Radio as RadioPrimitive } from \"@base-ui/react/radio\"\nimport { RadioGroup as RadioGroupPrimitive } from \"@base-ui/react/radio-group\"\nimport { cn } from \"cn\"\n\nfunction RadioGroup({ className, ...props }: RadioGroupPrimitive.Props) {\n return (\n <RadioGroupPrimitive\n data-slot=\"radio-group\"\n className={cn(\"grid w-full gap-3\", className)}\n {...props}\n />\n )\n}\n\nfunction RadioGroupItem({ className, ...props }: RadioPrimitive.Root.Props) {\n return (\n <RadioPrimitive.Root\n data-slot=\"radio-group-item\"\n className={cn(\n \"group/radio-group-item peer relative flex aspect-square size-4 shrink-0 rounded-full border border-input outline-none group-has-[:focus-visible]/field-label:ring-0 group-has-[:focus-visible]/field-label:not-data-checked:border-input after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-input/30 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground group-has-[:focus-visible]/field-label:data-checked:border-primary dark:data-checked:bg-primary\",\n className\n )}\n {...props}\n >\n <RadioPrimitive.Indicator\n data-slot=\"radio-group-indicator\"\n className=\"flex size-4 items-center justify-center\"\n >\n <span className=\"absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2 rounded-full bg-primary-foreground\" />\n </RadioPrimitive.Indicator>\n </RadioPrimitive.Root>\n )\n}\n\nexport { RadioGroup, RadioGroupItem }\n","import * as React from \"react\"\n\nimport type { BillingAppearance } from \"#orck/appearance\"\nimport { cn } from \"cn\"\n\nimport type { BillingError } from \"#orck/client/errors\"\nimport type { PaymentMethod, Subscription } from \"#orck/client/types\"\nimport { CardBrandPlate } from \"#orck/components/card-brands\"\nimport { Button } from \"#orck/components/ui/button\"\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from \"#orck/components/ui/dialog\"\nimport { Label } from \"#orck/components/ui/label\"\nimport { RadioGroup, RadioGroupItem } from \"#orck/components/ui/radio-group\"\nimport { Spinner } from \"#orck/components/ui/spinner\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport { usePaymentMethods } from \"#orck/react/hooks\"\nimport { useCustomerConfig } from \"#orck/react/config\"\nimport { canSavePaymentMethod, routedPsps } from \"#orck/psp\"\nimport { SavePaymentMethod } from \"#orck/save-payment-method\"\nimport { useScopeProps } from \"#orck/scope-context\"\nimport { cardText, RESET } from \"./format\"\nimport { ErrorState, ListSkeleton } from \"./section\"\n\n/** The choice that makes the subscription follow the default card. */\nconst FOLLOW_DEFAULT = \"default\"\n\n/** Cards the subscription's PSP can charge; expired cards are left out. */\nfunction eligibleCards(\n s: Subscription,\n methods: readonly PaymentMethod[]\n): PaymentMethod[] {\n return methods.filter(\n (m) =>\n m.health?.active !== false &&\n m.health?.expiry_status !== \"expired\" &&\n (!s.psp_id || !m.psp_id || m.psp_id === s.psp_id) &&\n (!s.rail || !m.rail || m.rail === s.rail)\n )\n}\n\nexport interface ChangeCardDialogProps {\n subscription: Subscription | null\n name: string\n onOpenChange: (open: boolean) => void\n pending: boolean\n /**\n * The subscription's own card, or null to follow the default card. Resolves\n * null on success; the dialog then closes.\n */\n onConfirm: (paymentMethodId: string | null) => Promise<BillingError | null>\n mode?: \"change\" | \"resume\"\n description?: string\n appearance?: BillingAppearance\n}\n\nexport function ChangeCardDialog({\n subscription,\n name,\n onOpenChange,\n pending,\n onConfirm,\n mode = \"change\",\n description,\n appearance,\n}: ChangeCardDialogProps) {\n const scope = useScopeProps(appearance)\n return (\n <Dialog\n open={subscription !== null}\n onOpenChange={(next) => {\n if (!next && pending) return\n onOpenChange(next)\n }}\n >\n <DialogContent\n showCloseButton={false}\n className={`${scope.className} ${RESET} max-h-[calc(100dvh-2rem)] overflow-y-auto bg-popover text-popover-foreground`}\n data-orck-theme={scope[\"data-orck-theme\"]}\n style={scope.style}\n >\n {subscription ? (\n <ChangeCardForm\n subscription={subscription}\n name={name}\n pending={pending}\n onCancel={() => onOpenChange(false)}\n onConfirm={onConfirm}\n mode={mode}\n description={description}\n appearance={appearance}\n />\n ) : null}\n </DialogContent>\n </Dialog>\n )\n}\n\n// Mounted only while open, so the card list loads on demand.\nfunction ChangeCardForm({\n subscription,\n name,\n pending,\n onCancel,\n onConfirm,\n mode,\n description,\n appearance,\n}: {\n subscription: Subscription\n name: string\n pending: boolean\n onCancel: () => void\n onConfirm: (paymentMethodId: string | null) => Promise<BillingError | null>\n mode: \"change\" | \"resume\"\n description?: string\n appearance?: BillingAppearance\n}) {\n const m = useMessages()\n const { t } = m\n const idPrefix = React.useId()\n const methods = usePaymentMethods()\n const current = subscription.payment_method_id ?? FOLLOW_DEFAULT\n const [selected, setSelected] = React.useState(current)\n const [error, setError] = React.useState<BillingError | null>(null)\n const [adding, setAdding] = React.useState(false)\n const [submitting, setSubmitting] = React.useState(false)\n const initialized = React.useRef(false)\n const busy = pending || submitting\n const cards = React.useMemo(\n () =>\n methods.methods ? eligibleCards(subscription, methods.methods) : null,\n [methods.methods, subscription]\n )\n React.useEffect(() => {\n if (mode !== \"resume\" || cards === null || initialized.current) return\n initialized.current = true\n setSelected(\n cards.some((card) => card.id === current) ? current : (cards[0]?.id ?? \"\")\n )\n setAdding(cards.length === 0)\n }, [cards, current, mode])\n const currency = subscription.price?.currency?.toUpperCase()\n const defaultCard = currency\n ? cards?.find((c) => (c.default_currencies ?? []).includes(currency))\n : undefined\n const choices = [\n ...(mode === \"change\" && defaultCard\n ? [{ id: FOLLOW_DEFAULT, card: defaultCard }]\n : []),\n ...(cards ?? []).map((card) => ({ id: card.id, card })),\n ]\n const canSwitch = choices.some((c) => c.id !== current)\n const selectable = choices.some((c) => c.id === selected)\n\n const confirm = async () => {\n if (!selectable || (mode === \"change\" && selected === current) || busy)\n return\n setError(null)\n setSubmitting(true)\n try {\n const result = await onConfirm(\n selected === FOLLOW_DEFAULT ? null : selected\n )\n if (result) setError(result)\n } finally {\n setSubmitting(false)\n }\n }\n\n let list: React.ReactNode\n if (cards === null && methods.error) {\n list = <ErrorState error={methods.error} onRetry={methods.refetch} />\n } else if (cards === null) {\n list = <ListSkeleton rows={2} />\n } else if (mode === \"resume\") {\n list = adding ? (\n <ResumeCardEntry\n subscription={subscription}\n appearance={appearance}\n onSaved={(id) => {\n setSelected(id)\n setAdding(false)\n methods.refetch()\n }}\n />\n ) : (\n <label className=\"grid gap-2 text-sm\">\n {t(\"changeCard.title\", { name })}\n <select\n aria-label={t(\"changeCard.title\", { name })}\n disabled={busy}\n value={selectable ? selected : \"\"}\n onChange={(event) => setSelected(event.target.value)}\n className=\"h-10 rounded-md border border-input bg-background px-3\"\n >\n {!selectable ? (\n <option value=\"\" disabled>\n {t(\"resume.chooseCard\")}\n </option>\n ) : null}\n {choices.map(({ id, card }) => (\n <option key={id} value={id}>\n {cardText(card.card, m)}\n </option>\n ))}\n </select>\n </label>\n )\n } else {\n list = (\n <RadioGroup\n value={selected}\n onValueChange={(next) => {\n if (typeof next === \"string\" && next) setSelected(next)\n }}\n disabled={busy}\n aria-label={t(\"changeCard.title\", { name })}\n className=\"grid gap-0\"\n >\n {choices.map(({ id: value, card }) => {\n const id = `${idPrefix}-${value}`\n const label = cardText(card.card, m)\n return (\n <Label\n key={value}\n htmlFor={id}\n data-testid=\"change-card-option\"\n className={cn(\n \"flex cursor-pointer items-center gap-3 py-1.5 select-none\",\n busy && \"cursor-default\"\n )}\n >\n <RadioGroupItem id={id} value={value} />\n <CardBrandPlate\n brand={card.card?.brand ?? undefined}\n fallback={(card.card?.brand ?? \"card\").slice(0, 4)}\n />\n <span className=\"min-w-0 flex-1 truncate text-sm font-medium tabular-nums\">\n {value === FOLLOW_DEFAULT\n ? t(\"changeCard.useDefault\", { card: label })\n : label}\n </span>\n {value === current ? (\n <span className=\"shrink-0 text-xs text-muted-foreground\">\n {t(\"changeCard.current\")}\n </span>\n ) : null}\n </Label>\n )\n })}\n </RadioGroup>\n )\n }\n\n return (\n <div className=\"grid gap-5\">\n <DialogHeader>\n <DialogTitle>\n {t(mode === \"resume\" ? \"resume.title\" : \"changeCard.title\", { name })}\n </DialogTitle>\n <DialogDescription>\n {description ??\n (cards !== null && !canSwitch\n ? t(\"changeCard.none\")\n : t(\"changeCard.description\"))}\n </DialogDescription>\n </DialogHeader>\n {list}\n {cards !== null && methods.error ? (\n <ErrorState error={methods.error} onRetry={methods.refetch} />\n ) : null}\n {mode === \"resume\" &&\n !adding &&\n cards !== null &&\n !selectable &&\n !methods.loading &&\n !methods.error ? (\n <p role=\"status\" className=\"text-sm text-muted-foreground\">\n {t(\"resume.savedCardUnavailable\")}\n </p>\n ) : null}\n {mode === \"resume\" && cards !== null ? (\n <Button\n type=\"button\"\n variant=\"link\"\n disabled={busy || (adding && cards.length === 0)}\n onClick={() => setAdding(!adding)}\n >\n {adding ? t(\"changeCard.title\", { name }) : t(\"paymentMethods.add\")}\n </Button>\n ) : null}\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {m.error(error)}\n </p>\n ) : null}\n <DialogFooter>\n <Button\n type=\"button\"\n variant=\"outline\"\n disabled={busy}\n onClick={onCancel}\n >\n {t(\"common.cancel\")}\n </Button>\n {!adding ? (\n <Button\n type=\"button\"\n onClick={() => void confirm()}\n disabled={\n busy || !selectable || (mode === \"change\" && selected === current)\n }\n >\n {busy ? <Spinner /> : null}\n {t(mode === \"resume\" ? \"resume.confirm\" : \"changeCard.confirm\")}\n </Button>\n ) : null}\n </DialogFooter>\n </div>\n )\n}\n\nfunction ResumeCardEntry({\n subscription,\n appearance,\n onSaved,\n}: {\n subscription: Subscription\n appearance?: BillingAppearance\n onSaved: (id: string) => void\n}) {\n const { t } = useMessages()\n const config = useCustomerConfig()\n const available = routedPsps(config.config?.payment.psps ?? []).filter(\n (psp) =>\n canSavePaymentMethod(psp) &&\n (!subscription.psp_id || psp.psp_id === subscription.psp_id) &&\n (!subscription.rail || psp.rail === subscription.rail)\n )\n const [selected, select] = React.useState<string>()\n const psp = available.find((item) => item.psp_id === selected) ?? available[0]\n if (config.error)\n return <ErrorState error={config.error} onRetry={config.refetch} />\n if (config.loading) return <ListSkeleton rows={2} />\n if (!psp)\n return (\n <p role=\"status\" className=\"text-sm text-muted-foreground\">\n {t(\"paymentMethods.addUnavailable\")}\n </p>\n )\n return (\n <div className=\"grid gap-4\">\n {available.length > 1 ? (\n <label className=\"grid gap-2 text-sm\">\n {t(\"paymentMethods.provider\")}\n <select\n value={psp.psp_id}\n onChange={(event) => select(event.target.value)}\n >\n {available.map((item) => (\n <option key={item.psp_id} value={item.psp_id}>\n {item.display_name}\n </option>\n ))}\n </select>\n </label>\n ) : null}\n <SavePaymentMethod\n key={psp.psp_id}\n psp={psp}\n appearance={appearance}\n onSaved={onSaved}\n />\n </div>\n )\n}\n","import type { BillingClient } from \"./client/client\"\nimport type { SubscriptionChange } from \"./client/types\"\nimport { loadStripeFor } from \"./lib/stripe\"\nimport { canAuthenticatePayment, type PspConfig } from \"./psp\"\n\n/**\n * Completes the issuer's authentication (3-D Secure) a subscription change\n * waits on, then confirms the change and answers it. A change with no\n * `authenticate` next action is answered as it is.\n */\nexport async function authenticateChange(\n client: BillingClient,\n subscriptionId: string,\n change: SubscriptionChange,\n psp: PspConfig\n): Promise<SubscriptionChange> {\n const next = change.next_action\n const secret = next?.payload?.client_secret\n if (\n change.status !== \"requires_action\" ||\n next?.type !== \"authenticate\" ||\n !secret ||\n !canAuthenticatePayment(psp)\n )\n return change\n const stripe = await loadStripeFor(psp.config!.publishable_key!)\n const answered = await stripe.handleNextAction({ clientSecret: secret })\n if (answered.error)\n throw new Error(answered.error.message ?? \"Authentication failed.\")\n return client.confirmSubscriptionChange(subscriptionId)\n}\n","import * as React from \"react\"\nimport { cn } from \"cn\"\n\nimport type { BillingAppearance } from \"#orck/appearance\"\nimport { authenticateChange } from \"#orck/authenticate\"\nimport type { SendSolanaTransaction } from \"#orck/client/client\"\nimport { isBillingError, type BillingError } from \"#orck/client/errors\"\nimport type {\n CurrencyScales,\n Subscription,\n SubscriptionChangeOption,\n} from \"#orck/client/types\"\nimport { Button } from \"#orck/components/ui/button\"\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from \"#orck/components/ui/dialog\"\nimport { Label } from \"#orck/components/ui/label\"\nimport { RadioGroup, RadioGroupItem } from \"#orck/components/ui/radio-group\"\nimport { Spinner } from \"#orck/components/ui/spinner\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport type { Translator } from \"#orck/i18n/messages\"\nimport { useCurrencyScales, useCustomerConfig } from \"#orck/react/config\"\nimport { useBillingContext } from \"#orck/react/context\"\nimport {\n useChangeOptions,\n type ChangeOptionsState,\n type SubscriptionAction,\n type SubscriptionsState,\n} from \"#orck/react/hooks\"\nimport { useScopeProps, useUiSettings } from \"#orck/scope-context\"\nimport { formatDate, formatMoney, intervalLabel, RESET } from \"./format\"\nimport { ErrorState, ListSkeleton } from \"./section\"\n\n// A plan change is a money write: its Idempotency-Key is reused until the\n// change has a definitive answer, so retrying a lost answer replays it.\nconst keys = new Map<string, string>()\nconst slot = (subscriptionId: string, priceId: string) =>\n JSON.stringify([subscriptionId, priceId])\n\nfunction changeKey(subscriptionId: string, priceId: string): string {\n const id = slot(subscriptionId, priceId)\n const key = keys.get(id) ?? crypto.randomUUID()\n keys.set(id, key)\n return key\n}\n\n// The change may have landed: the next attempt must replay the same key.\nconst uncertain = (error: BillingError) =>\n error.code === \"subscription_change_in_flight\" ||\n error.status === 0 ||\n error.status >= 500\n\nexport interface ChangePlanProps {\n subscription: Subscription\n name: string\n pending: SubscriptionAction | undefined\n changeSubscription: SubscriptionsState[\"changeSubscription\"]\n sendSolanaTransaction?: SendSolanaTransaction\n /** Announces the outcome once the dialog closes. */\n onChanged: (text: string) => void\n appearance?: BillingAppearance\n}\n\n/** The row's Change plan button and dialog, when another plan is open to it. */\nexport function ChangePlan({\n subscription,\n name,\n pending,\n changeSubscription,\n sendSolanaTransaction,\n onChanged,\n appearance,\n}: ChangePlanProps) {\n const m = useMessages()\n const { t } = m\n const { locale } = useUiSettings()\n const { client, notify } = useBillingContext()\n const { config: merchant } = useCustomerConfig()\n const options = useChangeOptions(subscription.id)\n const [open, setOpen] = React.useState(false)\n const [working, setWorking] = React.useState(false)\n\n if (!open && !options.options?.length) return null\n\n const confirm = async (\n option: SubscriptionChangeOption\n ): Promise<string | null> => {\n const id = subscription.id\n const priceId = option.price.id\n let result = await changeSubscription(\n id,\n { priceId, idempotencyKey: changeKey(id, priceId) },\n sendSolanaTransaction\n )\n if (isBillingError(result)) {\n if (!uncertain(result)) keys.delete(slot(id, priceId))\n return m.error(result)\n }\n const next = result.next_action\n if (next?.type === \"redirect_to_url\" && next.url) {\n window.location.assign(next.url)\n return null\n }\n if (result.status === \"requires_action\" && next?.type === \"authenticate\") {\n const psp = merchant?.payment.psps.find((p) => p.psp_id === next.psp_id)\n if (!psp) return m.t(\"paymentMethods.unavailable\")\n try {\n result = await authenticateChange(client, id, result, psp)\n } catch (err) {\n if (isBillingError(err)) return m.error(err)\n return (err instanceof Error && err.message) || m.t(\"errors.generic\")\n }\n notify({\n type: \"subscription.changed\",\n subscriptionId: id,\n change: result,\n })\n }\n if (result.status === \"requires_action\")\n return m.t(\"changePlan.actionRequired\")\n if (result.status !== \"processing\") keys.delete(slot(id, priceId))\n if (result.status === \"blocked\")\n return result.message || m.t(\"errors.generic\")\n setOpen(false)\n const product = option.product.display_name || name\n const date = formatDate(\n result.delayed_start ?? result.next_charge_date,\n locale\n )\n onChanged(\n result.status === \"processing\"\n ? t(\"changePlan.processing\")\n : result.effective === \"period_end\" && date\n ? t(\"changePlan.scheduled\", { name: product, date })\n : t(\"changePlan.done\", { name: product })\n )\n return null\n }\n\n return (\n <>\n <Button\n variant=\"ghost\"\n size=\"sm\"\n disabled={!!pending}\n aria-label={t(\"subscriptions.changePlanLabel\", { name })}\n onClick={() => {\n options.refetch()\n setOpen(true)\n }}\n >\n {t(\"subscriptions.changePlan\")}\n </Button>\n <ChangePlanDialog\n open={open}\n onOpenChange={setOpen}\n name={name}\n options={options}\n busy={working || !!pending}\n stage={pending}\n onConfirm={async (option) => {\n setWorking(true)\n try {\n return await confirm(option)\n } finally {\n setWorking(false)\n }\n }}\n appearance={appearance}\n />\n </>\n )\n}\n\nfunction ChangePlanDialog({\n open,\n onOpenChange,\n appearance,\n busy,\n ...form\n}: {\n open: boolean\n onOpenChange: (open: boolean) => void\n appearance?: BillingAppearance\n} & ChangePlanFormProps) {\n const scope = useScopeProps(appearance)\n return (\n <Dialog\n open={open}\n onOpenChange={(next) => {\n if (!next && busy) return\n onOpenChange(next)\n }}\n >\n <DialogContent\n showCloseButton={false}\n className={`${scope.className} ${RESET} bg-popover text-popover-foreground`}\n data-orck-theme={scope[\"data-orck-theme\"]}\n style={scope.style}\n >\n {open ? (\n <ChangePlanForm\n {...form}\n busy={busy}\n onCancel={() => onOpenChange(false)}\n />\n ) : null}\n </DialogContent>\n </Dialog>\n )\n}\n\ninterface ChangePlanFormProps {\n name: string\n options: ChangeOptionsState\n busy: boolean\n stage: SubscriptionAction | undefined\n /** Resolves null on success, else the message to show. */\n onConfirm: (option: SubscriptionChangeOption) => Promise<string | null>\n onCancel?: () => void\n}\n\nfunction ChangePlanForm({\n name,\n options,\n busy,\n stage,\n onConfirm,\n onCancel,\n}: ChangePlanFormProps) {\n const m = useMessages()\n const { t } = m\n const { locale } = useUiSettings()\n const scales = useCurrencyScales()\n const idPrefix = React.useId()\n const [selected, setSelected] = React.useState(\"\")\n const [error, setError] = React.useState<string | null>(null)\n const list = options.options\n const chosen = list?.find((o) => o.price.id === selected)\n\n let body: React.ReactNode\n if (list === null && options.error) {\n body = <ErrorState error={options.error} onRetry={options.refetch} />\n } else if (list === null) {\n body = <ListSkeleton rows={2} />\n } else {\n body = (\n <RadioGroup\n value={selected}\n onValueChange={(next) => {\n if (typeof next === \"string\" && next) setSelected(next)\n }}\n disabled={busy}\n aria-label={t(\"changePlan.title\", { name })}\n className=\"grid gap-0\"\n >\n {list.map((option) => {\n const id = `${idPrefix}-${option.price.id}`\n const price = formatMoney(\n option.price.unit_amount,\n option.price.currency,\n scales,\n locale\n )\n const interval = intervalLabel(option.price, m)\n return (\n <Label\n key={option.price.id}\n htmlFor={id}\n data-testid=\"change-plan-option\"\n className={cn(\n \"flex cursor-pointer items-start gap-3 py-2 select-none\",\n busy && \"cursor-default\"\n )}\n >\n <RadioGroupItem\n id={id}\n value={option.price.id}\n className=\"mt-0.5\"\n />\n <span className=\"grid min-w-0 flex-1 gap-0.5\">\n <span className=\"text-sm font-medium\">\n {option.product.display_name}\n {price ? (\n <span className=\"font-normal text-muted-foreground tabular-nums\">\n {\" · \"}\n {price}\n {interval ? ` ${interval}` : null}\n </span>\n ) : null}\n </span>\n <span className=\"text-xs font-normal text-muted-foreground tabular-nums\">\n {optionTerms(option, m, scales, locale)}\n </span>\n </span>\n </Label>\n )\n })}\n </RadioGroup>\n )\n }\n\n return (\n <form\n className=\"grid gap-5\"\n noValidate\n onSubmit={(event) => {\n event.preventDefault()\n if (!chosen || busy) return\n setError(null)\n void onConfirm(chosen).then(setError)\n }}\n >\n <DialogHeader>\n <DialogTitle>{t(\"changePlan.title\", { name })}</DialogTitle>\n <DialogDescription>\n {list?.length === 0\n ? t(\"changePlan.none\")\n : t(\"changePlan.description\")}\n </DialogDescription>\n </DialogHeader>\n {body}\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n ) : null}\n <DialogFooter>\n <Button\n type=\"button\"\n variant=\"outline\"\n disabled={busy}\n onClick={onCancel}\n >\n {t(\"common.cancel\")}\n </Button>\n <Button type=\"submit\" disabled={busy || !chosen}>\n {busy ? <Spinner /> : null}\n {stage === \"signing\"\n ? t(\"changePlan.signing\")\n : stage === \"confirming\"\n ? t(\"changePlan.confirming\")\n : t(\"changePlan.confirm\")}\n </Button>\n </DialogFooter>\n </form>\n )\n}\n\n/** What the change charges and when, from its preview. */\nfunction optionTerms(\n option: SubscriptionChangeOption,\n m: Translator,\n scales: CurrencyScales,\n locale?: string\n): string {\n const p = option.preview\n const next = formatMoney(p.next_charge_amount, p.currency, scales, locale)\n const date = formatDate(p.next_charge_date, locale)\n if (!next || !date) return p.message ?? \"\"\n if (p.effective !== \"now\")\n return m.t(\"changePlan.atPeriodEnd\", { next, date })\n const amount = formatMoney(p.amount_due_now, p.currency, scales, locale)\n if (!amount) return p.message ?? \"\"\n return m.t(\n p.is_estimate ? \"changePlan.chargeNowEstimate\" : \"changePlan.chargeNow\",\n {\n amount,\n next,\n date,\n }\n )\n}\n","import type { BillingAppearance } from \"#orck/appearance\"\nimport {\n AlertDialog,\n AlertDialogCancel,\n AlertDialogContent,\n AlertDialogDescription,\n AlertDialogFooter,\n AlertDialogHeader,\n AlertDialogTitle,\n} from \"#orck/components/ui/alert-dialog\"\nimport { Button } from \"#orck/components/ui/button\"\nimport { Spinner } from \"#orck/components/ui/spinner\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport { useScopeProps } from \"#orck/scope-context\"\nimport { RESET } from \"./format\"\n\n// Resuming re-arms renewals: the customer confirms they'll be charged again.\nexport function ResumeSubscriptionDialog({\n open,\n onOpenChange,\n name,\n price,\n date,\n busy,\n onConfirm,\n appearance,\n}: {\n open: boolean\n onOpenChange: (open: boolean) => void\n name: string\n /** The renewal amount, formatted. */\n price: string | null\n /** The next renewal date, formatted. */\n date: string | null\n busy: boolean\n onConfirm: () => void\n appearance?: BillingAppearance\n}) {\n const m = useMessages()\n const t = m.t\n const scope = useScopeProps(appearance)\n return (\n <AlertDialog\n open={open}\n onOpenChange={(next) => {\n if (!next && busy) return\n onOpenChange(next)\n }}\n >\n <AlertDialogContent\n className={`${scope.className} ${RESET} bg-popover text-popover-foreground`}\n data-orck-theme={scope[\"data-orck-theme\"]}\n style={scope.style}\n >\n <AlertDialogHeader>\n <AlertDialogTitle>{t(\"resume.title\", { name })}</AlertDialogTitle>\n <AlertDialogDescription>\n {price && date\n ? t(\"resume.description\", { price, date })\n : t(\"resume.descriptionNoDate\")}\n </AlertDialogDescription>\n </AlertDialogHeader>\n <AlertDialogFooter>\n <AlertDialogCancel disabled={busy}>{t(\"resume.keepCanceled\")}</AlertDialogCancel>\n <Button type=\"button\" disabled={busy} onClick={onConfirm}>\n {busy ? <Spinner /> : null}\n {t(\"resume.confirm\")}\n </Button>\n </AlertDialogFooter>\n </AlertDialogContent>\n </AlertDialog>\n )\n}\n","import * as React from \"react\"\nimport { HugeiconsIcon } from \"@hugeicons/react\"\nimport { ArrowUpRight01Icon } from \"@hugeicons/core-free-icons\"\nimport { cn } from \"cn\"\n\nimport type { BillingAppearance } from \"#orck/appearance\"\nimport type { SendSolanaTransaction } from \"#orck/client/client\"\nimport type { Subscription } from \"#orck/client/types\"\nimport { Button, buttonVariants } from \"#orck/components/ui/button\"\nimport { Spinner } from \"#orck/components/ui/spinner\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport { useSubscriptions, type SubscriptionsOptions } from \"#orck/react/hooks\"\nimport { useCurrencyScales } from \"#orck/react/config\"\nimport { useUiSettings } from \"#orck/scope-context\"\nimport { CancelSubscriptionDialog } from \"./cancel-dialog\"\nimport { ChangeCardDialog } from \"./change-card-dialog\"\nimport { ChangePlan } from \"./change-plan\"\nimport { ResumeSubscriptionDialog } from \"./resume-dialog\"\nimport {\n brandName,\n changeable,\n formatDate,\n formatMoney,\n intervalLabel,\n isEnding,\n isLive,\n LIVE_STATUSES,\n subscriptionName,\n} from \"./format\"\nimport { EmptyState, ErrorState, ListSkeleton, Section } from \"./section\"\nimport { useNotice } from \"./notice\"\nimport { BillingStatusBadge } from \"./status-badge\"\n\nexport interface SubscriptionsPanelProps extends SubscriptionsOptions {\n /**\n * Wallet for Solana subscriptions: plan changes and the optional on-chain\n * cancellation.\n */\n sendSolanaTransaction?: SendSolanaTransaction\n /** Empty-state link to the host's plans page (uses `navigate` if set). */\n plansHref?: string\n /** Host content under a row, e.g. a plan-change control. */\n renderSubscriptionFooter?: (subscription: Subscription) => React.ReactNode\n appearance?: BillingAppearance\n className?: string\n}\n\n// Canceled engine subscriptions support choosing a new card before resume.\n// Provider-managed and wallet subscriptions retain their own resume flow.\nconst resumesWithCard = (s: Subscription) =>\n (s.rail === \"nmi\" || s.rail === \"stripe\") && s.collection_policy === \"engine\"\n\nexport function SubscriptionsPanel({\n sendSolanaTransaction,\n plansHref,\n renderSubscriptionFooter,\n appearance,\n className,\n ...options\n}: SubscriptionsPanelProps) {\n const m = useMessages()\n const { t } = m\n const { locale, navigate } = useUiSettings()\n const state = useSubscriptions(options)\n const scales = useCurrencyScales()\n const [cancelling, setCancelling] = React.useState<Subscription | null>(null)\n const [resuming, setResuming] = React.useState<Subscription | null>(null)\n const [changingCard, setChangingCard] = React.useState<Subscription | null>(\n null\n )\n const [rowError, setRowError] = React.useState<{\n id: string\n message: string\n } | null>(null)\n const [notice, announce] = useNotice()\n\n const rows = React.useMemo(() => {\n const list = state.subscriptions ?? []\n return [...list.filter(isLive), ...list.filter((s) => !isLive(s))]\n }, [state.subscriptions])\n\n const resume = async (s: Subscription, paymentMethodId: string | null) => {\n setRowError(null)\n if (resumesWithCard(s) && paymentMethodId !== s.payment_method_id) {\n const error = await state.setPaymentMethod(s.id, paymentMethodId)\n if (error) return error\n }\n const error = await state.resume(s.id)\n if (!error) {\n setResuming(null)\n announce(t(\"subscriptions.resumed\"))\n }\n return error\n }\n\n const onChain = cancelling?.rail === \"solana\"\n\n let body: React.ReactNode\n if (state.subscriptions === null && state.error) {\n body = <ErrorState error={state.error} onRetry={state.refetch} />\n } else if (state.subscriptions === null) {\n body = <ListSkeleton />\n } else if (rows.length === 0) {\n body = (\n <EmptyState\n title={t(\"subscriptions.empty\")}\n description={t(\"subscriptions.emptyDescription\")}\n action={\n plansHref ? (\n <a\n href={plansHref}\n className={buttonVariants({ variant: \"outline\", size: \"sm\" })}\n onClick={(event) => {\n if (!navigate) return\n event.preventDefault()\n navigate(plansHref)\n }}\n >\n {t(\"subscriptions.browsePlans\")}\n </a>\n ) : null\n }\n />\n )\n } else {\n body = (\n <ul className=\"-my-1 divide-y divide-border\">\n {rows.map((s) => {\n const live = isLive(s)\n const pending = state.pending[s.id]\n const name = subscriptionName(s, m)\n const price = s.price\n ? formatMoney(s.price.unit_amount, s.price.currency, scales, locale)\n : null\n const interval = intervalLabel(s.price, m)\n const periodEnd = formatDate(s.current_period_ends_at, locale)\n const accessEnd = formatDate(s.access?.ends_at, locale)\n const endedAt = formatDate(\n s.ended_at ?? s.canceled_at ?? s.current_period_ends_at,\n locale\n )\n const scheduled = isEnding(s)\n const renews = live && !scheduled && !!s.price?.billing_interval_hours\n const when = !live\n ? s.status === \"canceled\"\n ? t(\"subscriptions.noMorePayments\")\n : endedAt && t(\"subscriptions.endedOn\", { date: endedAt })\n : renews && periodEnd\n ? t(\"subscriptions.renews\", { date: periodEnd })\n : accessEnd\n ? t(\"subscriptions.endsOn\", { date: accessEnd })\n : t(\"subscriptions.noMorePayments\")\n const paidWith = !renews\n ? null\n : s.rail === \"solana\"\n ? t(\"subscriptions.wallet\")\n : s.card?.last4\n ? t(\"subscriptions.paidWith\", {\n brand: brandName(\n s.card.brand,\n t(\"paymentMethods.fallbackBrand\")\n ),\n last4: s.card.last4,\n })\n : null\n const portal = live && !scheduled ? s.cancel_portal_url : null\n const canCancel = LIVE_STATUSES.has(s.status) && !scheduled && !portal\n const canChangeCard =\n ((s.resumable && s.collection_policy === \"engine\") ||\n ((s.status === \"active\" ||\n s.status === \"past_due\" ||\n s.status === \"awaiting_method\" ||\n s.status === \"unverified\") &&\n !scheduled)) &&\n !portal &&\n s.rail !== \"solana\" &&\n (s.collection_policy === \"engine\" ||\n s.collection_policy === \"nmi_schedule\")\n const status = s.cancel_scheduled ? \"cancel_scheduled\" : s.status\n const footer = renderSubscriptionFooter?.(s)\n return (\n <li\n key={s.id}\n data-testid=\"subscription-row\"\n data-subscription-id={s.id}\n className=\"grid gap-3 py-4 @md:grid-cols-[1fr_auto] @md:items-center\"\n >\n <div className=\"grid min-w-0 gap-1\">\n <div className=\"flex flex-wrap items-center gap-x-2 gap-y-1\">\n <span\n className={cn(\n \"truncate text-sm font-semibold\",\n !live && \"text-muted-foreground\"\n )}\n >\n {name}\n </span>\n <BillingStatusBadge status={status} />\n </div>\n <p className=\"text-sm text-muted-foreground tabular-nums\">\n {[when, paidWith].filter(Boolean).join(\" · \") ||\n t(\"common.notAvailable\")}\n </p>\n {price ? (\n <p\n className={cn(\n \"text-sm tabular-nums\",\n !live && \"text-muted-foreground\"\n )}\n >\n <span className=\"font-medium\">{price}</span>\n {interval ? (\n <span className=\"text-muted-foreground\"> {interval}</span>\n ) : null}\n </p>\n ) : null}\n {s.status === \"past_due\" || s.status === \"awaiting_method\" ? (\n <p className=\"text-sm text-destructive\">\n {t(\"subscriptions.pastDue\")}\n </p>\n ) : null}\n {rowError?.id === s.id ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {rowError.message}\n </p>\n ) : null}\n </div>\n <div className=\"flex flex-wrap gap-2 @md:justify-end\">\n {s.resumable ? (\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={!!pending}\n onClick={() => {\n setRowError(null)\n setResuming(s)\n }}\n >\n {pending === \"resume\" ? <Spinner /> : null}\n {pending === \"resume\"\n ? t(\"subscriptions.updating\")\n : t(\"subscriptions.resume\")}\n </Button>\n ) : null}\n {portal ? (\n <a\n href={portal}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className={buttonVariants({\n variant: \"outline\",\n size: \"sm\",\n })}\n >\n {t(\"subscriptions.manageAtProvider\")}\n <HugeiconsIcon icon={ArrowUpRight01Icon} aria-hidden />\n </a>\n ) : null}\n {changeable(s) &&\n (s.rail !== \"solana\" || sendSolanaTransaction) ? (\n <ChangePlan\n subscription={s}\n name={name}\n pending={pending}\n changeSubscription={state.changeSubscription}\n sendSolanaTransaction={sendSolanaTransaction}\n onChanged={announce}\n appearance={appearance}\n />\n ) : null}\n {canChangeCard ? (\n <Button\n variant=\"ghost\"\n size=\"sm\"\n disabled={!!pending}\n aria-label={t(\"subscriptions.changeCardLabel\", { name })}\n onClick={() => {\n setRowError(null)\n setChangingCard(s)\n }}\n >\n {pending === \"payment_method\" ? <Spinner /> : null}\n {t(\"subscriptions.changeCard\")}\n </Button>\n ) : null}\n {canCancel ? (\n <Button\n size=\"sm\"\n className=\"bg-red-600 text-white hover:bg-red-700\"\n disabled={!!pending}\n aria-label={t(\"subscriptions.cancelLabel\", { name })}\n onClick={() => {\n setRowError(null)\n setCancelling(s)\n }}\n >\n {pending === \"cancel\" ||\n (cancelling?.id === s.id && !!pending) ? (\n <Spinner />\n ) : null}\n {t(\"subscriptions.cancel\")}\n </Button>\n ) : null}\n </div>\n {footer ? (\n <div\n data-testid=\"subscription-footer\"\n className=\"border-t border-border/60 pt-3 @md:col-span-2\"\n >\n {footer}\n </div>\n ) : null}\n </li>\n )\n })}\n </ul>\n )\n }\n\n return (\n <Section\n title={t(\"subscriptions.title\")}\n description={t(\"subscriptions.description\")}\n appearance={appearance}\n className={className}\n data-testid=\"subscriptions-panel\"\n >\n {body}\n {state.subscriptions !== null && state.error ? (\n <div className=\"pt-3\">\n <ErrorState error={state.error} onRetry={state.refetch} />\n </div>\n ) : null}\n {notice}\n <ChangeCardDialog\n key={`card-${changingCard?.id ?? \"closed\"}`}\n subscription={changingCard}\n name={changingCard ? subscriptionName(changingCard, m) : \"\"}\n onOpenChange={(open) => !open && setChangingCard(null)}\n appearance={appearance}\n pending={\n !!changingCard && state.pending[changingCard.id] === \"payment_method\"\n }\n onConfirm={async (paymentMethodId) => {\n if (!changingCard) return null\n const error = await state.setPaymentMethod(\n changingCard.id,\n paymentMethodId\n )\n if (!error) {\n setChangingCard(null)\n announce(t(\"changeCard.done\"))\n }\n return error\n }}\n />\n <ChangeCardDialog\n key={`resume-${resuming?.id ?? \"closed\"}`}\n subscription={resuming && resumesWithCard(resuming) ? resuming : null}\n mode=\"resume\"\n onOpenChange={(open) => !open && setResuming(null)}\n name={resuming ? subscriptionName(resuming, m) : \"\"}\n description={\n resuming?.price && resuming.current_period_ends_at\n ? t(\"resume.description\", {\n price:\n formatMoney(\n resuming.price.unit_amount,\n resuming.price.currency,\n scales,\n locale\n ) ?? \"\",\n date: formatDate(resuming.current_period_ends_at, locale) ?? \"\",\n })\n : t(\"resume.descriptionNoDate\")\n }\n pending={resuming ? !!state.pending[resuming.id] : false}\n onConfirm={(paymentMethodId) =>\n resuming ? resume(resuming, paymentMethodId) : Promise.resolve(null)\n }\n appearance={appearance}\n />\n <ResumeSubscriptionDialog\n open={!!resuming && !resumesWithCard(resuming)}\n onOpenChange={(open) => !open && setResuming(null)}\n name={resuming ? subscriptionName(resuming, m) : \"\"}\n price={\n resuming?.price\n ? formatMoney(\n resuming.price.unit_amount,\n resuming.price.currency,\n scales,\n locale\n )\n : null\n }\n date={formatDate(resuming?.current_period_ends_at, locale)}\n busy={resuming ? !!state.pending[resuming.id] : false}\n onConfirm={async () => {\n if (!resuming) return\n const error = await resume(resuming, null)\n if (error) {\n setRowError({ id: resuming.id, message: m.error(error) })\n setResuming(null)\n }\n }}\n appearance={appearance}\n />\n <CancelSubscriptionDialog\n key={cancelling?.id ?? \"closed\"}\n open={cancelling !== null}\n onOpenChange={(open) => !open && setCancelling(null)}\n name={cancelling ? subscriptionName(cancelling, m) : \"\"}\n onChain={onChain && !!sendSolanaTransaction}\n appearance={appearance}\n pending={cancelling ? state.pending[cancelling.id] : undefined}\n onConfirm={async (reason, revokeOnChain) => {\n if (!cancelling) return null\n const error = await state.cancel(\n cancelling.id,\n reason,\n sendSolanaTransaction,\n revokeOnChain\n )\n if (!error) announce(t(\"cancel.done\"))\n return error\n }}\n />\n </Section>\n )\n}\n","import { cn } from \"cn\"\n\nimport type { BillingAppearance } from \"#orck/appearance\"\nimport type { SendSolanaTransaction } from \"#orck/client/client\"\nimport { BillingUiRoot } from \"#orck/scope\"\nimport { PaymentHistory } from \"./payment-history\"\nimport { PaymentMethodsPanel } from \"./payment-methods-panel\"\nimport {\n SubscriptionsPanel,\n type SubscriptionsPanelProps,\n} from \"./subscriptions-panel\"\n\nexport interface AccountBillingProps {\n /**\n * Offers to make a card the default for this currency: it pays the\n * currency's usage orders and every subscription in it without its own card.\n */\n defaultCurrency?: string\n /** Billing country to preselect when adding a card. */\n defaultCountry?: string\n sendSolanaTransaction?: SendSolanaTransaction\n plansHref?: string\n renderSubscriptionFooter?: SubscriptionsPanelProps[\"renderSubscriptionFooter\"]\n historyPageSize?: number\n appearance?: BillingAppearance\n className?: string\n}\n\n/** Subscriptions, payment methods and history in one column. */\nexport function AccountBilling({\n defaultCurrency,\n defaultCountry,\n sendSolanaTransaction,\n plansHref,\n renderSubscriptionFooter,\n historyPageSize,\n appearance,\n className,\n}: AccountBillingProps) {\n return (\n <BillingUiRoot\n appearance={appearance}\n className={cn(\"grid gap-6\", className)}\n data-testid=\"account-billing\"\n >\n <SubscriptionsPanel\n sendSolanaTransaction={sendSolanaTransaction}\n plansHref={plansHref}\n renderSubscriptionFooter={renderSubscriptionFooter}\n appearance={appearance}\n />\n <PaymentMethodsPanel\n defaultCurrency={defaultCurrency}\n defaultCountry={defaultCountry}\n appearance={appearance}\n />\n <PaymentHistory pageSize={historyPageSize} appearance={appearance} />\n </BillingUiRoot>\n )\n}\n","import { cn } from \"cn\"\n\nimport type { BillingAppearance } from \"#orck/appearance\"\nimport { buttonVariants } from \"#orck/components/ui/button\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport { useSubscriptions } from \"#orck/react/hooks\"\nimport { useScopeProps, useUiSettings } from \"#orck/scope-context\"\nimport { isLive, RESET } from \"./format\"\n\nexport interface RenewalPromptProps {\n /** The host's plans page (uses `navigate` if set). */\n plansHref: string\n appearance?: BillingAppearance\n className?: string\n}\n\n/**\n * Invites a customer whose subscriptions have all ended back to the plans\n * page; renders nothing otherwise. A host that grants access some other way\n * leaves it out for customers who have that access.\n */\nexport function RenewalPrompt({\n plansHref,\n appearance,\n className,\n}: RenewalPromptProps) {\n const { t } = useMessages()\n const { navigate } = useUiSettings()\n const scope = useScopeProps(appearance)\n const { subscriptions } = useSubscriptions()\n if (!subscriptions?.length || subscriptions.some(isLive)) return null\n return (\n <div\n data-testid=\"renewal-prompt\"\n data-orck-theme={scope[\"data-orck-theme\"]}\n style={scope.style}\n className={cn(\n scope.className,\n RESET,\n \"flex flex-wrap items-center justify-between gap-3 rounded-xl border border-border bg-card p-4 text-card-foreground\",\n className\n )}\n >\n <div className=\"grid min-w-0 gap-1\">\n <p className=\"text-sm font-semibold\">{t(\"renewal.title\")}</p>\n <p className=\"text-sm text-muted-foreground\">\n {t(\"renewal.description\")}\n </p>\n </div>\n <a\n href={plansHref}\n className={buttonVariants({ size: \"sm\" })}\n onClick={(event) => {\n if (!navigate) return\n event.preventDefault()\n navigate(plansHref)\n }}\n >\n {t(\"renewal.action\")}\n </a>\n </div>\n )\n}\n","// Solana Pay transfer request: the official SDK owns QR rendering while the\n// purchase owns lifecycle copy and the same-device wallet link.\nimport * as React from \"react\"\n\nimport { buttonVariants } from \"#orck/components/ui/button\"\nimport { cn } from \"cn\"\n\n// Keep the official renderer's full quiet zone. Cropping it makes the tile\n// denser but materially reduces scan reliability on lower-quality cameras.\nconst QR_SIZE = 208\n\nexport function SolanaBody({\n amountLabel,\n payload,\n statusLine,\n}: {\n amountLabel: string\n payload?: string\n statusLine: string\n}) {\n const qrRef = React.useRef<HTMLDivElement | null>(null)\n const [qrState, setQrState] = React.useState<\"loading\" | \"ready\" | \"failed\">(\n \"loading\"\n )\n\n React.useEffect(() => {\n const container = qrRef.current\n if (!container || !payload) return\n\n let canceled = false\n container.replaceChildren()\n setQrState(\"loading\")\n void import(\"@solana/pay\")\n .then(({ createQR }) => {\n if (canceled) return\n createQR(payload, QR_SIZE, \"#ffffff\", \"#18181b\").append(container)\n setQrState(\"ready\")\n })\n .catch(() => {\n if (!canceled) setQrState(\"failed\")\n })\n return () => {\n canceled = true\n container.replaceChildren()\n }\n }, [payload])\n\n return (\n <div className=\"grid justify-items-center gap-3 py-1\">\n <div className=\"grid place-items-center rounded-xl bg-white p-1 shadow-sm ring-1 ring-black/10\">\n {payload ? (\n <div\n role=\"img\"\n aria-label=\"Solana Pay QR code\"\n className=\"relative overflow-hidden rounded-lg\"\n style={{ width: QR_SIZE, height: QR_SIZE }}\n >\n <div ref={qrRef} className=\"absolute inset-0\" />\n {qrState === \"loading\" ? (\n <div\n aria-hidden\n className=\"absolute inset-0 animate-pulse rounded-lg bg-zinc-100\"\n />\n ) : null}\n {qrState === \"failed\" ? (\n <div className=\"absolute inset-0 grid place-items-center text-center text-xs text-zinc-600\">\n QR code unavailable\n </div>\n ) : null}\n </div>\n ) : (\n <div\n aria-hidden\n className=\"animate-pulse rounded-lg bg-zinc-100\"\n style={{ width: QR_SIZE, height: QR_SIZE }}\n />\n )}\n </div>\n <div className=\"text-[13px] font-medium text-balance\">\n Scan with a Solana wallet\n </div>\n <div\n className=\"text-center text-[12.5px] text-pretty text-muted-foreground tabular-nums\"\n aria-live=\"polite\"\n >\n {amountLabel} · {statusLine}\n </div>\n {payload ? (\n <a\n href={payload}\n className={cn(\n buttonVariants({ variant: \"secondary\" }),\n \"h-9 w-full max-w-56\"\n )}\n >\n Open in wallet\n </a>\n ) : null}\n </div>\n )\n}\n","// Cards the customer already stored with this merchant. Selecting one skips\n// gateway tokenization: the pay request carries the stored method's id. Rows\n// stay surfaceless like the rail list; the brand plate and ink carry selection.\nimport { HugeiconsIcon } from \"@hugeicons/react\"\nimport { Add01Icon } from \"@hugeicons/core-free-icons\"\nimport { CardBrandPlate } from \"#orck/components/card-brands\"\nimport { cardBrandLabel } from \"#orck/lib/card-brands\"\n\nimport { Label } from \"#orck/components/ui/label\"\nimport { RadioGroup, RadioGroupItem } from \"#orck/components/ui/radio-group\"\nimport { cn } from \"cn\"\nimport type { SavedPaymentMethod } from \"#orck/types\"\n\nexport const NEW_CARD_VALUE = \"new\"\n\n// Text plates for brands CardBrandPlate has no mark for.\nconst BRAND_PLATE: Record<string, string> = {\n visa: \"VISA\",\n mastercard: \"MC\",\n amex: \"AMEX\",\n discover: \"DISC\",\n jcb: \"JCB\",\n diners: \"DINERS\",\n}\n\nfunction brandPlate(brand?: string | null): string {\n const key = brand?.trim().toLowerCase() ?? \"\"\n return BRAND_PLATE[key] ?? \"CARD\"\n}\n\n// The plate is decorative; assistive tech gets the spoken brand instead.\nfunction brandName(brand?: string | null): string {\n return cardBrandLabel(brand) ?? \"Card\"\n}\n\nfunction expiryLabel(method: SavedPaymentMethod): string | undefined {\n const card = method.card\n if (!card?.exp_month || !card.exp_year) return undefined\n const month = String(card.exp_month).padStart(2, \"0\")\n return `${month}/${String(card.exp_year).slice(-2)}`\n}\n\nexport function SavedMethods({\n methods,\n value,\n onChange,\n disabled,\n idPrefix,\n}: {\n methods: SavedPaymentMethod[]\n value: string\n onChange: (value: string) => void\n disabled?: boolean\n idPrefix: string\n}) {\n return (\n <RadioGroup\n value={value}\n onValueChange={(next) => {\n if (typeof next === \"string\" && next) onChange(next)\n }}\n disabled={disabled}\n aria-label=\"Saved cards\"\n className=\"grid gap-0\"\n >\n {methods.map((method) => {\n const id = `${idPrefix}-${method.id}`\n const active = value === method.id\n const expires = expiryLabel(method)\n const brand = method.card?.brand\n const last4 = method.card?.last4\n return (\n <Label\n key={method.id}\n htmlFor={id}\n className={cn(\n \"flex cursor-pointer items-center gap-3 py-1.5 select-none\",\n disabled && \"cursor-default\"\n )}\n >\n <RadioGroupItem id={id} value={method.id} />\n <CardBrandPlate\n brand={brand ?? undefined}\n fallback={brandPlate(brand)}\n />\n <span\n className={cn(\n \"min-w-0 flex-1 truncate text-sm font-medium text-muted-foreground tabular-nums transition-colors\",\n active && \"font-semibold text-foreground\"\n )}\n >\n <span className=\"sr-only\">\n {brandName(brand)} card ending {last4}\n {expires ? `, expires ${expires}` : \"\"}\n </span>\n <span aria-hidden>\n {brandName(brand)} •••• {last4 ?? \"····\"}\n {expires ? (\n <span className=\"font-normal text-muted-foreground\">\n {\" \"}\n · {expires}\n </span>\n ) : null}\n </span>\n </span>\n </Label>\n )\n })}\n <Label\n htmlFor={`${idPrefix}-new`}\n className={cn(\n \"flex cursor-pointer items-center gap-3 py-1.5 text-sm font-medium text-muted-foreground select-none\",\n value === NEW_CARD_VALUE && \"font-semibold text-foreground\",\n disabled && \"cursor-default\"\n )}\n >\n <RadioGroupItem id={`${idPrefix}-new`} value={NEW_CARD_VALUE} />\n <span\n aria-hidden\n className={cn(\n \"grid h-7 w-11 shrink-0 place-items-center rounded-md border border-dashed border-border text-muted-foreground transition-colors\",\n value === NEW_CARD_VALUE &&\n \"border-solid border-transparent bg-foreground text-background\"\n )}\n >\n <HugeiconsIcon icon={Add01Icon} className=\"size-3.5\" />\n </span>\n Use a new card\n </Label>\n </RadioGroup>\n )\n}\n","// Terminal and transitional views. Each is quiet: one fact, one instruction,\n// no dead controls.\nimport { Skeleton } from \"#orck/components/ui/skeleton\"\nimport { Eyebrow } from \"#orck/components/eyebrow\"\n\nexport function LoadingSkeleton() {\n return (\n <div className=\"grid gap-4\" aria-hidden>\n <Skeleton className=\"h-3 w-24\" />\n <Skeleton className=\"h-6 w-52\" />\n <Skeleton className=\"mt-1.5 h-11 w-full\" />\n <Skeleton className=\"h-28 w-full\" />\n <Skeleton className=\"h-11 w-full\" />\n <Skeleton className=\"mt-1 h-[42px] w-full\" />\n </div>\n )\n}\n\nexport function SucceededView({\n merchantName,\n embedded,\n}: {\n merchantName: string\n embedded: boolean\n}) {\n return (\n <div className=\"grid gap-4\">\n <Eyebrow>{merchantName}</Eyebrow>\n <div className=\"grid justify-items-center gap-2.5 px-2 py-7 text-center\">\n <div className=\"grid size-11 place-items-center rounded-full bg-[color:var(--orck-success)]/12 text-[color:var(--orck-success)]\">\n <svg\n width=\"20\"\n height=\"20\"\n viewBox=\"0 0 20 20\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2.2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden\n >\n <path d=\"M4 10.5l4 4 8-9\" />\n </svg>\n </div>\n <div className=\"text-[15px] font-semibold\">Payment complete</div>\n <div className=\"text-[13px] text-muted-foreground\">\n {embedded ? \"You're all set.\" : `Returning to ${merchantName}…`}\n </div>\n </div>\n </div>\n )\n}\n\nexport function TerminalView({\n merchantName,\n headline,\n sub,\n}: {\n merchantName: string\n headline: string\n sub?: string\n}) {\n return (\n <div className=\"grid gap-4\">\n <Eyebrow>{merchantName}</Eyebrow>\n <div className=\"grid justify-items-center gap-2 px-2 py-7 text-center\">\n <div className=\"text-[15px] font-semibold\">{headline}</div>\n {sub ? (\n <div className=\"text-[13px] text-muted-foreground\">{sub}</div>\n ) : null}\n </div>\n </div>\n )\n}\n","// Apple Pay and Google Pay through Stripe's Express Checkout Element: the\n// wallet makes a payment method (`pm_`) the order charges as it does a new\n// card's. Stripe shows a wallet only on a registered payment-method domain,\n// in a browser that supports it, with a card in the wallet.\nimport * as React from \"react\"\nimport type {\n StripeExpressCheckoutElementConfirmEvent,\n StripeExpressCheckoutElementReadyEvent,\n} from \"@stripe/stripe-js\"\n\nimport { loadStripeFor } from \"#orck/lib/stripe\"\nimport { stripeAppearance } from \"#orck/lib/stripe-appearance\"\n\nexport interface StripeWalletsProps {\n publishableKey: string\n /** The total in the currency's minor units (Stripe's `amount`). */\n amount: number\n currency: string\n /** Pays with the wallet's payment method; false when the payment failed. */\n onPaymentMethod: (paymentMethod: string) => Promise<boolean>\n /** Whether a wallet button shows. */\n onAvailable?: (available: boolean) => void\n}\n\nexport function StripeWallets({\n publishableKey,\n amount,\n currency,\n onPaymentMethod,\n onAvailable,\n}: StripeWalletsProps) {\n const host = React.useRef<HTMLDivElement>(null)\n const pay = React.useRef(onPaymentMethod)\n const available = React.useRef(onAvailable)\n React.useEffect(() => {\n pay.current = onPaymentMethod\n available.current = onAvailable\n })\n const [shown, setShown] = React.useState(false)\n\n React.useEffect(() => {\n if (!host.current) return\n let canceled = false\n let unmount: (() => void) | undefined\n const show = (value: boolean) => {\n if (canceled) return\n setShown(value)\n available.current?.(value)\n }\n void loadStripeFor(publishableKey).then(\n (stripe) => {\n if (canceled || !host.current) return\n const elements = stripe.elements({\n mode: \"payment\",\n amount,\n currency: currency.toLowerCase(),\n paymentMethodCreation: \"manual\",\n paymentMethodTypes: [\"card\"],\n appearance: stripeAppearance(host.current),\n })\n const element = elements.create(\"expressCheckout\", {\n paymentMethods: {\n applePay: \"auto\",\n googlePay: \"auto\",\n link: \"never\",\n paypal: \"never\",\n amazonPay: \"never\",\n klarna: \"never\",\n },\n })\n element.on(\"ready\", (event: StripeExpressCheckoutElementReadyEvent) => {\n const methods = event.availablePaymentMethods\n show(!!methods && (methods.applePay || methods.googlePay))\n })\n element.on(\n \"confirm\",\n (event: StripeExpressCheckoutElementConfirmEvent) => {\n void (async () => {\n const submitted = await elements.submit()\n const created = submitted.error\n ? undefined\n : await stripe.createPaymentMethod({ elements })\n const method = created?.paymentMethod?.id\n if (!method || !(await pay.current(method)))\n event.paymentFailed({ reason: \"fail\" })\n })()\n }\n )\n element.mount(host.current)\n unmount = () => element.destroy()\n },\n () => show(false)\n )\n return () => {\n canceled = true\n unmount?.()\n }\n }, [publishableKey, amount, currency])\n\n return (\n <div\n ref={host}\n data-testid=\"stripe-wallets\"\n style={{ visibility: shown ? \"visible\" : \"hidden\" }}\n />\n )\n}\n","// A checkout's fallback PSPs: one kept back until the PSPs it stands in for\n// are not offered, or have failed often enough on the order. The checkout\n// decides this, never the merchant's PSP configuration.\nimport { z } from \"zod\"\n\nimport type { Order } from \"./client/types\"\nimport type { PspConfig } from \"./psp\"\n\n/** A PSP kept back for others, named by key. */\nexport interface PaymentFallback {\n /** The PSP keys it stands in for, e.g. `[\"mobius\"]`. */\n for: string[]\n /** Failed attempts through them on the order, combined, that reveal it. */\n afterFailures: number\n}\n\n/** Fallback PSPs by key: `{ ccbill: { for: [\"mobius\"], afterFailures: 2 } }`. */\nexport type PaymentFallbacks = Record<string, PaymentFallback>\n\ntype Option = Order[\"payment_options\"][number]\n\n/**\n * The psp_ids of the options a fallback keeps back: one of its `for` PSPs is\n * offered here and they have failed fewer than `afterFailures` times.\n */\nexport function hiddenFallbacks(\n fallbacks: PaymentFallbacks | undefined,\n options: Option[],\n psps: PspConfig[]\n): Set<string> {\n const hidden = new Set<string>()\n if (!fallbacks) return hidden\n const keyOf = new Map(psps.map((psp) => [psp.psp_id, psp.key.toLowerCase()]))\n const named = new Map(\n Object.entries(fallbacks).map(([key, f]) => [key.toLowerCase(), f])\n )\n for (const option of options) {\n const fallback = named.get(keyOf.get(option.psp_id) ?? \"\")\n if (!fallback) continue\n const primaries = new Set(fallback.for.map((key) => key.toLowerCase()))\n const offered = options.filter((o) =>\n primaries.has(keyOf.get(o.psp_id) ?? \"\")\n )\n const failed = offered.reduce((n, o) => n + o.failed_attempts, 0)\n if (offered.length > 0 && failed < fallback.afterFailures)\n hidden.add(option.psp_id)\n }\n return hidden\n}\n\n// The pay page reads fallbacks from its URL fragment, after the secret:\n// #pus_…&fallbacks=<JSON>. It accepts only small, well-formed values.\nconst FRAGMENT_PARAM = \"fallbacks\"\nconst MAX_FRAGMENT = 4096\nconst MAX_FALLBACKS_JSON = 1024\nconst MAX_ENTRIES = 8\nconst pspKey = z.string().regex(/^[a-z0-9][a-z0-9_-]{0,62}$/)\nconst fallbacksSchema = z\n .record(\n pspKey,\n z.strictObject({\n for: z.array(pspKey).min(1).max(MAX_ENTRIES),\n afterFailures: z.number().int().min(1).max(100),\n })\n )\n .refine((value) => {\n const n = Object.keys(value).length\n return n >= 1 && n <= MAX_ENTRIES\n })\n\n/** The pay URL carrying fallbacks to the pay page in its fragment. */\nexport function withPaymentFallbacks(\n url: string,\n fallbacks?: PaymentFallbacks\n): string {\n if (!fallbacks || Object.keys(fallbacks).length === 0) return url\n const at = url.indexOf(\"#\")\n const base = at < 0 ? url : url.slice(0, at)\n const fragment = at < 0 ? \"\" : url.slice(at + 1)\n const param = `${FRAGMENT_PARAM}=${encodeURIComponent(JSON.stringify(fallbacks))}`\n return `${base}#${fragment ? `${fragment}&` : \"\"}${param}`\n}\n\n/** A pay URL fragment's secret and fallbacks; invalid fallbacks are dropped. */\nexport function readPaymentFragment(hash: string): {\n secret: string | null\n fallbacks?: PaymentFallbacks\n} {\n const [secret = \"\", ...rest] = hash.replace(/^#/, \"\").split(\"&\")\n const out = { secret: secret.startsWith(\"pus_\") ? secret : null }\n if (hash.length > MAX_FRAGMENT) return out\n const raw = new URLSearchParams(rest.join(\"&\")).get(FRAGMENT_PARAM)\n if (!raw || raw.length > MAX_FALLBACKS_JSON) return out\n try {\n const parsed = fallbacksSchema.safeParse(JSON.parse(raw))\n return parsed.success ? { ...out, fallbacks: parsed.data } : out\n } catch {\n return out\n }\n}\n","// Shows an order and pays it, on the host's own page: a saved card, a new card\n// in the PSP's own fields (charged and saved in one call), Apple Pay or Google\n// Pay through a Stripe PSP (when asked), a Solana wallet through a Solana\n// Pay QR, or a PSP's own page. A bank challenge runs in the page, then\n// confirm. A fallback PSP (`fallbacks`) waits until the PSPs it stands in for\n// fail, then is offered as the way out of a failing card.\n// Driven only by the order API (GET, pay, confirm), GET /config and GET\n// /me/config; never cancels.\nimport * as React from \"react\"\n\nimport {\n appearanceStyle,\n appearanceTheme,\n type BillingAppearance,\n} from \"./appearance\"\nimport type { BillingClient, OrderResult } from \"./client/client\"\nimport { isBillingError } from \"./client/errors\"\nimport type { Order, OrderPaymentInput, PaymentMethod } from \"./client/types\"\nimport { PayButton, TrustLine } from \"./components/pay-button\"\nimport { Button } from \"./components/ui/button\"\nimport { SolanaBody } from \"./components/qr\"\nimport { SavedMethods, NEW_CARD_VALUE } from \"./components/saved-methods\"\nimport { LoadingSkeleton } from \"./components/states\"\nimport {\n StripeCardEntry,\n type StripeCardHandle,\n} from \"./components/stripe-card\"\nimport { StripeWallets } from \"./components/stripe-wallets\"\nimport { useMessages } from \"./i18n/context\"\nimport { hiddenFallbacks, type PaymentFallbacks } from \"./fallbacks\"\nimport { billingDetailsOf } from \"./lib/billing\"\nimport { amountToMinorUnits, formatAmount } from \"./lib/money\"\nimport { loadStripeFor } from \"./lib/stripe\"\nimport { cardSetupDriver, type PspConfig } from \"./psp\"\nimport { useConfig, useCurrencyScales, useCustomerConfig } from \"./react/config\"\nimport { useBillingContext } from \"./react/context\"\nimport {\n TokenizedCardForm,\n type TokenizedCardData,\n} from \"./tokenized-card-form\"\nimport { PlatformCardForm } from \"./components/platform-card-form\"\nimport type { SavedPaymentMethod } from \"./types\"\nimport { cn } from \"cn\"\n\nexport interface OrderPaymentProps {\n orderId: string\n /** The client to pay through; default: the provider's. */\n client?: BillingClient\n /** Where a redirect PSP will return to; card PSPs need none. */\n returnUrl?: string\n /** Offer the customer's saved cards (GET /me/payment-methods). Default true. */\n savedPaymentMethods?: boolean\n /**\n * Offer a PSP whose card entry is server. Default true; orders take\n * tokens only, so such a PSP is offered for saved cards alone.\n */\n serverCardEntry?: boolean\n /**\n * Offer Apple Pay and Google Pay through a Stripe PSP's Express Checkout\n * Element. The page's host must be a payment-method domain registered on\n * that Stripe account. Default false.\n */\n wallets?: boolean\n /**\n * PSPs kept back until the PSPs they stand in for are not offered, or have\n * failed `afterFailures` times on the order; then offered under \"Card\n * payment isn't working?\". `{ ccbill: { for: [\"mobius\"], afterFailures: 2 } }`.\n */\n fallbacks?: PaymentFallbacks\n /** Once the order is complete, or processing on an asynchronous rail. */\n onSettled?: (order: Order) => void\n appearance?: BillingAppearance\n className?: string\n}\n\nconst platformCard = (psp: PspConfig) =>\n psp.custodian === \"platform\" && psp.rail === \"nmi\" &&\n psp.flow === \"tokenize\" && !psp.status && !!psp.config?.public_api_key\n\nconst settled = (order: Order) =>\n order.status === \"complete\" || order.status === \"processing\"\n\n// How often a Solana order awaiting its wallet is read again.\nconst SOLANA_POLL_MS = 3000\n// How often an order whose payment OpenRails is still confirming is read\n// again; a lost card answer takes minutes to settle from the provider.\nconst PROCESSING_POLL_MS = 10000\n\n/** Pays one order. Requires `BillingProvider`. */\nexport function OrderPayment({\n orderId,\n client: given,\n returnUrl,\n savedPaymentMethods = true,\n serverCardEntry = true,\n wallets = false,\n fallbacks,\n onSettled,\n appearance,\n className,\n}: OrderPaymentProps) {\n const m = useMessages()\n const context = useBillingContext()\n const client = given ?? context.client\n const { config } = useConfig()\n const {\n config: merchant,\n error: merchantError,\n refetch: refetchMerchant,\n } = useCustomerConfig()\n const scales = useCurrencyScales()\n const [order, setOrder] = React.useState<Order>()\n const [methods, setMethods] = React.useState<PaymentMethod[]>([])\n const [choice, setChoice] = React.useState<string>(NEW_CARD_VALUE)\n const [pspID, setPspID] = React.useState<string>()\n const [error, setError] = React.useState<string>()\n const [busy, setBusy] = React.useState(false)\n const [pendingSaved, setPendingSaved] = React.useState<string>()\n const [walletShown, setWalletShown] = React.useState(false)\n // One key per pay attempt, minted at render: a retry of the same request\n // answers what the first did. A failed answer mints the next.\n const [key, setKey] = React.useState(() => crypto.randomUUID())\n const stripeCard = React.useRef<StripeCardHandle>(null)\n const settledRef = React.useRef(onSettled)\n React.useEffect(() => {\n settledRef.current = onSettled\n })\n\n React.useEffect(() => {\n const abort = new AbortController()\n client.getOrder(orderId, abort.signal).then(setOrder, (cause: unknown) => {\n if (!abort.signal.aborted) setError(m.error(cause))\n })\n return () => abort.abort()\n }, [client, orderId, m])\n\n React.useEffect(() => {\n if (!savedPaymentMethods || order?.collection_owner !== \"engine\") return\n const abort = new AbortController()\n client.listPaymentMethods({ signal: abort.signal }).then(\n (page) => setMethods(page.data),\n () => undefined\n )\n return () => abort.abort()\n }, [client, savedPaymentMethods, order?.collection_owner])\n\n React.useEffect(() => {\n if (order && settled(order)) settledRef.current?.(order)\n }, [order])\n\n // A Solana order awaits its wallet: confirm asks OpenRails to read the\n // chain, until the transfer lands.\n const awaitingWallet =\n order?.collection_owner === \"engine\" &&\n order?.payment.status === \"requires_action\" &&\n order.payment.next_action?.type === \"solana_pay\"\n React.useEffect(() => {\n if (!awaitingWallet || !order) return\n const timer = window.setInterval(() => {\n client.confirmOrder(order.id).then(\n (result) => setOrder(result.order),\n () => undefined\n )\n }, SOLANA_POLL_MS)\n return () => window.clearInterval(timer)\n }, [awaitingWallet, client, order])\n\n // A processing order is confirmed later: show the decline or the receipt\n // once OpenRails has it.\n const confirming =\n order?.collection_owner === \"engine\" && order.status === \"processing\"\n React.useEffect(() => {\n if (!confirming) return\n const abort = new AbortController()\n const timer = window.setInterval(() => {\n client.getOrder(orderId, abort.signal).then(\n (next) => {\n if (next.status === \"processing\") return\n setOrder(next)\n // Declined after all: say why, and pay again under a new key.\n if (next.status === \"open\") {\n const failure = next.payment.last_payment_error?.message\n if (failure) setError(failure)\n setKey(crypto.randomUUID())\n }\n },\n () => undefined\n )\n }, PROCESSING_POLL_MS)\n return () => {\n window.clearInterval(timer)\n abort.abort()\n }\n }, [confirming, client, orderId])\n\n // What the order offers here, less the fallbacks still kept back.\n const offered = React.useMemo(\n () => (order?.collection_owner === \"engine\" ? order.payment_options : []),\n [order]\n )\n const known = React.useMemo(\n () =>\n (merchant?.payment.psps ?? []).filter((psp) =>\n offered.some((option) => option.psp_id === psp.psp_id)\n ),\n [merchant, offered]\n )\n const hidden = hiddenFallbacks(fallbacks, offered, known)\n const options = offered.filter((option) => !hidden.has(option.psp_id))\n const psps = known.filter((psp) => !hidden.has(psp.psp_id))\n // New cards: PSPs whose own fields make a token, where the order takes\n // one (a renewal takes saved cards only).\n const cardPsps = psps.filter((psp) => {\n const driver = cardSetupDriver(psp)\n return (\n (driver === \"collect_js\" || driver === \"stripe_elements\" || platformCard(psp)) &&\n options.some(\n (option) =>\n option.psp_id === psp.psp_id && option.accepts.includes(\"new_card\")\n )\n )\n })\n const usable = psps.filter(\n (psp) => serverCardEntry || cardSetupDriver(psp) !== \"card\"\n )\n const saved: SavedPaymentMethod[] = methods\n .filter(\n (method) =>\n (method.status ?? \"active\") === \"active\" &&\n method.reusable !== false &&\n method.health?.active !== false &&\n usable.some((psp) =>\n psp.psp_id === method.psp_id || options.some((option) =>\n option.psp_id === psp.psp_id &&\n option.saved_payment_method_ids?.includes(method.id)\n )\n )\n )\n .map((method) => ({\n id: method.id,\n psp_id: method.psp_id ?? \"\",\n rail: method.rail ?? \"\",\n card: method.card ?? undefined,\n }))\n const psp: PspConfig | undefined =\n cardPsps.find((item) => item.psp_id === pspID) ?? cardPsps[0]\n const solana = options.find((option) => option.accepts.includes(\"solana_pay\"))\n // A PSP with no fields in this page takes the order on its hosted page.\n const redirects = psps.filter(\n (item) =>\n cardSetupDriver(item) === null &&\n options.some(\n (option) =>\n option.psp_id === item.psp_id && option.accepts.includes(\"redirect\")\n )\n )\n const fallsBack = (item: PspConfig) =>\n !!fallbacks &&\n Object.keys(fallbacks).some(\n (key) => key.toLowerCase() === item.key.toLowerCase()\n )\n const hosted = redirects.filter((item) => !fallsBack(item))\n const revealed = redirects.filter(fallsBack)\n const recurring = order?.lines.some((line) => line.billing_interval_hours !== null) ?? false\n const tokens = solana\n ? (merchant?.payment.solana?.tokens ?? []).filter(\n (token) => !recurring || token.recurring_eligible === true\n )\n : []\n const walletPsp = wallets\n ? cardPsps.find(\n (item) =>\n cardSetupDriver(item) === \"stripe_elements\" &&\n !!item.config?.publishable_key\n )\n : undefined\n\n if (!order)\n return error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n ) : (\n <LoadingSkeleton />\n )\n\n const decimals = scales[order.currency.toUpperCase()] ?? 2\n const money = (amount: string) =>\n formatAmount(amount, order.currency, decimals)\n const currency = config?.currencies?.find(\n (item) => item.code.toUpperCase() === order.currency.toUpperCase()\n )\n // Stripe takes the total in minor units; a total that is not a whole\n // number of them is offered no wallet.\n const walletAmount =\n walletPsp && currency?.minor_decimals != null\n ? amountToMinorUnits(\n order.total,\n currency.decimals,\n currency.minor_decimals\n )\n : null\n\n // answer applies an order request's answer: settle, run the bank's\n // challenge, or show why the payment failed.\n const answer = async (result: OrderResult): Promise<boolean> => {\n setOrder(result.order)\n if (result.error) {\n setError(\n result.order.payment.last_payment_error?.message ?? result.error.message\n )\n setKey(crypto.randomUUID())\n return false\n }\n const next = result.order.payment.next_action\n if (result.order.collection_owner !== \"engine\" || result.order.payment.status !== \"requires_action\" || !next) return true\n if (next.type === \"redirect_to_url\" && next.url) {\n window.location.assign(next.url)\n return true\n }\n const secret = next.payload?.client_secret\n const challenger = merchant?.payment.psps.find(\n (item) => item.psp_id === next.psp_id\n )\n const publishable = challenger?.config?.publishable_key\n if (next.type !== \"authenticate\" || !secret || !publishable) {\n setError(m.t(\"paymentMethods.unavailable\"))\n return false\n }\n if (stripeCard.current && next.psp_id === psp?.psp_id)\n await stripeCard.current.handleNextAction(secret)\n else {\n const stripe = await loadStripeFor(publishable)\n const answered = await stripe.handleNextAction({ clientSecret: secret })\n if (answered.error) throw new Error(answered.error.message)\n }\n return answer(await client.confirmOrder(order.id))\n }\n\n // pay answers whether the payment went through (or awaits its rail).\n const pay = async (\n payment: () => Promise<OrderPaymentInput>,\n preserveUnconfirmed = false,\n reusable?: boolean\n ): Promise<boolean> => {\n if (\n busy ||\n order.collection_owner !== \"engine\" ||\n (pendingSaved && !preserveUnconfirmed)\n )\n return false\n setBusy(true)\n setError(undefined)\n try {\n return await answer(\n await client.payOrder(order.id, {\n payment: await payment(),\n expectedTotal: order.total,\n idempotencyKey: key,\n ...(reusable === undefined ? {} : { reusable }),\n })\n )\n } catch (cause) {\n setError(\n !isBillingError(cause) && cause instanceof Error && cause.message\n ? cause.message\n : m.error(cause)\n )\n // Validation rejected the request before a charge; let the customer\n // correct it. Network, server and in-flight errors keep the same attempt.\n const rejected = isBillingError(cause) && cause.status === 400 &&\n cause.type === \"invalid_request_error\"\n if (preserveUnconfirmed && !rejected) throw cause\n setKey(crypto.randomUUID())\n return false\n } finally {\n setBusy(false)\n }\n }\n\n // A payment the bank asks the customer to authenticate before they came\n // here (a renewal charged while they were away).\n const authenticate = async () => {\n if (busy || order.collection_owner !== \"engine\") return\n setBusy(true)\n setError(undefined)\n try {\n await answer({ order })\n } catch (cause) {\n setError(\n !isBillingError(cause) && cause instanceof Error && cause.message\n ? cause.message\n : m.error(cause)\n )\n } finally {\n setBusy(false)\n }\n }\n const awaitingAuthentication =\n order.collection_owner === \"engine\" &&\n order.status === \"open\" &&\n order.payment.status === \"requires_action\" &&\n order.payment.next_action?.type === \"authenticate\"\n // Back from a PSP's page before it reported the payment.\n const awaitingRedirect =\n order.collection_owner === \"engine\" &&\n order.status === \"open\" &&\n order.payment.status === \"requires_action\" &&\n order.payment.next_action?.type === \"redirect_to_url\" &&\n !!order.payment.next_action.url\n const redirectPsp = merchant?.payment.psps.find(\n (item) => item.psp_id === order.payment.next_action?.psp_id\n )\n\n // A usage order is paid for what it still owes; a written-off one too.\n const payLabel = recurring ? \"Subscribe\" : \"Pay\"\n const profile = merchant?.merchant\n const terms =\n profile?.terms_url || profile?.privacy_url ? (\n <>\n By {recurring ? \"subscribing\" : \"paying\"}, you agree to our{\" \"}\n {profile.terms_url ? (\n <a href={profile.terms_url} target=\"_blank\" rel=\"noreferrer\" className=\"underline\">\n Terms of Service\n </a>\n ) : null}\n {profile.terms_url && profile.privacy_url ? \" and \" : null}\n {profile.privacy_url ? (\n <a href={profile.privacy_url} target=\"_blank\" rel=\"noreferrer\" className=\"underline\">\n Privacy Policy\n </a>\n ) : null}\n .\n </>\n ) : undefined\n const open =\n order.collection_owner === \"engine\" &&\n (order.status === \"open\" ||\n (order.status === \"uncollectible\" && !!order.usage)) &&\n order.payment.status === \"requires_payment_method\"\n\n return (\n <div\n className={cn(\"orck grid gap-5\", className)}\n data-orck-theme={appearanceTheme(appearance)}\n style={appearanceStyle(appearance)}\n >\n <div className=\"grid\">\n {order.lines.map((line) => (\n <div\n key={line.id}\n className=\"flex items-start justify-between gap-4 py-2 text-[13.5px]\"\n >\n <span>\n {line.description}\n {line.quantity && line.quantity > 1 ? ` × ${line.quantity}` : \"\"}\n </span>\n <span className=\"whitespace-nowrap tabular-nums\">\n {money(line.amount)}\n </span>\n </div>\n ))}\n <div className=\"flex items-start justify-between gap-4 border-t border-border pt-3 text-[13.5px] font-semibold\">\n <span>Total</span>\n <span className=\"whitespace-nowrap tabular-nums\">\n {money(order.total)}\n </span>\n </div>\n {order.usage && order.usage.amount_paid !== \"0\" && (\n <div className=\"flex items-start justify-between gap-4 pt-1 text-[13.5px]\">\n <span>Due</span>\n <span className=\"whitespace-nowrap tabular-nums\">\n {money(order.usage.amount_due)}\n </span>\n </div>\n )}\n </div>\n\n {awaitingWallet ? (\n <SolanaBody\n amountLabel={`${order.payment.next_action?.payload?.token_amount ?? \"\"} ${order.payment.next_action?.payload?.token_symbol ?? \"\"}`.trim()}\n payload={order.payment.next_action?.url ?? undefined}\n statusLine=\"Waiting for your wallet's payment\"\n />\n ) : order.status === \"complete\" ? (\n <p role=\"status\" className=\"text-sm font-semibold\">\n Payment complete\n </p>\n ) : order.collection_owner !== \"engine\" ? (\n <p role=\"status\" className=\"text-sm text-muted-foreground\">\n This bill is collected by the payment provider. No payment is needed here.\n </p>\n ) : order.status === \"processing\" ? (\n <p role=\"status\" className=\"text-sm text-muted-foreground\">\n We're confirming this payment with the payment provider. You won't be\n charged twice, and this page updates once the provider answers.\n </p>\n ) : order.status !== \"open\" ? (\n <p role=\"status\" className=\"text-sm text-muted-foreground\">\n This order can no longer be paid.\n </p>\n ) : awaitingRedirect ? (\n <form\n className=\"grid gap-4\"\n onSubmit={(event) => {\n event.preventDefault()\n window.location.assign(order.payment.next_action!.url!)\n }}\n >\n <p className=\"text-sm text-muted-foreground\">\n Your payment is waiting on{\" \"}\n {redirectPsp?.display_name ?? \"the payment page\"}.\n </p>\n <PayButton\n label={`Continue to ${redirectPsp?.display_name ?? \"the payment page\"}`}\n processing={false}\n />\n </form>\n ) : awaitingAuthentication ? (\n <form\n className=\"grid gap-4\"\n onSubmit={(event) => {\n event.preventDefault()\n void authenticate()\n }}\n >\n <p className=\"text-sm text-muted-foreground\">\n Your bank asks you to confirm this payment.\n </p>\n <PayButton label=\"Confirm payment\" processing={busy} />\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n ) : null}\n </form>\n ) : (\n <div className=\"grid gap-4\">\n {!pendingSaved && walletPsp && walletAmount ? (\n <StripeWallets\n publishableKey={walletPsp.config!.publishable_key!}\n amount={walletAmount}\n currency={order.currency}\n onAvailable={setWalletShown}\n onPaymentMethod={(method) =>\n pay(async () => ({ token: method, psp_id: walletPsp.psp_id }))\n }\n />\n ) : null}\n {!pendingSaved && walletShown && walletPsp && walletAmount ? (\n <p className=\"text-center text-[13px] text-muted-foreground\">\n or pay another way\n </p>\n ) : null}\n {saved.length > 0 ? (\n <SavedMethods\n methods={saved}\n value={choice}\n onChange={setChoice}\n disabled={busy || !open || !!pendingSaved}\n idPrefix={`orck-order-${order.id}`}\n />\n ) : null}\n {choice !== NEW_CARD_VALUE ? (\n <form\n className=\"grid gap-4\"\n onSubmit={(event) => {\n event.preventDefault()\n const method = pendingSaved ?? choice\n const platform = options.some((option) =>\n option.saved_payment_method_ids?.includes(method)\n )\n void pay(async () => ({ payment_method_id: method }), platform)\n .then(() => setPendingSaved(undefined))\n .catch(() => setPendingSaved(method))\n }}\n >\n <PayButton\n label={pendingSaved ? \"Retry payment\" : payLabel}\n processing={busy}\n disabled={!open}\n />\n </form>\n ) : psp ? (\n <>\n {cardPsps.length > 1 ? (\n <select\n aria-label=\"Pay with\"\n className=\"h-9 rounded-md border border-border bg-transparent px-2 text-sm\"\n value={psp.psp_id}\n onChange={(event) => setPspID(event.target.value)}\n >\n {cardPsps.map((item) => (\n <option key={item.psp_id} value={item.psp_id}>\n {item.display_name}\n </option>\n ))}\n </select>\n ) : null}\n {platformCard(psp) ? (\n <PlatformCardForm\n key={psp.psp_id}\n publicKey={psp.config!.public_api_key!}\n submitLabel={payLabel}\n disabled={busy || !open}\n onTokenized={(card) => pay(async () => ({\n token: card.payment_token,\n psp_id: psp.psp_id,\n billing_details: billingDetailsOf(card),\n }), true)}\n />\n ) : cardSetupDriver(psp) === \"collect_js\" ? (\n <TokenizedCardForm\n key={psp.psp_id}\n tokenizationKey={psp.config!.tokenization_key!}\n tokenizationURL={psp.config!.tokenization_url!}\n submitLabel={payLabel}\n disabled={busy || !open}\n appearance={appearance}\n defaultCountry={merchant?.client_country || undefined}\n saveOptInMerchant={recurring ? undefined : profile?.display_name}\n terms={terms}\n statementDescriptor={profile?.statement_descriptor ?? undefined}\n // A refused payment leaves the form open for another card.\n onTokenized={(card: TokenizedCardData) =>\n pay(\n async () => ({\n token: card.payment_token,\n psp_id: psp.psp_id,\n billing_details: billingDetailsOf(card),\n }),\n false,\n card.reusable\n )\n }\n />\n ) : (\n <form\n className=\"grid gap-4\"\n onSubmit={(event) => {\n event.preventDefault()\n void pay(async () => ({\n token: await stripeCard.current!.tokenize(),\n psp_id: psp.psp_id,\n }))\n }}\n >\n <StripeCardEntry\n key={psp.psp_id}\n ref={stripeCard}\n psp={psp}\n client={client}\n unavailableMessage={m.t(\"paymentMethods.unavailable\")}\n verificationPendingMessage={m.t(\n \"paymentMethods.verificationPending\"\n )}\n />\n <PayButton\n label={payLabel}\n processing={busy}\n disabled={!open}\n />\n <TrustLine />\n </form>\n )}\n </>\n ) : solana || hosted.length > 0 || revealed.length > 0 ? null : !merchant ? (\n // The merchant's payment setup is still loading, or failed to:\n // never read that as card entry being unavailable.\n merchantError ? (\n <div role=\"alert\" className=\"grid gap-2 text-sm\">\n <p className=\"text-destructive\">{m.error(merchantError)}</p>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" onClick={refetchMerchant}>\n {m.t(\"common.retry\")}\n </Button>\n </div>\n ) : (\n <p className=\"text-sm text-muted-foreground\">{m.t(\"common.loading\")}</p>\n )\n ) : (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {m.t(\"paymentMethods.unavailable\")}\n </p>\n )}\n {hosted.map((item) => (\n <form\n key={item.psp_id}\n onSubmit={(event) => {\n event.preventDefault()\n void pay(async () => ({\n return_url: returnUrl ?? window.location.href,\n psp_id: item.psp_id,\n }))\n }}\n >\n <PayButton\n label={`${payLabel} with ${item.display_name}`}\n processing={busy}\n disabled={!open || !!pendingSaved}\n />\n </form>\n ))}\n {revealed.length > 0 ? (\n <div className=\"grid gap-2 border-t border-border pt-4\">\n <p className=\"text-[13px] text-muted-foreground\">\n Card payment isn't working?\n </p>\n {revealed.map((item) => {\n // A CCBill page names the customer; one it cannot name yet\n // says what to add first.\n const requires =\n options.find((option) => option.psp_id === item.psp_id)\n ?.requires ?? []\n const blocked = requires.length > 0\n const reason = `${item.psp_id}-requires`\n return (\n <React.Fragment key={item.psp_id}>\n <button\n type=\"button\"\n className=\"h-9 rounded-md border border-border text-sm disabled:cursor-not-allowed disabled:opacity-60\"\n disabled={busy || !open || !!pendingSaved || blocked}\n aria-describedby={blocked ? reason : undefined}\n onClick={() =>\n void pay(async () => ({\n return_url: returnUrl ?? window.location.href,\n psp_id: item.psp_id,\n }))\n }\n >\n Pay with {item.display_name}\n </button>\n {blocked ? (\n <p id={reason} className=\"text-[13px] text-muted-foreground\">\n {m.t(\n requires.length > 1\n ? \"errors.customer_email_required\"\n : requires[0] === \"username\"\n ? \"errors.ccbill_username_required\"\n : \"errors.ccbill_email_required\"\n )}\n </p>\n ) : null}\n </React.Fragment>\n )\n })}\n </div>\n ) : null}\n {solana && tokens.length > 0 ? (\n <div className=\"grid gap-2 border-t border-border pt-4\">\n {tokens.map((token) => (\n <button\n key={token.symbol}\n type=\"button\"\n className=\"h-9 rounded-md border border-border text-sm\"\n disabled={busy || !open || !!pendingSaved}\n onClick={() =>\n void pay(async () => ({\n token_symbol: token.symbol,\n psp_id: solana.psp_id,\n }))\n }\n >\n Pay with {token.symbol} on Solana\n </button>\n ))}\n </div>\n ) : null}\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n ) : null}\n </div>\n )}\n </div>\n )\n}\n","// An order's pay URL framed on the merchant's own page, as Stripe's\n// embedded Checkout: the order's pay URL (embedded) in an\n// iframe the checkout origin allows only on the merchant's registered origins.\n// The framed page reports its height and the order's completion, and only\n// messages from the pay URL's origin and this iframe are heard. Fulfil\n// on order.completed, never on the completion message. Fallbacks reach the\n// framed page in the URL fragment, never through the server.\nimport * as React from \"react\"\n\nimport { withPaymentFallbacks, type PaymentFallbacks } from \"./fallbacks\"\n\n/** The framed page's message once the order completes. */\nexport const PAYMENT_COMPLETE_MESSAGE = \"openrails.payment.complete\"\n/** The framed page's message when its height changes. */\nexport const PAYMENT_RESIZE_MESSAGE = \"openrails.payment.resize\"\n\nexport interface EmbeddedPaymentCompletion {\n orderId: string\n /**\n * The order's success_url, with the order id filled in; \"\" for a\n * customer's own pay URL, which returns nowhere (the frame says it is paid).\n */\n successUrl: string\n}\n\nexport interface EmbeddedPaymentProps {\n /** The order's pay_url, secret and all. */\n url: string\n /**\n * Called once the order completes. Without it the page goes to the\n * order's success_url, if it has one.\n */\n onComplete?: (completion: EmbeddedPaymentCompletion) => void\n /** As OrderPayment's: the framed page keeps these PSPs back the same way. */\n fallbacks?: PaymentFallbacks\n /** Called once when the pay page never loads (no message from the frame). */\n onLoadFailure?: () => void\n title?: string\n className?: string\n}\n\n// The pay page posts its height on mount; silence this long means it failed.\nconst LOAD_TIMEOUT_MS = 12_000\n\nexport function EmbeddedPayment(props: EmbeddedPaymentProps) {\n return <PaymentFrame key={props.url} {...props} />\n}\n\nfunction PaymentFrame({\n url,\n onComplete,\n fallbacks,\n onLoadFailure,\n title = \"Payment\",\n className,\n}: EmbeddedPaymentProps) {\n const frame = React.useRef<HTMLIFrameElement>(null)\n const [height, setHeight] = React.useState<number>()\n const [attempt, setAttempt] = React.useState(0)\n const [loaded, setLoaded] = React.useState(false)\n const [failed, setFailed] = React.useState(false)\n const reported = React.useRef(false)\n const failure = React.useRef(onLoadFailure)\n React.useEffect(() => {\n failure.current = onLoadFailure\n })\n const completed = React.useRef(onComplete)\n React.useEffect(() => {\n completed.current = onComplete\n })\n const destination = React.useMemo(() => {\n try {\n const parsed = new URL(url)\n const orderId = /^\\/pay\\/([^/]+)$/.exec(parsed.pathname)?.[1]\n return (parsed.protocol === \"https:\" || parsed.protocol === \"http:\") &&\n orderId\n ? { origin: parsed.origin, orderId }\n : null\n } catch {\n return null\n }\n }, [url])\n const origin = destination?.origin\n const orderId = destination?.orderId\n\n React.useEffect(() => {\n if (!origin) return\n let done = false\n const heard = (event: MessageEvent) => {\n if (\n event.origin !== origin ||\n !frame.current ||\n event.source !== frame.current.contentWindow\n )\n return\n const data: unknown = event.data\n if (!data || typeof data !== \"object\") return\n setLoaded(true)\n const message = data as Record<string, unknown>\n if (\n message.type === PAYMENT_RESIZE_MESSAGE &&\n typeof message.height === \"number\" &&\n message.height > 0 &&\n message.height < 20_000\n ) {\n setHeight(Math.ceil(message.height))\n return\n }\n if (\n message.type !== PAYMENT_COMPLETE_MESSAGE ||\n typeof message.order_id !== \"string\" ||\n message.order_id !== orderId ||\n done\n )\n return\n done = true\n const successUrl =\n typeof message.success_url === \"string\" ? message.success_url : \"\"\n if (completed.current)\n completed.current({ orderId: message.order_id, successUrl })\n else if (/^https?:\\/\\//i.test(successUrl))\n window.location.assign(successUrl)\n }\n window.addEventListener(\"message\", heard)\n return () => window.removeEventListener(\"message\", heard)\n }, [origin, orderId])\n\n React.useEffect(() => {\n if (!origin || loaded || failed) return\n const timer = window.setTimeout(() => {\n setFailed(true)\n if (!reported.current) {\n reported.current = true\n failure.current?.()\n }\n }, LOAD_TIMEOUT_MS)\n return () => window.clearTimeout(timer)\n }, [origin, loaded, failed, attempt])\n\n if (!origin) return null\n if (failed)\n return (\n <div role=\"alert\" className=\"grid gap-3 p-6 text-center\">\n <p className=\"text-sm font-medium text-foreground\">\n The secure payment page didn't load.\n </p>\n <p className=\"text-sm text-muted-foreground\">\n Please try again in a moment.\n </p>\n <button\n type=\"button\"\n className=\"mx-auto rounded-md border border-input px-4 py-2 text-sm\"\n onClick={() => {\n setFailed(false)\n setAttempt((n) => n + 1)\n }}\n >\n Try again\n </button>\n </div>\n )\n return (\n <>\n {loaded ? null : (\n <p className=\"p-6 text-center text-sm text-muted-foreground\">\n Loading secure payment page…\n </p>\n )}\n <iframe\n key={attempt}\n ref={frame}\n src={withPaymentFallbacks(url, fallbacks)}\n title={title}\n className={className}\n scrolling=\"no\"\n allow=\"payment *; publickey-credentials-get *; publickey-credentials-create *\"\n style={{\n border: 0,\n width: \"100%\",\n height: loaded ? (height ?? 640) : 0,\n visibility: loaded ? \"visible\" : \"hidden\",\n }}\n />\n </>\n )\n}\n","// Shows the customer's cart, priced live, removes lines and checks it out:\n// one order made from the cart (cart: true, at the total shown), then paid\n// here with OrderPayment unless the host takes the order itself. Hosts add\n// and change lines with client.setCartLine.\nimport * as React from \"react\"\n\nimport {\n appearanceStyle,\n appearanceTheme,\n type BillingAppearance,\n} from \"./appearance\"\nimport type { BillingClient } from \"./client/client\"\nimport type { Cart as CartData, Order } from \"./client/types\"\nimport { PayButton } from \"./components/pay-button\"\nimport type { PaymentFallbacks } from \"./fallbacks\"\nimport { LoadingSkeleton } from \"./components/states\"\nimport { useMessages } from \"./i18n/context\"\nimport { formatAmount } from \"./lib/money\"\nimport { OrderPayment } from \"./order-payment\"\nimport { useCurrencyScales } from \"./react/config\"\nimport { useBillingContext } from \"./react/context\"\nimport { cn } from \"cn\"\n\nexport interface CartProps {\n /** The client to read and buy through; default: the provider's. */\n client?: BillingClient\n /**\n * The order made from the cart. Default: pay it here with OrderPayment.\n */\n onOrder?: (order: Order) => void\n /** Passed to OrderPayment: the order is complete, or processing. */\n onSettled?: (order: Order) => void\n /** Passed to OrderPayment: PSPs kept back until others fail on the order. */\n fallbacks?: PaymentFallbacks\n appearance?: BillingAppearance\n className?: string\n}\n\n/** The customer's cart. Requires `BillingProvider`. */\nexport function Cart({\n client: given,\n onOrder,\n onSettled,\n fallbacks,\n appearance,\n className,\n}: CartProps) {\n const m = useMessages()\n const context = useBillingContext()\n const client = given ?? context.client\n const scales = useCurrencyScales()\n const [cart, setCart] = React.useState<CartData>()\n const [order, setOrder] = React.useState<Order>()\n const [error, setError] = React.useState<string>()\n const [busy, setBusy] = React.useState(false)\n // One key per order attempt: a retry answers the same order.\n const [key, setKey] = React.useState(() => crypto.randomUUID())\n\n React.useEffect(() => {\n const abort = new AbortController()\n client.getCart(abort.signal).then(setCart, (cause: unknown) => {\n if (!abort.signal.aborted) setError(m.error(cause))\n })\n return () => abort.abort()\n }, [client, m])\n\n const act = async (work: () => Promise<void>) => {\n if (busy) return\n setBusy(true)\n setError(undefined)\n try {\n await work()\n } catch (cause) {\n setError(m.error(cause))\n } finally {\n setBusy(false)\n }\n }\n\n if (order && !onOrder)\n return (\n <OrderPayment\n orderId={order.id}\n client={client}\n onSettled={onSettled}\n fallbacks={fallbacks}\n appearance={appearance}\n className={className}\n />\n )\n if (!cart)\n return error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n ) : (\n <LoadingSkeleton />\n )\n\n const decimals = scales[cart.currency.toUpperCase()] ?? 2\n const money = (amount: string) =>\n formatAmount(amount, cart.currency, decimals)\n const buyable =\n cart.lines.length > 0 && cart.lines.every((line) => !line.refusal)\n\n const remove = (priceId: string) =>\n act(async () => {\n setCart(await client.setCartLine(priceId, { quantity: 0 }))\n setKey(crypto.randomUUID())\n })\n\n const purchase = () =>\n act(async () => {\n const result = await client.createOrder({\n cart: true,\n expectedTotal: cart.total,\n idempotencyKey: key,\n })\n if (result.error) throw result.error\n setOrder(result.order)\n onOrder?.(result.order)\n })\n\n return (\n <div\n className={cn(\"orck grid gap-5\", className)}\n data-orck-theme={appearanceTheme(appearance)}\n style={appearanceStyle(appearance)}\n >\n {cart.lines.length === 0 ? (\n <p role=\"status\" className=\"text-sm text-muted-foreground\">\n Your cart is empty.\n </p>\n ) : (\n <div className=\"grid\">\n {cart.lines.map((line) => (\n <div\n key={line.price_id}\n className=\"grid gap-1 border-b border-border py-2 text-[13.5px]\"\n >\n <div className=\"flex items-start justify-between gap-4\">\n <span>{line.description || line.price_id}</span>\n <span className=\"whitespace-nowrap tabular-nums\">\n {money(line.amount)}\n </span>\n </div>\n <div className=\"flex items-center gap-2\">\n {line.quantity != null && line.quantity > 1 ? (\n <span className=\"text-[13px] text-muted-foreground\">\n Quantity {line.quantity}\n </span>\n ) : null}\n <button\n type=\"button\"\n className=\"text-[13px] text-muted-foreground underline\"\n disabled={busy}\n onClick={() => void remove(line.price_id)}\n >\n Remove\n </button>\n </div>\n {line.refusal ? (\n <p className=\"text-[13px] text-destructive\">\n {line.refusal.message}\n </p>\n ) : null}\n </div>\n ))}\n <div className=\"flex items-start justify-between gap-4 pt-3 text-[13.5px] font-semibold\">\n <span>Total</span>\n <span className=\"whitespace-nowrap tabular-nums\">\n {money(cart.total)}\n </span>\n </div>\n </div>\n )}\n {cart.lines.length > 0 ? (\n <form\n className=\"grid gap-2\"\n onSubmit={(event) => {\n event.preventDefault()\n void purchase()\n }}\n >\n <PayButton label=\"Check out\" processing={busy} disabled={!buyable} />\n <button\n type=\"button\"\n className=\"text-[13px] text-muted-foreground underline\"\n disabled={busy}\n onClick={() =>\n void act(async () => {\n await client.clearCart()\n setCart(await client.getCart())\n })\n }\n >\n Empty cart\n </button>\n </form>\n ) : null}\n {error ? (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n ) : null}\n </div>\n )\n}\n","import { formatMoney } from \"../account/format\"\nimport type { CurrencyScales, Price } from \"../client/types\"\nimport type { Translator } from \"../i18n/messages\"\nimport { periodOf } from \"./period\"\n\n/** \"$4.99\", \"Rent for 3 days, $1.99\" or \"$10.00 every 30 days\". */\nexport function priceLabel(\n price: Pick<\n Price,\n | \"unit_amount\"\n | \"currency\"\n | \"billing_interval_hours\"\n | \"access_duration_hours\"\n >,\n scales: CurrencyScales,\n m: Translator,\n locale?: string\n): string {\n const amount =\n formatMoney(price.unit_amount, price.currency, scales, locale) ??\n `${price.unit_amount} ${price.currency}`\n const every = periodOf(price.billing_interval_hours)\n if (every)\n return m.t(\"products.recurring\", {\n amount,\n every: m.plural(`interval.every.${every.unit}`, every.count),\n })\n const access = periodOf(price.access_duration_hours)\n if (access)\n return m.t(\"products.rent\", {\n amount,\n period: m.plural(`interval.duration.${access.unit}`, access.count),\n })\n return m.t(\"products.once\", { amount })\n}\n","// The payment dialogs — hosts, not flows: one Dialog around OrderPayment, or\n// around the order's embedded payment page on the checkout origin. Closing is always\n// possible; an accepted payment settles on the server whether or not the\n// dialog stays open, and the order stays the customer's to pay.\nimport type { ReactNode } from \"react\"\n\nimport {\n appearanceStyle,\n appearanceTheme,\n type BillingAppearance,\n} from \"#orck/appearance\"\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogTitle,\n} from \"#orck/components/ui/dialog\"\nimport {\n EmbeddedPayment,\n type EmbeddedPaymentProps,\n} from \"#orck/embedded-payment\"\nimport { OrderPayment, type OrderPaymentProps } from \"#orck/order-payment\"\n\ninterface DialogProps {\n open: boolean\n onOpenChange: (open: boolean) => void\n}\n\nfunction PayDialog({\n open,\n onOpenChange,\n appearance,\n children,\n}: DialogProps & { appearance?: BillingAppearance; children: ReactNode }) {\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent\n className=\"orck max-h-[calc(100dvh-2rem)] w-[460px] max-w-[calc(100vw-2rem)] gap-0 overflow-hidden bg-background p-6 text-foreground ring-0 [&>[data-slot=dialog-close]]:top-5 [&>[data-slot=dialog-close]]:right-5 [&>[data-slot=dialog-close]]:text-foreground\"\n data-orck-theme={appearanceTheme(appearance)}\n style={appearanceStyle(appearance)}\n showCloseButton\n >\n <DialogTitle className=\"sr-only\">Payment</DialogTitle>\n <DialogDescription className=\"sr-only\">\n Complete your payment\n </DialogDescription>\n <div className=\"max-h-[calc(100dvh-5rem)] min-h-0 touch-pan-y [scrollbar-width:none] overflow-y-auto overscroll-contain pt-7 pr-6 [-webkit-overflow-scrolling:touch] [&::-webkit-scrollbar]:hidden\">\n {children}\n </div>\n </DialogContent>\n </Dialog>\n )\n}\n\nexport interface OrderModalProps extends OrderPaymentProps, DialogProps {}\n\nexport function OrderModal({\n open,\n onOpenChange,\n ...payment\n}: OrderModalProps) {\n return (\n <PayDialog\n open={open}\n onOpenChange={onOpenChange}\n appearance={payment.appearance}\n >\n <OrderPayment {...payment} />\n </PayDialog>\n )\n}\n\nexport interface EmbeddedModalProps extends EmbeddedPaymentProps, DialogProps {\n appearance?: BillingAppearance\n}\n\nexport function EmbeddedModal({\n open,\n onOpenChange,\n appearance,\n ...payment\n}: EmbeddedModalProps) {\n return (\n <PayDialog open={open} onOpenChange={onOpenChange} appearance={appearance}>\n <EmbeddedPayment {...payment} />\n </PayDialog>\n )\n}\n","// BuyButton buys one price the host's page carries: it creates the signed-in\n// customer's order and pays it, in OrderPayment on the page, or, on a site\n// the merchant registered to frame its pay URLs, in the order's embedded\n// pay URL on the checkout origin. The app never handles the order itself.\nimport * as React from \"react\"\nimport { cn } from \"cn\"\n\nimport type { BillingAppearance } from \"#orck/appearance\"\nimport { isBillingError, localError, toBillingError } from \"#orck/client/errors\"\nimport type { Order, Price } from \"#orck/client/types\"\nimport type { PaymentFallbacks } from \"#orck/fallbacks\"\nimport { Button } from \"#orck/components/ui/button\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport { priceLabel } from \"#orck/lib/price-label\"\nimport { EmbeddedModal, OrderModal } from \"#orck/modal\"\nimport { useCurrencyScales } from \"#orck/react/config\"\nimport { useBillingContext } from \"#orck/react/context\"\nimport { useScopeProps, useUiSettings } from \"#orck/scope-context\"\n\nexport interface BuyButtonProps {\n /**\n * The price to buy, from a product the host's server put in its page (the\n * Go Client's ListProducts, its prices as a buyer sees them:\n * `billing.BuyerPrices`). The browser never reads the catalog.\n */\n price: Price\n /** The button's text; by default the price's amount and terms. */\n label?: string\n /**\n * A customer-chosen deposit, in the price currency's native units, for a\n * price with `customer_amount`; the order charges exactly this.\n */\n amount?: string\n /** Where a redirect PSP (Stripe's hosted page) returns the buyer: one of the app's return origins. */\n returnUrl?: string\n /** PSPs kept back until others fail on the order; see OrderPayment. */\n fallbacks?: PaymentFallbacks\n /**\n * The order is paid. A hint: the host's own gate decides access, so send\n * the buyer to the content it guards.\n */\n onPaid: (order: Order) => void\n /**\n * Buying needs a signed-in customer: called instead of paying when\n * `signedIn` is false or OpenRails answers 401.\n */\n onSignInRequired: () => void\n /** false when the host knows the visitor is signed out. */\n signedIn?: boolean\n appearance?: BillingAppearance\n className?: string\n}\n\n// An unpaid order of the customer's that holds what is being bought: the\n// refusal names it, and the customer pays that one instead.\nfunction heldBy(err: unknown): string | undefined {\n if (!isBillingError(err) || err.code !== \"already_owned\") return undefined\n const owner = err.metadata.owned_by\n return typeof owner === \"string\" && owner.startsWith(\"ord_\")\n ? owner\n : undefined\n}\n\n// Where the order is paid: on this page, or framed from the checkout origin.\ntype Paying =\n | { kind: \"inline\"; orderId: string }\n | { kind: \"embedded\"; orderId: string; url: string }\n\n// A page on an origin the merchant registered to frame its pay URLs pays\n// there; any other pays on the page.\nconst framesCheckout = (origins: string[]) =>\n typeof window !== \"undefined\" && origins.includes(window.location.origin)\n\n/** One price's button and its order. Requires `BillingProvider`. */\nexport function BuyButton({\n price,\n label,\n amount,\n returnUrl,\n fallbacks,\n onPaid,\n onSignInRequired,\n signedIn,\n appearance,\n className,\n}: BuyButtonProps) {\n const m = useMessages()\n const { locale } = useUiSettings()\n const scales = useCurrencyScales()\n const scope = useScopeProps(appearance)\n const { client } = useBillingContext()\n const [paying, setPaying] = React.useState<Paying>()\n const [starting, setStarting] = React.useState(false)\n const [failure, setFailure] = React.useState<string>()\n const paid = (order: Order) => {\n if (order.status !== \"complete\") return\n setPaying(undefined)\n onPaid(order)\n }\n\n const buy = async () => {\n if (signedIn === false) return onSignInRequired()\n setFailure(undefined)\n setStarting(true)\n try {\n const { merchant } = await client.getCustomerConfig()\n const embedded = framesCheckout(merchant.embed_origins)\n let order: Order\n try {\n // No key: OpenRails answers the customer's open order of these lines,\n // so a second click, a reopened dialog or a reload pays the same one.\n ;({ order } = await client.createOrder({\n lines: [{ price_id: price.id, ...(amount ? { amount } : {}) }],\n ...(embedded ? { payUrl: { embedded: true } } : {}),\n }))\n } catch (err) {\n const held = heldBy(err)\n // Only an order made with a pay URL answers its URL.\n if (!held || embedded) throw err\n setPaying({ kind: \"inline\", orderId: held })\n return\n }\n if (order.status === \"complete\") return paid(order)\n if (!embedded) {\n setPaying({ kind: \"inline\", orderId: order.id })\n return\n }\n const url = order.pay_url\n if (!url)\n throw localError(\n \"invalid_response\",\n \"the order answered no pay URL\"\n )\n setPaying({ kind: \"embedded\", orderId: order.id, url })\n } catch (err) {\n if (isBillingError(err) && err.status === 401) onSignInRequired()\n else setFailure(m.error(toBillingError(err)))\n } finally {\n setStarting(false)\n }\n }\n\n const close = (open: boolean) => !open && setPaying(undefined)\n return (\n <span\n className={cn(scope.className, \"inline-flex flex-col gap-1\", className)}\n data-orck-theme={scope[\"data-orck-theme\"]}\n // A styling root is a size container; a button sizes to its label.\n style={{ ...scope.style, containerType: \"normal\" }}\n >\n <Button disabled={starting} onClick={() => void buy()}>\n {label ?? priceLabel(price, scales, m, locale)}\n </Button>\n {failure ? (\n <span role=\"alert\" className=\"text-sm text-destructive\">\n {failure}\n </span>\n ) : null}\n {paying?.kind === \"inline\" ? (\n <OrderModal\n open\n onOpenChange={close}\n orderId={paying.orderId}\n returnUrl={returnUrl}\n fallbacks={fallbacks}\n appearance={appearance}\n onSettled={paid}\n />\n ) : null}\n {paying?.kind === \"embedded\" ? (\n <EmbeddedModal\n open\n onOpenChange={close}\n url={paying.url}\n fallbacks={fallbacks}\n appearance={appearance}\n // The frame's word is a hint: the order says whether it is paid.\n onComplete={() =>\n void client.getOrder(paying.orderId).then(paid, () => undefined)\n }\n onLoadFailure={() =>\n void client\n .reportPayURLFailure(paying.orderId)\n .catch(() => undefined)\n }\n />\n ) : null}\n </span>\n )\n}\n","// ProductList sells the products the host's page carries: each one on sale,\n// one buy button per price. The host's server decides what to sell (say from\n// its gate's 402) and puts the products in its page; the browser never reads\n// the catalog. The host decides what happens once it's paid.\nimport * as React from \"react\"\nimport { cn } from \"cn\"\n\nimport { RESET } from \"#orck/account/format\"\nimport { EmptyState } from \"#orck/account/section\"\nimport type { BillingAppearance } from \"#orck/appearance\"\nimport { BuyButton } from \"#orck/buy-button\"\nimport type { Order, Product } from \"#orck/client/types\"\nimport type { PaymentFallbacks } from \"#orck/fallbacks\"\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from \"#orck/components/ui/card\"\nimport { useMessages } from \"#orck/i18n/context\"\nimport { useScopeProps } from \"#orck/scope-context\"\n\nexport interface ProductListProps {\n /**\n * What to sell, from the host's own server: the Go Client's ListProducts\n * (by product key or entitlement), their prices as a buyer sees them\n * (`billing.BuyerPrices`).\n */\n products: Product[]\n /**\n * The order is paid. A hint: the host's own gate decides access, so send\n * the buyer back to the content it guards.\n */\n onPaid: (order: Order) => void\n /**\n * Buying needs a signed-in customer: called instead of the purchase when\n * `signedIn` is false or OpenRails answers 401.\n */\n onSignInRequired: () => void\n /** false when the host knows the visitor is signed out. */\n signedIn?: boolean\n /** Where a redirect PSP (Stripe's hosted page) returns the buyer: one of the app's return origins. */\n returnUrl?: string\n /** PSPs kept back until others fail on the order; see OrderPayment. */\n fallbacks?: PaymentFallbacks\n appearance?: BillingAppearance\n className?: string\n}\n\ntype ListedPrice = ProductListProps[\"products\"][number][\"prices\"][number]\n\nconst sameTerms = (a: ListedPrice, b: ListedPrice) =>\n a.unit_amount === b.unit_amount &&\n a.currency === b.currency &&\n a.billing_interval_hours === b.billing_interval_hours &&\n a.access_duration_hours === (b.provider?.access_duration_default ? b.billing_interval_hours : b.access_duration_hours) &&\n !a.trial_unit_amount && !b.trial_unit_amount &&\n !a.trial_duration_hours && !b.trial_duration_hours &&\n !a.quantity && !b.quantity\n\nexport function ProductList({\n products: given,\n onPaid,\n onSignInRequired,\n signedIn,\n returnUrl,\n fallbacks,\n appearance,\n className,\n}: ProductListProps) {\n const m = useMessages()\n const scope = useScopeProps(appearance)\n\n // A deposit's amount is chosen before purchase; ProductList sells fixed\n // prices. A provider's price on the terms of one of ours is that price's\n // fallback on the order, not a price of its own.\n const products = given\n .filter((product) => !product.archived)\n .map((product) => {\n const live = product.prices.filter(\n (p) => !p.archived && !p.customer_amount && (!p.provider || p.provider.rail === \"ccbill\")\n )\n return {\n product,\n prices: live.filter(\n (p) => !p.provider || !live.some((o) => !o.provider && (!o.sell_via?.length || o.sell_via.includes(\"card\")) && sameTerms(o, p))\n ),\n }\n })\n .filter((entry) => entry.prices.length > 0)\n\n let body: React.ReactNode\n if (products.length === 0) {\n body = <EmptyState title={m.t(\"products.empty\")} />\n } else {\n body = products.map(({ product, prices }) => (\n <Card key={product.id} className=\"gap-4\" data-testid=\"product\">\n <CardHeader>\n <CardTitle role=\"heading\" aria-level={2}>\n {product.display_name}\n </CardTitle>\n {product.description ? (\n <CardDescription>{product.description}</CardDescription>\n ) : null}\n </CardHeader>\n <CardContent className=\"flex flex-wrap gap-2\">\n {prices.map((price) => (\n <BuyButton\n key={price.id}\n price={price}\n onPaid={onPaid}\n onSignInRequired={onSignInRequired}\n signedIn={signedIn}\n returnUrl={returnUrl}\n fallbacks={fallbacks}\n appearance={appearance}\n />\n ))}\n </CardContent>\n </Card>\n ))\n }\n\n return (\n <div\n className={cn(scope.className, RESET, \"grid gap-4\", className)}\n data-orck-theme={scope[\"data-orck-theme\"]}\n style={scope.style}\n >\n {body}\n </div>\n )\n}\n","export interface BillingNotificationItem {\n kind: string\n data?: unknown\n}\nexport type BillingNotificationAction =\n | \"update_payment_method\"\n | \"resubscribe\"\n | \"authenticate_payment\"\n | \"contact_support\"\n | \"manage_billing\"\nexport type BillingNotificationActions = Partial<\n Record<BillingNotificationAction, string>\n>\n\nexport function dataOf(item: BillingNotificationItem): Record<string, unknown> {\n return item.data && typeof item.data === \"object\" && !Array.isArray(item.data)\n ? (item.data as Record<string, unknown>)\n : {}\n}\n\n/** The selected billing lifecycle outcomes, rather than signup/cancel confirmations. */\nexport function isPaymentFailure(kind: string): boolean {\n return [\n \"payment_method_failed\",\n \"payment_method_update_required\",\n \"payment_authentication_required\",\n \"order_collection_stopped\",\n ].includes(kind)\n}\n\nexport function isBillingNotification(item: BillingNotificationItem): boolean {\n return (\n isPaymentFailure(item.kind) ||\n item.kind === \"premium_ended\" ||\n (item.kind === \"premium_renewed\" && dataOf(item).downgrade_applied === true)\n )\n}\n\n/** The immutable event's guidance; it is not a claim that a debt remains open. */\nexport function billingNotificationAction(\n item: BillingNotificationItem\n): BillingNotificationAction {\n const action =\n dataOf(item).recovery_action ??\n (item.kind === \"payment_method_update_required\"\n ? \"update_payment_method\"\n : item.kind === \"payment_authentication_required\"\n ? \"authenticate_payment\"\n : undefined)\n return action === \"update_payment_method\" ||\n action === \"resubscribe\" ||\n action === \"authenticate_payment\" ||\n action === \"contact_support\"\n ? action\n : \"manage_billing\"\n}\n","import { useMessages } from \"../i18n/context\"\nimport {\n createTranslator,\n resolveMessages,\n type Translator,\n type BillingUiMessageBundle,\n} from \"../i18n/messages\"\nimport { BillingUiRoot } from \"../scope\"\nimport type { BillingAppearance } from \"../appearance\"\n\nimport {\n dataOf,\n isPaymentFailure,\n isBillingNotification,\n billingNotificationAction,\n type BillingNotificationItem,\n type BillingNotificationActions,\n} from \"../lib/billing-notification\"\n\n/** Shared billing wording. Hosts supply only their authorized destination URLs. */\nexport function BillingNotification({\n item,\n actions = {},\n language,\n messages,\n appearance,\n}: {\n item: BillingNotificationItem\n actions?: BillingNotificationActions\n language?: string\n messages?: BillingUiMessageBundle\n appearance?: BillingAppearance\n}) {\n const inherited = useMessages()\n const translator =\n language || messages\n ? createTranslator(\n messages ? resolveMessages(messages) : inherited.messages,\n undefined,\n language ?? inherited.locale\n )\n : inherited\n const { t } = translator\n if (!isBillingNotification(item)) return null\n const data = dataOf(item)\n const title =\n item.kind === \"payment_method_update_required\"\n ? t(\"billingNotifications.paymentMethodRequiredTitle\")\n : item.kind === \"payment_authentication_required\"\n ? t(\"billingNotifications.authenticationRequiredTitle\")\n : item.kind === \"order_collection_stopped\"\n ? t(\"billingNotifications.collectionStoppedTitle\")\n : isPaymentFailure(item.kind)\n ? t(\"billingNotifications.paymentFailed\")\n : item.kind === \"premium_ended\"\n ? t(\"billingNotifications.membershipEnded\")\n : t(\"billingNotifications.membershipDowngraded\")\n let detail: string\n if (isPaymentFailure(item.kind)) {\n const attempt = date(data.next_attempt_at, translator)\n detail =\n data.retry_status === \"scheduled\" && attempt\n ? t(\"billingNotifications.retryScheduled\", { date: attempt })\n : data.retry_status === \"payment_method_required\"\n ? t(\"billingNotifications.paymentMethodRequired\")\n : data.retry_status === \"stopped\"\n ? t(\"billingNotifications.retryStopped\")\n : t(\"billingNotifications.retryUnknown\")\n } else if (item.kind === \"premium_ended\") {\n const ended = date(data.ended_at, translator)\n detail = ended\n ? t(\"billingNotifications.endedAt\", { date: ended })\n : t(\"billingNotifications.ended\")\n } else {\n detail =\n typeof data.from_product_name === \"string\" &&\n typeof data.to_product_name === \"string\" &&\n data.from_product_name &&\n data.to_product_name\n ? t(\"billingNotifications.downgradedTo\", {\n from: data.from_product_name,\n to: data.to_product_name,\n })\n : t(\"billingNotifications.downgraded\")\n }\n const action = billingNotificationAction(item)\n const href = actions[action] ?? actions.manage_billing\n const label = actions[action] ? action : \"manage_billing\"\n return (\n <BillingUiRoot\n appearance={appearance}\n className=\"grid gap-2\"\n data-orck=\"billing-notification\"\n >\n <p className=\"font-medium\">{title}</p>\n <p className=\"text-muted-foreground\">{detail}</p>\n {isPaymentFailure(item.kind) && (\n <p className=\"text-muted-foreground\">\n {t(`billingNotifications.instructions.${action}`)}\n </p>\n )}\n {href && (\n <a href={href} className=\"font-medium underline underline-offset-4\">\n {t(`billingNotifications.actions.${label}`)}\n </a>\n )}\n </BillingUiRoot>\n )\n}\n\nfunction date(value: unknown, translator: Translator): string | undefined {\n if (typeof value !== \"string\" || !Number.isFinite(Date.parse(value)))\n return undefined\n return new Intl.DateTimeFormat(translator.locale, {\n dateStyle: \"medium\",\n timeStyle: \"short\",\n }).format(new Date(value))\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAOA,SAAgB,GAAc,EAC5B,eACA,cACA,UACA,GAAG,KAC0D;CAC7D,IAAM,IAAQ,EAAc,CAAU;CACtC,OACE,kBAAC,OAAD;EACE,mBAAiB,EAAM;EACvB,WAAW,EAAG,EAAM,WAAW,CAAS;EACxC,OAAO;GAAE,GAAG,EAAM;GAAO,GAAG;EAAM;EAClC,GAAI;CACL,CAAA;AAEL;;;AClBA,IAAM,KAAiB,GACrB,8lBACA;CACE,UAAU;EACR,SAAS;GACP,SAAS;GACT,SACE;GACF,WACE;GACF,OACE;GACF,aACE;GACF,MAAM;EACR;EACA,MAAM;GACJ,SACE;GACF,IAAI;GACJ,IAAI;GACJ,IAAI;GACJ,MAAM;GACN,WACE;GACF,WACE;GACF,WAAW;EACb;CACF;CACA,iBAAiB;EACf,SAAS;EACT,MAAM;CACR;AACF,CACF;AAEA,SAAS,EAAO,EACd,cACA,aAAU,WACV,UAAO,WACP,GAAG,KAC2D;CAC9D,OACE,kBAAC,GAAD;EACE,aAAU;EACV,WAAW,EAAG,GAAe;GAAE;GAAS;GAAM;EAAU,CAAC,CAAC;EAC1D,GA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