@fantastic.dev/better-stripe 0.37.1 → 0.39.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 (210) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/MIGRATION.md +9 -0
  3. package/README.md +25 -1
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +506 -2
  5. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +253 -1
  7. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +506 -2
  9. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts +253 -1
  11. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  12. package/dist/client/core/accountCapabilities.d.ts +20 -0
  13. package/dist/client/core/accountCapabilities.d.ts.map +1 -0
  14. package/dist/client/core/accountCapabilities.js +7 -0
  15. package/dist/client/core/accountCapabilities.js.map +1 -0
  16. package/dist/client/core/accountConfigurations.d.ts +46 -0
  17. package/dist/client/core/accountConfigurations.d.ts.map +1 -0
  18. package/dist/client/core/accountConfigurations.js +99 -0
  19. package/dist/client/core/accountConfigurations.js.map +1 -0
  20. package/dist/client/core/accountLinks.d.ts +29 -2
  21. package/dist/client/core/accountLinks.d.ts.map +1 -1
  22. package/dist/client/core/accountLinks.js +56 -4
  23. package/dist/client/core/accountLinks.js.map +1 -1
  24. package/dist/client/core/accounts.d.ts +2 -36
  25. package/dist/client/core/accounts.d.ts.map +1 -1
  26. package/dist/client/core/accounts.js +3 -73
  27. package/dist/client/core/accounts.js.map +1 -1
  28. package/dist/client/core/billingPortalClient.d.ts +14 -0
  29. package/dist/client/core/billingPortalClient.d.ts.map +1 -0
  30. package/dist/client/core/billingPortalClient.js +18 -0
  31. package/dist/client/core/billingPortalClient.js.map +1 -0
  32. package/dist/client/costRecovery-invoices.d.ts +4 -4
  33. package/dist/client/costRecovery.d.ts +19 -1
  34. package/dist/client/costRecovery.d.ts.map +1 -1
  35. package/dist/client/costRecovery.js +4 -0
  36. package/dist/client/costRecovery.js.map +1 -1
  37. package/dist/client/financialOutcomes/adapters.d.ts +18 -0
  38. package/dist/client/financialOutcomes/adapters.d.ts.map +1 -0
  39. package/dist/client/financialOutcomes/adapters.js +60 -0
  40. package/dist/client/financialOutcomes/adapters.js.map +1 -0
  41. package/dist/client/financialOutcomes/contracts.d.ts +42 -0
  42. package/dist/client/financialOutcomes/contracts.d.ts.map +1 -0
  43. package/dist/client/financialOutcomes/contracts.js +39 -0
  44. package/dist/client/financialOutcomes/contracts.js.map +1 -0
  45. package/dist/client/financialOutcomes/errors.d.ts +6 -0
  46. package/dist/client/financialOutcomes/errors.d.ts.map +1 -0
  47. package/dist/client/financialOutcomes/errors.js +22 -0
  48. package/dist/client/financialOutcomes/errors.js.map +1 -0
  49. package/dist/client/financialOutcomes/index.d.ts +6 -0
  50. package/dist/client/financialOutcomes/index.d.ts.map +1 -0
  51. package/dist/client/financialOutcomes/index.js +4 -0
  52. package/dist/client/financialOutcomes/index.js.map +1 -0
  53. package/dist/client/financialOutcomes/retry.d.ts +24 -0
  54. package/dist/client/financialOutcomes/retry.d.ts.map +1 -0
  55. package/dist/client/financialOutcomes/retry.js +31 -0
  56. package/dist/client/financialOutcomes/retry.js.map +1 -0
  57. package/dist/client/index.d.ts +21 -111
  58. package/dist/client/index.d.ts.map +1 -1
  59. package/dist/client/index.js +11 -85
  60. package/dist/client/index.js.map +1 -1
  61. package/dist/client/processingCostDeficit/index.d.ts +27 -0
  62. package/dist/client/processingCostDeficit/index.d.ts.map +1 -0
  63. package/dist/client/processingCostDeficit/index.js +54 -0
  64. package/dist/client/processingCostDeficit/index.js.map +1 -0
  65. package/dist/client/products/catalog.d.ts +26 -0
  66. package/dist/client/products/catalog.d.ts.map +1 -0
  67. package/dist/client/products/catalog.js +140 -0
  68. package/dist/client/products/catalog.js.map +1 -0
  69. package/dist/client/products/catalogClient.d.ts +109 -0
  70. package/dist/client/products/catalogClient.d.ts.map +1 -0
  71. package/dist/client/products/catalogClient.js +84 -0
  72. package/dist/client/products/catalogClient.js.map +1 -0
  73. package/dist/client/products/prices.d.ts +1 -0
  74. package/dist/client/products/prices.d.ts.map +1 -1
  75. package/dist/client/products/prices.js +1 -0
  76. package/dist/client/products/prices.js.map +1 -1
  77. package/dist/client/publicTypes.d.ts +2 -0
  78. package/dist/client/publicTypes.d.ts.map +1 -1
  79. package/dist/component/_generated/api.d.ts +284 -0
  80. package/dist/component/_generated/api.d.ts.map +1 -0
  81. package/dist/component/_generated/api.js +31 -0
  82. package/dist/component/_generated/api.js.map +1 -0
  83. package/dist/component/_generated/component.d.ts +535 -0
  84. package/dist/component/_generated/component.d.ts.map +1 -1
  85. package/dist/component/balanceFunding/helpers.d.ts +86 -0
  86. package/dist/component/balanceFunding/helpers.d.ts.map +1 -0
  87. package/dist/component/balanceFunding/helpers.js +68 -0
  88. package/dist/component/balanceFunding/helpers.js.map +1 -0
  89. package/dist/component/balanceFunding/importHandler.d.ts +13 -0
  90. package/dist/component/balanceFunding/importHandler.d.ts.map +1 -0
  91. package/dist/component/balanceFunding/importHandler.js +130 -0
  92. package/dist/component/balanceFunding/importHandler.js.map +1 -0
  93. package/dist/component/balanceFunding/lifecycleHandlers.d.ts +85 -0
  94. package/dist/component/balanceFunding/lifecycleHandlers.d.ts.map +1 -0
  95. package/dist/component/balanceFunding/lifecycleHandlers.js +60 -0
  96. package/dist/component/balanceFunding/lifecycleHandlers.js.map +1 -0
  97. package/dist/component/balanceFunding/mutationValidators.d.ts +238 -0
  98. package/dist/component/balanceFunding/mutationValidators.d.ts.map +1 -0
  99. package/dist/component/balanceFunding/mutationValidators.js +55 -0
  100. package/dist/component/balanceFunding/mutationValidators.js.map +1 -0
  101. package/dist/component/balanceFunding/mutations.d.ts +335 -0
  102. package/dist/component/balanceFunding/mutations.d.ts.map +1 -0
  103. package/dist/component/balanceFunding/mutations.js +106 -0
  104. package/dist/component/balanceFunding/mutations.js.map +1 -0
  105. package/dist/component/balanceFunding/preparationHandlers.d.ts +55 -0
  106. package/dist/component/balanceFunding/preparationHandlers.d.ts.map +1 -0
  107. package/dist/component/balanceFunding/preparationHandlers.js +165 -0
  108. package/dist/component/balanceFunding/preparationHandlers.js.map +1 -0
  109. package/dist/component/balanceFunding/queries.d.ts +151 -0
  110. package/dist/component/balanceFunding/queries.d.ts.map +1 -0
  111. package/dist/component/balanceFunding/queries.js +180 -0
  112. package/dist/component/balanceFunding/queries.js.map +1 -0
  113. package/dist/component/balanceFunding/schema.d.ts +748 -0
  114. package/dist/component/balanceFunding/schema.d.ts.map +1 -0
  115. package/dist/component/balanceFunding/schema.js +124 -0
  116. package/dist/component/balanceFunding/schema.js.map +1 -0
  117. package/dist/component/balanceFunding/stateHandlers.d.ts +58 -0
  118. package/dist/component/balanceFunding/stateHandlers.d.ts.map +1 -0
  119. package/dist/component/balanceFunding/stateHandlers.js +160 -0
  120. package/dist/component/balanceFunding/stateHandlers.js.map +1 -0
  121. package/dist/component/convex.config.d.ts.map +1 -1
  122. package/dist/component/convex.config.js +2 -0
  123. package/dist/component/convex.config.js.map +1 -1
  124. package/dist/component/costRecovery/completion.d.ts +1 -0
  125. package/dist/component/costRecovery/completion.d.ts.map +1 -1
  126. package/dist/component/costRecovery/helpers.d.ts +1 -0
  127. package/dist/component/costRecovery/helpers.d.ts.map +1 -1
  128. package/dist/component/costRecovery/mutations.d.ts +5 -0
  129. package/dist/component/costRecovery/mutations.d.ts.map +1 -1
  130. package/dist/component/costRecovery/preparation.d.ts +50 -0
  131. package/dist/component/costRecovery/preparation.d.ts.map +1 -0
  132. package/dist/component/costRecovery/preparation.js +108 -0
  133. package/dist/component/costRecovery/preparation.js.map +1 -0
  134. package/dist/component/costRecovery/queries.d.ts +1 -0
  135. package/dist/component/costRecovery/queries.d.ts.map +1 -1
  136. package/dist/component/costRecovery/reservations.d.ts +2 -0
  137. package/dist/component/costRecovery/reservations.d.ts.map +1 -1
  138. package/dist/component/costRecovery/schema.d.ts +7 -2
  139. package/dist/component/costRecovery/schema.d.ts.map +1 -1
  140. package/dist/component/costRecovery/schema.js +1 -0
  141. package/dist/component/costRecovery/schema.js.map +1 -1
  142. package/dist/component/durableExecution/runtime.d.ts +3 -0
  143. package/dist/component/durableExecution/runtime.d.ts.map +1 -0
  144. package/dist/component/durableExecution/runtime.js +12 -0
  145. package/dist/component/durableExecution/runtime.js.map +1 -0
  146. package/dist/component/earnings/triggers.d.ts +242 -2
  147. package/dist/component/earnings/triggers.d.ts.map +1 -1
  148. package/dist/component/products/mutations.d.ts +9 -0
  149. package/dist/component/products/mutations.d.ts.map +1 -1
  150. package/dist/component/products/mutations.js +31 -2
  151. package/dist/component/products/mutations.js.map +1 -1
  152. package/dist/component/schema.d.ts +253 -1
  153. package/dist/component/schema.js +4 -0
  154. package/dist/component/schema.js.map +1 -1
  155. package/docs/read-contracts.md +33 -0
  156. package/package.json +4 -2
  157. package/src/client/core/account-session-client.test.ts +74 -0
  158. package/src/client/core/accountCapabilities.ts +22 -0
  159. package/src/client/core/accountConfigurations.test.ts +183 -0
  160. package/src/client/core/accountConfigurations.ts +161 -0
  161. package/src/client/core/accountLinks.test.ts +6 -2
  162. package/src/client/core/accountLinks.ts +122 -5
  163. package/src/client/core/accounts.ts +8 -115
  164. package/src/client/core/billingPortal.test.ts +247 -0
  165. package/src/client/core/billingPortalClient.ts +35 -0
  166. package/src/client/costRecovery.test.ts +34 -0
  167. package/src/client/costRecovery.ts +21 -0
  168. package/src/client/financialOutcomes/adapters.ts +88 -0
  169. package/src/client/financialOutcomes/contracts.ts +43 -0
  170. package/src/client/financialOutcomes/errors.ts +29 -0
  171. package/src/client/financialOutcomes/index.ts +5 -0
  172. package/src/client/financialOutcomes/outcomes.test.ts +254 -0
  173. package/src/client/financialOutcomes/retry.ts +52 -0
  174. package/src/client/index.test.ts +0 -64
  175. package/src/client/index.ts +35 -185
  176. package/src/client/processingCostDeficit/README.md +35 -0
  177. package/src/client/processingCostDeficit/calculator.test.ts +176 -0
  178. package/src/client/processingCostDeficit/index.ts +91 -0
  179. package/src/client/products/catalog.test.ts +389 -0
  180. package/src/client/products/catalog.ts +225 -0
  181. package/src/client/products/catalogClient.ts +172 -0
  182. package/src/client/products/prices.test.ts +24 -0
  183. package/src/client/products/prices.ts +2 -0
  184. package/src/client/publicTypes.ts +13 -0
  185. package/src/component/_generated/api.ts +27 -1
  186. package/src/component/_generated/component.ts +707 -0
  187. package/src/component/balanceFunding/failure.test.ts +116 -0
  188. package/src/component/balanceFunding/helpers.ts +102 -0
  189. package/src/component/balanceFunding/import.test.ts +221 -0
  190. package/src/component/balanceFunding/importHandler.ts +146 -0
  191. package/src/component/balanceFunding/lifecycleHandlers.ts +90 -0
  192. package/src/component/balanceFunding/lookup.test.ts +113 -0
  193. package/src/component/balanceFunding/mutationValidators.ts +63 -0
  194. package/src/component/balanceFunding/mutations.ts +136 -0
  195. package/src/component/balanceFunding/preparation.test.ts +146 -0
  196. package/src/component/balanceFunding/preparationHandlers.ts +204 -0
  197. package/src/component/balanceFunding/queries.ts +221 -0
  198. package/src/component/balanceFunding/requestLookup.test.ts +160 -0
  199. package/src/component/balanceFunding/schema.ts +169 -0
  200. package/src/component/balanceFunding/state.test.ts +352 -0
  201. package/src/component/balanceFunding/stateHandlers.ts +198 -0
  202. package/src/component/balanceFunding/validation.test.ts +100 -0
  203. package/src/component/convex.config.ts +2 -0
  204. package/src/component/costRecovery/preparation.test.ts +355 -0
  205. package/src/component/costRecovery/preparation.ts +124 -0
  206. package/src/component/costRecovery/schema.ts +1 -0
  207. package/src/component/durableExecution/composition.test.ts +568 -0
  208. package/src/component/durableExecution/runtime.ts +12 -0
  209. package/src/component/products/mutations.ts +39 -2
  210. package/src/component/schema.ts +8 -0
