@fantastic.dev/better-stripe 0.37.0 → 0.38.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 (96) hide show
  1. package/CHANGELOG.md +64 -158
  2. package/README.md +5 -1
  3. package/dist/client/core/accountCapabilities.d.ts +20 -0
  4. package/dist/client/core/accountCapabilities.d.ts.map +1 -0
  5. package/dist/client/core/accountCapabilities.js +7 -0
  6. package/dist/client/core/accountCapabilities.js.map +1 -0
  7. package/dist/client/core/accountConfigurations.d.ts +46 -0
  8. package/dist/client/core/accountConfigurations.d.ts.map +1 -0
  9. package/dist/client/core/accountConfigurations.js +99 -0
  10. package/dist/client/core/accountConfigurations.js.map +1 -0
  11. package/dist/client/core/accountLinks.d.ts +29 -2
  12. package/dist/client/core/accountLinks.d.ts.map +1 -1
  13. package/dist/client/core/accountLinks.js +56 -4
  14. package/dist/client/core/accountLinks.js.map +1 -1
  15. package/dist/client/core/accounts.d.ts +2 -36
  16. package/dist/client/core/accounts.d.ts.map +1 -1
  17. package/dist/client/core/accounts.js +3 -73
  18. package/dist/client/core/accounts.js.map +1 -1
  19. package/dist/client/core/billingPortalClient.d.ts +14 -0
  20. package/dist/client/core/billingPortalClient.d.ts.map +1 -0
  21. package/dist/client/core/billingPortalClient.js +18 -0
  22. package/dist/client/core/billingPortalClient.js.map +1 -0
  23. package/dist/client/costRecovery-invoices.d.ts +4 -4
  24. package/dist/client/costRecovery.d.ts +1 -1
  25. package/dist/client/financialOutcomes/adapters.d.ts +18 -0
  26. package/dist/client/financialOutcomes/adapters.d.ts.map +1 -0
  27. package/dist/client/financialOutcomes/adapters.js +60 -0
  28. package/dist/client/financialOutcomes/adapters.js.map +1 -0
  29. package/dist/client/financialOutcomes/contracts.d.ts +42 -0
  30. package/dist/client/financialOutcomes/contracts.d.ts.map +1 -0
  31. package/dist/client/financialOutcomes/contracts.js +39 -0
  32. package/dist/client/financialOutcomes/contracts.js.map +1 -0
  33. package/dist/client/financialOutcomes/errors.d.ts +6 -0
  34. package/dist/client/financialOutcomes/errors.d.ts.map +1 -0
  35. package/dist/client/financialOutcomes/errors.js +22 -0
  36. package/dist/client/financialOutcomes/errors.js.map +1 -0
  37. package/dist/client/financialOutcomes/index.d.ts +6 -0
  38. package/dist/client/financialOutcomes/index.d.ts.map +1 -0
  39. package/dist/client/financialOutcomes/index.js +4 -0
  40. package/dist/client/financialOutcomes/index.js.map +1 -0
  41. package/dist/client/financialOutcomes/retry.d.ts +24 -0
  42. package/dist/client/financialOutcomes/retry.d.ts.map +1 -0
  43. package/dist/client/financialOutcomes/retry.js +31 -0
  44. package/dist/client/financialOutcomes/retry.js.map +1 -0
  45. package/dist/client/index.d.ts +20 -111
  46. package/dist/client/index.d.ts.map +1 -1
  47. package/dist/client/index.js +10 -85
  48. package/dist/client/index.js.map +1 -1
  49. package/dist/client/products/catalog.d.ts +26 -0
  50. package/dist/client/products/catalog.d.ts.map +1 -0
  51. package/dist/client/products/catalog.js +140 -0
  52. package/dist/client/products/catalog.js.map +1 -0
  53. package/dist/client/products/catalogClient.d.ts +109 -0
  54. package/dist/client/products/catalogClient.d.ts.map +1 -0
  55. package/dist/client/products/catalogClient.js +84 -0
  56. package/dist/client/products/catalogClient.js.map +1 -0
  57. package/dist/client/products/prices.d.ts +1 -0
  58. package/dist/client/products/prices.d.ts.map +1 -1
  59. package/dist/client/products/prices.js +1 -0
  60. package/dist/client/products/prices.js.map +1 -1
  61. package/dist/client/publicTypes.d.ts +2 -0
  62. package/dist/client/publicTypes.d.ts.map +1 -1
  63. package/dist/component/_generated/component.d.ts +8 -0
  64. package/dist/component/_generated/component.d.ts.map +1 -1
  65. package/dist/component/products/mutations.d.ts +9 -0
  66. package/dist/component/products/mutations.d.ts.map +1 -1
  67. package/dist/component/products/mutations.js +31 -2
  68. package/dist/component/products/mutations.js.map +1 -1
  69. package/docs/read-contracts.md +33 -0
  70. package/package.json +1 -1
  71. package/src/client/core/account-session-client.test.ts +74 -0
  72. package/src/client/core/accountCapabilities.ts +22 -0
  73. package/src/client/core/accountConfigurations.test.ts +183 -0
  74. package/src/client/core/accountConfigurations.ts +161 -0
  75. package/src/client/core/accountLinks.test.ts +6 -2
  76. package/src/client/core/accountLinks.ts +122 -5
  77. package/src/client/core/accounts.ts +8 -115
  78. package/src/client/core/billingPortal.test.ts +247 -0
  79. package/src/client/core/billingPortalClient.ts +35 -0
  80. package/src/client/financialOutcomes/adapters.ts +88 -0
  81. package/src/client/financialOutcomes/contracts.ts +43 -0
  82. package/src/client/financialOutcomes/errors.ts +29 -0
  83. package/src/client/financialOutcomes/index.ts +5 -0
  84. package/src/client/financialOutcomes/outcomes.test.ts +254 -0
  85. package/src/client/financialOutcomes/retry.ts +52 -0
  86. package/src/client/index.test.ts +0 -64
  87. package/src/client/index.ts +34 -185
  88. package/src/client/products/catalog.test.ts +389 -0
  89. package/src/client/products/catalog.ts +225 -0
  90. package/src/client/products/catalogClient.ts +172 -0
  91. package/src/client/products/prices.test.ts +24 -0
  92. package/src/client/products/prices.ts +2 -0
  93. package/src/client/publicTypes.ts +13 -0
  94. package/src/component/_generated/api.ts +4 -0
  95. package/src/component/_generated/component.ts +14 -0
  96. package/src/component/products/mutations.ts +39 -2
