@fantastic.dev/better-stripe 0.47.1 → 0.48.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 (80) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/historyPages.d.ts +22 -0
  4. package/dist/client/billing/historyPages.d.ts.map +1 -0
  5. package/dist/client/billing/historyPages.js +8 -0
  6. package/dist/client/billing/historyPages.js.map +1 -0
  7. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +10 -0
  8. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +21 -16
  10. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  11. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +42 -32
  12. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  13. package/dist/client/connect/payoutSyncTestHelpers.d.ts +5 -0
  14. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  15. package/dist/client/publicTypes.d.ts +1 -0
  16. package/dist/client/publicTypes.d.ts.map +1 -1
  17. package/dist/client/readContracts.d.ts +4 -0
  18. package/dist/client/readContracts.d.ts.map +1 -1
  19. package/dist/client/readContracts.js +8 -0
  20. package/dist/client/readContracts.js.map +1 -1
  21. package/dist/client/webhooks/handler.d.ts.map +1 -1
  22. package/dist/client/webhooks/handler.js +6 -3
  23. package/dist/client/webhooks/handler.js.map +1 -1
  24. package/dist/client/webhooks/processors.d.ts.map +1 -1
  25. package/dist/client/webhooks/processors.js +3 -65
  26. package/dist/client/webhooks/processors.js.map +1 -1
  27. package/dist/client/webhooks/refundDelivery.d.ts +5 -0
  28. package/dist/client/webhooks/refundDelivery.d.ts.map +1 -0
  29. package/dist/client/webhooks/refundDelivery.js +28 -0
  30. package/dist/client/webhooks/refundDelivery.js.map +1 -0
  31. package/dist/client/webhooks/refundRecovery.d.ts +5 -0
  32. package/dist/client/webhooks/refundRecovery.d.ts.map +1 -0
  33. package/dist/client/webhooks/refundRecovery.js +36 -0
  34. package/dist/client/webhooks/refundRecovery.js.map +1 -0
  35. package/dist/component/_generated/api.d.ts +4 -0
  36. package/dist/component/_generated/api.d.ts.map +1 -1
  37. package/dist/component/_generated/api.js.map +1 -1
  38. package/dist/component/_generated/component.d.ts +100 -0
  39. package/dist/component/_generated/component.d.ts.map +1 -1
  40. package/dist/component/balanceFunding/mutations.d.ts +16 -16
  41. package/dist/component/billing/schema.d.ts +5 -0
  42. package/dist/component/billing/schema.d.ts.map +1 -1
  43. package/dist/component/billing/schema.js +13 -0
  44. package/dist/component/billing/schema.js.map +1 -1
  45. package/dist/component/billingHistory/queries.d.ts +97 -0
  46. package/dist/component/billingHistory/queries.d.ts.map +1 -0
  47. package/dist/component/billingHistory/queries.js +65 -0
  48. package/dist/component/billingHistory/queries.js.map +1 -0
  49. package/dist/component/billingHistory/scope.d.ts +23 -0
  50. package/dist/component/billingHistory/scope.d.ts.map +1 -0
  51. package/dist/component/billingHistory/scope.js +54 -0
  52. package/dist/component/billingHistory/scope.js.map +1 -0
  53. package/dist/component/earnings/triggers.d.ts +10 -0
  54. package/dist/component/earnings/triggers.d.ts.map +1 -1
  55. package/dist/component/processingCostReconciliation/rollback.d.ts +1 -1
  56. package/dist/component/refundSync/mutations.d.ts +1 -1
  57. package/dist/component/refundSync/mutations.d.ts.map +1 -1
  58. package/dist/component/schema.d.ts +5 -0
  59. package/docs/billing-history.md +13 -0
  60. package/docs/refund-context.md +42 -9
  61. package/package.json +2 -1
  62. package/src/client/billing/historyPages.test.ts +58 -0
  63. package/src/client/billing/historyPages.ts +48 -0
  64. package/src/client/publicTypes.ts +7 -0
  65. package/src/client/readContracts.ts +16 -0
  66. package/src/client/webhooks/handler.ts +7 -3
  67. package/src/client/webhooks/processors.test.ts +9 -7
  68. package/src/client/webhooks/processors.ts +3 -88
  69. package/src/client/webhooks/refund-delivery.test.ts +512 -0
  70. package/src/client/webhooks/refundDelivery.ts +42 -0
  71. package/src/client/webhooks/refundRecovery.ts +52 -0
  72. package/src/client/webhooks.test.ts +35 -42
  73. package/src/component/_generated/api.ts +4 -0
  74. package/src/component/_generated/component.ts +128 -0
  75. package/src/component/billing/schema.ts +13 -0
  76. package/src/component/billingHistory/guards.test.ts +235 -0
  77. package/src/component/billingHistory/options.test.ts +35 -0
  78. package/src/component/billingHistory/pages.test.ts +74 -0
  79. package/src/component/billingHistory/queries.ts +88 -0
  80. package/src/component/billingHistory/scope.ts +77 -0
