LCOV - code coverage report
Current view: top level - packages/account-core/src/core/billing - topup.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 11.0 % 100 11
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : /**
       2              :  * The top-up command: one credit purchase mapped onto the shared billing
       3              :  * lifecycle. This module owns the request and response shapes and nothing
       4              :  * else — the status-read gate, single-flight, polling, routing, the pointer,
       5              :  * failure meaning, and telemetry all come from the lifecycle it runs on.
       6              :  *
       7              :  * The result is a command-level union rather than an extension of
       8              :  * `BillingErrorCode`: what a top-up can conclude (refused by capability,
       9              :  * declined by the provider, not available on this backend) is the command's
      10              :  * own vocabulary, and the terminal operation is embedded whenever one was
      11              :  * observed so a host reads the coded decline and recovery action from it.
      12              :  */
      13              : import type {
      14              :   InteractiveTopupRequest,
      15              :   TopupAutoTopUpSettings
      16              : } from '@comfyorg/ingest-types'
      17              : import {
      18              :   zCreateTopupCheckoutRequest,
      19              :   zCreateTopupCheckoutResponse,
      20              :   zCreateTopupRequest,
      21              :   zCreateTopupResponse,
      22              :   zInteractiveTopupRequest,
      23              :   zTopupQuoteResponse
      24              : } from '@comfyorg/ingest-types/zod'
      25              : 
      26              : import type {
      27              :   BillingFailure,
      28              :   BillingResult,
      29              :   BillingTransport
      30              : } from './billingContracts'
      31              : import { matchesServerCode } from './billingContracts'
      32              : import type { CapabilitiesReader } from './capabilities'
      33              : import type { CapabilityDenialReason } from './capabilityDenials'
      34              : import type { CreditsReader } from './credits'
      35              : import type {
      36              :   BillingOperationLifecycle,
      37              :   IssuedBillingOperation
      38              : } from './operationLifecycle'
      39              : import type {
      40              :   BillingOperationState,
      41              :   FailedBillingOperation
      42              : } from './operationState'
      43              : import { isTerminal, validateActionUrl } from './operationState'
      44              : import { readValidatedBillingResponse } from './sharedRead'
      45              : import { wireCents } from './wireCents'
      46              : 
      47         2356 : export const TOPUP_ROUTE = '/billing/topup'
      48              : /**
      49              :  * The hosted variant: a provider-hosted Checkout session with no operation to
      50              :  * observe. The purchase happens on the returned page and the credits land
      51              :  * through a webhook, so completion is the host's return plus a balance watch.
      52              :  */
      53         2356 : export const TOPUP_CHECKOUT_ROUTE = '/billing/topup/checkout'
      54              : /** A read the backend shapes as a POST: nothing is charged or reserved. */
      55         2356 : export const TOPUP_QUOTE_ROUTE = '/billing/topup/quote'
      56              : /** Pay once with a new card or an explicitly chosen saved card; an older backend answers 404. */
      57         2356 : export const INTERACTIVE_TOPUP_ROUTE = '/billing/topup/interactive'
      58              : 
      59              : /** The server's own server code for an amount it will not sell. */
      60         2356 : const INVALID_AMOUNT_SERVER_CODE = 'INVALID_AMOUNT'
      61              : 
      62         2356 : const TopupQuoteSchema = zTopupQuoteResponse.extend({
      63              :   amount_cents: wireCents,
      64              :   credits: wireCents
      65              : })
      66              : 
      67              : /**
      68              :  * What the server says an amount buys. `credits` is the server's display
      69              :  * count; `expiresAt` is when the grant would lapse, which the server may
      70              :  * move, so a host never states the expiry policy itself.
      71              :  */
      72              : export interface TopupQuote {
      73              :   readonly amountCents: number
      74              :   readonly credits: number
      75              :   readonly expiresAt: string
      76              :   /** The provider configuration a pay-once card form mounts with; absent when the server configured none. */
      77              :   readonly paymentMethodConfigurationId?: string
      78              : }
      79              : 
      80              : export type TopupQuoteResult =
      81              :   | { readonly status: 'ok'; readonly value: TopupQuote }
      82              :   | BillingFailure
      83              :   | TopupNotAvailable
      84              :   | TopupInvalidAmount
      85              : 
      86              : export interface QuoteTopupInput {
      87              :   readonly amountCents: number
      88              :   readonly signal?: AbortSignal
      89              : }
      90              : 
      91              : /** The one coded error body this command acts on; every other code stays a `BillingFailure`. */
      92         2356 : const NO_PAYMENT_METHOD_SERVER_CODE = 'NO_PAYMENT_METHOD'
      93              : 
      94              : type OperationIn<P extends BillingOperationState['phase']> = Extract<
      95              :   BillingOperationState,
      96              :   { readonly phase: P }
      97              : >
      98              : 
      99              : export interface TopupSucceeded {
     100              :   readonly status: 'ok'
     101              :   readonly operation: OperationIn<'succeeded'>
     102              :   /**
     103              :    * True once the balance read after settlement exceeds the one read before
     104              :    * the command. False is "payment received, credits pending": the purchase
     105              :    * settled and the balance has not caught up, or no baseline was readable.
     106              :    */
     107              :   readonly creditsReconciled: boolean
     108              : }
     109              : 
     110              : export interface TopupDeclined {
     111              :   readonly status: 'declined'
     112              :   readonly operation: FailedBillingOperation
     113              : }
     114              : 
     115              : /** The lifecycle stopped observing without a verdict; the id is the host's handle to support. */
     116              : export interface TopupUnsettled {
     117              :   readonly status: 'unsettled'
     118              :   readonly operation: OperationIn<'timed_out' | 'reconciliation_needed'>
     119              : }
     120              : 
     121              : /** The server resolved `can_top_up` false for this scope; nothing was sent. */
     122              : export interface TopupDenied {
     123              :   readonly status: 'error'
     124              :   readonly code: 'ACCESS_DENIED'
     125              :   readonly denial?: CapabilityDenialReason
     126              : }
     127              : 
     128              : /** The top-up route is not deployed on this backend. */
     129              : export interface TopupNotAvailable {
     130              :   readonly status: 'error'
     131              :   readonly code: 'NOT_AVAILABLE'
     132              : }
     133              : 
     134              : export interface TopupNoPaymentMethod {
     135              :   readonly status: 'error'
     136              :   readonly code: 'NO_PAYMENT_METHOD'
     137              :   readonly recoveryAction: 'replace_payment_method'
     138              : }
     139              : 
     140              : /** The amount fails the generated request contract; nothing was sent. */
     141              : export interface TopupInvalidAmount {
     142              :   readonly status: 'error'
     143              :   readonly code: 'INVALID_AMOUNT'
     144              : }
     145              : 
     146              : export type TopupFailure =
     147              :   | BillingFailure
     148              :   | TopupDenied
     149              :   | TopupNotAvailable
     150              :   | TopupNoPaymentMethod
     151              :   | TopupInvalidAmount
     152              : 
     153              : export type TopupResult =
     154              :   | TopupSucceeded
     155              :   | TopupDeclined
     156              :   | TopupUnsettled
     157              :   | TopupFailure
     158              : 
     159              : /** The return URL fails the generated request contract; nothing was sent. */
     160              : export interface TopupInvalidReturnUrl {
     161              :   readonly status: 'error'
     162              :   readonly code: 'INVALID_RETURN_URL'
     163              : }
     164              : 
     165              : /**
     166              :  * A hosted Checkout session the host now sends the customer to. There is no
     167              :  * operation and none is invented: the host executes its `OpenUrlMode` on
     168              :  * `url`, and on return arms `createBalanceWatch` with `baselineMicros` to
     169              :  * learn that the credits landed.
     170              :  */
     171              : export interface HostedTopupCheckout {
     172              :   readonly status: 'ok'
     173              :   /** The provider-hosted Checkout page; https only. */
     174              :   readonly url: string
     175              :   /** The provider's session id, for support and log correlation. */
     176              :   readonly sessionId?: string
     177              :   /** The balance read before the session was created; absent when that read failed. */
     178              :   readonly baselineMicros?: number
     179              : }
     180              : 
     181              : export type HostedTopupCheckoutFailure =
     182              :   | BillingFailure
     183              :   | TopupDenied
     184              :   | TopupNotAvailable
     185              :   | TopupInvalidAmount
     186              :   | TopupInvalidReturnUrl
     187              : 
     188              : export type HostedTopupCheckoutResult =
     189              :   | HostedTopupCheckout
     190              :   | HostedTopupCheckoutFailure
     191              : 
     192              : export interface CreateHostedTopupCheckoutInput {
     193              :   readonly amountCents: number
     194              :   /** Where the provider returns the customer; the backend allowlists its origin. */
     195              :   readonly returnUrl: string
     196              :   /** Turns auto top-up on once this purchase is paid; the checkout read reports the outcome. */
     197              :   readonly autoTopUp?: TopupAutoTopUpSettings
     198              :   readonly signal?: AbortSignal
     199              : }
     200              : 
     201              : export interface CreateTopupCheckoutInput {
     202              :   readonly amountCents: number
     203              :   /**
     204              :    * Releases the capability read and the POST. Once the operation is adopted
     205              :    * the lifecycle owns it, and the wait follows it to a terminal state.
     206              :    */
     207              :   readonly signal?: AbortSignal
     208              : }
     209              : 
     210              : /** Exactly one payment authority: a new card's confirmation token, or a saved card the customer chose. */
     211              : export type InteractiveTopupPayment =
     212              :   | { readonly confirmationToken: string; readonly returnUrl: string }
     213              :   | { readonly savedPaymentMethodId: string }
     214              : 
     215              : export interface CreateInteractiveTopupInput {
     216              :   readonly amountCents: number
     217              :   readonly payment: InteractiveTopupPayment
     218              :   /** The caller's key for this purchase, resent unchanged while its outcome is unresolved. */
     219              :   readonly idempotencyKey: string
     220              :   readonly signal?: AbortSignal
     221              : }
     222              : 
     223              : export interface TopupCommandOptions {
     224              :   readonly transport: BillingTransport
     225              :   readonly lifecycle: Pick<BillingOperationLifecycle, 'begin' | 'settled'>
     226              :   readonly capabilities: Pick<CapabilitiesReader, 'read' | 'invalidate'>
     227              :   readonly credits: Pick<CreditsReader, 'read'>
     228              :   /** One key per POST attempt: the backend dedupes on it and the transport replays a 401 under it. */
     229              :   readonly idempotencyKey?: () => string
     230              : }
     231              : 
     232              : export interface TopupCommand {
     233              :   /**
     234              :    * Quotes an amount without starting anything. It does not check the plan
     235              :    * tier or the payment method, so a quote does not promise the top-up will
     236              :    * go through.
     237              :    */
     238              :   quoteTopup: (input: QuoteTopupInput) => Promise<TopupQuoteResult>
     239              :   createTopupCheckout: (input: CreateTopupCheckoutInput) => Promise<TopupResult>
     240              :   /** Pays once with the given authority; never saves the card or changes the default. */
     241              :   createInteractiveTopup: (
     242              :     input: CreateInteractiveTopupInput
     243              :   ) => Promise<TopupResult>
     244              :   /**
     245              :    * The route Workshop and Platform ship on today. Unlike
     246              :    * `createTopupCheckout` it resolves as soon as the session exists, because
     247              :    * nothing about the purchase can be observed until the customer returns.
     248              :    */
     249              :   createHostedTopupCheckout: (
     250              :     input: CreateHostedTopupCheckoutInput
     251              :   ) => Promise<HostedTopupCheckoutResult>
     252              : }
     253              : 
     254         2356 : const INVALID_AMOUNT = {
     255              :   status: 'error',
     256              :   code: 'INVALID_AMOUNT'
     257              : } as const satisfies TopupInvalidAmount
     258              : 
     259         2356 : const INVALID_RETURN_URL = {
     260              :   status: 'error',
     261              :   code: 'INVALID_RETURN_URL'
     262              : } as const satisfies TopupInvalidReturnUrl
     263              : 
     264         2356 : const NOT_AVAILABLE = {
     265              :   status: 'error',
     266              :   code: 'NOT_AVAILABLE'
     267              : } as const satisfies TopupNotAvailable
     268              : 
     269            0 : function hostedCheckoutBody(input: CreateHostedTopupCheckoutInput) {
     270            0 :   return {
     271              :     amount_cents: input.amountCents,
     272              :     return_url: input.returnUrl,
     273              :     ...(input.autoTopUp === undefined ? {} : { auto_top_up: input.autoTopUp })
     274              :   }
     275              : }
     276              : 
     277            0 : function validateHostedCheckoutInput(
     278              :   input: CreateHostedTopupCheckoutInput
     279              : ): TopupInvalidAmount | TopupInvalidReturnUrl | undefined {
     280            0 :   const parsed = zCreateTopupCheckoutRequest.safeParse(
     281              :     hostedCheckoutBody(input)
     282              :   )
     283            0 :   if (parsed.success) return undefined
     284              :   const fields = new Set(parsed.error.issues.map((issue) => issue.path[0]))
     285            0 :   return fields.has('amount_cents') ? INVALID_AMOUNT : INVALID_RETURN_URL
     286              : }
     287              : 
     288              : type PurchaseBody = Pick<
     289              :   InteractiveTopupRequest,
     290              :   'amount_cents' | 'idempotency_key'
     291              : >
     292              : 
     293         2356 : const SUPERSEDED = {
     294              :   status: 'error',
     295              :   code: 'SUPERSEDED'
     296              : } as const satisfies BillingFailure
     297              : 
     298            0 : function commandFailure(failure: BillingFailure): TopupFailure {
     299            0 :   if (matchesServerCode(failure, NO_PAYMENT_METHOD_SERVER_CODE)) {
     300            0 :     return {
     301              :       status: 'error',
     302              :       code: 'NO_PAYMENT_METHOD',
     303              :       recoveryAction: 'replace_payment_method'
     304              :     }
     305              :   }
     306            0 :   if (failure.httpStatus === 404) return NOT_AVAILABLE
     307            0 :   return failure
     308              : }
     309              : 
     310            0 : export function createTopupCommand(options: TopupCommandOptions): TopupCommand {
     311            0 :   const {
     312              :     transport,
     313              :     lifecycle,
     314              :     capabilities,
     315              :     credits,
     316              :     idempotencyKey = () => crypto.randomUUID()
     317              :   } = options
     318              : 
     319            0 :   async function issue(
     320              :     route: string,
     321              :     body: PurchaseBody,
     322              :     signal: AbortSignal | undefined
     323              :   ): Promise<BillingResult<IssuedBillingOperation>> {
     324            0 :     const response = await readValidatedBillingResponse(
     325              :       transport,
     326              :       {
     327              :         method: 'POST',
     328              :         route,
     329              :         body,
     330              :         idempotencyKey: body.idempotency_key,
     331              :         ...(signal === undefined ? {} : { signal })
     332              :       },
     333              :       (raw) => zCreateTopupResponse.safeParse(raw)
     334              :     )
     335            0 :     if (response.status === 'error') return response
     336            0 :     return {
     337              :       status: 'ok',
     338              :       value: { operationId: response.value.data.billing_op_id }
     339              :     }
     340              :   }
     341              : 
     342            0 :   async function conclude(
     343              :     operation: BillingOperationState,
     344              :     baselineMicros: number | undefined
     345              :   ): Promise<TopupResult> {
     346            0 :     if (!isTerminal(operation)) return SUPERSEDED
     347            0 :     switch (operation.phase) {
     348              :       case 'succeeded': {
     349            0 :         capabilities.invalidate()
     350            0 :         const after = await credits.read()
     351            0 :         return {
     352              :           status: 'ok',
     353              :           operation,
     354              :           creditsReconciled:
     355              :             baselineMicros !== undefined &&
     356              :             after.status === 'ok' &&
     357              :             after.value.balance.amount_micros > baselineMicros
     358              :         }
     359              :       }
     360              :       case 'failed':
     361            0 :         return { status: 'declined', operation }
     362              :       case 'timed_out':
     363              :       case 'reconciliation_needed':
     364            0 :         return { status: 'unsettled', operation }
     365              :       case 'superseded':
     366            0 :         return SUPERSEDED
     367              :     }
     368              :   }
     369              : 
     370            0 :   async function readTopupEligibility(
     371              :     signal: AbortSignal | undefined
     372              :   ): Promise<BillingFailure | TopupDenied | undefined> {
     373            0 :     const allowed = await capabilities.read(
     374              :       signal === undefined ? {} : { signal }
     375              :     )
     376            0 :     if (allowed.status === 'error') return allowed
     377            0 :     if (allowed.value.capabilities.can_top_up) return undefined
     378            0 :     const denial = allowed.value.denials.can_top_up
     379            0 :     return {
     380              :       status: 'error',
     381              :       code: 'ACCESS_DENIED',
     382              :       ...(denial === undefined ? {} : { denial })
     383              :     }
     384              :   }
     385              : 
     386            0 :   async function purchase(
     387              :     route: string,
     388              :     body: PurchaseBody,
     389              :     signal: AbortSignal | undefined
     390              :   ): Promise<TopupResult> {
     391            0 :     const refused = await readTopupEligibility(signal)
     392            0 :     if (refused) return refused
     393              : 
     394            0 :     const baseline = await credits.read()
     395            0 :     const baselineMicros =
     396              :       baseline.status === 'ok'
     397              :         ? baseline.value.balance.amount_micros
     398              :         : undefined
     399              : 
     400            0 :     let issueFailure: TopupFailure | undefined
     401            0 :     const began = await lifecycle.begin('topup', async () => {
     402            0 :       const issued = await issue(route, body, signal)
     403            0 :       if (issued.status === 'error') issueFailure = commandFailure(issued)
     404            0 :       return issued
     405              :     })
     406            0 :     if (began.status === 'error') return issueFailure ?? began
     407              : 
     408            0 :     const settled = lifecycle.settled(began.value.id)
     409            0 :     if (settled === undefined) return SUPERSEDED
     410            0 :     return conclude(await settled, baselineMicros)
     411              :   }
     412              : 
     413            0 :   async function createTopupCheckout(
     414              :     input: CreateTopupCheckoutInput
     415              :   ): Promise<TopupResult> {
     416            0 :     const { amountCents, signal } = input
     417            0 :     if (!zCreateTopupRequest.safeParse({ amount_cents: amountCents }).success) {
     418            0 :       return INVALID_AMOUNT
     419              :     }
     420            0 :     return purchase(
     421              :       TOPUP_ROUTE,
     422              :       { amount_cents: amountCents, idempotency_key: idempotencyKey() },
     423              :       signal
     424              :     )
     425              :   }
     426              : 
     427            0 :   async function createInteractiveTopup(
     428              :     input: CreateInteractiveTopupInput
     429              :   ): Promise<TopupResult> {
     430            0 :     const { amountCents, payment, signal } = input
     431            0 :     const body = {
     432              :       amount_cents: amountCents,
     433              :       idempotency_key: input.idempotencyKey,
     434              :       ...('confirmationToken' in payment
     435              :         ? {
     436              :             confirmation_token: payment.confirmationToken,
     437              :             return_url: payment.returnUrl
     438              :           }
     439              :         : { saved_payment_method_id: payment.savedPaymentMethodId })
     440              :     }
     441            0 :     if (!zInteractiveTopupRequest.safeParse(body).success) return INVALID_AMOUNT
     442            0 :     return purchase(INTERACTIVE_TOPUP_ROUTE, body, signal)
     443              :   }
     444              : 
     445            0 :   async function issueHostedCheckout(
     446              :     input: CreateHostedTopupCheckoutInput
     447              :   ): Promise<BillingResult<Pick<HostedTopupCheckout, 'url' | 'sessionId'>>> {
     448            0 :     const body = {
     449              :       ...hostedCheckoutBody(input),
     450              :       idempotency_key: idempotencyKey()
     451              :     }
     452            0 :     const response = await readValidatedBillingResponse(
     453              :       transport,
     454              :       {
     455              :         method: 'POST',
     456              :         route: TOPUP_CHECKOUT_ROUTE,
     457              :         body,
     458              :         idempotencyKey: body.idempotency_key,
     459              :         ...(input.signal === undefined ? {} : { signal: input.signal })
     460              :       },
     461              :       (raw) => zCreateTopupCheckoutResponse.safeParse(raw)
     462              :     )
     463            0 :     if (response.status === 'error') return response
     464              : 
     465            0 :     const { data, httpStatus } = response.value
     466            0 :     const url = validateActionUrl(data.checkout_url)
     467            0 :     if (url === undefined) {
     468            0 :       return { status: 'error', code: 'MALFORMED_RESPONSE', httpStatus }
     469              :     }
     470            0 :     return {
     471              :       status: 'ok',
     472              :       value: {
     473              :         url,
     474              :         ...(data.session_id === undefined ? {} : { sessionId: data.session_id })
     475              :       }
     476              :     }
     477              :   }
     478              : 
     479            0 :   async function createHostedTopupCheckout(
     480              :     input: CreateHostedTopupCheckoutInput
     481              :   ): Promise<HostedTopupCheckoutResult> {
     482            0 :     const invalid = validateHostedCheckoutInput(input)
     483            0 :     if (invalid) return invalid
     484              : 
     485            0 :     const refused = await readTopupEligibility(input.signal)
     486            0 :     if (refused) return refused
     487              : 
     488            0 :     const baseline = await credits.read()
     489            0 :     if (input.signal?.aborted)
     490            0 :       return { status: 'error', code: 'REQUEST_FAILED' }
     491            0 :     const session = await issueHostedCheckout(input)
     492            0 :     if (session.status === 'error') {
     493            0 :       return session.httpStatus === 404 ? NOT_AVAILABLE : session
     494              :     }
     495            0 :     return {
     496              :       status: 'ok',
     497              :       ...session.value,
     498              :       ...(baseline.status === 'ok'
     499              :         ? { baselineMicros: baseline.value.balance.amount_micros }
     500              :         : {})
     501              :     }
     502              :   }
     503              : 
     504            0 :   async function quoteTopup(input: QuoteTopupInput): Promise<TopupQuoteResult> {
     505            0 :     const { amountCents, signal } = input
     506            0 :     if (!wireCents.positive().safeParse(amountCents).success)
     507            0 :       return INVALID_AMOUNT
     508            0 :     const response = await readValidatedBillingResponse(
     509              :       transport,
     510              :       {
     511              :         method: 'POST',
     512              :         route: TOPUP_QUOTE_ROUTE,
     513              :         body: { amount_cents: amountCents },
     514              :         ...(signal === undefined ? {} : { signal })
     515              :       },
     516              :       (raw) => TopupQuoteSchema.safeParse(raw)
     517              :     )
     518            0 :     if (response.status === 'error') {
     519            0 :       if (matchesServerCode(response, INVALID_AMOUNT_SERVER_CODE))
     520            0 :         return INVALID_AMOUNT
     521            0 :       return response.httpStatus === 404 ? NOT_AVAILABLE : response
     522              :     }
     523            0 :     const quote = response.value.data
     524            0 :     return {
     525              :       status: 'ok',
     526              :       value: {
     527              :         amountCents: quote.amount_cents,
     528              :         credits: quote.credits,
     529              :         expiresAt: quote.expires_at,
     530              :         ...(quote.payment_method_configuration_id === undefined
     531              :           ? {}
     532              :           : {
     533              :               paymentMethodConfigurationId:
     534              :                 quote.payment_method_configuration_id
     535              :             })
     536              :       }
     537              :     }
     538              :   }
     539              : 
     540            0 :   return {
     541              :     quoteTopup,
     542              :     createTopupCheckout,
     543              :     createInteractiveTopup,
     544              :     createHostedTopupCheckout
     545              :   }
     546              : }
        

Generated by: LCOV version 2.0-1