@fantastic.dev/better-stripe 0.39.0 → 0.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +1 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +442 -0
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +221 -0
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +442 -0
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +221 -0
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/costRecovery-invoices.d.ts +2 -2
  12. package/dist/client/costRecovery-invoices.d.ts.map +1 -1
  13. package/dist/client/costRecovery-invoices.js +7 -6
  14. package/dist/client/costRecovery-invoices.js.map +1 -1
  15. package/dist/client/costRecovery.d.ts +5 -2
  16. package/dist/client/costRecovery.d.ts.map +1 -1
  17. package/dist/client/costRecovery.js +3 -1
  18. package/dist/client/costRecovery.js.map +1 -1
  19. package/dist/client/index.d.ts +3 -2
  20. package/dist/client/index.d.ts.map +1 -1
  21. package/dist/client/index.js +2 -2
  22. package/dist/client/index.js.map +1 -1
  23. package/dist/client/paymentSource/client.d.ts +21 -0
  24. package/dist/client/paymentSource/client.d.ts.map +1 -0
  25. package/dist/client/paymentSource/client.js +8 -0
  26. package/dist/client/paymentSource/client.js.map +1 -0
  27. package/dist/client/paymentSource/contracts.d.ts +30 -0
  28. package/dist/client/paymentSource/contracts.d.ts.map +1 -0
  29. package/dist/client/paymentSource/contracts.js +16 -0
  30. package/dist/client/paymentSource/contracts.js.map +1 -0
  31. package/dist/client/paymentSource/economics.d.ts +12 -0
  32. package/dist/client/paymentSource/economics.d.ts.map +1 -0
  33. package/dist/client/paymentSource/economics.js +13 -0
  34. package/dist/client/paymentSource/economics.js.map +1 -0
  35. package/dist/client/paymentSource/funding.d.ts +10 -0
  36. package/dist/client/paymentSource/funding.d.ts.map +1 -0
  37. package/dist/client/paymentSource/funding.js +12 -0
  38. package/dist/client/paymentSource/funding.js.map +1 -0
  39. package/dist/client/paymentSource/history.d.ts +13 -0
  40. package/dist/client/paymentSource/history.d.ts.map +1 -0
  41. package/dist/client/paymentSource/history.js +41 -0
  42. package/dist/client/paymentSource/history.js.map +1 -0
  43. package/dist/client/paymentSource/resolver.d.ts +6 -0
  44. package/dist/client/paymentSource/resolver.d.ts.map +1 -0
  45. package/dist/client/paymentSource/resolver.js +222 -0
  46. package/dist/client/paymentSource/resolver.js.map +1 -0
  47. package/dist/client/recoveryWorkflow/client.d.ts +14 -0
  48. package/dist/client/recoveryWorkflow/client.d.ts.map +1 -0
  49. package/dist/client/recoveryWorkflow/client.js +34 -0
  50. package/dist/client/recoveryWorkflow/client.js.map +1 -0
  51. package/dist/client/recoveryWorkflow/contracts.d.ts +63 -0
  52. package/dist/client/recoveryWorkflow/contracts.d.ts.map +1 -0
  53. package/dist/client/recoveryWorkflow/contracts.js +11 -0
  54. package/dist/client/recoveryWorkflow/contracts.js.map +1 -0
  55. package/dist/client/recoveryWorkflow/provider.d.ts +10 -0
  56. package/dist/client/recoveryWorkflow/provider.d.ts.map +1 -0
  57. package/dist/client/recoveryWorkflow/provider.js +80 -0
  58. package/dist/client/recoveryWorkflow/provider.js.map +1 -0
  59. package/dist/client/recoveryWorkflow/settlement.d.ts +6 -0
  60. package/dist/client/recoveryWorkflow/settlement.d.ts.map +1 -0
  61. package/dist/client/recoveryWorkflow/settlement.js +43 -0
  62. package/dist/client/recoveryWorkflow/settlement.js.map +1 -0
  63. package/dist/client/settlement/verifiedSale.d.ts.map +1 -1
  64. package/dist/client/settlement/verifiedSale.js +4 -6
  65. package/dist/client/settlement/verifiedSale.js.map +1 -1
  66. package/dist/component/_generated/api.d.ts +12 -0
  67. package/dist/component/_generated/api.d.ts.map +1 -1
  68. package/dist/component/_generated/api.js.map +1 -1
  69. package/dist/component/_generated/component.d.ts +164 -0
  70. package/dist/component/_generated/component.d.ts.map +1 -1
  71. package/dist/component/earnings/triggers.d.ts +194 -0
  72. package/dist/component/earnings/triggers.d.ts.map +1 -1
  73. package/dist/component/payoutRelease/queries.d.ts +2 -2
  74. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  75. package/dist/component/recoveryWorkflow/bridge.d.ts +21 -0
  76. package/dist/component/recoveryWorkflow/bridge.d.ts.map +1 -0
  77. package/dist/component/recoveryWorkflow/bridge.js +52 -0
  78. package/dist/component/recoveryWorkflow/bridge.js.map +1 -0
  79. package/dist/component/recoveryWorkflow/helpers.d.ts +83 -0
  80. package/dist/component/recoveryWorkflow/helpers.d.ts.map +1 -0
  81. package/dist/component/recoveryWorkflow/helpers.js +48 -0
  82. package/dist/component/recoveryWorkflow/helpers.js.map +1 -0
  83. package/dist/component/recoveryWorkflow/mutations.d.ts +91 -0
  84. package/dist/component/recoveryWorkflow/mutations.d.ts.map +1 -0
  85. package/dist/component/recoveryWorkflow/mutations.js +177 -0
  86. package/dist/component/recoveryWorkflow/mutations.js.map +1 -0
  87. package/dist/component/recoveryWorkflow/queries.d.ts +118 -0
  88. package/dist/component/recoveryWorkflow/queries.d.ts.map +1 -0
  89. package/dist/component/recoveryWorkflow/queries.js +20 -0
  90. package/dist/component/recoveryWorkflow/queries.js.map +1 -0
  91. package/dist/component/recoveryWorkflow/schema.d.ts +653 -0
  92. package/dist/component/recoveryWorkflow/schema.d.ts.map +1 -0
  93. package/dist/component/recoveryWorkflow/schema.js +81 -0
  94. package/dist/component/recoveryWorkflow/schema.js.map +1 -0
  95. package/dist/component/recoveryWorkflow/steps.d.ts +70 -0
  96. package/dist/component/recoveryWorkflow/steps.d.ts.map +1 -0
  97. package/dist/component/recoveryWorkflow/steps.js +94 -0
  98. package/dist/component/recoveryWorkflow/steps.js.map +1 -0
  99. package/dist/component/recoveryWorkflow/workflow.d.ts +22 -0
  100. package/dist/component/recoveryWorkflow/workflow.d.ts.map +1 -0
  101. package/dist/component/recoveryWorkflow/workflow.js +56 -0
  102. package/dist/component/recoveryWorkflow/workflow.js.map +1 -0
  103. package/dist/component/schema.d.ts +221 -0
  104. package/dist/component/schema.js +3 -0
  105. package/dist/component/schema.js.map +1 -1
  106. package/docs/settlement.md +48 -0
  107. package/package.json +1 -1
  108. package/src/client/costRecovery-invoices.ts +9 -7
  109. package/src/client/costRecovery.ts +8 -3
  110. package/src/client/index.ts +6 -2
  111. package/src/client/paymentSource/client.ts +13 -0
  112. package/src/client/paymentSource/contracts.ts +33 -0
  113. package/src/client/paymentSource/economics.ts +20 -0
  114. package/src/client/paymentSource/funding.ts +23 -0
  115. package/src/client/paymentSource/history.ts +48 -0
  116. package/src/client/paymentSource/resolver.test.ts +582 -0
  117. package/src/client/paymentSource/resolver.ts +350 -0
  118. package/src/client/recoveryWorkflow/client.test.ts +37 -0
  119. package/src/client/recoveryWorkflow/client.ts +76 -0
  120. package/src/client/recoveryWorkflow/contracts.ts +72 -0
  121. package/src/client/recoveryWorkflow/provider.test.ts +424 -0
  122. package/src/client/recoveryWorkflow/provider.ts +119 -0
  123. package/src/client/recoveryWorkflow/settlement.ts +67 -0
  124. package/src/client/settlement/verifiedSale.ts +4 -10
  125. package/src/component/_generated/api.ts +12 -0
  126. package/src/component/_generated/component.ts +222 -0
  127. package/src/component/recoveryWorkflow/bridge.test.ts +481 -0
  128. package/src/component/recoveryWorkflow/bridge.ts +66 -0
  129. package/src/component/recoveryWorkflow/helpers.ts +58 -0
  130. package/src/component/recoveryWorkflow/journal.test.ts +104 -0
  131. package/src/component/recoveryWorkflow/mutations.ts +224 -0
  132. package/src/component/recoveryWorkflow/queries.ts +19 -0
  133. package/src/component/recoveryWorkflow/schema.ts +92 -0
  134. package/src/component/recoveryWorkflow/state.test.ts +191 -0
  135. package/src/component/recoveryWorkflow/steps.ts +97 -0
  136. package/src/component/recoveryWorkflow/workflow.ts +73 -0
  137. package/src/component/schema.ts +6 -0
