diff --git a/packages/account-core/src/core/billing/contracts/README.md b/packages/account-core/src/core/billing/contracts/README.md new file mode 100644 index 00000000000..5afe821904c --- /dev/null +++ b/packages/account-core/src/core/billing/contracts/README.md @@ -0,0 +1,19 @@ +# Generated billing contracts + +One file per endpoint contract the billing SDK core decodes. Each pins the +fields the core actually reads and the enum members it branches on, so a +regenerated `@comfyorg/ingest-types` that renames, drops, or widens one of them +fails here instead of surfacing as a runtime `MALFORMED_RESPONSE`. + +Each file pins its contract twice, and the two halves fail in different jobs: + +- `describe` blocks hold the runtime pins — what the generated schema accepts + and rejects. `pnpm --filter @comfyorg/account-core test` fails on those. +- Module-scope `expectTypeOf` calls hold the type pins — the shapes the SDK + reads off a parsed body. Vitest never evaluates them; the package + `typecheck` script is what fails, as a `TS2344`. They sit outside `it` so + the vitest report never counts a pass vitest did not check. + +A failure means the backend contract moved: fix the SDK, not the test. Where +the SDK reads a field more leniently than the generated schema does, the test +name says so — that row pins the generated shape, not the SDK's. diff --git a/packages/account-core/src/core/billing/contracts/billingBalance.contract.test.ts b/packages/account-core/src/core/billing/contracts/billingBalance.contract.test.ts new file mode 100644 index 00000000000..c36126b8013 --- /dev/null +++ b/packages/account-core/src/core/billing/contracts/billingBalance.contract.test.ts @@ -0,0 +1,52 @@ +import { zBillingBalanceResponse } from '@comfyorg/ingest-types/zod' +import { describe, expect, expectTypeOf, it } from 'vitest' +import type { z } from 'zod' + +type BalanceBody = z.input +type Balance = z.infer + +function balanceBody(overrides: Partial = {}): BalanceBody { + return { + amount_micros: 12_500_000, + currency: 'usd', + ...overrides + } +} + +// Compile-time pins: a regen that moves these fails the package typecheck. +expectTypeOf().toEqualTypeOf() +expectTypeOf< + Pick< + Balance, + | 'cloud_credit_balance_micros' + | 'effective_balance_micros' + | 'pending_charges_micros' + | 'prepaid_balance_micros' + > +>().toEqualTypeOf<{ + cloud_credit_balance_micros?: number + effective_balance_micros?: number + pending_charges_micros?: number + prepaid_balance_micros?: number +}>() + +describe('billing balance contract', () => { + it('accepts a balance carrying only the required fields', () => { + expect(zBillingBalanceResponse.safeParse(balanceBody())).toMatchObject({ + success: true + }) + }) + + it('keeps every balance breakdown optional beside the headline amount', () => { + const breakdown = balanceBody({ + cloud_credit_balance_micros: 1, + effective_balance_micros: 2, + pending_charges_micros: 3, + prepaid_balance_micros: 4 + }) + + expect(zBillingBalanceResponse.safeParse(breakdown)).toMatchObject({ + success: true + }) + }) +}) diff --git a/packages/account-core/src/core/billing/contracts/billingCapabilities.contract.test.ts b/packages/account-core/src/core/billing/contracts/billingCapabilities.contract.test.ts new file mode 100644 index 00000000000..27c05058a90 --- /dev/null +++ b/packages/account-core/src/core/billing/contracts/billingCapabilities.contract.test.ts @@ -0,0 +1,113 @@ +import { zBillingCapabilitiesResponse } from '@comfyorg/ingest-types/zod' +import type { + zBillingCapabilities, + zBillingCapabilityRolloutDefaults, + zBillingCapabilityScope +} from '@comfyorg/ingest-types/zod' +import { describe, expect, expectTypeOf, it } from 'vitest' +import type { z } from 'zod' + +type CapabilitiesResponseBody = z.input +type CapabilitiesResponse = z.infer +type Capabilities = z.infer +type CapabilityScope = z.infer +type RolloutDefaults = z.infer + +function capabilities(): Capabilities { + return { + can_cancel: true, + can_change_seats: true, + can_downgrade_to_personal: false, + can_invite_members: true, + can_reactivate: false, + can_subscribe_self_serve: true, + can_top_up: true + } +} + +function capabilitiesBody( + overrides: Partial = {} +): CapabilitiesResponseBody { + return { + capabilities: capabilities(), + expires_at: '2024-06-15T12:01:00.000Z', + resolved_for: { user_id: 'uid-1', workspace_id: 'ws-1' }, + revision: 42n, + rollout_defaults_applied: { + can_downgrade_to_personal: false, + can_subscribe_self_serve: false, + can_top_up: false + }, + ...overrides + } +} + +// Compile-time pins: a regen that moves these fails the package typecheck. + +// The five fields the reader composes its own schema from. +expectTypeOf().toEqualTypeOf< + | 'capabilities' + | 'expires_at' + | 'resolved_for' + | 'revision' + | 'rollout_defaults_applied' +>() +expectTypeOf().toEqualTypeOf<{ + can_cancel: boolean + can_change_seats: boolean + can_downgrade_to_personal: boolean + can_invite_members: boolean + can_reactivate: boolean + can_subscribe_self_serve: boolean + can_top_up: boolean +}>() +expectTypeOf().toEqualTypeOf<{ + user_id: string + workspace_id: string +}>() +expectTypeOf().toEqualTypeOf<{ + can_downgrade_to_personal: boolean + can_subscribe_self_serve: boolean + can_top_up: boolean +}>() +// The expiry the reader paces freshness from; the revision it reads as a number. +expectTypeOf().toEqualTypeOf() +expectTypeOf().toEqualTypeOf() + +describe('billing capabilities contract', () => { + it('accepts the body the capabilities endpoint returns', () => { + expect( + zBillingCapabilitiesResponse.safeParse(capabilitiesBody()) + ).toMatchObject({ success: true }) + }) + + it('requires a datetime expiry, which the reader re-decodes leniently as a plain string', () => { + expect( + zBillingCapabilitiesResponse.safeParse( + capabilitiesBody({ expires_at: 'not-a-date' }) + ).success + ).toBe(false) + }) + + it('bounds the revision to the safe range the reader reads it back as a number over', () => { + const safe = { ...capabilitiesBody(), revision: Number.MAX_SAFE_INTEGER } + const unsafe = capabilitiesBody({ + revision: BigInt(Number.MAX_SAFE_INTEGER) + 1n + }) + + expect(zBillingCapabilitiesResponse.safeParse(safe)).toMatchObject({ + success: true + }) + expect(zBillingCapabilitiesResponse.safeParse(unsafe).success).toBe(false) + }) + + it('omits denied reasons, which the reader therefore decodes off the raw body', () => { + const parsed = zBillingCapabilitiesResponse.safeParse({ + ...capabilitiesBody(), + denied_reasons: { can_subscribe_self_serve: 'not_workspace_owner' } + }) + + expect(parsed).toMatchObject({ success: true }) + expect(parsed.success && 'denied_reasons' in parsed.data).toBe(false) + }) +}) diff --git a/packages/account-core/src/core/billing/contracts/billingOpStatus.contract.test.ts b/packages/account-core/src/core/billing/contracts/billingOpStatus.contract.test.ts new file mode 100644 index 00000000000..97875f75984 --- /dev/null +++ b/packages/account-core/src/core/billing/contracts/billingOpStatus.contract.test.ts @@ -0,0 +1,116 @@ +import { zBillingOpStatusResponse } from '@comfyorg/ingest-types/zod' +import { describe, expect, expectTypeOf, it } from 'vitest' +import type { z } from 'zod' + +type OpStatusBody = z.input +type OpStatus = z.infer + +function opStatusBody(overrides: Partial = {}): OpStatusBody { + return { + id: 'op-1', + started_at: '2024-06-15T12:00:00.000Z', + status: 'pending', + ...overrides + } +} + +/** Every value the reducer distinguishes; 'pending' is its stay-put branch. */ +const REDUCED_STATUSES = [ + 'pending', + 'succeeded', + 'failed', + 'reconciliation_needed' +] as const satisfies readonly OpStatus['status'][] + +/** Every value the pending reducer reads or `settleChallenge` assigns. */ +const AUTHENTICATION_STATES = [ + 'requires_action', + 'processing', + 'failed_retryable', + 'succeeded', + 'reconciliation_needed' +] as const satisfies readonly NonNullable[] + +// Compile-time pins: a regen that moves these fails the package typecheck. + +// The tables above are exhaustive, so a new member reaches an `it.for` row. +expectTypeOf().toEqualTypeOf< + (typeof REDUCED_STATUSES)[number] +>() +expectTypeOf().toEqualTypeOf< + (typeof AUTHENTICATION_STATES)[number] | undefined +>() +// The decline reasons a failed operation reports, including the fallback. +expectTypeOf().toEqualTypeOf< + | 'card_declined' + | 'insufficient_funds' + | 'expired_card' + | 'incorrect_cvc' + | 'authentication_required' + | 'authentication_failed' + | 'processing_error' + | 'generic' + | undefined +>() +// The recovery actions a host offers after a decline. +expectTypeOf().toEqualTypeOf< + | 'retry' + | 'replace_payment_method' + | 'authenticate_payment' + | 'contact_support' + | undefined +>() +// The server phases the pending state mirrors. +expectTypeOf().toEqualTypeOf< + | 'awaiting_payment_method' + | 'awaiting_invoice_payment' + | 'in_progress' + | undefined +>() +expectTypeOf().toEqualTypeOf() +expectTypeOf().toEqualTypeOf() +expectTypeOf().toEqualTypeOf< + string | undefined +>() +expectTypeOf().toEqualTypeOf() + +describe('billing operation status contract', () => { + it('accepts a status carrying only the required fields', () => { + expect(zBillingOpStatusResponse.safeParse(opStatusBody())).toMatchObject({ + success: true + }) + }) + + it('requires a datetime start time, so a malformed one fails the whole poll', () => { + expect( + zBillingOpStatusResponse.safeParse( + opStatusBody({ started_at: 'not-a-date' }) + ).success + ).toBe(false) + }) + + it.for(REDUCED_STATUSES)('accepts the %s status', (status) => { + expect( + zBillingOpStatusResponse.safeParse(opStatusBody({ status })) + ).toMatchObject({ success: true }) + }) + + it.for(AUTHENTICATION_STATES)( + 'accepts the %s authentication state', + (authentication_state) => { + expect( + zBillingOpStatusResponse.safeParse( + opStatusBody({ authentication_state }) + ) + ).toMatchObject({ success: true }) + } + ) + + it('leaves retryable absent by default, so a decline is not retryable unless the server says so', () => { + const parsed = zBillingOpStatusResponse.safeParse( + opStatusBody({ status: 'failed' }) + ) + + expect(parsed.success && parsed.data.retryable).toBeUndefined() + }) +}) diff --git a/packages/account-core/src/core/billing/contracts/billingStatus.contract.test.ts b/packages/account-core/src/core/billing/contracts/billingStatus.contract.test.ts new file mode 100644 index 00000000000..39101c12804 --- /dev/null +++ b/packages/account-core/src/core/billing/contracts/billingStatus.contract.test.ts @@ -0,0 +1,125 @@ +import { zBillingStatusResponse } from '@comfyorg/ingest-types/zod' +import { describe, expect, expectTypeOf, it } from 'vitest' +import type { z } from 'zod' + +type StatusBody = z.input +type Status = z.infer + +function statusBody(overrides: Partial = {}): StatusBody { + return { + has_funds: true, + is_active: true, + max_seats: 5, + occupied_seats: 1, + scheduled_change: null, + team_credit_stop: null, + ...overrides + } +} + +/** Every rail presentation routing distinguishes; only 'stripe' reaches the embedded challenge. */ +const BILLING_RAILS = [ + 'legacy_stripe', + 'metronome', + 'stripe' +] as const satisfies readonly NonNullable[] + +/** Every kind the lifecycle adopts from a server-reported pending operation. */ +const PENDING_OP_TYPES = [ + 'subscription', + 'topup' +] as const satisfies readonly NonNullable[] + +/** Every value subscribe eligibility distinguishes; only 'canceled' reroutes to resubscribe. */ +const SUBSCRIPTION_STATUSES = [ + 'active', + 'ended', + 'canceled' +] as const satisfies readonly NonNullable[] + +/** Every tier the status can report; eligibility reads only 'FREE' as unpaid. */ +const SUBSCRIPTION_TIERS = [ + 'FREE', + 'STANDARD', + 'CREATOR', + 'PRO', + 'FOUNDERS_EDITION', + 'TEAM', + 'ENTERPRISE' +] as const satisfies readonly NonNullable[] + +// Compile-time pins: a regen that moves these fails the package typecheck. + +// The tables above are exhaustive, so a new member reaches an `it.for` row. +expectTypeOf().toEqualTypeOf< + (typeof BILLING_RAILS)[number] | undefined +>() +expectTypeOf().toEqualTypeOf< + (typeof PENDING_OP_TYPES)[number] | undefined +>() +expectTypeOf().toEqualTypeOf< + (typeof SUBSCRIPTION_STATUSES)[number] | undefined +>() +expectTypeOf().toEqualTypeOf< + (typeof SUBSCRIPTION_TIERS)[number] | undefined +>() +expectTypeOf().toEqualTypeOf() +// The pending operation the lifecycle reattaches to, and the continuations it +// adopts alongside it. +expectTypeOf().toEqualTypeOf< + string | undefined +>() +expectTypeOf().toEqualTypeOf() +expectTypeOf().toEqualTypeOf< + string | undefined +>() + +describe('billing status contract', () => { + it('accepts a status carrying only the required fields', () => { + expect(zBillingStatusResponse.safeParse(statusBody())).toMatchObject({ + success: true + }) + }) + + it.for(BILLING_RAILS)('accepts the %s rail', (billing_rail) => { + expect( + zBillingStatusResponse.safeParse(statusBody({ billing_rail })) + ).toMatchObject({ success: true }) + }) + + it.for(PENDING_OP_TYPES)( + 'accepts a pending %s operation', + (pending_billing_op_type) => { + const body = statusBody({ + pending_billing_op_id: 'op-1', + pending_billing_op_type + }) + + expect(zBillingStatusResponse.safeParse(body)).toMatchObject({ + success: true + }) + } + ) + + it.for(SUBSCRIPTION_STATUSES)( + 'accepts the %s subscription status', + (subscription_status) => { + const body = statusBody({ + subscription_status, + subscription_tier: 'PRO' + }) + + expect(zBillingStatusResponse.safeParse(body)).toMatchObject({ + success: true + }) + } + ) + + it.for(SUBSCRIPTION_TIERS)('accepts the %s tier', (subscription_tier) => { + const body = statusBody({ subscription_tier }) + + expect(zBillingStatusResponse.safeParse(body)).toMatchObject({ + success: true + }) + }) +}) diff --git a/packages/account-core/src/core/billing/contracts/cancelSubscription.contract.test.ts b/packages/account-core/src/core/billing/contracts/cancelSubscription.contract.test.ts new file mode 100644 index 00000000000..fb7ec095761 --- /dev/null +++ b/packages/account-core/src/core/billing/contracts/cancelSubscription.contract.test.ts @@ -0,0 +1,42 @@ +import { zCancelSubscriptionResponse2 } from '@comfyorg/ingest-types/zod' +import { describe, expect, expectTypeOf, it } from 'vitest' +import type { z } from 'zod' + +type CancelBody = z.input +type Cancel = z.infer + +const CANCEL_VARIANTS = [ + { + variant: 'scheduled', + body: { billing_op_id: 'op-1', cancel_at: '2024-07-15T12:00:00.000Z' } + }, + { + variant: 'accepted', + body: { billing_op_id: 'op-1', status: 'pending' } + } +] as const satisfies readonly { variant: string; body: CancelBody }[] + +// Compile-time pins: a regen that moves these fails the package typecheck. + +// Every member of the response union carries the operation id. +expectTypeOf().toEqualTypeOf() + +describe('cancel subscription contract', () => { + it.for(CANCEL_VARIANTS)( + 'reads the operation id off the $variant response', + ({ body }) => { + const parsed = zCancelSubscriptionResponse2.safeParse(body) + + expect(parsed.success && parsed.data.billing_op_id).toBe('op-1') + } + ) + + it('rejects a scheduled cancellation dated by an unreadable timestamp', () => { + const parsed = zCancelSubscriptionResponse2.safeParse({ + billing_op_id: 'op-1', + cancel_at: 'not-a-date' + }) + + expect(parsed.success).toBe(false) + }) +}) diff --git a/packages/account-core/src/core/billing/contracts/errorResponse.contract.test.ts b/packages/account-core/src/core/billing/contracts/errorResponse.contract.test.ts new file mode 100644 index 00000000000..848b95e3d45 --- /dev/null +++ b/packages/account-core/src/core/billing/contracts/errorResponse.contract.test.ts @@ -0,0 +1,32 @@ +import { zErrorResponse } from '@comfyorg/ingest-types/zod' +import { describe, expect, expectTypeOf, it } from 'vitest' +import type { z } from 'zod' + +type ErrorBody = z.input +type ErrorResponse = z.infer + +function errorBody(): ErrorBody { + return { + code: 'NO_PAYMENT_METHOD', + message: 'The workspace has no payment method on file.' + } +} + +// Compile-time pins: a regen that moves these fails the package typecheck. + +// An open string the commands match against their own closed set of codes. +expectTypeOf().toEqualTypeOf() + +describe('billing error body contract', () => { + it('accepts an error carrying only a code and a message', () => { + expect(zErrorResponse.safeParse(errorBody())).toMatchObject({ + success: true + }) + }) + + it('rejects a body without a message', () => { + expect( + zErrorResponse.safeParse({ code: 'NO_PAYMENT_METHOD' }).success + ).toBe(false) + }) +}) diff --git a/packages/account-core/src/core/billing/contracts/paymentPortal.contract.test.ts b/packages/account-core/src/core/billing/contracts/paymentPortal.contract.test.ts new file mode 100644 index 00000000000..7d7bc81d97b --- /dev/null +++ b/packages/account-core/src/core/billing/contracts/paymentPortal.contract.test.ts @@ -0,0 +1,34 @@ +import { zPaymentPortalResponse } from '@comfyorg/ingest-types/zod' +import { describe, expect, expectTypeOf, it } from 'vitest' +import type { z } from 'zod' + +type PortalBody = z.input +type Portal = z.infer + +function portalResponse(overrides: Partial = {}): PortalBody { + return { url: 'https://billing.comfy.org/portal/session-1', ...overrides } +} + +// Compile-time pins: a regen that moves these fails the package typecheck. +expectTypeOf().toEqualTypeOf() + +describe('payment portal contract', () => { + it('accepts a response carrying only the portal url', () => { + expect(zPaymentPortalResponse.safeParse(portalResponse())).toMatchObject({ + success: true + }) + }) + + it('requires the url', () => { + expect(zPaymentPortalResponse.safeParse({}).success).toBe(false) + }) + + it('validates the url no further than a string, so the command checks the scheme itself', () => { + expect( + zPaymentPortalResponse.safeParse(portalResponse({ url: 'http://host' })) + ).toMatchObject({ success: true }) + expect( + zPaymentPortalResponse.safeParse(portalResponse({ url: 'not-a-url' })) + ).toMatchObject({ success: true }) + }) +}) diff --git a/packages/account-core/src/core/billing/contracts/previewSubscribe.contract.test.ts b/packages/account-core/src/core/billing/contracts/previewSubscribe.contract.test.ts new file mode 100644 index 00000000000..f09bac0f6b1 --- /dev/null +++ b/packages/account-core/src/core/billing/contracts/previewSubscribe.contract.test.ts @@ -0,0 +1,186 @@ +import { + zPreviewSubscribeRequest, + zPreviewSubscribeResponse +} from '@comfyorg/ingest-types/zod' +import { describe, expect, expectTypeOf, it } from 'vitest' +import type { z } from 'zod' + +type PreviewRequestBody = z.input +type PreviewRequest = z.infer +type PreviewResponseBody = z.input +type PreviewResponse = z.infer + +function previewRequest( + overrides: Partial = {} +): PreviewRequestBody { + return { plan_slug: 'pro_monthly', ...overrides } +} + +const planInfo: PreviewResponseBody['new_plan'] = { + credits_cents: 2000n, + duration: 'MONTHLY', + price_cents: 3000n, + seat_summary: { + seat_count: 1, + total_cost_cents: 3000n, + total_credits_cents: 2000n + }, + slug: 'pro_monthly', + tier: 'PRO' +} + +function previewResponse( + overrides: Partial = {} +): PreviewResponseBody { + return { + allowed: true, + cost_next_period_cents: 3000n, + cost_today_cents: 3000n, + credits_next_period_cents: 2000n, + credits_today_cents: 2000n, + effective_at: '2024-06-15T12:00:00.000Z', + is_immediate: true, + new_plan: planInfo, + transition_type: 'new_subscription', + ...overrides + } +} + +/** Every transition the quote can describe; a host renders all four. */ +const TRANSITION_TYPES = [ + 'new_subscription', + 'upgrade', + 'downgrade', + 'duration_change' +] as const satisfies readonly PreviewResponse['transition_type'][] + +/** Every amount the quote can carry, each one the host formats as money. */ +const MONEY_FIELDS = [ + 'amount_due_cents', + 'cost_next_period_cents', + 'cost_today_cents', + 'credits_next_period_cents', + 'credits_today_cents', + 'renewal_amount_cents' +] as const satisfies readonly (keyof PreviewResponseBody)[] + +const INT64_MIN = -9223372036854775808n +const INT64_MAX = 9223372036854775807n + +// Compile-time pins: a regen that moves these fails the package typecheck. + +// The money table above is exhaustive, so a seventh amount reaches both the +// coercion rows and the int64 rows. +expectTypeOf<(typeof MONEY_FIELDS)[number]>().toEqualTypeOf< + Extract +>() +// The plan slug is the only required request field. +expectTypeOf().toEqualTypeOf<{ + plan_slug: string + checkout_attempt_id?: string + promotion_code?: string + team_credit_stop_id?: string +}>() +// The transition table above is exhaustive, so a new member reaches a row. +expectTypeOf().toEqualTypeOf< + (typeof TRANSITION_TYPES)[number] +>() +expectTypeOf().toEqualTypeOf() +expectTypeOf().toEqualTypeOf() +expectTypeOf().toEqualTypeOf() +// Money is an int64, so a host formats a bigint rather than a number. +expectTypeOf().toEqualTypeOf() +expectTypeOf< + PreviewResponse['cost_next_period_cents'] +>().toEqualTypeOf() +expectTypeOf().toEqualTypeOf() +expectTypeOf< + PreviewResponse['credits_next_period_cents'] +>().toEqualTypeOf() +expectTypeOf().toEqualTypeOf< + bigint | undefined +>() +expectTypeOf().toEqualTypeOf< + bigint | undefined +>() +// The reactivation confirmation the subscribe command is asked to resend. +expectTypeOf< + PreviewResponse['requires_reactivation_confirmation'] +>().toEqualTypeOf() + +describe('preview subscribe contract', () => { + it('accepts the request the command builds from its camel-cased input', () => { + const body = previewRequest({ + checkout_attempt_id: 'attempt-1', + promotion_code: 'LAUNCH', + team_credit_stop_id: 'stop-1' + }) + + expect(zPreviewSubscribeRequest.safeParse(body)).toMatchObject({ + success: true + }) + }) + + it('requires the plan slug', () => { + expect(zPreviewSubscribeRequest.safeParse({}).success).toBe(false) + }) + + it('accepts a quote carrying only the required fields', () => { + expect( + zPreviewSubscribeResponse.safeParse(previewResponse()) + ).toMatchObject({ success: true }) + }) + + it.for(TRANSITION_TYPES)('quotes the %s transition', (transition_type) => { + const parsed = zPreviewSubscribeResponse.safeParse( + previewResponse({ transition_type }) + ) + + expect(parsed.success && parsed.data.transition_type).toBe(transition_type) + }) + + it('rejects an effective date a host could not read the change from', () => { + expect( + zPreviewSubscribeResponse.safeParse( + previewResponse({ effective_at: 'not-a-date' }) + ).success + ).toBe(false) + }) + + it.for(MONEY_FIELDS)( + 'coerces the JSON number the wire actually carries for %s', + (field) => { + const parsed = zPreviewSubscribeResponse.safeParse({ + ...previewResponse(), + [field]: 3000 + }) + + expect(parsed.success && parsed.data[field]).toBe(3000n) + } + ) + + it.for(MONEY_FIELDS)('bounds %s to the int64 range', (field) => { + const parseAmount = (amount: bigint) => + zPreviewSubscribeResponse.safeParse({ + ...previewResponse(), + [field]: amount + }) + + expect(parseAmount(INT64_MIN)).toMatchObject({ success: true }) + expect(parseAmount(INT64_MAX)).toMatchObject({ success: true }) + expect(parseAmount(INT64_MIN - 1n).success).toBe(false) + expect(parseAmount(INT64_MAX + 1n).success).toBe(false) + }) + + it('describes discounts as product copy the host renders rather than matches', () => { + const body = previewResponse({ + discounts: [{ code: 'LAUNCH', kind: 'promotion', name: 'Launch offer' }] + }) + const parsed = zPreviewSubscribeResponse.safeParse(body) + + expect(parsed.success && parsed.data.discounts?.[0]).toMatchObject({ + code: 'LAUNCH', + kind: 'promotion' + }) + }) +}) diff --git a/packages/account-core/src/core/billing/contracts/resubscribe.contract.test.ts b/packages/account-core/src/core/billing/contracts/resubscribe.contract.test.ts new file mode 100644 index 00000000000..388deb60925 --- /dev/null +++ b/packages/account-core/src/core/billing/contracts/resubscribe.contract.test.ts @@ -0,0 +1,46 @@ +import { zResubscribeResponse } from '@comfyorg/ingest-types/zod' +import { describe, expect, expectTypeOf, it } from 'vitest' +import type { z } from 'zod' + +type ResubscribeBody = z.input +type Resubscribe = z.infer + +function resubscribeResponse( + overrides: Partial = {} +): ResubscribeBody { + return { billing_op_id: 'op-1', status: 'active', ...overrides } +} + +const RESUBSCRIBE_STATUSES = [ + 'active', + 'pending' +] as const satisfies readonly Resubscribe['status'][] + +// Compile-time pins: a regen that moves these fails the package typecheck. + +// The table above is exhaustive, so a new status reaches an `it.for` row. +expectTypeOf().toEqualTypeOf< + (typeof RESUBSCRIBE_STATUSES)[number] +>() +expectTypeOf().toEqualTypeOf() + +describe('resubscribe contract', () => { + it('accepts a response carrying only the operation id and its status', () => { + expect(zResubscribeResponse.safeParse(resubscribeResponse())).toMatchObject( + { + success: true + } + ) + }) + + it.for(RESUBSCRIBE_STATUSES)( + 'carries the operation id alongside the %s status', + (status) => { + const parsed = zResubscribeResponse.safeParse( + resubscribeResponse({ status }) + ) + + expect(parsed.success && parsed.data.billing_op_id).toBe('op-1') + } + ) +}) diff --git a/packages/account-core/src/core/billing/contracts/subscribe.contract.test.ts b/packages/account-core/src/core/billing/contracts/subscribe.contract.test.ts new file mode 100644 index 00000000000..d9b30e50240 --- /dev/null +++ b/packages/account-core/src/core/billing/contracts/subscribe.contract.test.ts @@ -0,0 +1,92 @@ +import { + zSubscribeRequest, + zSubscribeResponse +} from '@comfyorg/ingest-types/zod' +import { describe, expect, expectTypeOf, it } from 'vitest' +import type { z } from 'zod' + +type SubscribeRequestBody = z.input +type SubscribeRequest = z.infer +type SubscribeResponseBody = z.input +type SubscribeResponse = z.infer + +function subscribeRequest( + overrides: Partial = {} +): SubscribeRequestBody { + return { plan_slug: 'pro_monthly', ...overrides } +} + +function subscribeResponse( + overrides: Partial = {} +): SubscribeResponseBody { + return { billing_op_id: 'op-1', status: 'subscribed', ...overrides } +} + +/** Every outcome the command distinguishes; only 'needs_payment_method' demands a hosted page. */ +const SUBSCRIBE_STATUSES = [ + 'subscribed', + 'needs_payment_method', + 'pending_payment' +] as const satisfies readonly SubscribeResponse['status'][] + +// Compile-time pins: a regen that moves these fails the package typecheck. + +// The payment credentials the command deconflicts before sending. +expectTypeOf().toEqualTypeOf< + string | undefined +>() +expectTypeOf().toEqualTypeOf< + string | undefined +>() +expectTypeOf().toEqualTypeOf< + string | undefined +>() +expectTypeOf().toEqualTypeOf< + boolean | undefined +>() +// The table above is exhaustive, so a new outcome reaches an `it.for` row. +expectTypeOf().toEqualTypeOf< + (typeof SUBSCRIBE_STATUSES)[number] +>() +expectTypeOf().toEqualTypeOf() +expectTypeOf().toEqualTypeOf< + string | undefined +>() + +describe('subscribe contract', () => { + it('accepts a request carrying only the plan slug', () => { + expect(zSubscribeRequest.safeParse(subscribeRequest())).toMatchObject({ + success: true + }) + }) + + it('rejects a saved payment method that is not a Stripe payment-method id', () => { + const rejected = subscribeRequest({ saved_payment_method_id: 'card_123' }) + const accepted = subscribeRequest({ saved_payment_method_id: 'pm_123' }) + + expect(zSubscribeRequest.safeParse(rejected).success).toBe(false) + expect(zSubscribeRequest.safeParse(accepted)).toMatchObject({ + success: true + }) + }) + + it('accepts the reactivation confirmation the server asks callers to resend', () => { + const body = subscribeRequest({ confirm_reactivation: true }) + + expect(zSubscribeRequest.safeParse(body)).toMatchObject({ success: true }) + }) + + it.for(SUBSCRIBE_STATUSES)('accepts the %s outcome', (status) => { + expect( + zSubscribeResponse.safeParse(subscribeResponse({ status })) + ).toMatchObject({ success: true }) + }) + + it('leaves the hosted payment page optional, which the command reads as a missing url', () => { + const parsed = zSubscribeResponse.safeParse( + subscribeResponse({ status: 'needs_payment_method' }) + ) + + expect(parsed.success && parsed.data.payment_method_url).toBeUndefined() + }) +}) diff --git a/packages/account-core/src/core/billing/contracts/topup.contract.test.ts b/packages/account-core/src/core/billing/contracts/topup.contract.test.ts new file mode 100644 index 00000000000..3b632210e13 --- /dev/null +++ b/packages/account-core/src/core/billing/contracts/topup.contract.test.ts @@ -0,0 +1,116 @@ +import { + zCreateTopupRequest, + zCreateTopupResponse +} from '@comfyorg/ingest-types/zod' +import { describe, expect, expectTypeOf, it } from 'vitest' +import type { z } from 'zod' + +type TopupRequestBody = z.input +type TopupRequest = z.infer +type TopupResponseBody = z.input +type TopupResponse = z.infer + +const MINIMUM_AMOUNT_CENTS = 500 +const INT64_MAX = 9223372036854775807n + +function topupRequest(): TopupRequestBody { + return { amount_cents: BigInt(MINIMUM_AMOUNT_CENTS) } +} + +function topupResponse( + overrides: Partial = {} +): TopupResponseBody { + return { + amount_cents: BigInt(MINIMUM_AMOUNT_CENTS), + billing_op_id: 'op-1', + status: 'pending', + topup_id: 'topup-1', + ...overrides + } +} + +const TOPUP_STATUSES = [ + 'pending', + 'completed', + 'failed' +] as const satisfies readonly TopupResponse['status'][] + +// Compile-time pins: a regen that moves these fails the package typecheck. + +// The amount the command validates, coerced to an int64 the transport never +// serializes, and the idempotency key it mints per attempt. +expectTypeOf().toEqualTypeOf() +expectTypeOf().toEqualTypeOf< + string | undefined +>() +// The table above is exhaustive, so a new status reaches an `it.for` row. +expectTypeOf().toEqualTypeOf< + (typeof TOPUP_STATUSES)[number] +>() +expectTypeOf().toEqualTypeOf() + +describe('topup contract', () => { + it('accepts a request carrying only the amount', () => { + expect(zCreateTopupRequest.safeParse(topupRequest())).toMatchObject({ + success: true + }) + }) + + it('validates the JSON number the command sends and coerces it to an int64 the transport never serializes', () => { + const parsed = zCreateTopupRequest.safeParse({ + amount_cents: MINIMUM_AMOUNT_CENTS + }) + + expect(parsed.success && parsed.data.amount_cents).toBe( + BigInt(MINIMUM_AMOUNT_CENTS) + ) + }) + + it('rejects an amount below the minimum the command reports as invalid', () => { + const below = { amount_cents: MINIMUM_AMOUNT_CENTS - 1 } + + expect(zCreateTopupRequest.safeParse(below).success).toBe(false) + expect( + zCreateTopupRequest.safeParse({ amount_cents: MINIMUM_AMOUNT_CENTS }) + ).toMatchObject({ success: true }) + }) + + it('rejects an amount past the int64 ceiling the command reports as invalid', () => { + expect( + zCreateTopupRequest.safeParse({ amount_cents: INT64_MAX }) + ).toMatchObject({ success: true }) + expect( + zCreateTopupRequest.safeParse({ amount_cents: INT64_MAX + 1n }).success + ).toBe(false) + }) + + it('coerces the JSON number the wire carries for the response amount', () => { + const parsed = zCreateTopupResponse.safeParse({ + ...topupResponse(), + amount_cents: MINIMUM_AMOUNT_CENTS + }) + + expect(parsed.success && parsed.data.amount_cents).toBe( + BigInt(MINIMUM_AMOUNT_CENTS) + ) + }) + + it('bounds the response amount to the int64 range', () => { + const parseAmount = (amount_cents: bigint) => + zCreateTopupResponse.safeParse({ ...topupResponse(), amount_cents }) + + expect(parseAmount(INT64_MAX)).toMatchObject({ success: true }) + expect(parseAmount(-INT64_MAX - 1n)).toMatchObject({ success: true }) + expect(parseAmount(INT64_MAX + 1n).success).toBe(false) + expect(parseAmount(-INT64_MAX - 2n).success).toBe(false) + }) + + it.for(TOPUP_STATUSES)( + 'carries the operation id alongside the %s status', + (status) => { + const parsed = zCreateTopupResponse.safeParse(topupResponse({ status })) + + expect(parsed.success && parsed.data.billing_op_id).toBe('op-1') + } + ) +}) diff --git a/packages/account-core/src/core/billing/contracts/topupCheckout.contract.test.ts b/packages/account-core/src/core/billing/contracts/topupCheckout.contract.test.ts new file mode 100644 index 00000000000..d783713089d --- /dev/null +++ b/packages/account-core/src/core/billing/contracts/topupCheckout.contract.test.ts @@ -0,0 +1,126 @@ +import { + zCreateTopupCheckoutRequest, + zCreateTopupCheckoutResponse +} from '@comfyorg/ingest-types/zod' +import { describe, expect, expectTypeOf, it } from 'vitest' +import type { z } from 'zod' + +type CheckoutRequestBody = z.input +type CheckoutRequest = z.infer +type CheckoutResponseBody = z.input +type CheckoutResponse = z.infer + +const MINIMUM_AMOUNT_CENTS = 500 +const MAXIMUM_AMOUNT_CENTS = 473_900 +const RETURN_URL = 'https://app.comfy.org/billing/return' + +function checkoutRequest(): CheckoutRequestBody { + return { + amount_cents: BigInt(MINIMUM_AMOUNT_CENTS), + return_url: RETURN_URL + } +} + +function checkoutResponse( + overrides: Partial = {} +): CheckoutResponseBody { + return { + checkout_url: 'https://checkout.stripe.com/c/session-1', + ...overrides + } +} + +/** + * The command tells an invalid amount from an invalid return url by the + * issue's own path, so the field names are part of the contract. + */ +const INVALID_REQUESTS = [ + { + rejected: 'an amount below the minimum', + field: 'amount_cents', + body: { amount_cents: MINIMUM_AMOUNT_CENTS - 1, return_url: RETURN_URL } + }, + { + rejected: 'an amount above the maximum', + field: 'amount_cents', + body: { amount_cents: MAXIMUM_AMOUNT_CENTS + 1, return_url: RETURN_URL } + }, + { + rejected: 'a return url that is not a url', + field: 'return_url', + body: { amount_cents: MINIMUM_AMOUNT_CENTS, return_url: 'not-a-url' } + } +] as const satisfies readonly { + rejected: string + field: keyof CheckoutRequestBody + body: Partial> +}[] + +// Compile-time pins: a regen that moves these fails the package typecheck. + +// The amount coerced to an int64 the transport never serializes. +expectTypeOf().toEqualTypeOf() +expectTypeOf().toEqualTypeOf() +expectTypeOf().toEqualTypeOf< + string | undefined +>() + +describe('hosted topup checkout contract', () => { + it('accepts a request carrying an in-range amount and a return url', () => { + expect( + zCreateTopupCheckoutRequest.safeParse(checkoutRequest()) + ).toMatchObject({ success: true }) + expect( + zCreateTopupCheckoutRequest.safeParse({ + amount_cents: MAXIMUM_AMOUNT_CENTS, + return_url: RETURN_URL + }) + ).toMatchObject({ success: true }) + }) + + it('coerces the JSON amount to an int64 the transport never serializes', () => { + const parsed = zCreateTopupCheckoutRequest.safeParse({ + amount_cents: MINIMUM_AMOUNT_CENTS, + return_url: RETURN_URL + }) + + expect(parsed.success && parsed.data.amount_cents).toBe( + BigInt(MINIMUM_AMOUNT_CENTS) + ) + }) + + it.for(INVALID_REQUESTS)('blames $field for $rejected', ({ field, body }) => { + const parsed = zCreateTopupCheckoutRequest.safeParse(body) + const paths = parsed.success + ? [] + : parsed.error.issues.map((issue) => issue.path[0]) + + expect(paths).toContain(field) + }) + + it('requires the hosted page url', () => { + expect( + zCreateTopupCheckoutResponse.safeParse(checkoutResponse()) + ).toMatchObject({ success: true }) + expect(zCreateTopupCheckoutResponse.safeParse({}).success).toBe(false) + }) + + it('validates the hosted page as a url but not as https, which the command re-checks itself', () => { + expect( + zCreateTopupCheckoutResponse.safeParse( + checkoutResponse({ checkout_url: 'http://host' }) + ) + ).toMatchObject({ success: true }) + expect( + zCreateTopupCheckoutResponse.safeParse( + checkoutResponse({ checkout_url: 'not-a-url' }) + ).success + ).toBe(false) + }) + + it('leaves the provider session id optional, so the host correlates only when it is sent', () => { + const parsed = zCreateTopupCheckoutResponse.safeParse(checkoutResponse()) + + expect(parsed.success && parsed.data.session_id).toBeUndefined() + }) +})