@@ -0,0 +1,29 @@
1
+ import { ConvexError } from "convex/values";
2
+ import {
3
+ financialUnavailableSchema,
4
+ type FinancialUnavailable,
5
+ } from "./contracts.js";
6
+
7
+ /** Carry only a validated outcome across a Convex action boundary. */
8
+ export function throwFinancialOutcome(outcome: FinancialUnavailable): never {
9
+ const safe = financialUnavailableSchema.parse(outcome);
10
+ throw new ConvexError({ code: "FINANCIAL_OUTCOME", outcome: safe });
11
+ }
12
+
13
+ /** Convex structured data only. Never parse an exception's English message. */
14
+ export function readFinancialOutcomeError(
15
+ error: unknown,
16
+ ): FinancialUnavailable | null {
17
+ if (!error || typeof error !== "object" || !("data" in error)) return null;
18
+ const data = error.data;
19
+ if (
20
+ !data ||
21
+ typeof data !== "object" ||
22
+ !("code" in data) ||
23
+ data.code !== "FINANCIAL_OUTCOME" ||
24
+ !("outcome" in data)
25
+ )
26
+ return null;
27
+ const parsed = financialUnavailableSchema.safeParse(data.outcome);
28
+ return parsed.success ? parsed.data : null;
29
+ }
@@ -0,0 +1,5 @@
1
+ export type { FinancialOutcome, FinancialUnavailable } from "./contracts.js";
2
+ export { verifiedSaleOutcome, processingCostOutcome } from "./adapters.js";
3
+ export { throwFinancialOutcome, readFinancialOutcomeError } from "./errors.js";
4
+ export { financialRetryDecision } from "./retry.js";
5
+ export type { FinancialRetryPolicy, FinancialRetryDecision } from "./retry.js";
@@ -0,0 +1,254 @@
1
+ import { ConvexError } from "convex/values";
2
+ import { describe, expect, it } from "vitest";
3
+ import type { ProcessingCostContext } from "../settlement/processingCosts.js";
4
+ import type { VerifiedSale } from "../settlement/verifiedSale.js";
5
+ import {
6
+ financialRetryDecision,
7
+ processingCostOutcome,
8
+ readFinancialOutcomeError,
9
+ throwFinancialOutcome,
10
+ verifiedSaleOutcome,
11
+ } from "./index.js";
12
+
13
+ const policy = { maxRetries: 10, initialDelayMs: 1000, maxDelayMs: 60000 };
14
+ const pending = {
15
+ status: "not_ready",
16
+ reason: "fee_pending",
17
+ retryable: true,
18
+ } as const;
19
+
20
+ describe("legacy readiness adapters", () => {
21
+ it.each([
22
+ ["payment_processing", "provider_pending"],
23
+ ["charge_unavailable", "provider_pending"],
24
+ ["processing_fee_unavailable", "fee_pending"],
25
+ ["invoice_not_paid", "provider_pending"],
26
+ ])(
27
+ "converts verified sale %s without using English messages",
28
+ (reason, mapped) => {
29
+ expect(
30
+ verifiedSaleOutcome({ status: "pending", reason, retryable: true }),
31
+ ).toEqual({
32
+ status: "not_ready",
33
+ reason: mapped,
34
+ retryable: true,
35
+ });
36
+ },
37
+ );
38
+ it.each(["payment_not_succeeded", "charge_refunded_or_disputed"])(
39
+ "rejects terminal sale reason %s even if a caller marks it retryable",
40
+ (reason) => {
41
+ expect(
42
+ verifiedSaleOutcome({ status: "not_payable", reason, retryable: true }),
43
+ ).toEqual({
44
+ status: "rejected",
45
+ reason: "payment_not_payable",
46
+ retryable: false,
47
+ });
48
+ },
49
+ );
50
+ it("fails closed for unrecognized sale reasons and disabled retry flags", () => {
51
+ for (const sale of [
52
+ {
53
+ status: "pending",
54
+ reason: "processing fees are not available yet",
55
+ retryable: true,
56
+ },
57
+ { status: "pending", reason: "payment_processing", retryable: false },
58
+ ] as VerifiedSale[]) {
59
+ expect(verifiedSaleOutcome(sale)).toEqual({
60
+ status: "rejected",
61
+ reason: "unsupported_source",
62
+ retryable: false,
63
+ });
64
+ }
65
+ });
66
+ it("retains the complete ready sale without changing the legacy object", () => {
67
+ const sale: VerifiedSale = {
68
+ status: "ready",
69
+ paymentIntentId: "pi_one",
70
+ chargeId: "ch_one",
71
+ gross: 100,
72
+ processingFee: 3,
73
+ currency: "usd",
74
+ metadata: {},
75
+ };
76
+ expect(verifiedSaleOutcome(sale)).toEqual({ status: "ready", value: sale });
77
+ });
78
+ it.each([
79
+ ["charge_unavailable", "provider_pending"],
80
+ ["refund_pending", "provider_pending"],
81
+ ["charge_transaction_unavailable", "fee_pending"],
82
+ ["refund_transaction_unavailable", "fee_pending"],
83
+ ["refund_failure_transaction_unavailable", "fee_pending"],
84
+ ["dispute_transactions_unavailable", "fee_pending"],
85
+ ["dispute_reinstatement_unavailable", "fee_pending"],
86
+ ] as const)("converts processing cost %s", (reason, mapped) => {
87
+ expect(
88
+ processingCostOutcome({
89
+ status: "not_ready",
90
+ paymentIntentId: "pi_one",
91
+ reason,
92
+ }),
93
+ ).toEqual({ status: "not_ready", reason: mapped, retryable: true });
94
+ });
95
+ it.each([
96
+ ["payment_not_succeeded", "payment_not_payable"],
97
+ ["currency_mismatch", "currency_mismatch"],
98
+ ] as const)(
99
+ "rejects cost %s without scheduling more financial actions",
100
+ (reason, mapped) => {
101
+ expect(
102
+ processingCostOutcome({
103
+ status: "not_ready",
104
+ paymentIntentId: "pi_one",
105
+ reason,
106
+ }),
107
+ ).toEqual({ status: "rejected", reason: mapped, retryable: false });
108
+ },
109
+ );
110
+ it("preserves ready processing cost evidence", () => {
111
+ const cost: ProcessingCostContext = {
112
+ status: "ready",
113
+ paymentIntentId: "pi_one",
114
+ chargeId: "ch_one",
115
+ currency: "usd",
116
+ gross: 100,
117
+ metadata: {},
118
+ processingFee: 3,
119
+ refundFeeAdjustment: 0,
120
+ disputeFeeAdjustment: 0,
121
+ netFees: 3,
122
+ refundedPrincipal: 0,
123
+ disputedPrincipal: 0,
124
+ principalReturned: 0,
125
+ refunds: [],
126
+ disputes: [],
127
+ transactions: [],
128
+ };
129
+ expect(processingCostOutcome(cost)).toEqual({
130
+ status: "ready",
131
+ value: cost,
132
+ });
133
+ });
134
+ });
135
+
136
+ describe("bounded financial retries", () => {
137
+ it("caps exponential delay and permits exactly the selected retry count", () => {
138
+ expect(
139
+ Array.from({ length: 10 }, (_, attempt) =>
140
+ financialRetryDecision(pending, attempt, policy),
141
+ ),
142
+ ).toEqual(
143
+ [1000, 2000, 4000, 8000, 16000, 32000, 60000, 60000, 60000, 60000].map(
144
+ (delayMs, attempt) => ({
145
+ status: "retry",
146
+ delayMs,
147
+ nextAttempt: attempt + 1,
148
+ }),
149
+ ),
150
+ );
151
+ expect(financialRetryDecision(pending, 10, policy)).toEqual({
152
+ status: "stop",
153
+ reason: "exhausted",
154
+ });
155
+ expect(financialRetryDecision(pending, 11, policy)).toEqual({
156
+ status: "stop",
157
+ reason: "exhausted",
158
+ });
159
+ });
160
+ it("allows zero retries", () => {
161
+ expect(
162
+ financialRetryDecision(pending, 0, { ...policy, maxRetries: 0 }),
163
+ ).toEqual({ status: "stop", reason: "exhausted" });
164
+ });
165
+ it.each([
166
+ { status: "conflict", reason: "scope_busy", retryable: false },
167
+ { status: "conflict", reason: "revision_changed", retryable: false },
168
+ { status: "conflict", reason: "identity_changed", retryable: false },
169
+ { status: "rejected", reason: "invalid_scope", retryable: false },
170
+ { status: "rejected", reason: "policy_invalid", retryable: false },
171
+ { status: "unknown", reason: "provider_outcome_unknown", retryable: false },
172
+ { status: "unknown", reason: "history_incomplete", retryable: false },
173
+ { status: "ready", value: {} },
174
+ ] as const)("never retries $status/$reason", (outcome) => {
175
+ expect(financialRetryDecision(outcome, 0, policy)).toEqual({
176
+ status: "stop",
177
+ reason: "not_retryable",
178
+ });
179
+ });
180
+ it.each([-1, 0.5, NaN, Infinity, Number.MAX_SAFE_INTEGER + 1])(
181
+ "rejects invalid attempts %s",
182
+ (attempt) => {
183
+ expect(() => financialRetryDecision(pending, attempt, policy)).toThrow();
184
+ },
185
+ );
186
+ it.each([
187
+ { maxRetries: -1 },
188
+ { maxRetries: 21 },
189
+ { maxRetries: 0.5 },
190
+ { initialDelayMs: 0 },
191
+ { initialDelayMs: NaN },
192
+ { maxDelayMs: Infinity },
193
+ { maxDelayMs: 86400001 },
194
+ { initialDelayMs: 60001 },
195
+ ])("rejects invalid policy %j", (invalid) => {
196
+ expect(() =>
197
+ financialRetryDecision(pending, 0, { ...policy, ...invalid }),
198
+ ).toThrow();
199
+ });
200
+ });
201
+
202
+ describe("serializable financial errors", () => {
203
+ it("round trips only a validated nonsecret outcome through Convex data", () => {
204
+ let caught: unknown;
205
+ try {
206
+ throwFinancialOutcome(pending);
207
+ } catch (error) {
208
+ caught = error;
209
+ }
210
+ expect(caught).toBeInstanceOf(ConvexError);
211
+ expect(readFinancialOutcomeError(caught)).toEqual(pending);
212
+ const serialized = JSON.parse(
213
+ JSON.stringify((caught as { data: unknown }).data),
214
+ );
215
+ expect(readFinancialOutcomeError({ data: serialized })).toEqual(pending);
216
+ expect(serialized).toEqual({ code: "FINANCIAL_OUTCOME", outcome: pending });
217
+ });
218
+ it.each([
219
+ new Error(
220
+ "Stripe processing fees are not available yet; retry settlement.",
221
+ ),
222
+ {
223
+ data: {
224
+ code: "STRIPE_API_ERROR",
225
+ message: "processing fees are not available",
226
+ },
227
+ },
228
+ {
229
+ data: {
230
+ code: "FINANCIAL_OUTCOME",
231
+ outcome: { ...pending, retryable: false },
232
+ },
233
+ },
234
+ {
235
+ data: {
236
+ code: "FINANCIAL_OUTCOME",
237
+ outcome: { ...pending, reason: "arbitrary" },
238
+ },
239
+ },
240
+ {
241
+ data: {
242
+ code: "FINANCIAL_OUTCOME",
243
+ outcome: { ...pending, secret: "redacted" },
244
+ },
245
+ },
246
+ null,
247
+ "not_ready",
248
+ ])(
249
+ "does not infer retryability from unrelated or malformed errors",
250
+ (error) => {
251
+ expect(readFinancialOutcomeError(error)).toBeNull();
252
+ },
253
+ );
254
+ });
@@ -0,0 +1,52 @@
1
+ import {
2
+ financialUnavailableSchema,
3
+ type FinancialOutcome,
4
+ } from "./contracts.js";
5
+
6
+ export type FinancialRetryPolicy = {
7
+ /** Additional attempts after the initial call, from 0 to 20. */
8
+ maxRetries: number;
9
+ /** Positive integer milliseconds, no greater than maxDelayMs. */
10
+ initialDelayMs: number;
11
+ /** Positive integer milliseconds, at most one day. */
12
+ maxDelayMs: number;
13
+ };
14
+ export type FinancialRetryDecision =
15
+ | { status: "retry"; delayMs: number; nextAttempt: number }
16
+ | { status: "stop"; reason: "not_retryable" | "exhausted" };
17
+
18
+ /**
19
+ * Schedules nothing and retries no provider write. The caller schedules a new
20
+ * readiness observation only. attempt is the number of retries already made.
21
+ * Conflicts require fresh state/policy; unknown writes require reconciliation.
22
+ */
23
+ export function financialRetryDecision(
24
+ outcome: FinancialOutcome<unknown>,
25
+ attempt: number,
26
+ policy: FinancialRetryPolicy,
27
+ ): FinancialRetryDecision {
28
+ if (
29
+ !Number.isSafeInteger(attempt) ||
30
+ attempt < 0 ||
31
+ !Number.isSafeInteger(policy.maxRetries) ||
32
+ policy.maxRetries < 0 ||
33
+ policy.maxRetries > 20 ||
34
+ !Number.isSafeInteger(policy.initialDelayMs) ||
35
+ policy.initialDelayMs < 1 ||
36
+ !Number.isSafeInteger(policy.maxDelayMs) ||
37
+ policy.maxDelayMs < 1 ||
38
+ policy.maxDelayMs > 86400000 ||
39
+ policy.initialDelayMs > policy.maxDelayMs
40
+ )
41
+ throw new RangeError("Invalid financial retry attempt or policy.");
42
+ const parsed = financialUnavailableSchema.safeParse(outcome);
43
+ if (!parsed.success || parsed.data.status !== "not_ready")
44
+ return { status: "stop", reason: "not_retryable" };
45
+ if (attempt >= policy.maxRetries)
46
+ return { status: "stop", reason: "exhausted" };
47
+ return {
48
+ status: "retry",
49
+ delayMs: Math.min(policy.maxDelayMs, policy.initialDelayMs * 2 ** attempt),
50
+ nextAttempt: attempt + 1,
51
+ };
52
+ }
@@ -67,9 +67,6 @@ const mockStripeInstance = {
67
67
  accountLinks: {
68
68
  create: vi.fn(),
69
69
  },
70
- accountSessions: {
71
- create: vi.fn(),
72
- },
73
70
  accounts: {
74
71
  createLoginLink: vi.fn(),
75
72
  },
@@ -1444,67 +1441,6 @@ describe("BetterStripe", () => {
1444
1441
  });
1445
1442
  });