@@ -0,0 +1,58 @@
1
+ import { expect, it, vi } from "vitest";
2
+ import { components } from "../setup.test.js";
3
+ import { ReadContractClient } from "../readContracts.js";
4
+
5
+ it("exposes both independent bounded billing history readers on the public client", () => {
6
+ expect(ReadContractClient.prototype).toHaveProperty(
7
+ "paginateSubscriptions",
8
+ expect.any(Function),
9
+ );
10
+ expect(ReadContractClient.prototype).toHaveProperty(
11
+ "paginateCheckoutSessions",
12
+ expect.any(Function),
13
+ );
14
+ });
15
+
16
+ it("forwards the original buyer/account and independent cursors without provider operations", async () => {
17
+ const client = new ReadContractClient(components.betterStripe);
18
+ const result = { page: [], isDone: true, continueCursor: "original_cursor" };
19
+ const runQuery = vi.fn().mockResolvedValue(result);
20
+ const ctx = { runQuery };
21
+ const subscriptions = {
22
+ userId: "original_buyer",
23
+ accountId: "acct_original",
24
+ status: "trialing" as const,
25
+ paginationOpts: { cursor: "subscription_cursor", numItems: 17 },
26
+ };
27
+ const sessions = {
28
+ userId: "original_buyer",
29
+ status: "complete" as const,
30
+ paginationOpts: { cursor: "checkout_cursor", numItems: 19 },
31
+ };
32
+ expect(await client.paginateSubscriptions(ctx, subscriptions)).toBe(result);
33
+ expect(await client.paginateCheckoutSessions(ctx, sessions)).toBe(result);
34
+ expect(runQuery).toHaveBeenNthCalledWith(
35
+ 1,
36
+ components.betterStripe.billingHistory.queries.paginateSubscriptions,
37
+ subscriptions,
38
+ );
39
+ expect(runQuery).toHaveBeenNthCalledWith(
40
+ 2,
41
+ components.betterStripe.billingHistory.queries.paginateCheckoutSessions,
42
+ sessions,
43
+ );
44
+ });
45
+
46
+ it("propagates component read errors without returning an empty success page", async () => {
47
+ const client = new ReadContractClient(components.betterStripe);
48
+ const runQuery = vi.fn().mockRejectedValue(new Error("read failed"));
49
+ await expect(
50
+ client.paginateSubscriptions(
51
+ { runQuery },
52
+ {
53
+ userId: "original",
54
+ paginationOpts: { cursor: null, numItems: 10 },
55
+ },
56
+ ),
57
+ ).rejects.toThrow("read failed");
58
+ });
@@ -0,0 +1,48 @@
1
+ import type { PaginationOptions, PaginationResult } from "convex/server";
2
+ import type {
3
+ CheckoutSessionStatus,
4
+ SubscriptionStatus,
5
+ } from "../../component/billing/validators.js";
6
+ import type { Component, RunCtx } from "../helpers.js";
7
+ import type { Doc } from "../../component/_generated/dataModel.js";
8
+ import { componentRef } from "../webhooks/helpers.js";
9
+
10
+ /** A trusted host supplies the authorized original buyer; the cursor is not authorization. */
11
+ export type SubscriptionHistoryPageOptions = {
12
+ userId: string;
13
+ accountId?: string;
14
+ status?: SubscriptionStatus;
15
+ paginationOpts: PaginationOptions;
16
+ };
17
+ export type CheckoutSessionHistoryPageOptions = {
18
+ userId: string;
19
+ accountId?: string;
20
+ status?: CheckoutSessionStatus;
21
+ paginationOpts: PaginationOptions;
22
+ };
23
+ export type SubscriptionHistoryPage = PaginationResult<Doc<"subscriptions">>;
24
+ export type CheckoutSessionHistoryPage = PaginationResult<
25
+ Doc<"checkoutSessions">
26
+ >;
27
+
28
+ export function paginateSubscriptions(
29
+ component: Component,
30
+ ctx: RunCtx,
31
+ opts: SubscriptionHistoryPageOptions,
32
+ ): Promise<SubscriptionHistoryPage> {
33
+ return ctx.runQuery(
34
+ componentRef(component, "billingHistory/queries/paginateSubscriptions"),
35
+ opts,
36
+ );
37
+ }
38
+
39
+ export function paginateCheckoutSessions(
40
+ component: Component,
41
+ ctx: RunCtx,
42
+ opts: CheckoutSessionHistoryPageOptions,
43
+ ): Promise<CheckoutSessionHistoryPage> {
44
+ return ctx.runQuery(
45
+ componentRef(component, "billingHistory/queries/paginateCheckoutSessions"),
46
+ opts,
47
+ );
48
+ }
@@ -91,3 +91,10 @@ export type {
91
91
  PrepareBalanceFundingOptions,
92
92
  SetBalanceFundingOptions,
93
93
  } from "./billing/balanceFunding.js";