@@ -5,6 +5,54 @@ and recovery. Your server authenticates the caller, resolves recipient accounts,
5
5
  selects rates, and authorizes the allocation. Never accept these values directly
6
6
  from a browser. Amounts below are integer minor units in one currency.
7
7
 
8
+ ## Resolve original payment provenance
9
+
10
+ Use `getVerifiedPaymentSource` when the host has an authorized PaymentIntent and
11
+ needs its original invoice price for settlement or processing-cost recovery:
12
+
13
+ ```ts
14
+ const source = await stripe.getVerifiedPaymentSource(ctx, {
15
+ paymentIntentId,
16
+ customerAccountId, // Optional expected binding; authorize this in your host.
17
+ stripeAccountId, // Optional connected-account execution scope.
18
+ gross: expectedGross,
19
+ currency: expectedCurrency,
20
+ maxHistoryPages: 5,
21
+ maxHistoryItems: 500,
22
+ });
23
+ if (source.status !== "ready") return source;
24
+ // Authorize source.value.stripeProductId before applying application policy.
25
+ ```
26
+
27
+ The read-only result contains provider IDs, original gross and processing fee,
28
+ currency and live/test mode. Optional expected `invoiceId` and `subscriptionId`
29
+ are also checked. Provider reads inherit the SDK's configured Stripe API version
30
+ and connected-account scope. Authentication, seller/product ownership, metadata
31
+ interpretation, commission and retry scheduling remain host responsibilities.
32
+
33
+ Resolution requires complete inverse PaymentIntent funding history, complete
34
+ invoice funding history, one fully paid PaymentIntent allocation and one original
35
+ priced invoice line. It verifies customer, invoice, subscription, charge and
36
+ balance-transaction bindings, currencies and reconciled gross/fee/net amounts.
37
+ Current subscription items and metadata never establish the original price.
38
+ Prorations, partial/credit/multiple-payment funding and ambiguous price allocation
39
+ are rejected instead of guessed. Refunded or disputed charges retain their
40
+ original provenance; a ready source does **not** establish settlement eligibility
41
+ or calculate subsequent refund/dispute costs.
42
+
43
+ Each of the three history walks has independent validated limits: 1–20 pages and
44
+ 1–2,000 items (defaults 5 and 500), at most 100 items per page. Reaching a limit
45
+ before `has_more: false`, malformed pages, repeated IDs or failed history reads
46
+ returns `unknown/history_incomplete`, with `retryable: false`. Missing processing
47
+ fees return `not_ready/fee_pending`; only a provider-verified zero fee becomes
48
+ zero. Identity conflicts and unsupported sources are terminal typed outcomes.
49
+ Other failed provider reads return sanitized `unknown/provider_outcome_unknown`.
50
+ The method performs no writes or automatic financial-operation retries.
51
+
52
+ `getVerifiedSale` and the existing cost readers keep their existing contracts,
53
+ including settlement eligibility checks. The new resolver shares their pure
54
+ currency/amount and single-funding checks without changing their result shapes.
55
+
8
56
  ## Read, allocate, settle