1446
1443
 
1447
- // =========================================================================
1448
- // Account link methods: createAccountSession
1449
- // =========================================================================
1450
-
1451
- describe("createAccountSession", () => {
1452
- it("calls Stripe accountSessions.create and returns the clientSecret", async () => {
1453
- const bs = new BetterStripe(components.betterStripe, {
1454
- STRIPE_SECRET_KEY: "sk_test_xxx",
1455
- });
1456
-
1457
- mockStripeInstance.accountSessions.create.mockResolvedValue({
1458
- client_secret: "as_secret_123",
1459
- });
1460
-
1461
- const result = await bs.createAccountSession(mockCtx, {
1462
- stripeAccountId: "acct_123",
1463
- components: {
1464
- account_management: { enabled: true },
1465
- },
1466
- });
1467
-
1468
- expect(mockStripeInstance.accountSessions.create).toHaveBeenCalledWith({
1469
- account: "acct_123",
1470
- components: {
1471
- account_management: { enabled: true },
1472
- },
1473
- });
1474
- expect(result).toEqual({ clientSecret: "as_secret_123" });
1475
- });
1476
-
1477
- it("wraps Stripe failures in a structured STRIPE_API_ERROR", async () => {
1478
- const bs = new BetterStripe(components.betterStripe, {
1479
- STRIPE_SECRET_KEY: "sk_test_xxx",
1480
- });
1481
-
1482
- mockStripeInstance.accountSessions.create.mockRejectedValue(
1483
- Object.assign(new Error("No such account: acct_missing"), {
1484
- type: "StripeInvalidRequestError",
1485
- code: "resource_missing",
1486
- }),
1487
- );
1488
-
1489
- const error = await bs
1490
- .createAccountSession(mockCtx, {
1491
- stripeAccountId: "acct_missing",
1492
- components: { account_onboarding: { enabled: true } },
1493
- })
1494
- .catch((e: unknown) => e);
1495
-
1496
- expect(error).toBeInstanceOf(ConvexError);
1497
- expect((error as { data: Record<string, unknown> }).data).toMatchObject({
1498
- code: "STRIPE_API_ERROR",
1499
- stripeError: {
1500
- type: "StripeInvalidRequestError",
1501
- code: "resource_missing",
1502
- message: "No such account: acct_missing",
1503
- },
1504
- });
1505
- });
1506
- });
1507
-
1508
1444
  // =========================================================================
1509
1445
  // syncAllProducts
1510
1446
  // =========================================================================