@fantastic.dev/better-stripe 0.56.0 → 0.58.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 (248) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +5 -1
  3. package/dist/client/billing/setup-intent-read.d.ts +12 -1
  4. package/dist/client/billing/setup-intent-read.d.ts.map +1 -1
  5. package/dist/client/billing/setup-intent-read.js +13 -8
  6. package/dist/client/billing/setup-intent-read.js.map +1 -1
  7. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +366 -2
  8. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +183 -1
  10. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  11. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +366 -2
  12. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  13. package/dist/client/connect/payoutSyncTestHelpers.d.ts +183 -1
  14. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  15. package/dist/client/index.d.ts +2 -12
  16. package/dist/client/index.d.ts.map +1 -1
  17. package/dist/client/index.js +3 -20
  18. package/dist/client/index.js.map +1 -1
  19. package/dist/client/types/triggers.d.ts +3 -1
  20. package/dist/client/types/triggers.d.ts.map +1 -1
  21. package/dist/client/usage/allowanceClient.d.ts +51 -0
  22. package/dist/client/usage/allowanceClient.d.ts.map +1 -0
  23. package/dist/client/usage/allowanceClient.js +64 -0
  24. package/dist/client/usage/allowanceClient.js.map +1 -0
  25. package/dist/client/usage/allowanceTerms.d.ts +64 -0
  26. package/dist/client/usage/allowanceTerms.d.ts.map +1 -0
  27. package/dist/client/usage/allowanceTerms.js +101 -0
  28. package/dist/client/usage/allowanceTerms.js.map +1 -0
  29. package/dist/client/usage/client.d.ts +2 -2
  30. package/dist/client/usage/client.d.ts.map +1 -1
  31. package/dist/client/usage/client.js +4 -4
  32. package/dist/client/usage/client.js.map +1 -1
  33. package/dist/client/usage/creditCapacity.d.ts +5 -0
  34. package/dist/client/usage/creditCapacity.d.ts.map +1 -0
  35. package/dist/client/usage/creditCapacity.js +47 -0
  36. package/dist/client/usage/creditCapacity.js.map +1 -0
  37. package/dist/client/usage/creditClient.d.ts +104 -0
  38. package/dist/client/usage/creditClient.d.ts.map +1 -0
  39. package/dist/client/usage/creditClient.js +111 -0
  40. package/dist/client/usage/creditClient.js.map +1 -0
  41. package/dist/client/usage/creditDelivery.d.ts +6 -0
  42. package/dist/client/usage/creditDelivery.d.ts.map +1 -0
  43. package/dist/client/usage/creditDelivery.js +71 -0
  44. package/dist/client/usage/creditDelivery.js.map +1 -0
  45. package/dist/client/usage/creditInvoice.d.ts +6 -0
  46. package/dist/client/usage/creditInvoice.d.ts.map +1 -0
  47. package/dist/client/usage/creditInvoice.js +63 -0
  48. package/dist/client/usage/creditInvoice.js.map +1 -0
  49. package/dist/client/usage/creditLifecycle.d.ts +14 -0
  50. package/dist/client/usage/creditLifecycle.d.ts.map +1 -0
  51. package/dist/client/usage/creditLifecycle.js +90 -0
  52. package/dist/client/usage/creditLifecycle.js.map +1 -0
  53. package/dist/client/usage/creditNative.d.ts +20 -0
  54. package/dist/client/usage/creditNative.d.ts.map +1 -0
  55. package/dist/client/usage/creditNative.js +100 -0
  56. package/dist/client/usage/creditNative.js.map +1 -0
  57. package/dist/client/usage/creditObservation.d.ts +23 -0
  58. package/dist/client/usage/creditObservation.d.ts.map +1 -0
  59. package/dist/client/usage/creditObservation.js +54 -0
  60. package/dist/client/usage/creditObservation.js.map +1 -0
  61. package/dist/client/usage/creditProofs.d.ts +50 -0
  62. package/dist/client/usage/creditProofs.d.ts.map +1 -0
  63. package/dist/client/usage/creditProofs.js +58 -0
  64. package/dist/client/usage/creditProofs.js.map +1 -0
  65. package/dist/client/usage/creditProvider.d.ts +11 -0
  66. package/dist/client/usage/creditProvider.d.ts.map +1 -0
  67. package/dist/client/usage/creditProvider.js +195 -0
  68. package/dist/client/usage/creditProvider.js.map +1 -0
  69. package/dist/client/usage/creditRead.d.ts +47 -0
  70. package/dist/client/usage/creditRead.d.ts.map +1 -0
  71. package/dist/client/usage/creditRead.js +18 -0
  72. package/dist/client/usage/creditRead.js.map +1 -0
  73. package/dist/client/usage/creditReconciliation.d.ts +20 -0
  74. package/dist/client/usage/creditReconciliation.d.ts.map +1 -0
  75. package/dist/client/usage/creditReconciliation.js +157 -0
  76. package/dist/client/usage/creditReconciliation.js.map +1 -0
  77. package/dist/client/usage/creditTerms.d.ts +89 -0
  78. package/dist/client/usage/creditTerms.d.ts.map +1 -0
  79. package/dist/client/usage/creditTerms.js +76 -0
  80. package/dist/client/usage/creditTerms.js.map +1 -0
  81. package/dist/client/usage/creditTransport.fixtures.d.ts +101 -0
  82. package/dist/client/usage/creditTransport.fixtures.d.ts.map +1 -0
  83. package/dist/client/usage/creditTransport.fixtures.js +271 -0
  84. package/dist/client/usage/creditTransport.fixtures.js.map +1 -0
  85. package/dist/client/usage/deliveryProvider.d.ts.map +1 -1
  86. package/dist/client/usage/deliveryProvider.js +2 -0
  87. package/dist/client/usage/deliveryProvider.js.map +1 -1
  88. package/dist/client/usage/index.d.ts +4 -0
  89. package/dist/client/usage/index.d.ts.map +1 -1
  90. package/dist/client/usage/index.js +1 -0
  91. package/dist/client/usage/index.js.map +1 -1
  92. package/dist/client/usage/records.d.ts +2 -0
  93. package/dist/client/usage/records.d.ts.map +1 -1
  94. package/dist/client/usage/records.js +22 -0
  95. package/dist/client/usage/records.js.map +1 -1
  96. package/dist/client/usage/subscriptionTransport.fixtures.d.ts +1 -1
  97. package/dist/client/usage/subscriptionTransport.fixtures.d.ts.map +1 -1
  98. package/dist/client/usage/subscriptionTransport.fixtures.js +4 -1
  99. package/dist/client/usage/subscriptionTransport.fixtures.js.map +1 -1
  100. package/dist/client/usage/summary.js +2 -2
  101. package/dist/client/usage/summary.js.map +1 -1
  102. package/dist/client/usageExports.d.ts +16 -0
  103. package/dist/client/usageExports.d.ts.map +1 -0
  104. package/dist/client/usageExports.js +3 -0
  105. package/dist/client/usageExports.js.map +1 -0
  106. package/dist/client/webhooks/subscriptionDeleted.d.ts +5 -0
  107. package/dist/client/webhooks/subscriptionDeleted.d.ts.map +1 -0
  108. package/dist/client/webhooks/subscriptionDeleted.js +34 -0
  109. package/dist/client/webhooks/subscriptionDeleted.js.map +1 -0
  110. package/dist/component/_generated/api.d.ts +18 -0
  111. package/dist/component/_generated/api.d.ts.map +1 -1
  112. package/dist/component/_generated/api.js.map +1 -1
  113. package/dist/component/_generated/component.d.ts +360 -0
  114. package/dist/component/_generated/component.d.ts.map +1 -1
  115. package/dist/component/accountClosure/mutations.d.ts.map +1 -1
  116. package/dist/component/accountClosure/mutations.js +10 -0
  117. package/dist/component/accountClosure/mutations.js.map +1 -1
  118. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  119. package/dist/component/balanceFunding/mutations.d.ts +16 -16
  120. package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
  121. package/dist/component/balanceFunding/queries.d.ts +1 -1
  122. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  123. package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
  124. package/dist/component/earnings/triggers.d.ts +352 -18
  125. package/dist/component/earnings/triggers.d.ts.map +1 -1
  126. package/dist/component/payoutRelease/queries.d.ts +2 -2
  127. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  128. package/dist/component/schema.d.ts +183 -1
  129. package/dist/component/schema.js +8 -0
  130. package/dist/component/schema.js.map +1 -1
  131. package/dist/component/usage/mutations.d.ts.map +1 -1
  132. package/dist/component/usage/mutations.js +7 -0
  133. package/dist/component/usage/mutations.js.map +1 -1
  134. package/dist/component/usage/schema.d.ts +15 -1
  135. package/dist/component/usage/schema.d.ts.map +1 -1
  136. package/dist/component/usage/schema.js +12 -0
  137. package/dist/component/usage/schema.js.map +1 -1
  138. package/dist/component/usageAllowance/helpers.d.ts +78 -0
  139. package/dist/component/usageAllowance/helpers.d.ts.map +1 -0
  140. package/dist/component/usageAllowance/helpers.js +99 -0
  141. package/dist/component/usageAllowance/helpers.js.map +1 -0
  142. package/dist/component/usageAllowance/mutations.d.ts +37 -0
  143. package/dist/component/usageAllowance/mutations.d.ts.map +1 -0
  144. package/dist/component/usageAllowance/mutations.js +99 -0
  145. package/dist/component/usageAllowance/mutations.js.map +1 -0
  146. package/dist/component/usageAllowance/queries.d.ts +36 -0
  147. package/dist/component/usageAllowance/queries.d.ts.map +1 -0
  148. package/dist/component/usageAllowance/queries.js +113 -0
  149. package/dist/component/usageAllowance/queries.js.map +1 -0
  150. package/dist/component/usageAllowance/reservations.d.ts +25 -0
  151. package/dist/component/usageAllowance/reservations.d.ts.map +1 -0
  152. package/dist/component/usageAllowance/reservations.js +150 -0
  153. package/dist/component/usageAllowance/reservations.js.map +1 -0
  154. package/dist/component/usageAllowance/schema.d.ts +77 -0
  155. package/dist/component/usageAllowance/schema.d.ts.map +1 -0
  156. package/dist/component/usageAllowance/schema.js +32 -0
  157. package/dist/component/usageAllowance/schema.js.map +1 -0
  158. package/dist/component/usageCredits/helpers.d.ts +205 -0
  159. package/dist/component/usageCredits/helpers.d.ts.map +1 -0
  160. package/dist/component/usageCredits/helpers.js +129 -0
  161. package/dist/component/usageCredits/helpers.js.map +1 -0
  162. package/dist/component/usageCredits/mutations.d.ts +80 -0
  163. package/dist/component/usageCredits/mutations.d.ts.map +1 -0
  164. package/dist/component/usageCredits/mutations.js +344 -0
  165. package/dist/component/usageCredits/mutations.js.map +1 -0
  166. package/dist/component/usageCredits/purchase.d.ts +23 -0
  167. package/dist/component/usageCredits/purchase.d.ts.map +1 -0
  168. package/dist/component/usageCredits/purchase.js +166 -0
  169. package/dist/component/usageCredits/purchase.js.map +1 -0
  170. package/dist/component/usageCredits/queries.d.ts +184 -0
  171. package/dist/component/usageCredits/queries.d.ts.map +1 -0
  172. package/dist/component/usageCredits/queries.js +243 -0
  173. package/dist/component/usageCredits/queries.js.map +1 -0
  174. package/dist/component/usageCredits/reservations.d.ts +16 -0
  175. package/dist/component/usageCredits/reservations.d.ts.map +1 -0
  176. package/dist/component/usageCredits/reservations.js +161 -0
  177. package/dist/component/usageCredits/reservations.js.map +1 -0
  178. package/dist/component/usageCredits/schema.d.ts +282 -0
  179. package/dist/component/usageCredits/schema.d.ts.map +1 -0
  180. package/dist/component/usageCredits/schema.js +92 -0
  181. package/dist/component/usageCredits/schema.js.map +1 -0
  182. package/docs/README.md +4 -0
  183. package/docs/setup-intent-recovery.md +7 -0
  184. package/docs/usage-credits.md +255 -0
  185. package/docs/usage-ledger.md +7 -0
  186. package/docs/usage-limits.md +217 -0
  187. package/docs/webhooks.md +15 -1
  188. package/package.json +3 -1
  189. package/src/client/billing/setup-intent-read.test.ts +40 -0
  190. package/src/client/billing/setup-intent-read.ts +23 -9
  191. package/src/client/index.ts +9 -67
  192. package/src/client/types/triggers.ts +2 -0
  193. package/src/client/usage/allowanceClient.test.ts +93 -0
  194. package/src/client/usage/allowanceClient.ts +134 -0
  195. package/src/client/usage/allowanceTerms.test.ts +131 -0
  196. package/src/client/usage/allowanceTerms.ts +172 -0
  197. package/src/client/usage/client.ts +4 -4
  198. package/src/client/usage/creditCapacity.test.ts +83 -0
  199. package/src/client/usage/creditCapacity.ts +76 -0
  200. package/src/client/usage/creditClient.test.ts +221 -0
  201. package/src/client/usage/creditClient.ts +246 -0
  202. package/src/client/usage/creditDelivery.ts +105 -0
  203. package/src/client/usage/creditInvoice.test.ts +149 -0
  204. package/src/client/usage/creditInvoice.ts +87 -0
  205. package/src/client/usage/creditLifecycle.ts +175 -0
  206. package/src/client/usage/creditNative.ts +148 -0
  207. package/src/client/usage/creditObservation.test.ts +150 -0
  208. package/src/client/usage/creditObservation.ts +82 -0
  209. package/src/client/usage/creditProofs.ts +61 -0
  210. package/src/client/usage/creditProvider.test.ts +202 -0
  211. package/src/client/usage/creditProvider.ts +304 -0
  212. package/src/client/usage/creditRead.ts +32 -0
  213. package/src/client/usage/creditReconciliation.ts +213 -0
  214. package/src/client/usage/creditTerms.test.ts +48 -0
  215. package/src/client/usage/creditTerms.ts +140 -0
  216. package/src/client/usage/creditTransport.fixtures.ts +282 -0
  217. package/src/client/usage/deliveryProvider.ts +2 -0
  218. package/src/client/usage/index.ts +16 -0
  219. package/src/client/usage/record-composition.test.ts +195 -0
  220. package/src/client/usage/records.ts +26 -0
  221. package/src/client/usage/subscriptionTransport.fixtures.ts +6 -0
  222. package/src/client/usage/summary.test.ts +1 -1
  223. package/src/client/usage/summary.ts +2 -2
  224. package/src/client/usageExports.ts +56 -0
  225. package/src/client/webhook-handlers.test.ts +0 -34
  226. package/src/client/webhooks/subscription-deleted-dispatch.test.ts +61 -0
  227. package/src/client/webhooks/subscription-deleted.integration.test.ts +313 -0
  228. package/src/client/webhooks/subscriptionDeleted.ts +56 -0
  229. package/src/component/_generated/api.ts +18 -0
  230. package/src/component/_generated/component.ts +486 -0
  231. package/src/component/accountClosure/mutations.ts +14 -0
  232. package/src/component/schema.ts +16 -0
  233. package/src/component/usage/allowance.test.ts +435 -0
  234. package/src/component/usage/ledger.test.ts +8 -15
  235. package/src/component/usage/mutations.ts +22 -0
  236. package/src/component/usage/schema.ts +14 -0
  237. package/src/component/usageAllowance/helpers.ts +137 -0
  238. package/src/component/usageAllowance/mutations.ts +139 -0
  239. package/src/component/usageAllowance/queries.ts +133 -0
  240. package/src/component/usageAllowance/reservations.ts +220 -0
  241. package/src/component/usageAllowance/schema.ts +36 -0
  242. package/src/component/usageCredits/accounting.test.ts +389 -0
  243. package/src/component/usageCredits/helpers.ts +160 -0
  244. package/src/component/usageCredits/mutations.ts +451 -0
  245. package/src/component/usageCredits/purchase.ts +219 -0
  246. package/src/component/usageCredits/queries.ts +300 -0
  247. package/src/component/usageCredits/reservations.ts +214 -0
  248. package/src/component/usageCredits/schema.ts +106 -0