9
57
 
10
58
  ```ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fantastic.dev/better-stripe",
3
- "version": "0.39.0",
3
+ "version": "0.41.0",
4
4
  "description": "A Convex component for Stripe V2 Accounts API integration.",
5
5
  "keywords": [
6
6
  "stripe",
@@ -1,3 +1,4 @@
1
+ import { singleInvoiceFunding } from "./paymentSource/funding.js";
1
2
  import { getProcessingCostContext } from "./settlement/processingCosts.js";
2
3
  import type Stripe from "stripe";
3
4
  import type { RecoveryGroup, RecoveryScope } from "./costRecovery.js";
@@ -20,6 +21,7 @@ export function attachRecoveryInvoice(
20
21
  opts: RecoveryInvoiceOptions,
21
22
  bind: BindInvoiceItem,
22
23
  create?: true,
24
+ maxItems?: number,
23
25
  ): Promise<InvoiceReceipt>;
24
26
  export function attachRecoveryInvoice(
25
27
  stripe: Stripe,
@@ -27,6 +29,7 @@ export function attachRecoveryInvoice(
27
29
  opts: RecoveryInvoiceOptions,
28
30
  bind: BindInvoiceItem,
29
31
  create: false,
32
+ maxItems?: number,
30
33
  ): Promise<
31
34
  | InvoiceReceipt
32
35
  | (Omit<InvoiceReceipt, "invoiceItemId"> & { invoiceItemId: null })
@@ -39,6 +42,7 @@ export async function attachRecoveryInvoice(
39
42
  opts: RecoveryInvoiceOptions,
40
43
  bind: (invoiceItemId: string) => Promise<RecoveryGroup>,
41
44
  create = true,
45
+ maxItems = Number.POSITIVE_INFINITY,
42
46
  ) {
43
47
  if (
44
48
  !group ||
@@ -65,10 +69,13 @@ export async function attachRecoveryInvoice(
65
69
  if (invoice.currency !== group.currency)
66
70
  throw new Error("Recovery invoice currency does not match.");
67
71
  let found: Stripe.InvoiceItem | undefined;
72
+ let inspected = 0;
68
73
  for await (const item of stripe.invoiceItems.list({
69
74
  invoice: invoice.id,
70
75
  limit: 100,
71
76
  })) {
77
+ if (++inspected > maxItems)
78
+ throw new Error("Recovery invoice history exceeded its item bound.");
72
79
  if (item.metadata?.[marker] !== group._id) continue;
73
80
  if (found)
74
81
  throw new Error(
@@ -152,13 +159,8 @@ export async function readInvoiceFunding(stripe: Stripe, group: RecoveryGroup) {
152
159
  throw new Error("Invoice payment identity or currency does not match.");
153
160
  if (payment.status === "paid") payments.push(payment);
154
161
  }
155
- const payment = payments[0];
156
- if (
157
- payments.length !== 1 ||
158
- payment?.payment.type !== "payment_intent" ||
159
- !payment.payment.payment_intent ||
160
- payment.amount_paid !== invoice.amount_paid
161
- )
162
+ const payment = singleInvoiceFunding(payments, invoice.amount_paid);
163
+ if (!payment)
162
164
  return {
163
165
  status: "not_ready" as const,
164
166
  reason: "invoice_funding_allocation_required" as const,
@@ -1,3 +1,6 @@
1
+ import { RecoveryWorkflowClient } from "./recoveryWorkflow/client.js";
2
+ export type * from "./recoveryWorkflow/contracts.js";
3
+ export type { RecoveryProviderOptions } from "./recoveryWorkflow/provider.js";
1
4
  import type Stripe from "stripe";
2
5
  import {
3
6
  readInvoiceFunding,
@@ -96,11 +99,13 @@ export type RecoveryPreparationResult =
96
99
  retryable: false;
97
100
  };
98
101
  /** Host authorizes policy and scope. Provider methods verify invoice outcomes. */
99
- export class CostRecoveryClient {
102
+ export class CostRecoveryClient extends RecoveryWorkflowClient {
100
103
  constructor(
101
- private readonly component: Component,
104
+ protected readonly component: Component,
102
105
  private readonly provider?: () => Stripe,
103
- ) {}
106
+ ) {
107
+ super();
108
+ }
104
109
  private async mutate<T>(
105
110
  ctx: RunCtx,
106
111
  path: string,
@@ -20,7 +20,7 @@ import type { CreateCheckoutSessionOptions } from "./billing/checkoutOptions.js"
20
20
  export type { CreateCheckoutSessionOptions } from "./billing/checkoutOptions.js";
21
21
  import * as intentsImpl from "./billing/intents.js";
22
22
  export type * from "./billing/intents.js";
23
- import { CatalogClient } from "./products/catalogClient.js";
23
+ import { PaymentSourceClient } from "./paymentSource/client.js";
24
24
  export type {
25
25
  CreateBillingPortalConfigurationOptions,
26
26
  RetrieveBillingPortalConfigurationOptions,
@@ -91,6 +91,10 @@ export type {
91
91
  VerifiedSale,
92
92
  VerifiedSaleOptions,
93
93
  } from "./settlement/verifiedSale.js";
94
+ export type {
95
+ VerifiedPaymentSource,
96
+ VerifiedPaymentSourceOptions,
97
+ } from "./paymentSource/contracts.js";
94
98
  export type { SettleSaleOptions } from "./settlement/settleSale.js";
95
99
  export type { SettlementResult } from "./settlement/execution.js";
96
100
  export type {
@@ -205,7 +209,7 @@ export type BetterStripeComponent = ComponentApi;
205
209
 
206
210
  // BETTER STRIPE CLIENT
207
211
 
208
- export class BetterStripe extends CatalogClient {
212
+ export class BetterStripe extends PaymentSourceClient {
209
213
  readonly stripeApiVersion: SupportedStripeApiVersion;
210
214
  private _apiKey?: string;
211
215
  private _triggers?: SyncTriggers;
@@ -0,0 +1,13 @@
1
+ import { CatalogClient } from "../products/catalogClient.js";
2
+ import type { RunCtx } from "../helpers.js";
3
+ import { resolveVerifiedPaymentSource } from "./resolver.js";
4
+ import type { VerifiedPaymentSourceOptions } from "./contracts.js";
5
+
6
+ export abstract class PaymentSourceClient extends CatalogClient {
7
+ async getVerifiedPaymentSource(
8
+ _ctx: RunCtx,
9
+ opts: VerifiedPaymentSourceOptions,
10
+ ) {
11
+ return resolveVerifiedPaymentSource(this.stripe(), opts);
12
+ }
13
+ }
@@ -0,0 +1,33 @@
1
+ import { z } from "zod";
2
+
3
+ const identifier = z.string().min(1).max(200);
4
+ export const paymentSourceOptions = z
5
+ .object({
6
+ paymentIntentId: identifier,
7
+ customerAccountId: identifier.optional(),
8
+ stripeAccountId: identifier.optional(),
9
+ invoiceId: identifier.optional(),
10
+ subscriptionId: identifier.optional(),
11
+ currency: z.string().regex(/^[a-z]{3}$/),
12
+ gross: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),
13
+ maxHistoryPages: z.number().int().min(1).max(20).default(5),
14
+ maxHistoryItems: z.number().int().min(1).max(2000).default(500),
15
+ })
16
+ .strict();
17
+ export type VerifiedPaymentSourceOptions = z.input<typeof paymentSourceOptions>;
18
+ /** Provider identities/economics only. The host still authorizes these identities. */
19
+ export type VerifiedPaymentSource = Readonly<{
20
+ paymentIntentId: string;
21
+ chargeId: string;
22
+ invoiceId: string;
23
+ invoicePaymentId: string;
24
+ subscriptionId?: string;
25
+ customerAccountId: string;
26
+ stripeAccountId?: string;
27
+ stripePriceId: string;
28
+ stripeProductId: string;
29
+ gross: number;
30
+ processingFee: number;
31
+ currency: string;
32
+ livemode: boolean;
33
+ }>;
@@ -0,0 +1,20 @@
1
+ /** The existing settlement amount/currency rules, shared without changing its result contract. */
2
+ export function saleAmountFailure(
3
+ payment: { currency: string; amount_received: number },
4
+ charge: { currency: string; amount: number },
5
+ balance: { currency: string; fee: number },
6
+ ): "currency" | "amounts" | null {
7
+ if (
8
+ balance.currency !== payment.currency ||
9
+ charge.currency !== payment.currency
10
+ )
11
+ return "currency";
12
+ if (
13
+ ![payment.amount_received, balance.fee].every(Number.isSafeInteger) ||
14
+ balance.fee < 0 ||
15
+ balance.fee > payment.amount_received ||
16
+ charge.amount !== payment.amount_received
17
+ )
18
+ return "amounts";
19
+ return null;
20
+ }
@@ -0,0 +1,23 @@
1
+ import type Stripe from "stripe";
2
+ export type IntentFunding = Stripe.InvoicePayment & {
3
+ payment: {
4
+ type: "payment_intent";
5
+ payment_intent: string | Stripe.PaymentIntent;
6
+ };
7
+ };
8
+ /** Shared existing funding rule; callers must independently prove scope and complete history. */
9
+ export function singleInvoiceFunding(
10
+ rows: Stripe.InvoicePayment[],
11
+ amountPaid: number,
12
+ ): IntentFunding | null {
13
+ const paid = rows.filter((row) => row.status === "paid");
14
+ const payment = paid[0];
15
+ if (
16
+ paid.length !== 1 ||
17
+ payment?.payment.type !== "payment_intent" ||
18
+ !payment.payment.payment_intent ||
19
+ payment.amount_paid !== amountPaid
20
+ )
21
+ return null;
22
+ return payment as IntentFunding;
23
+ }
@@ -0,0 +1,48 @@
1
+ import type Stripe from "stripe";
2
+
3
+ const incomplete = () => ({
4
+ status: "unknown" as const,
5
+ reason: "history_incomplete" as const,
6
+ retryable: false as const,
7
+ });
8
+ /** Completeness is mandatory; previews, repeated cursors and exhausted budgets are not evidence of uniqueness. */
9
+ export async function completeHistory<T extends { id: string }>(
10
+ fetch: (
11
+ cursor: string | undefined,
12
+ limit: number,
13
+ ) => Promise<Stripe.ApiList<T>>,
14
+ maxPages: number,
15
+ maxItems: number,
16
+ ) {
17
+ const data: T[] = [];
18
+ const seen = new Set<string>();
19
+ let cursor: string | undefined;
20
+ for (let pageIndex = 0; pageIndex < maxPages; pageIndex++) {
21
+ const limit = Math.min(100, maxItems - data.length);
22
+ if (limit < 1) return incomplete();
23
+ let page: Stripe.ApiList<T>;
24
+ try {
25
+ page = await fetch(cursor, limit);
26
+ } catch {
27
+ return incomplete();
28
+ }
29
+ if (
30
+ !page ||
31
+ page.object !== "list" ||
32
+ !Array.isArray(page.data) ||
33
+ page.data.length > limit ||
34
+ typeof page.has_more !== "boolean" ||
35
+ (page.has_more && !page.data.length)
36
+ )
37
+ return incomplete();
38
+ for (const row of page.data) {
39
+ if (!row || typeof row.id !== "string" || !row.id || seen.has(row.id))
40
+ return incomplete();
41
+ seen.add(row.id);
42
+ data.push(row);
43
+ }
44
+ if (!page.has_more) return { status: "complete" as const, data };
45
+ cursor = data[data.length - 1]!.id;
46
+ }
47
+ return incomplete();
48
+ }