LCOV - code coverage report
Current view: top level - packages/billing-core/src - client.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 23.4 % 111 26
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import type {
       2              :   AutoReloadSettings,
       3              :   BillingBalanceResponse,
       4              :   BillingCapabilitiesResponse,
       5              :   BillingCapabilityDenials,
       6              :   BillingEventsResponse,
       7              :   BillingOpStatusResponse,
       8              :   BillingPlansResponse,
       9              :   BillingStatus,
      10              :   BillingStatusResponse as GeneratedBillingStatusResponse,
      11              :   CancelSubscriptionRequest,
      12              :   CancelSubscriptionResponse,
      13              :   CreateTopupCheckoutRequest,
      14              :   CreateTopupCheckoutResponse,
      15              :   CreateTopupQuoteRequest,
      16              :   CreateTopupRequest,
      17              :   CreateTopupResponse,
      18              :   HostedTopupCheckout,
      19              :   HostedTopupCheckoutList,
      20              :   PaymentPortalRequest,
      21              :   PaymentPortalResponse,
      22              :   Plan,
      23              :   PreviewSubscribeRequest,
      24              :   PreviewSubscribeResponse,
      25              :   RenewalInvoice,
      26              :   ResubscribeRequest,
      27              :   ResubscribeResponse,
      28              :   RetentionAcceptance,
      29              :   RetentionAcceptRequest,
      30              :   RetentionFlowEventRequest,
      31              :   RetentionFlowResponse,
      32              :   RevertScheduledChangeRequest,
      33              :   RevertScheduledChangeResponse,
      34              :   SavedPaymentMethod,
      35              :   ScheduledPlanChange,
      36              :   SubscribeRequest,
      37              :   SubscribeResponse,
      38              :   SubscriptionDuration,
      39              :   SubscriptionTier,
      40              :   TeamCreditStops,
      41              :   TeamCreditStopSummary,
      42              :   TopupAutoTopUpSettings,
      43              :   TopupQuoteResponse
      44              : } from '@comfyorg/ingest-types'
      45              : import {
      46              :   zRetentionAcceptance,
      47              :   zRetentionFlowResponse
      48              : } from '@comfyorg/ingest-types/zod'
      49              : import type { BillingTelemetryEvent } from '@comfyorg/account-core/billing'
      50              : import type { AxiosInstance, AxiosRequestConfig } from 'axios'
      51              : 
      52              : export type BillingRail = NonNullable<BillingStatusResponse['billing_rail']>
      53              : type SubscribeBillingCycle = 'monthly' | 'yearly'
      54              : export interface SubscribeOptions {
      55              :   confirmationToken?: string
      56              :   promotionCode?: string
      57              :   quoteId?: string
      58              :   quoteVersion?: number
      59              :   savedPaymentMethodId?: string
      60              :   returnUrl?: string
      61              :   cancelUrl?: string
      62              :   teamCreditStopId?: string
      63              :   billingCycle?: SubscribeBillingCycle
      64              :   confirmReactivation?: boolean
      65              :   prorationAt?: string
      66              :   attemptStartedAt?: number
      67              : }
      68              : 
      69              : export interface PreviewSubscribeOptions {
      70              :   teamCreditStopId?: string
      71              :   promotionCode?: string
      72              : }
      73              : 
      74            0 : function assertExclusivePaymentCredentials(options: SubscribeOptions): void {
      75            0 :   if (options.confirmationToken && options.savedPaymentMethodId) {
      76            0 :     throw new TypeError(
      77              :       'confirmationToken and savedPaymentMethodId are mutually exclusive'
      78              :     )
      79              :   }
      80              : }
      81              : 
      82              : export type { SubscribeResponse }
      83              : 
      84              : export type { PreviewSubscribeResponse }
      85              : 
      86              : export type BillingSubscriptionStatus = NonNullable<
      87              :   BillingStatusResponse['subscription_status']
      88              : >
      89              : 
      90              : export type { BillingStatus }
      91              : export type BillingStatusResponse = Omit<
      92              :   GeneratedBillingStatusResponse,
      93              :   'ended_at' | 'next_charge'
      94              : > &
      95              :   Partial<Pick<GeneratedBillingStatusResponse, 'ended_at' | 'next_charge'>>
      96              : export type { RenewalInvoice }
      97              : export type { ScheduledPlanChange }
      98              : 
      99              : export type { AutoReloadSettings }
     100              : export type { BillingBalanceResponse }
     101              : export type { BillingEventsResponse }
     102              : export type { BillingCapabilitiesResponse }
     103              : export type BillingCapabilitiesRead = Omit<
     104              :   BillingCapabilitiesResponse,
     105              :   'denied_reasons' | 'auto_top_up_enabled' | 'billing_web_checkout_ui'
     106              : > &
     107              :   Partial<
     108              :     Pick<
     109              :       BillingCapabilitiesResponse,
     110              :       'auto_top_up_enabled' | 'billing_web_checkout_ui'
     111              :     >
     112              :   > & {
     113              :     denied_reasons?: Readonly<Partial<Record<string, string>>>
     114              :   }
     115              : export type BillingTopUpDenial = NonNullable<
     116              :   BillingCapabilityDenials['can_top_up']
     117              : >
     118         2356 : const SERVED_TOP_UP_DENIALS: Record<BillingTopUpDenial, true> = {
     119              :   not_a_member: true,
     120              :   not_workspace_owner: true,
     121              :   creator_only_provisioning: true,
     122              :   payment_past_due: true,
     123              :   tier_not_self_serve: true,
     124              :   subscription_status_unrecognized: true,
     125              :   topup_purchases_paused: true,
     126              :   free_plan: true,
     127              :   no_subscription: true,
     128              :   subscription_ended: true
     129              : }
     130              : 
     131            0 : function isBillingTopUpDenial(reason: string): reason is BillingTopUpDenial {
     132            0 :   return Object.hasOwn(SERVED_TOP_UP_DENIALS, reason)
     133              : }
     134              : 
     135           15 : export function parseBillingTopUpDenial(
     136              :   reason: string | undefined
     137              : ): BillingTopUpDenial | undefined {
     138           15 :   return reason !== undefined && isBillingTopUpDenial(reason)
     139              :     ? reason
     140              :     : undefined
     141              : }
     142              : export type { CreateTopupResponse }
     143              : export type { BillingOpStatusResponse }
     144              : export type { SavedPaymentMethod }
     145              : export type BillingAuthenticationState = NonNullable<
     146              :   BillingOpStatusResponse['authentication_state']
     147              : >
     148              : export type BillingDeclineReason = NonNullable<
     149              :   BillingOpStatusResponse['decline_reason']
     150              : >
     151              : export type BillingOperationPhase = NonNullable<
     152              :   BillingOpStatusResponse['phase']
     153              : >
     154              : export type BillingRecoveryAction = NonNullable<
     155              :   BillingOpStatusResponse['recovery_action']
     156              : >
     157              : 
     158              : interface GetBillingEventsParams {
     159              :   page?: number
     160              :   limit?: number
     161              : }
     162              : 
     163              : export type { SubscriptionTier }
     164              : export type { SubscriptionDuration }
     165              : export type { Plan }
     166              : export type { BillingPlansResponse }
     167              : export type { TeamCreditStops }
     168              : export type { TeamCreditStopSummary }
     169              : 
     170              : export interface BillingApiOptions {
     171              :   client: AxiosInstance
     172              :   requestAuth: () => Promise<AxiosRequestConfig>
     173              :   resolveUrl: (route: string) => string
     174              :   handleError: (error: unknown, operation: string) => never
     175              :   trackBillingEvent: (event: BillingTelemetryEvent) => void
     176              : }
     177              : 
     178         2356 : export function createBillingApi({
     179              :   client,
     180              :   requestAuth,
     181              :   resolveUrl,
     182              :   handleError,
     183              :   trackBillingEvent
     184              : }: BillingApiOptions) {
     185            0 :   function handleAxiosError(error: unknown, operation: string): never {
     186            0 :     return handleError(error, operation)
     187              :   }
     188         2356 :   return {
     189              :     async getBillingStatus(): Promise<BillingStatusResponse> {
     190           19 :       const auth = await requestAuth()
     191           19 :       try {
     192              :         const response = await client.get<BillingStatusResponse>(
     193              :           resolveUrl('/billing/status'),
     194              :           auth
     195              :         )
     196           19 :         return response.data
     197              :       } catch (err) {
     198            0 :         handleAxiosError(err, 'getBillingStatus')
     199              :       }
     200              :     },
     201              :     async getBillingBalance(): Promise<BillingBalanceResponse> {
     202           26 :       const auth = await requestAuth()
     203           26 :       try {
     204              :         const response = await client.get<BillingBalanceResponse>(
     205              :           resolveUrl('/billing/balance'),
     206              :           auth
     207              :         )
     208           26 :         return response.data
     209              :       } catch (err) {
     210            0 :         handleAxiosError(err, 'getBillingBalance')
     211              :       }
     212              :     },
     213              :     async getBillingCapabilities(
     214              :       signal?: AbortSignal
     215              :     ): Promise<BillingCapabilitiesResponse> {
     216           25 :       const auth = await requestAuth()
     217           25 :       try {
     218              :         const response = await client.get<BillingCapabilitiesResponse>(
     219              :           resolveUrl('/billing/capabilities'),
     220              :           { ...auth, timeout: 10_000, signal }
     221              :         )
     222           25 :         return response.data
     223              :       } catch (err) {
     224            0 :         handleAxiosError(err, 'getBillingCapabilities')
     225              :       }
     226              :     },
     227              :     async getBillingAutoReload(): Promise<AutoReloadSettings> {
     228            2 :       const auth = await requestAuth()
     229            2 :       try {
     230              :         const response = await client.get<AutoReloadSettings>(
     231              :           resolveUrl('/billing/auto-reload'),
     232              :           { ...auth, timeout: 10_000 }
     233              :         )
     234            2 :         return response.data
     235              :       } catch (err) {
     236            0 :         handleAxiosError(err, 'getBillingAutoReload')
     237              :       }
     238              :     },
     239              :     async getBillingPlans(): Promise<BillingPlansResponse> {
     240           19 :       const auth = await requestAuth()
     241           19 :       try {
     242              :         const response = await client.get<BillingPlansResponse>(
     243              :           resolveUrl('/billing/plans'),
     244              :           auth
     245              :         )
     246           19 :         return response.data
     247              :       } catch (err) {
     248            0 :         handleAxiosError(err, 'getBillingPlans')
     249              :       }
     250              :     },
     251              :     async listSavedPaymentMethods(): Promise<SavedPaymentMethod[]> {
     252            0 :       const auth = await requestAuth()
     253            0 :       try {
     254              :         const response = await client.get<SavedPaymentMethod[]>(
     255              :           resolveUrl('/billing/payment-methods'),
     256              :           auth
     257              :         )
     258            0 :         return response.data
     259              :       } catch (err) {
     260            0 :         handleAxiosError(err, 'listSavedPaymentMethods')
     261              :       }
     262              :     },
     263              :     async previewSubscribe(
     264              :       planSlug: string,
     265              :       options: PreviewSubscribeOptions = {}
     266              :     ): Promise<PreviewSubscribeResponse> {
     267            0 :       const auth = await requestAuth()
     268            0 :       try {
     269              :         const response = await client.post<PreviewSubscribeResponse>(
     270              :           resolveUrl('/billing/preview-subscribe'),
     271              :           {
     272              :             plan_slug: planSlug,
     273              :             team_credit_stop_id: options.teamCreditStopId,
     274              :             promotion_code: options.promotionCode
     275              :           } satisfies PreviewSubscribeRequest,
     276              :           auth
     277              :         )
     278            0 :         return response.data
     279              :       } catch (err) {
     280            0 :         handleAxiosError(err, 'previewSubscribe')
     281              :       }
     282              :     },
     283              :     async subscribe(
     284              :       planSlug: string,
     285              :       options: SubscribeOptions = {}
     286              :     ): Promise<SubscribeResponse> {
     287            0 :       assertExclusivePaymentCredentials(options)
     288            0 :       const auth = await requestAuth()
     289            0 :       try {
     290            0 :         trackBillingEvent({
     291              :           operation: 'subscription_checkout',
     292              :           stage: 'request_sent',
     293              :           outcome: 'pending'
     294              :         })
     295            0 :         const response = await client.post<SubscribeResponse>(
     296              :           resolveUrl('/billing/subscribe'),
     297              :           {
     298              :             plan_slug: planSlug,
     299              :             confirmation_token: options.confirmationToken || undefined,
     300              :             saved_payment_method_id: options.savedPaymentMethodId || undefined,
     301              :             promotion_code: options.promotionCode,
     302              :             quote_id: options.quoteId,
     303              :             quote_version: options.quoteVersion,
     304              :             return_url: options.returnUrl,
     305              :             cancel_url: options.cancelUrl,
     306              :             team_credit_stop_id: options.teamCreditStopId,
     307              :             billing_cycle: options.billingCycle,
     308              :             confirm_reactivation: options.confirmReactivation,
     309              :             proration_at: options.prorationAt
     310              :           } satisfies SubscribeRequest,
     311              :           auth
     312              :         )
     313            0 :         trackBillingEvent({
     314              :           operation: 'subscription_checkout',
     315              :           stage: 'checkout_received',
     316              :           outcome: 'pending',
     317              :           billing_op_id: response.data.billing_op_id,
     318              :           checkout_status: response.data.status
     319              :         })
     320            0 :         return response.data
     321              :       } catch (err) {
     322            0 :         handleAxiosError(err, 'subscribe')
     323              :       }
     324              :     },
     325              :     async cancelSubscription(
     326              :       idempotencyKey?: string
     327              :     ): Promise<CancelSubscriptionResponse> {
     328            0 :       const auth = await requestAuth()
     329            0 :       try {
     330              :         const response = await client.post<CancelSubscriptionResponse>(
     331              :           resolveUrl('/billing/subscription/cancel'),
     332              :           {
     333              :             idempotency_key: idempotencyKey
     334              :           } satisfies CancelSubscriptionRequest,
     335              :           auth
     336              :         )
     337            0 :         return response.data
     338              :       } catch (err) {
     339            0 :         handleAxiosError(err, 'cancelSubscription')
     340              :       }
     341              :     },
     342              :     async prepareRetentionFlow(): Promise<RetentionFlowResponse> {
     343            0 :       const auth = await requestAuth()
     344            0 :       try {
     345            0 :         const response = await client.post<unknown>(
     346              :           resolveUrl('/billing/retention/prepare'),
     347              :           {},
     348              :           { ...auth, timeout: 5_000 }
     349              :         )
     350            0 :         return zRetentionFlowResponse.parse(response.data)
     351              :       } catch (err) {
     352            0 :         handleAxiosError(err, 'prepareRetentionFlow')
     353              :       }
     354              :     },
     355              :     async acceptRetentionOffer(
     356              :       sessionId: string
     357              :     ): Promise<RetentionAcceptance> {
     358            0 :       const auth = await requestAuth()
     359            0 :       try {
     360            0 :         const response = await client.post<unknown>(
     361              :           resolveUrl('/billing/retention/accept'),
     362              :           { session_id: sessionId } satisfies RetentionAcceptRequest,
     363              :           auth
     364              :         )
     365            0 :         return zRetentionAcceptance.parse(response.data)
     366              :       } catch (err) {
     367            0 :         handleAxiosError(err, 'acceptRetentionOffer')
     368              :       }
     369              :     },
     370              :     async recordRetentionFlowEvent(
     371              :       request: RetentionFlowEventRequest
     372              :     ): Promise<void> {
     373            0 :       const auth = await requestAuth()
     374            0 :       try {
     375            0 :         await client.post(
     376              :           resolveUrl('/billing/retention/events'),
     377              :           request,
     378              :           auth
     379              :         )
     380              :       } catch (err) {
     381            0 :         handleAxiosError(err, 'recordRetentionFlowEvent')
     382              :       }
     383              :     },
     384              :     async resubscribe(idempotencyKey?: string): Promise<ResubscribeResponse> {
     385            0 :       const auth = await requestAuth()
     386            0 :       try {
     387              :         const response = await client.post<ResubscribeResponse>(
     388              :           resolveUrl('/billing/subscription/resubscribe'),
     389              :           { idempotency_key: idempotencyKey } satisfies ResubscribeRequest,
     390              :           auth
     391              :         )
     392            0 :         return response.data
     393              :       } catch (err) {
     394            0 :         handleAxiosError(err, 'resubscribe')
     395              :       }
     396              :     },
     397              :     async revertScheduledChange(
     398              :       idempotencyKey?: string
     399              :     ): Promise<RevertScheduledChangeResponse> {
     400            0 :       const auth = await requestAuth()
     401            0 :       try {
     402              :         const response = await client.post<RevertScheduledChangeResponse>(
     403              :           resolveUrl('/billing/subscription/revert-scheduled-change'),
     404              :           {
     405              :             idempotency_key: idempotencyKey
     406              :           } satisfies RevertScheduledChangeRequest,
     407              :           auth
     408              :         )
     409            0 :         return response.data
     410              :       } catch (err) {
     411            0 :         handleAxiosError(err, 'revertScheduledChange')
     412              :       }
     413              :     },
     414              :     async getPaymentPortalUrl(
     415              :       returnUrl?: string,
     416              :       flowType?: PaymentPortalRequest['flow_type']
     417              :     ): Promise<PaymentPortalResponse> {
     418            0 :       const auth = await requestAuth()
     419            0 :       try {
     420              :         const response = await client.post<PaymentPortalResponse>(
     421              :           resolveUrl('/billing/payment-portal'),
     422              :           {
     423              :             return_url: returnUrl,
     424              :             flow_type: flowType
     425              :           } satisfies PaymentPortalRequest,
     426              :           { ...auth, timeout: 30_000 }
     427              :         )
     428            0 :         return response.data
     429              :       } catch (err) {
     430            0 :         handleAxiosError(err, 'getPaymentPortalUrl')
     431              :       }
     432              :     },
     433              :     async createTopup(
     434              :       amountCents: number,
     435              :       idempotencyKey?: string
     436              :     ): Promise<CreateTopupResponse> {
     437            0 :       const auth = await requestAuth()
     438            0 :       try {
     439            0 :         trackBillingEvent({
     440              :           operation: 'topup',
     441              :           stage: 'request_sent',
     442              :           outcome: 'pending'
     443              :         })
     444            0 :         const response = await client.post<CreateTopupResponse>(
     445              :           resolveUrl('/billing/topup'),
     446              :           {
     447              :             amount_cents: amountCents,
     448              :             idempotency_key: idempotencyKey
     449              :           } satisfies CreateTopupRequest,
     450              :           auth
     451              :         )
     452            0 :         trackBillingEvent({
     453              :           operation: 'topup',
     454              :           stage: 'checkout_received',
     455              :           outcome: 'pending',
     456              :           billing_op_id: response.data.billing_op_id,
     457              :           checkout_status: response.data.status
     458              :         })
     459            0 :         return response.data
     460              :       } catch (err) {
     461            0 :         handleAxiosError(err, 'createTopup')
     462              :       }
     463              :     },
     464              :     async createTopupCheckout(
     465              :       amountCents: number,
     466              :       returnUrl: string,
     467              :       signal?: AbortSignal,
     468              :       autoTopUp?: TopupAutoTopUpSettings
     469              :     ): Promise<CreateTopupCheckoutResponse> {
     470            0 :       const auth = await requestAuth()
     471            0 :       signal?.throwIfAborted()
     472            0 :       try {
     473              :         const response = await client.post<CreateTopupCheckoutResponse>(
     474              :           resolveUrl('/billing/topup/checkout'),
     475              :           {
     476              :             amount_cents: amountCents,
     477              :             return_url: returnUrl,
     478              :             idempotency_key: crypto.randomUUID(),
     479              :             ...(autoTopUp === undefined ? {} : { auto_top_up: autoTopUp })
     480              :           } satisfies CreateTopupCheckoutRequest,
     481              :           { ...auth, signal }
     482              :         )
     483            0 :         return response.data
     484              :       } catch (err) {
     485            0 :         handleAxiosError(err, 'createTopupCheckout')
     486              :       }
     487              :     },
     488              :     async quoteTopup(
     489              :       amountCents: number,
     490              :       signal?: AbortSignal
     491              :     ): Promise<TopupQuoteResponse> {
     492            5 :       const auth = await requestAuth()
     493            5 :       try {
     494              :         const response = await client.post<TopupQuoteResponse>(
     495              :           resolveUrl('/billing/topup/quote'),
     496              :           { amount_cents: amountCents } satisfies CreateTopupQuoteRequest,
     497              :           { ...auth, signal }
     498              :         )
     499            5 :         return response.data
     500              :       } catch (err) {
     501            0 :         handleAxiosError(err, 'quoteTopup')
     502              :       }
     503              :     },
     504              :     async listTopupCheckouts(): Promise<HostedTopupCheckoutList> {
     505            7 :       const auth = await requestAuth()
     506            7 :       try {
     507              :         const response = await client.get<HostedTopupCheckoutList>(
     508              :           resolveUrl('/billing/topup/checkouts'),
     509              :           { ...auth, timeout: 10_000 }
     510              :         )
     511            7 :         return response.data
     512              :       } catch (err) {
     513            0 :         handleAxiosError(err, 'listTopupCheckouts')
     514              :       }
     515              :     },
     516              :     async getTopupCheckout(
     517              :       sessionId: string,
     518              :       signal?: AbortSignal
     519              :     ): Promise<HostedTopupCheckout> {
     520            0 :       const auth = await requestAuth()
     521            0 :       signal?.throwIfAborted()
     522            0 :       try {
     523              :         const response = await client.get<HostedTopupCheckout>(
     524              :           resolveUrl(
     525              :             `/billing/topup/checkouts/${encodeURIComponent(sessionId)}`
     526              :           ),
     527              :           { ...auth, timeout: 10_000, signal }
     528              :         )
     529            0 :         return response.data
     530              :       } catch (err) {
     531            0 :         handleAxiosError(err, 'getTopupCheckout')
     532              :       }
     533              :     },
     534              :     async getBillingEvents(
     535              :       params?: GetBillingEventsParams
     536              :     ): Promise<BillingEventsResponse> {
     537            0 :       const auth = await requestAuth()
     538            0 :       try {
     539              :         const response = await client.get<BillingEventsResponse>(
     540              :           resolveUrl('/billing/events'),
     541              :           { ...auth, params }
     542              :         )
     543            0 :         return response.data
     544              :       } catch (err) {
     545            0 :         handleAxiosError(err, 'getBillingEvents')
     546              :       }
     547              :     },
     548              :     async getBillingOpStatus(opId: string): Promise<BillingOpStatusResponse> {
     549            0 :       const auth = await requestAuth()
     550            0 :       try {
     551              :         const response = await client.get<BillingOpStatusResponse>(
     552              :           resolveUrl(`/billing/ops/${encodeURIComponent(opId)}`),
     553              :           { ...auth, timeout: 30_000 }
     554              :         )
     555            0 :         return response.data
     556              :       } catch (err) {
     557            0 :         handleAxiosError(err, 'getBillingOpStatus')
     558              :       }
     559              :     }
     560              :   }
     561              : }
     562              : 
     563              : export type BillingApi = ReturnType<typeof createBillingApi>
     564              : export type BillingApiOperation = keyof BillingApi
        

Generated by: LCOV version 2.0-1