@@ -0,0 +1,83 @@
1
+ import Stripe from "stripe";
2
+ import { expect, it } from "vitest";
3
+ import { verifyNativeCreditCapacity } from "./creditCapacity.js";
4
+ import { creditPurchaseTerms } from "./creditTerms.js";
5
+ const terms = creditPurchaseTerms({
6
+ scope: {
7
+ stripeAccountId: "acct_platform",
8
+ customerAccount: "acct_buyer",
9
+ meterId: "mtr_calls",
10
+ livemode: false,
11
+ },
12
+ binding: {
13
+ stripeCustomerId: "cus_buyer",
14
+ stripePriceId: "price_calls",
15
+ eventName: "calls",
16
+ plan: {
17
+ key: "calls",
18
+ version: "v1",
19
+ model: "prepaid",
20
+ unit: { name: "call", precision: 0 },
21
+ rate: { currency: "usd", unitAmountDecimal: "2" },
22
+ insufficientBalance: "reject",
23
+ },
24
+ },
25
+ purchaseId: "topup1",
26
+ quantity: "10",
27
+ ownership: "issuer",
28
+ rollover: "retain_original_terms",
29
+ });
30
+ function fixture(ledger: number, more = false, foreign = false) {
31
+ const methods: string[] = [];
32
+ const stripe = new Stripe("sk_test_credit_capacity", {
33
+ httpClient: Stripe.createFetchHttpClient(async (input, init) => {
34
+ methods.push(init?.method ?? "GET");
35
+ const value = new URL(String(input)).pathname.endsWith("/credit_grants")
36
+ ? {
37
+ data: more
38
+ ? []
39
+ : [
40
+ {
41
+ id: "credgr_existing",
42
+ customer_account: foreign ? "acct_other" : "acct_buyer",
43
+ livemode: false,
44
+ expires_at: null,
45
+ voided_at: null,
46
+ },
47
+ ],
48
+ has_more: more,
49
+ }
50
+ : {
51
+ customer_account: "acct_buyer",
52
+ livemode: false,
53
+ balances: [
54
+ {
55
+ ledger_balance: { monetary: { value: ledger } },
56
+ available_balance: { monetary: { value: 0 } },
57
+ },
58
+ ],
59
+ };
60
+ return new Response(JSON.stringify(value), {
61
+ headers: { "content-type": "application/json" },
62
+ });
63
+ }),
64
+ });
65
+ return { stripe, methods };
66
+ }
67
+ it("counts native ledger credits awaiting finalization and all reserved purchase slots before payment creation", async () => {
68
+ const f = fixture(20);
69
+ await expect(
70
+ verifyNativeCreditCapacity(f.stripe, terms, 100),
71
+ ).rejects.toThrow(/capacity/i);
72
+ await verifyNativeCreditCapacity(f.stripe, terms, 99);
73
+ expect(f.methods.every((m) => m === "GET")).toBe(true);
74
+ });
75
+ it("permits verified depleted grants but holds incomplete or foreign native inventory", async () => {
76
+ await verifyNativeCreditCapacity(fixture(0).stripe, terms, 100);
77
+ await expect(
78
+ verifyNativeCreditCapacity(fixture(0, true).stripe, terms, 1),
79
+ ).rejects.toThrow(/incomplete/i);
80
+ await expect(
81
+ verifyNativeCreditCapacity(fixture(0, false, true).stripe, terms, 1),
82
+ ).rejects.toThrow(/scope/i);
83
+ });
@@ -0,0 +1,76 @@
1
+ import type Stripe from "stripe";
2
+ import { creditRequire } from "./creditNative.js";
3
+ import type { UsageCreditPurchaseTerms } from "./creditTerms.js";
4
+ /** Read-only, bounded prepayment guard. Pending component intents reserve slots separately. */
5
+ export async function verifyNativeCreditCapacity(
6
+ stripe: Stripe,
7
+ terms: UsageCreditPurchaseTerms,
8
+ pending: number,
9
+ ) {
10
+ let cursor: string | undefined,
11
+ complete = false;
12
+ const candidates: Stripe.Billing.CreditGrant[] = [];
13
+ for (let page = 0; page < 10; page++) {
14
+ const result = await stripe.billing.creditGrants.list({
15
+ customer_account: terms.scope.customerAccount,
16
+ limit: 100,
17
+ ...(cursor ? { starting_after: cursor } : {}),
18
+ });
19
+ for (const grant of result.data) {
20
+ creditRequire(
21
+ grant.customer_account === terms.scope.customerAccount &&
22
+ grant.livemode === terms.scope.livemode,
23
+ "Native credit inventory scope mismatch",
24
+ );
25
+ if (
26
+ !grant.voided_at &&
27
+ (grant.expires_at === null || grant.expires_at > Date.now() / 1000)
28
+ )
29
+ candidates.push(grant);
30
+ }
31
+ creditRequire(
32
+ candidates.length <= 100,
33
+ "Native credit capacity proof budget exceeded",
34
+ );
35
+ if (!result.has_more) {
36
+ complete = true;
37
+ break;
38
+ }
39
+ const next = result.data[result.data.length - 1]?.id;
40
+ creditRequire(
41
+ next && next !== cursor,
42
+ "Native credit capacity inventory incomplete",
43
+ );
44
+ cursor = next;
45
+ }
46
+ creditRequire(complete, "Native credit capacity inventory incomplete");
47
+ let unused = 0;
48
+ for (let start = 0; start < candidates.length; start += 5) {
49
+ const balances = await Promise.all(
50
+ candidates.slice(start, start + 5).map((grant) =>
51
+ stripe.billing.creditBalanceSummaries.retrieve({
52
+ customer_account: terms.scope.customerAccount,
53
+ filter: { type: "credit_grant", credit_grant: grant.id },
54
+ }),
55
+ ),
56
+ );
57
+ for (const balance of balances) {
58
+ creditRequire(
59
+ balance.livemode === terms.scope.livemode &&
60
+ balance.customer_account === terms.scope.customerAccount &&
61
+ balance.balances.length === 1,
62
+ "Native credit capacity balance unavailable",
63
+ );
64
+ const value = balance.balances[0].ledger_balance.monetary?.value;
65
+ creditRequire(
66
+ typeof value === "number" && Number.isSafeInteger(value) && value >= 0,
67
+ "Native credit capacity amount unavailable",
68
+ );
69
+ if (value > 0) unused++;
70
+ }
71
+ }
72
+ creditRequire(
73
+ Number.isInteger(pending) && pending >= 1 && unused + pending <= 100,
74
+ "Native unused credit grant capacity exhausted",
75
+ );
76
+ }
@@ -0,0 +1,221 @@
1
+ import { afterEach, expect, it, vi } from "vitest";
2
+ import { BetterStripe } from "../index.js";
3
+ import type { RunCtx } from "../helpers.js";
4
+ import { componentRef } from "../webhooks/helpers.js";
5
+ import { creditFixture } from "./creditTransport.fixtures.js";
6
+ import { verifyCreditDelivery } from "./creditDelivery.js";
7
+ import type { Doc } from "../../component/_generated/dataModel.js";
8
+ afterEach(() => vi.useRealTimers());
9
+ it("exposes paid credits, exact reservations, immutable consumption and scoped pages through the package facade", async () => {
10
+ const f = creditFixture(),
11
+ client = new BetterStripe(f.component),
12
+ options = { stripeSecretKey: "sk_test_credit", httpClient: f.httpClient };
13
+ const view = await f.ready();
14
+ await f.t.action((ctx) =>
15
+ client.usage.purchaseCredits(ctx as RunCtx, f.purchase, options),
16
+ );
17
+ f.state.paid = true;
18
+ await f.t.action((ctx) =>
19
+ client.usage.observeCreditPurchase(ctx as RunCtx, f.purchase, options),
20
+ );
21
+ const subscription = view.bindings[0].subscription;
22
+ const event = {
23
+ scope: f.purchase.scope,
24
+ binding: f.purchase.binding,
25
+ sourceEventId: "work1",
26
+ quantity: "6",
27
+ occurredAt: 700,
28
+ };
29
+ const reservation = await f.t.action((ctx) =>
30
+ client.usage.reserveCredits(ctx as RunCtx, { event, subscription }),
31
+ );
32
+ const receipt = await f.t.action((ctx) =>
33
+ client.usage.record(ctx as RunCtx, {
34
+ event,
35
+ subscription,
36
+ reservationId: reservation.reservationId,
37
+ }),
38
+ );
39
+ expect(
40
+ await f.t.query((ctx) =>
41
+ client.usage.getCreditBalance(ctx as RunCtx, f.purchase),
42
+ ),
43
+ ).toMatchObject({
44
+ availableQuantity: "4",
45
+ reservedQuantity: "0",
46
+ consumedQuantity: "6",
47
+ cashCollection: "none",
48
+ });
49
+ const history = await f.t.query((ctx) =>
50
+ client.usage.readCreditHistory(ctx as RunCtx, {
51
+ ...f.purchase,
52
+ limit: 2,
53
+ cursor: null,
54
+ }),
55
+ );
56
+ expect(history.records).toHaveLength(2);
57
+ expect(history.cursor).not.toBeNull();
58
+ expect(
59
+ (
60
+ await f.t.query((ctx) =>
61
+ client.usage.getCreditBalance(ctx as RunCtx, {
62
+ ...f.purchase,
63
+ scope: { ...f.purchase.scope, customerAccount: "acct_other" },
64
+ }),
65
+ )
66
+ ).availableQuantity,
67
+ ).toBe("0");
68
+ const saved = (await f.t.action((ctx) =>
69
+ ctx.runQuery(componentRef(f.component, "usage/queries/get"), {
70
+ scope: f.purchase.scope,
71
+ eventId: receipt.eventId,
72
+ }),
73
+ )) as { event: Doc<"usageEvents"> };
74
+ await f.t.action((ctx) =>
75
+ verifyCreditDelivery(
76
+ f.stripe,
77
+ f.component,
78
+ ctx as RunCtx,
79
+ saved.event,
80
+ JSON.parse(saved.event.recordJson),
81
+ ),
82
+ );
83
+ f.state.nativeAvailable = 0;
84
+ await expect(
85
+ f.t.action((ctx) =>
86
+ verifyCreditDelivery(
87
+ f.stripe,
88
+ f.component,
89
+ ctx as RunCtx,
90
+ saved.event,
91
+ JSON.parse(saved.event.recordJson),
92
+ ),
93
+ ),
94
+ ).rejects.toThrow(/backing reconciliation/i);
95
+ });
96
+ it("reconciles unspent native grants, disables them before refund and records verified original refund evidence", async () => {
97
+ const f = creditFixture(),
98
+ client = new BetterStripe(f.component),
99
+ options = { stripeSecretKey: "sk_test_credit", httpClient: f.httpClient };
100
+ await f.ready();
101
+ await f.t.action((ctx) =>
102
+ client.usage.purchaseCredits(ctx as RunCtx, f.purchase, options),
103
+ );
104
+ f.state.paid = true;
105
+ await f.t.action((ctx) =>
106
+ client.usage.observeCreditPurchase(ctx as RunCtx, f.purchase, options),
107
+ );
108
+ expect(
109
+ await f.t.action((ctx) =>
110
+ client.usage.reconcileCreditPurchase(ctx as RunCtx, f.purchase, options),
111
+ ),
112
+ ).toMatchObject({
113
+ status: "available",
114
+ value: {
115
+ backing: "sufficient",
116
+ ledgerAmount: 20,
117
+ applied: 0,
118
+ cashCollection: "none",
119
+ },
120
+ });
121
+ expect(
122
+ await f.t.action((ctx) =>
123
+ client.usage.prepareCreditRefund(ctx as RunCtx, f.purchase, options),
124
+ ),
125
+ ).toMatchObject({
126
+ paymentIntentId: "pi_topup1",
127
+ amount: 20,
128
+ creditState: "disabled",
129
+ cashRefund: "required",
130
+ });
131
+ await expect(
132
+ f.t.action((ctx) =>
133
+ client.usage.closeCreditAccount(ctx as RunCtx, f.purchase),
134
+ ),
135
+ ).rejects.toThrow();
136
+ f.state.refunded = true;
137
+ await f.t.action((ctx) =>
138
+ client.usage.reconcileCreditPurchase(ctx as RunCtx, f.purchase, options),
139
+ );
140
+ await f.t.action((ctx) =>
141
+ client.usage.closeCreditAccount(ctx as RunCtx, f.purchase),
142
+ );
143
+ expect(
144
+ await f.t.query((ctx) =>
145
+ client.usage.getCreditBalance(ctx as RunCtx, f.purchase),
146
+ ),
147
+ ).toMatchObject({
148
+ status: "held",
149
+ availableQuantity: "0",
150
+ expiredQuantity: "10",
151
+ });
152
+ });
153
+ it("holds incomplete native history instead of treating it as a zero balance", async () => {
154
+ const f = creditFixture(),
155
+ client = new BetterStripe(f.component),
156
+ options = { stripeSecretKey: "sk_test_credit", httpClient: f.httpClient };
157
+ await f.ready();
158
+ await f.t.action((ctx) =>
159
+ client.usage.purchaseCredits(ctx as RunCtx, f.purchase, options),
160
+ );
161
+ f.state.paid = true;
162
+ await f.t.action((ctx) =>
163
+ client.usage.observeCreditPurchase(ctx as RunCtx, f.purchase, options),
164
+ );
165
+ f.state.incomplete = true;
166
+ expect(
167
+ await f.t.action((ctx) =>
168
+ client.usage.reconcileCreditPurchase(ctx as RunCtx, f.purchase, options),
169
+ ),
170
+ ).toMatchObject({
171
+ status: "available",
172
+ value: { backing: "held", reason: "invoice_provenance_unavailable" },
173
+ });
174
+ expect(
175
+ await f.t.query((ctx) =>
176
+ client.usage.getCreditBalance(ctx as RunCtx, f.purchase),
177
+ ),
178
+ ).toMatchObject({ status: "held", availableQuantity: "0" });
179
+ await expect(
180
+ f.t.action((ctx) =>
181
+ client.usage.resumeCreditAccount(ctx as RunCtx, f.purchase),
182
+ ),
183
+ ).rejects.toThrow();
184
+ f.state.incomplete = false;
185
+ await f.t.action((ctx) =>
186
+ client.usage.reconcileCreditPurchase(ctx as RunCtx, f.purchase, options),
187
+ );
188
+ await f.t.action((ctx) =>
189
+ client.usage.resumeCreditAccount(ctx as RunCtx, f.purchase),
190
+ );
191
+ expect(
192
+ await f.t.query((ctx) =>
193
+ client.usage.getCreditBalance(ctx as RunCtx, f.purchase),
194
+ ),
195
+ ).toMatchObject({ status: "available", availableQuantity: "10" });
196
+ });
197
+
198
+ it("does not authorize a full cash refund when native credits are consumed during expiration", async () => {
199
+ const f = creditFixture(),
200
+ client = new BetterStripe(f.component),
201
+ options = { stripeSecretKey: "sk_test_credit", httpClient: f.httpClient };
202
+ await f.ready();
203
+ await f.t.action((ctx) =>
204
+ client.usage.purchaseCredits(ctx as RunCtx, f.purchase, options),
205
+ );
206
+ f.state.paid = true;
207
+ await f.t.action((ctx) =>
208
+ client.usage.observeCreditPurchase(ctx as RunCtx, f.purchase, options),
209
+ );
210
+ f.state.applyAtExpire = true;
211
+ await expect(
212
+ f.t.action((ctx) =>
213
+ client.usage.prepareCreditRefund(ctx as RunCtx, f.purchase, options),
214
+ ),
215
+ ).rejects.toThrow(/expiration|reconciliation/i);
216
+ expect(
217
+ await f.t.query((ctx) =>
218
+ client.usage.getCreditBalance(ctx as RunCtx, f.purchase),
219
+ ),
220
+ ).toMatchObject({ status: "held", availableQuantity: "0" });
221
+ });
@@ -0,0 +1,246 @@
1
+ import {
2
+ cancelCreditPurchase,
3
+ prepareCreditRefund,
4
+ } from "./creditLifecycle.js";
5
+ import { reconcileCreditPurchase } from "./creditReconciliation.js";
6
+ import Stripe from "stripe";
7
+ import type { RunCtx } from "../helpers.js";
8
+ import { runMutationOrThrow } from "../helpers.js";
9
+ import type { StripeApiVersion } from "../stripe-types.js";
10
+ import { componentRef } from "../webhooks/helpers.js";
11
+ import { UsageSubscriptionClient } from "./subscriptionClient.js";
12
+ import { prepareUsageRecord, scopeSchema, type UsageScope } from "./records.js";
13
+ import type { UsageSubscriptionBinding } from "./boundaries.js";
14
+ import {
15
+ creditBinding,
16
+ UsageCreditError,
17
+ type UsageCreditBinding,
18
+ type UsageCreditPurchaseOptions,
19
+ type UsageCreditBalance,
20
+ } from "./creditTerms.js";
21
+ import {
22
+ ensureCreditPurchase,
23
+ observeCreditPurchase,
24
+ creditPurchaseView,
25
+ } from "./creditProvider.js";
26
+ import type { UsageDeliveryProviderOptions } from "./deliveryProvider.js";
27
+ import type { Doc, Id } from "../../component/_generated/dataModel.js";
28
+ import { z } from "zod";
29
+ const provider = (
30
+ input: UsageCreditBinding,
31
+ options: UsageDeliveryProviderOptions,
32
+ ) => {
33
+ if (!options.stripeSecretKey)
34
+ throw new UsageCreditError(
35
+ "provider_unavailable",
36
+ "Native usage credit credentials unavailable",
37
+ );
38
+ return new Stripe(options.stripeSecretKey, {
39
+ apiVersion: creditBinding(input).binding.apiVersion as StripeApiVersion,
40
+ maxNetworkRetries: 0,
41
+ timeout: 15000,
42
+ ...(options.httpClient ? { httpClient: options.httpClient } : {}),
43
+ });
44
+ };
45
+ async function operation<T>(fn: () => Promise<T>): Promise<T> {
46
+ try {
47
+ return await fn();
48
+ } catch (error) {
49
+ if (error instanceof UsageCreditError) throw error;
50
+ throw new UsageCreditError(
51
+ error instanceof Error && /insufficient/i.test(error.message)
52
+ ? "insufficient_credits"
53
+ : "reconciliation_required",
54
+ "Usage credit operation could not complete",
55
+ );
56
+ }
57
+ }
58
+ /** Trusted host authorizes the exact payer/realm/meter, activity and original terms. */
59
+ export class UsageCreditClient extends UsageSubscriptionClient {
60
+ reconcileCreditPurchase(
61
+ ctx: RunCtx,
62
+ input: UsageCreditPurchaseOptions,
63
+ options: UsageDeliveryProviderOptions,
64
+ ) {
65
+ return reconcileCreditPurchase(
66
+ provider(input, options),
67
+ this.component,
68
+ ctx,
69
+ input,
70
+ );
71
+ }
72
+ prepareCreditRefund(
73
+ ctx: RunCtx,
74
+ input: UsageCreditPurchaseOptions,
75
+ options: UsageDeliveryProviderOptions,
76
+ ) {
77
+ return prepareCreditRefund(
78
+ provider(input, options),
79
+ this.component,
80
+ ctx,
81
+ input,
82
+ );
83
+ }
84
+ cancelCreditPurchase(
85
+ ctx: RunCtx,
86
+ input: UsageCreditPurchaseOptions,
87
+ options: UsageDeliveryProviderOptions,
88
+ ) {
89
+ return cancelCreditPurchase(
90
+ provider(input, options),
91
+ this.component,
92
+ ctx,
93
+ input,
94
+ );
95
+ }
96
+ purchaseCredits(
97
+ ctx: RunCtx,
98
+ input: UsageCreditPurchaseOptions,
99
+ options: UsageDeliveryProviderOptions,
100
+ ) {
101
+ return ensureCreditPurchase(
102
+ provider(input, options),
103
+ this.component,
104
+ ctx,
105
+ input,
106
+ );
107
+ }
108
+ observeCreditPurchase(
109
+ ctx: RunCtx,
110
+ input: UsageCreditPurchaseOptions,
111
+ options: UsageDeliveryProviderOptions,
112
+ ) {
113
+ return observeCreditPurchase(
114
+ provider(input, options),
115
+ this.component,
116
+ ctx,
117
+ input,
118
+ );
119
+ }
120
+ async getCreditPurchase(
121
+ ctx: RunCtx,
122
+ input: UsageCreditBinding & { purchaseId: string },
123
+ ) {
124
+ const row = (await ctx.runQuery(
125
+ componentRef(this.component, "usageCredits/queries/getPurchase"),
126
+ {
127
+ bindingJson: JSON.stringify(creditBinding(input)),
128
+ purchaseId: input.purchaseId,
129
+ },
130
+ )) as Doc<"usageCreditPurchases"> | null;
131
+ return row ? creditPurchaseView(row) : null;
132
+ }
133
+ resumeCreditAccount(ctx: RunCtx, input: UsageCreditBinding) {
134
+ return operation(() =>
135
+ runMutationOrThrow(
136
+ ctx,
137
+ componentRef(this.component, "usageCredits/mutations/resumeAccount"),
138
+ {
139
+ bindingJson: JSON.stringify(creditBinding(input)),
140
+ },
141
+ ),
142
+ );
143
+ }
144
+ closeCreditAccount(ctx: RunCtx, input: UsageCreditBinding) {
145
+ return operation(() =>
146
+ runMutationOrThrow(
147
+ ctx,
148
+ componentRef(this.component, "usageCredits/mutations/closeAccount"),
149
+ {
150
+ bindingJson: JSON.stringify(creditBinding(input)),
151
+ },
152
+ ),
153
+ );
154
+ }
155
+ getCreditBalance(
156
+ ctx: RunCtx,
157
+ input: UsageCreditBinding,
158
+ ): Promise<UsageCreditBalance> {
159
+ return ctx.runQuery(
160
+ componentRef(this.component, "usageCredits/queries/balance"),
161
+ { bindingJson: JSON.stringify(creditBinding(input)) },
162
+ );
163
+ }
164
+ reserveCredits(
165
+ ctx: RunCtx,
166
+ input: { event: unknown; subscription: UsageSubscriptionBinding },
167
+ ): Promise<{
168
+ reservationId: Id<"usageReservations">;
169
+ state: "reserved" | "committed" | "released";
170
+ }> {
171
+ const event = prepareUsageRecord(input.event);
172
+ const original = {
173
+ scope: event.scope,
174
+ binding: event.binding,
175
+ quantity: event.quantity,
176
+ sourceEventId: event.sourceEventId,
177
+ occurredAt: event.occurredAt,
178
+ };
179
+ return operation(() =>
180
+ runMutationOrThrow(
181
+ ctx,
182
+ componentRef(this.component, "usageCredits/mutations/reserve"),
183
+ {
184
+ inputJson: JSON.stringify(original),
185
+ subscriptionJson: JSON.stringify(input.subscription),
186
+ },
187
+ ),
188
+ );
189
+ }
190
+ releaseCredits(
191
+ ctx: RunCtx,
192
+ input: {
193
+ scope: UsageScope;
194
+ reservationId: Id<"usageReservations">;
195
+ reason: "work_failed" | "abandoned_before_work";
196
+ },
197
+ ) {
198
+ return operation(() =>
199
+ runMutationOrThrow(
200
+ ctx,
201
+ componentRef(this.component, "usageCredits/mutations/release"),
202
+ {
203
+ scope: scopeSchema.parse(input.scope),
204
+ reservationId: input.reservationId,
205
+ reason: input.reason,
206
+ },
207
+ ),
208
+ );
209
+ }
210
+ readCreditHistory(
211
+ ctx: RunCtx,
212
+ input: UsageCreditBinding & { limit: number; cursor: string | null },
213
+ ) {
214
+ return this.creditPage<Doc<"usageCreditHistory">>(
215
+ ctx,
216
+ "readHistory",
217
+ input,
218
+ );
219
+ }
220
+ readCreditGrants(
221
+ ctx: RunCtx,
222
+ input: UsageCreditBinding & { limit: number; cursor: string | null },
223
+ ) {
224
+ return this.creditPage<Doc<"usageCreditGrants">>(ctx, "readGrants", input);
225
+ }
226
+ private async creditPage<T>(
227
+ ctx: RunCtx,
228
+ name: string,
229
+ input: UsageCreditBinding & { limit: number; cursor: string | null },
230
+ ) {
231
+ const limit = z.number().int().min(1).max(100).parse(input.limit);
232
+ const cursor = z.string().max(2048).nullable().parse(input.cursor);
233
+ const result = (await ctx.runQuery(
234
+ componentRef(this.component, "usageCredits/queries/" + name),
235
+ {
236
+ bindingJson: JSON.stringify(creditBinding(input)),
237
+ paginationOpts: { numItems: limit, cursor },
238
+ },
239
+ )) as { page: T[]; isDone: boolean; continueCursor: string };
240
+ return {
241
+ records: result.page,
242
+ cursor: result.isDone ? null : result.continueCursor,
243
+ isDone: result.isDone,
244
+ };
245
+ }
246
+ }