94
+
95
+ export type {
96
+ SubscriptionHistoryPageOptions,
97
+ CheckoutSessionHistoryPageOptions,
98
+ SubscriptionHistoryPage,
99
+ CheckoutSessionHistoryPage,
100
+ } from "./billing/historyPages.js";
@@ -1,3 +1,4 @@
1
+ import * as historyPages from "./billing/historyPages.js";
1
2
  import { OperationEvidenceClient } from "./operationEvidence.js";
2
3
  import {
3
4
  normalizeRefundCommandBindings,
@@ -24,6 +25,21 @@ import { componentRef } from "./webhooks/helpers.js";
24
25
  /** Shared component readers inherited by BetterStripe. */
25
26
  export class ReadContractClient {
26
27
  constructor(public component: Component) {}
28
+ /** Cached buyer observations only; the host authorizes exact selectors on every page. */
29
+ paginateSubscriptions(
30
+ ctx: RunCtx,
31
+ opts: historyPages.SubscriptionHistoryPageOptions,
32
+ ) {
33
+ return historyPages.paginateSubscriptions(this.component, ctx, opts);
34
+ }
35
+
36
+ paginateCheckoutSessions(
37
+ ctx: RunCtx,
38
+ opts: historyPages.CheckoutSessionHistoryPageOptions,
39
+ ) {
40
+ return historyPages.paginateCheckoutSessions(this.component, ctx, opts);
41
+ }
42
+
27
43
  get operationEvidence() {
28
44
  return new OperationEvidenceClient(this.component);
29
45
  }
@@ -186,6 +186,10 @@ export async function handleWebhookRequest(
186
186
  console.error("[better-stripe] retryOnHookError selector failed:", error);
187
187
  return jsonResponse({ error: "Webhook retry policy failed" }, 500);
188
188
  }
189
+ // Refund synchronization is required independently of optional app hook policy.
190
+ const requiresLedgerSuccess =
191
+ requiresHookSuccess ||
192
+ ["refund.created", "refund.updated", "refund.failed"].includes(event.type);
189
193
  // --- Atomic webhook dedup via event ledger ---
190
194
  const eventId = event.id;
191
195
  console.info(
@@ -202,7 +206,7 @@ export async function handleWebhookRequest(
202
206
  },
203
207
  );
204
208
  if (dedupStatus !== "inserted") {
205
- if (requiresHookSuccess && dedupStatus === "processing") {
209
+ if (requiresLedgerSuccess && dedupStatus === "processing") {
206
210
  return jsonResponse({ error: "Event processing in progress" }, 503);
207
211
  }
208
212
  console.info(`[better-stripe] ↳ deduplicated (already processed)`);
@@ -214,7 +218,7 @@ export async function handleWebhookRequest(
214
218
  `[better-stripe] Webhook ledger insert failed for ${eventId}:`,
215
219
  error,
216
220
  );
217
- if (requiresHookSuccess)
221
+ if (requiresLedgerSuccess)
218
222
  return jsonResponse({ error: "Webhook ledger unavailable" }, 500);
219
223
  }
220
224
 
@@ -270,7 +274,7 @@ export async function handleWebhookRequest(
270
274
  },
271
275
  );
272
276
  } catch {
273
- if (requiresHookSuccess)
277
+ if (requiresLedgerSuccess)
274
278
  return jsonResponse({ error: "Webhook completion unavailable" }, 500);
275
279
  /* ledger update best-effort */
276
280
  }
@@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
5
5
  import { computeReversalSlices } from "../../component/lib/reversals.js";
6
6
  import type { WebhookContext } from "./helpers.js";
7
7
  import { processEvent } from "./processors.js";
8
+ import { processRefund } from "../../../tests/fixtures/refund-recovery.js";
8
9
 
9
10
  const TO_REF = Symbol.for("toReferencePath");
10
11
 
@@ -98,6 +99,7 @@ function makeStripe() {
98
99
  return {
99
100
  payouts: { retrieve: vi.fn() },
100
101
  refunds: {
102
+ retrieve: vi.fn(),
101
103
  list: vi.fn(() =>
102
104
  (async function* () {
103
105
  yield { amount: 5000, status: "succeeded" };
@@ -2382,7 +2384,7 @@ describe("processEvent — refunds: split clawback + fee-refund denormalization
2382
2384
  amount_refunded: 5000,
2383
2385
  });
2384
2386
  const whCtx = makeWhCtx({ ctx, stripe });
2385
- await processEvent(whCtx, refundEvent());
2387
+ await processRefund(whCtx, refundEvent());
2386
2388
  expect(stripe.transfers.createReversal).toHaveBeenCalledTimes(2);
2387
2389
  expect(stripe.transfers.createReversal).toHaveBeenCalledWith(
2388
2390
  "tr_s",
@@ -2409,7 +2411,7 @@ describe("processEvent — refunds: split clawback + fee-refund denormalization
2409
2411
  amount_refunded: 10000,
2410
2412
  });
2411
2413
  const whCtx = makeWhCtx({ ctx, stripe });
2412
- await processEvent(whCtx, refundEvent({ amount: 10000 }));
2414
+ await processRefund(whCtx, refundEvent({ amount: 10000 }));
2413
2415
  expect(stripe.transfers.createReversal).toHaveBeenCalledWith(
2414
2416
  "tr_s",
2415
2417
  { amount: 7000 },
@@ -2437,7 +2439,7 @@ describe("processEvent — refunds: split clawback + fee-refund denormalization
2437
2439
  amount_refunded: 7000, // cumulative: 5000 + this refund's 2000
2438
2440
  });
2439
2441
  const whCtx = makeWhCtx({ ctx, stripe });
2440
- await processEvent(whCtx, refundEvent({ id: "re_2", amount: 2000 }));
2442
+ await processRefund(whCtx, refundEvent({ id: "re_2", amount: 2000 }));
2441
2443
  expect(stripe.transfers.createReversal).toHaveBeenCalledWith(
2442
2444
  "tr_s",
2443
2445
  { amount: 1400 },
@@ -2460,14 +2462,14 @@ describe("processEvent — refunds: split clawback + fee-refund denormalization
2460
2462
  amount_refunded: 5000,
2461
2463
  });
2462
2464
  const whCtx = makeWhCtx({ ctx, stripe });
2463
- await processEvent(whCtx, refundEvent());
2465
+ await processRefund(whCtx, refundEvent());
2464
2466
  expect(stripe.transfers.createReversal).not.toHaveBeenCalled();
2465
2467
  });
2466
2468
  it("skips clawback quietly for a refund on a non-split sale", async () => {
2467
2469
  const ctx = makeCtx({ query: [] });
2468
2470
  const stripe = makeStripe();
2469
2471
  const whCtx = makeWhCtx({ ctx, stripe });
2470
- await processEvent(whCtx, refundEvent());
2472
+ await processRefund(whCtx, refundEvent());
2471
2473
  expect(stripe.charges.retrieve).not.toHaveBeenCalled();
2472
2474
  expect(stripe.transfers.createReversal).not.toHaveBeenCalled();
2473
2475
  });
@@ -2475,7 +2477,7 @@ describe("processEvent — refunds: split clawback + fee-refund denormalization
2475
2477
  const ctx = makeCtx({ query: ledgerLegs() });
2476
2478
  const stripe = makeStripe();
2477
2479
  const whCtx = makeWhCtx({ ctx, stripe });
2478
- await processEvent(whCtx, refundEvent({ status: "pending" }));
2480
+ await processRefund(whCtx, refundEvent({ status: "pending" }));
2479
2481
  expect(stripe.transfers.createReversal).not.toHaveBeenCalled();
2480
2482
  });
2481
2483
  it("propagates a reversal failure so the event is marked failed and Stripe retries", async () => {
@@ -2488,7 +2490,7 @@ describe("processEvent — refunds: split clawback + fee-refund denormalization
2488
2490
  });
2489
2491
  stripe.transfers.createReversal.mockRejectedValue(new Error("stripe down"));
2490
2492
  const whCtx = makeWhCtx({ ctx, stripe });
2491
- await expect(processEvent(whCtx, refundEvent())).rejects.toThrow(
2493
+ await expect(processRefund(whCtx, refundEvent())).rejects.toThrow(
2492
2494
  "stripe down",
2493
2495
  );
2494
2496
  });
@@ -1,15 +1,12 @@
1
+ import { handleRefundEvent } from "./refundDelivery.js";
1
2
  import { handlePayoutEvent } from "./payoutReconciliation.js";
2
3
  import { reconcileDisputeMoney } from "./disputeRecovery.js";
3
- import { successfulRefundPrincipal } from "../connect/refundPrincipal.js";
4
4
  import { subscriptionRouting } from "../billing/subscriptionRouting.js";
5
5
  import { cancelsAtPeriodEnd } from "../billing/subscriptionCancellation.js";
6
6
  import type Stripe from "stripe";
7
7
 
8
8
  import type { SplitRecipient } from "../../component/lib/fees.js";
9
- import {
10
- createSplitTransfers,
11
- reverseTransfersForRefund,
12
- } from "../connect/transfers.js";
9
+ import { createSplitTransfers } from "../connect/transfers.js";
13
10
  import { validateStatementDescriptorSuffix } from "../core/descriptors.js";
14
11
  import { computeFee } from "../core/fees.js";
15
12
  import type { PlatformFeeConfig } from "../types.js";
@@ -110,7 +107,7 @@ export async function processEvent(
110
107
  case "refund.created":
111
108
  case "refund.updated":
112
109
  case "refund.failed":
113
- await handleRefundEvent(whCtx, obj as Stripe.Refund);
110
+ await handleRefundEvent(whCtx, obj as Stripe.Refund, event.account);
114
111
  break;
115
112
  case "application_fee.refunded":
116
113
  // Keep feeCollectedAmount/feeRefundedAmount accurate on the linked
@@ -902,88 +899,6 @@ async function upsertPaymentFromStripe(
902
899
  }
903
900
 
904
901
  // Stripe types Refund.status as `string | null`; clamp to the documented union.
905
- const REFUND_STATUSES = new Set([
906
- "pending",
907
- "requires_action",
908
- "succeeded",
909
- "failed",
910
- "canceled",
911
- ]);
912
- const REFUND_REASONS = new Set([
913
- "duplicate",
914
- "fraudulent",
915
- "requested_by_customer",
916
- "expired_uncaptured_charge",
917
- ]);
918
-
919
- async function handleRefundEvent(
920
- whCtx: WebhookContext,
921
- refund: Stripe.Refund,
922
- ): Promise<void> {
923
- const paymentIntentId =
924
- typeof refund.payment_intent === "string"
925
- ? refund.payment_intent
926
- : (refund.payment_intent?.id ?? undefined);
927
- const chargeId =
928
- typeof refund.charge === "string"
929
- ? refund.charge
930
- : (refund.charge?.id ?? undefined);
931
-
932
- const status =
933
- refund.status && REFUND_STATUSES.has(refund.status)
934
- ? refund.status
935
- : "pending";
936
- const reason =
937
- refund.reason && REFUND_REASONS.has(refund.reason)
938
- ? refund.reason
939
- : undefined;
940
-
941
- await dispatchUpsert(whCtx, "refundUpserted", {
942
- stripeRefundId: refund.id,
943
- stripePaymentIntentId: paymentIntentId,
944
- stripeChargeId: chargeId,
945
- amount: refund.amount,
946
- currency: refund.currency,
947
- status,
948
- reason,
949
- failureReason: refund.failure_reason ?? undefined,
950
- metadata: refund.metadata ?? undefined,
951
- });
952
-
953
- // Split-sale clawback (BTS-34): when a separate-charges sale is refunded,
954
- // pull the refunded share back from each recipient pro-rata. Only ledger
955
- // legs identify a split sale — destination-charge auto-transfers are not in
956
- // the ledger and are handled by Stripe-native `reverse_transfer` at refund
957
- // creation. Runs on `refund.updated` too so a pending→succeeded refund
958
- // (e.g. ACH) still claws back. Errors propagate → event `failed` → Stripe
959
- // retries; `reverseTransfersForRefund`'s delta-to-target math makes the
960
- // re-run converge without double-reversing.
961
- if (status !== "succeeded" || !chargeId) return;
962
- const legs = ((await whCtx.ctx.runQuery(
963
- componentRef(whCtx.component, "connect/queries/listTransfersByCharge"),
964
- { sourceChargeId: chargeId },
965
- )) ?? []) as unknown[];
966
- if (legs.length === 0) {
967
- const obligations = (await whCtx.ctx.runQuery(
968
- componentRef(
969
- whCtx.component,
970
- "affiliateRecovery/queries/chargeObligations",
971
- ),
972
- { sourceChargeId: chargeId },
973
- )) as unknown[] | null;
974
- if (!obligations?.length) return;
975
- }
976
-
977
- // Fetch succeeded refunds: charge.amount_refunded can include pending funds.
978
- const charge = await whCtx.stripe.charges.retrieve(chargeId);
979
- await reverseTransfersForRefund(whCtx.stripe, whCtx.component, whCtx.ctx, {
980
- sourceChargeId: chargeId,
981
- refundId: refund.id,
982
- chargeAmount: charge.amount,
983
- amountRefunded: await successfulRefundPrincipal(whCtx.stripe, chargeId),
984
- });
985
- }
986
-
987
902
  /**
988
903
  * Denormalize fee-refund state from `application_fee.refunded` (BTS-34, folded
989
904
  * in from BTS-51): set the linked payment's `feeRefundedAmount` and correct