@@ -0,0 +1,247 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import type Stripe from "stripe";
3
+ import { BetterStripe, type BetterStripeComponent } from "../index.js";
4
+ import type { RunCtx } from "../helpers.js";
5
+ import {
6
+ createBillingPortalConfiguration,
7
+ retrieveBillingPortalConfiguration,
8
+ updateBillingPortalConfiguration,
9
+ createBillingPortalSession,
10
+ } from "./accountLinks.js";
11
+ const ctx = {} as RunCtx;
12
+ function makeStripe() {
13
+ return {
14
+ billingPortal: {
15
+ configurations: { create: vi.fn(), retrieve: vi.fn(), update: vi.fn() },
16
+ sessions: { create: vi.fn() },
17
+ },
18
+ };
19
+ }
20
+ const asStripe = (stripe: ReturnType<typeof makeStripe>) =>
21
+ stripe as unknown as Stripe;
22
+
23
+ describe("Billing Portal configurations", () => {
24
+ const params = {
25
+ features: {
26
+ subscription_update: {
27
+ enabled: true,
28
+ default_allowed_updates: ["price" as const],
29
+ products: [
30
+ { product: "prod_host", prices: ["price_current", "price_legacy"] },
31
+ ],
32
+ proration_behavior: "always_invoice" as const,
33
+ },
34
+ subscription_cancel: { enabled: true, mode: "at_period_end" as const },
35
+ },
36
+ };
37
+
38
+ it.each([undefined, "acct_connected"])(
39
+ "creates a host-configured policy in scope %s",
40
+ async (connectedAccountId) => {
41
+ const stripe = makeStripe();
42
+ const configuration = { id: "bpc_host", ...params };
43
+ stripe.billingPortal.configurations.create.mockResolvedValue(
44
+ configuration,
45
+ );
46
+ const result = await createBillingPortalConfiguration(
47
+ asStripe(stripe),
48
+ ctx,
49
+ { params, connectedAccountId },
50
+ );
51
+ expect(result).toEqual(configuration);
52
+ expect(stripe.billingPortal.configurations.create.mock.calls[0]).toEqual(
53
+ connectedAccountId
54
+ ? [params, { stripeAccount: connectedAccountId }]
55
+ : [params],
56
+ );
57
+ },
58
+ );
59
+
60
+ it.each([undefined, "acct_connected"])(
61
+ "retrieves a configuration in scope %s",
62
+ async (connectedAccountId) => {
63
+ const stripe = makeStripe();
64
+ stripe.billingPortal.configurations.retrieve.mockResolvedValue({
65
+ id: "bpc_host",
66
+ ...params,
67
+ });
68
+ const result = await retrieveBillingPortalConfiguration(
69
+ asStripe(stripe),
70
+ ctx,
71
+ { configurationId: "bpc_host", connectedAccountId },
72
+ );
73
+ expect(result.id).toBe("bpc_host");
74
+ expect(
75
+ stripe.billingPortal.configurations.retrieve.mock.calls[0],
76
+ ).toEqual(
77
+ connectedAccountId
78
+ ? ["bpc_host", {}, { stripeAccount: connectedAccountId }]
79
+ : ["bpc_host"],
80
+ );
81
+ },
82
+ );
83
+
84
+ it.each([undefined, "acct_connected"])(
85
+ "updates a configuration in scope %s",
86
+ async (connectedAccountId) => {
87
+ const stripe = makeStripe();
88
+ const update = { active: false, ...params };
89
+ stripe.billingPortal.configurations.update.mockResolvedValue({
90
+ id: "bpc_host",
91
+ ...update,
92
+ });
93
+ const result = await updateBillingPortalConfiguration(
94
+ asStripe(stripe),
95
+ ctx,
96
+ { configurationId: "bpc_host", params: update, connectedAccountId },
97
+ );
98
+ expect(result.active).toBe(false);
99
+ expect(stripe.billingPortal.configurations.update.mock.calls[0]).toEqual(
100
+ connectedAccountId
101
+ ? ["bpc_host", update, { stripeAccount: connectedAccountId }]
102
+ : ["bpc_host", update],
103
+ );
104
+ },
105
+ );
106
+
107
+ it.each(["create", "retrieve", "update"] as const)(
108
+ "reports %s provider errors without an unscoped fallback",
109
+ async (operation) => {
110
+ const stripe = makeStripe();
111
+ stripe.billingPortal.configurations[operation].mockRejectedValue({
112
+ type: "StripeInvalidRequestError",
113
+ code: "resource_missing",
114
+ message: "Configuration unavailable in this account",
115
+ });
116
+ const opts = {
117
+ configurationId: "bpc_missing",
118
+ params,
119
+ connectedAccountId: "acct_connected",
120
+ };
121
+ const methods = {
122
+ create: createBillingPortalConfiguration,
123
+ retrieve: retrieveBillingPortalConfiguration,
124
+ update: updateBillingPortalConfiguration,
125
+ };
126
+ await expect(
127
+ methods[operation](asStripe(stripe), ctx, opts),
128
+ ).rejects.toMatchObject({
129
+ data: {
130
+ code: "STRIPE_API_ERROR",
131
+ stripeError: { code: "resource_missing" },
132
+ },
133
+ });
134
+ expect(
135
+ stripe.billingPortal.configurations[operation],
136
+ ).toHaveBeenCalledTimes(1);
137
+ },
138
+ );
139
+ });
140
+
141
+ describe("configured Billing Portal sessions", () => {
142
+ it.each([undefined, "acct_connected"])(
143
+ "selects the configuration and customer account in scope %s",
144
+ async (connectedAccountId) => {
145
+ const stripe = makeStripe();
146
+ stripe.billingPortal.sessions.create.mockResolvedValue({
147
+ url: "https://portal",
148
+ });
149
+ const result = await createBillingPortalSession(asStripe(stripe), ctx, {
150
+ stripeAccountId: "acct_customer",
151
+ returnUrl: "https://return",
152
+ configurationId: "bpc_host",
153
+ connectedAccountId,
154
+ });
155
+ expect(result).toEqual({ url: "https://portal" });
156
+ const params = {
157
+ customer_account: "acct_customer",
158
+ return_url: "https://return",
159
+ configuration: "bpc_host",
160
+ };
161
+ expect(stripe.billingPortal.sessions.create.mock.calls[0]).toEqual(
162
+ connectedAccountId
163
+ ? [params, { stripeAccount: connectedAccountId }]
164
+ : [params],
165
+ );
166
+ },
167
+ );
168
+
169
+ it("reports a provider error without retrying against platform scope", async () => {
170
+ const stripe = makeStripe();
171
+ stripe.billingPortal.sessions.create.mockRejectedValue({
172
+ type: "StripeInvalidRequestError",
173
+ code: "resource_missing",
174
+ message: "No such configuration",
175
+ });
176
+ await expect(
177
+ createBillingPortalSession(asStripe(stripe), ctx, {
178
+ stripeAccountId: "acct_customer",
179
+ returnUrl: "https://return",
180
+ configurationId: "bpc_missing",
181
+ connectedAccountId: "acct_connected",
182
+ }),
183
+ ).rejects.toMatchObject({
184
+ data: {
185
+ code: "STRIPE_API_ERROR",
186
+ stripeError: { code: "resource_missing" },
187
+ },
188
+ });
189
+ expect(stripe.billingPortal.sessions.create).toHaveBeenCalledTimes(1);
190
+ });
191
+ });
192
+
193
+ describe("BetterStripe portal API", () => {
194
+ it("exposes configuration lifecycle and configured sessions through the client", async () => {
195
+ const stripe = makeStripe();
196
+ class TestClient extends BetterStripe {
197
+ protected stripe() {
198
+ return asStripe(stripe);
199
+ }
200
+ }
201
+ const client = new TestClient({} as BetterStripeComponent);
202
+ const params = { features: { invoice_history: { enabled: true } } };
203
+ const opts = {
204
+ configurationId: "bpc_client",
205
+ params,
206
+ connectedAccountId: "acct_owner",
207
+ };
208
+ stripe.billingPortal.configurations.create.mockResolvedValue({
209
+ id: "bpc_client",
210
+ });
211
+ stripe.billingPortal.configurations.retrieve.mockResolvedValue({
212
+ id: "bpc_client",
213
+ });
214
+ stripe.billingPortal.configurations.update.mockResolvedValue({
215
+ id: "bpc_client",
216
+ active: false,
217
+ });
218
+ stripe.billingPortal.sessions.create.mockResolvedValue({
219
+ url: "https://portal",
220
+ });
221
+ expect(await client.createBillingPortalConfiguration(ctx, opts)).toEqual({
222
+ id: "bpc_client",
223
+ });
224
+ expect(await client.retrieveBillingPortalConfiguration(ctx, opts)).toEqual({
225
+ id: "bpc_client",
226
+ });
227
+ expect(await client.updateBillingPortalConfiguration(ctx, opts)).toEqual({
228
+ id: "bpc_client",
229
+ active: false,
230
+ });
231
+ expect(
232
+ await client.createBillingPortalSession(ctx, {
233
+ ...opts,
234
+ stripeAccountId: "acct_customer",
235
+ returnUrl: "https://return",
236
+ }),
237
+ ).toEqual({ url: "https://portal" });
238
+ expect(stripe.billingPortal.sessions.create).toHaveBeenCalledWith(
239
+ {
240
+ configuration: "bpc_client",
241
+ customer_account: "acct_customer",
242
+ return_url: "https://return",
243
+ },
244
+ { stripeAccount: "acct_owner" },
245
+ );
246
+ });
247
+ });
@@ -0,0 +1,35 @@
1
+ import type Stripe from "stripe";
2
+ import { FinancialOwnershipHost } from "../financialOwnership.js";
3
+ import type { RunCtx } from "../helpers.js";
4
+ import * as portal from "./accountLinks.js";
5
+
6
+ /** Portal APIs inherited by BetterStripe. Hosts authorize account scope and supply policy. */
7
+ export abstract class BillingPortalClient extends FinancialOwnershipHost {
8
+ async createBillingPortalConfiguration(
9
+ ctx: RunCtx,
10
+ opts: portal.CreateBillingPortalConfigurationOptions,
11
+ ): Promise<Stripe.BillingPortal.Configuration> {
12
+ return portal.createBillingPortalConfiguration(this.stripe(), ctx, opts);
13
+ }
14
+
15
+ async retrieveBillingPortalConfiguration(
16
+ ctx: RunCtx,
17
+ opts: portal.RetrieveBillingPortalConfigurationOptions,
18
+ ): Promise<Stripe.BillingPortal.Configuration> {
19
+ return portal.retrieveBillingPortalConfiguration(this.stripe(), ctx, opts);
20
+ }
21
+
22
+ async updateBillingPortalConfiguration(
23
+ ctx: RunCtx,
24
+ opts: portal.UpdateBillingPortalConfigurationOptions,
25
+ ): Promise<Stripe.BillingPortal.Configuration> {
26
+ return portal.updateBillingPortalConfiguration(this.stripe(), ctx, opts);
27
+ }
28
+
29
+ async createBillingPortalSession(
30
+ ctx: RunCtx,
31
+ opts: portal.CreateBillingPortalSessionOptions,
32
+ ) {
33
+ return portal.createBillingPortalSession(this.stripe(), ctx, opts);
34
+ }
35
+ }
@@ -74,3 +74,37 @@ it("uses the real component through the public recovery client without any provi
74
74
  reservedAmount: 0,
75
75
  });
76
76
  });
77
+ it("prepares recovery through one component mutation without a provider key", async () => {
78
+ const t = initConvexTest();
79
+ t.registerComponent("betterStripe", schema, modules);
80
+ const stripe = new BetterStripe(
81
+ componentsGeneric().betterStripe as unknown as Component,
82
+ {},
83
+ );
84
+ let writes = 0;
85
+ const ctx = {
86
+ runMutation: (
87
+ ref: FunctionReference<"mutation">,
88
+ args: Record<string, unknown>,
89
+ ) => {
90
+ writes++;
91
+ return t.mutation(ref, args);
92
+ },
93
+ } as unknown as RunCtx;
94
+ const opts = {
95
+ accountId: "acct_owner",
96
+ scopeKey: "store",
97
+ currency: "usd",
98
+ groupKey: "empty",
99
+ sourceKind: "invoice" as const,
100
+ sourceId: "in_empty",
101
+ maxDebit: 100,
102
+ maxCredit: 100,
103
+ };
104
+ expect(await stripe.costRecovery.prepareGroup(ctx, opts)).toMatchObject({
105
+ status: "prepared",
106
+ isDone: true,
107
+ group: { status: "sealed", amount: 0 },
108
+ });
109
+ expect(writes).toBe(1);
110
+ });
@@ -63,6 +63,7 @@ export type RecoveryGroup = RecoveryGroupOptions & {
63
63
  _creationTime: number;
64
64
  amount: number;
65
65
  pendingOperations: number;
66
+ preparationSequence?: number;
66
67
  invoiceItemId?: string;
67
68
  invoiceFunding?: {
68
69
  sourceChargeId: string;
@@ -82,6 +83,18 @@ export type RecoveryReservation = {
82
83
  allocations: { claimId: string; claimKey: string; amount: number }[];
83
84
  status: "reserved" | "collected" | "released" | "empty";
84
85
  };
86
+ export type RecoveryPreparationResult =
87
+ | { status: "prepared"; group: RecoveryGroup; isDone: boolean }
88
+ | {
89
+ status: "conflict";
90
+ reason: "scope_busy" | "identity_changed";
91
+ retryable: false;
92
+ }
93
+ | {
94
+ status: "rejected";
95
+ reason: "invalid_scope" | "policy_invalid";
96
+ retryable: false;
97
+ };
85
98
  /** Host authorizes policy and scope. Provider methods verify invoice outcomes. */
86
99
  export class CostRecoveryClient {
87
100
  constructor(
@@ -213,6 +226,14 @@ export class CostRecoveryClient {
213
226
  recordClaim(ctx: RunCtx, opts: RecoveryObservation) {
214
227
  return this.mutate<RecoveryClaim>(ctx, "mutations/record", opts);
215
228
  }
229
+ /** Authorize scope and limits first. Repeat bounded calls until isDone. */
230
+ prepareGroup(ctx: RunCtx, opts: RecoveryGroupOptions & { limit?: number }) {
231
+ return this.mutate<RecoveryPreparationResult>(
232
+ ctx,
233
+ "preparation/prepare",
234
+ opts,
235
+ );
236
+ }
216
237
  reserve(
217
238
  ctx: RunCtx,
218
239
  opts: RecoveryGroupOptions & { operationKey: string; limit?: number },
@@ -0,0 +1,88 @@
1
+ import type { VerifiedSale } from "../settlement/verifiedSale.js";
2
+ import type { ProcessingCostContext } from "../settlement/processingCosts.js";
3
+ import type { FinancialUnavailable, FinancialOutcome } from "./contracts.js";
4
+
5
+ /** Additive adapter; the existing getVerifiedSale result remains unchanged. */
6
+ export function verifiedSaleOutcome(
7
+ sale: Exclude<VerifiedSale, { status: "ready" }>,
8
+ ): FinancialUnavailable;
9
+ export function verifiedSaleOutcome(
10
+ sale: VerifiedSale,
11
+ ): FinancialOutcome<Extract<VerifiedSale, { status: "ready" }>>;
12
+ export function verifiedSaleOutcome(
13
+ sale: VerifiedSale,
14
+ ): FinancialOutcome<Extract<VerifiedSale, { status: "ready" }>> {
15
+ if (sale.status === "ready") return { status: "ready", value: sale };
16
+ if (
17
+ sale.status === "not_payable" &&
18
+ ["payment_not_succeeded", "charge_refunded_or_disputed"].includes(
19
+ sale.reason,
20
+ )
21
+ )
22
+ return {
23
+ status: "rejected",
24
+ reason: "payment_not_payable",
25
+ retryable: false,
26
+ };
27
+ if (sale.status === "pending" && sale.retryable) {
28
+ if (sale.reason === "processing_fee_unavailable")
29
+ return { status: "not_ready", reason: "fee_pending", retryable: true };
30
+ if (
31
+ ["payment_processing", "charge_unavailable", "invoice_not_paid"].includes(
32
+ sale.reason,
33
+ )
34
+ )
35
+ return {
36
+ status: "not_ready",
37
+ reason: "provider_pending",
38
+ retryable: true,
39
+ };
40
+ }
41
+ return { status: "rejected", reason: "unsupported_source", retryable: false };
42
+ }
43
+
44
+ /** Missing fees never become zero; a currency mismatch is terminal. */
45
+ export function processingCostOutcome(
46
+ cost: Extract<ProcessingCostContext, { status: "not_ready" }>,
47
+ ): FinancialUnavailable;
48
+ export function processingCostOutcome(
49
+ cost: ProcessingCostContext,
50
+ ): FinancialOutcome<Extract<ProcessingCostContext, { status: "ready" }>>;
51
+ export function processingCostOutcome(
52
+ cost: ProcessingCostContext,
53
+ ): FinancialOutcome<Extract<ProcessingCostContext, { status: "ready" }>> {
54
+ if (cost.status === "ready") return { status: "ready", value: cost };
55
+ switch (cost.reason) {
56
+ case "payment_not_succeeded":
57
+ return {
58
+ status: "rejected",
59
+ reason: "payment_not_payable",
60
+ retryable: false,
61
+ };
62
+ case "currency_mismatch":
63
+ return {
64
+ status: "rejected",
65
+ reason: "currency_mismatch",
66
+ retryable: false,
67
+ };
68
+ case "charge_unavailable":
69
+ case "refund_pending":
70
+ return {
71
+ status: "not_ready",
72
+ reason: "provider_pending",
73
+ retryable: true,
74
+ };
75
+ case "charge_transaction_unavailable":
76
+ case "refund_transaction_unavailable":
77
+ case "refund_failure_transaction_unavailable":
78
+ case "dispute_transactions_unavailable":
79
+ case "dispute_reinstatement_unavailable":
80
+ return { status: "not_ready", reason: "fee_pending", retryable: true };
81
+ default:
82
+ return {
83
+ status: "rejected",
84
+ reason: "unsupported_source",
85
+ retryable: false,
86
+ };
87
+ }
88
+ }
@@ -0,0 +1,43 @@
1
+ import { z } from "zod";
2
+
3
+ /** Safe to persist. Provider messages, credentials and financial payloads stay out. */
4
+ export const financialUnavailableSchema = z.discriminatedUnion("status", [
5
+ z
6
+ .object({
7
+ status: z.literal("not_ready"),
8
+ reason: z.enum(["provider_pending", "fee_pending", "history_incomplete"]),
9
+ retryable: z.literal(true),
10
+ })
11
+ .strict(),
12
+ z
13
+ .object({
14
+ status: z.literal("conflict"),
15
+ reason: z.enum(["scope_busy", "revision_changed", "identity_changed"]),
16
+ retryable: z.literal(false),
17
+ })
18
+ .strict(),
19
+ z
20
+ .object({
21
+ status: z.literal("rejected"),
22
+ reason: z.enum([
23
+ "invalid_scope",
24
+ "unsupported_source",
25
+ "policy_invalid",
26
+ "payment_not_payable",
27
+ "currency_mismatch",
28
+ ]),
29
+ retryable: z.literal(false),
30
+ })
31
+ .strict(),
32
+ z
33
+ .object({
34
+ status: z.literal("unknown"),
35
+ reason: z.enum(["provider_outcome_unknown", "history_incomplete"]),
36
+ retryable: z.literal(false),
37
+ })
38
+ .strict(),
39
+ ]);
40
+
41
+ export type FinancialUnavailable = z.infer<typeof financialUnavailableSchema>;
42
+ export type FinancialOutcome<T> =
43
+ { status: "ready"; value: T } | FinancialUnavailable;
@@ -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";