@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,255 @@
1
+ # Payment-backed prepaid usage
2
+
3
+ BetterStripe tracks prepaid units against an original Stripe payment and a
4
+ price-scoped Billing Credit Grant. Stripe keeps the monetary credit ledger.
5
+ Consuming units creates a usage event, not a new payment or seller settlement.
6
+
7
+ Use this for the issuer's own services. Set ownership to issuer explicitly.
8
+ Third-party purchases and transferable wallets are unsupported. See Stripe's
9
+ [billing-credit eligibility](https://docs.stripe.com/billing/subscriptions/usage-based/billing-credits).
10
+
11
+ ## Prerequisites
12
+
13
+ Complete the [native setup](./metering-setup.md), provision a
14
+ [prepaid meter and price](./usage-catalog.md), and create an active
15
+ [managed subscription](./usage-subscriptions.md). Prepaid accounting requires
16
+ send_invoice collection. It does not attach an automatic cash collector to usage
17
+ invoices. A mismatched collection policy fails closed.
18
+
19
+ Configure the original plan on the server:
20
+
21
+ ```ts
22
+ const plan = defineUsagePlan({
23
+ key: "api-calls",
24
+ version: "v1",
25
+ model: "prepaid",
26
+ unit: { name: "call", precision: 0 },
27
+ rate: { currency: "usd", unitAmountDecimal: "2" },
28
+ insufficientBalance: "reject",
29
+ });
30
+ ```
31
+
32
+ Rates are minor currency units per whole billable unit. Quantities are decimal
33
+ strings. Each purchase and reservation must have an exact positive whole minor
34
+ currency amount. For example, 50 calls at 2 cents require 100 cents of backing.
35
+ Fractional-minor-unit consumption is rejected rather than rounded. Batch work
36
+ into an exact supported quantity when necessary.
37
+
38
+ Every host endpoint must authenticate the caller and authorize the complete
39
+ Stripe realm, test/live mode, Accounts v2 payer, meter and activity. Read the
40
+ original binding and price from server-owned configuration. Never forward a
41
+ browser-supplied scope, price, plan, reservation or purchase ID without checking
42
+ ownership. Component functions and this server facade are trusted host APIs.
43
+
44
+ ## Purchase and top up
45
+
46
+ Use a unique application purchase ID for each intended purchase. Reuse it on
47
+ retry and keep its quantity, original binding, rollover and expiry unchanged:
48
+
49
+ ```ts
50
+ const purchase = {
51
+ scope,
52
+ binding, // original native meter/price, payer and plan
53
+ purchaseId: checkoutAttemptId,
54
+ quantity: "50",
55
+ ownership: "issuer" as const,
56
+ rollover: "retain_original_terms" as const,
57
+ };
58
+ const provider = { stripeSecretKey: process.env.STRIPE_SECRET_KEY };
59
+ const result = await stripe.usage.purchaseCredits(ctx, purchase, provider);
60
+ ```
61
+
62
+ This action creates or recovers one card PaymentIntent. Return clientSecret only
63
+ to that authenticated purchaser and confirm it with Stripe's payment UI. Never
64
+ persist it in documents, operation arguments, logs or Workflow state. The package
65
+ stores the PaymentIntent ID and normalized evidence.
66
+
67
+ After confirmation, call observeCreditPurchase from an authorized action or a
68
+ trusted webhook adapter:
69
+
70
+ ```ts
71
+ await stripe.usage.observeCreditPurchase(ctx, purchase, provider);
72
+ ```
73
+
74
+ Its fresh native read verifies successful capture, amount, currency, payer,
75
+ realm/mode and original metadata. Pending or failed payments do not grant units.
76
+ It then creates or recovers one paid Credit Grant scoped to the original price.
77
+
78
+ Read getCreditPurchase reactively with scope, binding and purchaseId to show
79
+ pending, ready, frozen or canceled. Ready requires verified payment and durable
80
+ grant persistence. Duplicate and out-of-order notifications trigger fresh native
81
+ reads and cannot grant twice.
82
+
83
+ Payment and grant creation have separate durable retry windows. The grant window
84
+ starts when payment success is first persisted, so delayed payments can complete.
85
+ Missing pinned resources, ambiguous discovery or an unknown create outside its
86
+ 23-hour window requires reconciliation. A new purchase ID must not bypass a hold.
87
+
88
+ Each top-up is another purchase with a new ID. A host can implement a threshold
89
+ policy using getCreditBalance and its authenticated payment-confirmation flow.
90
+ The package does not silently charge a saved card or convert exhausted prepaid
91
+ work into pay-as-you-go billing.
92
+
93
+ ## Reserve, perform work and record
94
+
95
+ Reserve before work that must fit the prepaid cap:
96
+
97
+ ```ts
98
+ const event = {
99
+ scope,
100
+ binding,
101
+ sourceEventId: job.id,
102
+ quantity: "6",
103
+ occurredAt: job.originalUsageTimestamp,
104
+ };
105
+ const reservation = await stripe.usage.reserveCredits(ctx, {
106
+ event,
107
+ subscription, // original item and half-open billing period
108
+ });
109
+ if (reservation.state === "reserved") {
110
+ await performIdempotentWork(job); // host deduplicates work under job.id
111
+ await stripe.usage.record(ctx, {
112
+ event,
113
+ subscription,
114
+ reservationId: reservation.reservationId,
115
+ });
116
+ }
117
+ ```
118
+
119
+ A committed reservation means work was already accepted. A released reservation
120
+ means the host explicitly abandoned it. Do not rerun work simply because a client
121
+ retries. Acceptance commits the exact reservation in the same transaction as its
122
+ immutable event and outbox. Original time, quantity, customer, price/version and
123
+ subscription snapshot cannot change on replay.
124
+
125
+ Concurrent reservations cannot spend the same units. UsageCreditError exposes
126
+ insufficient_credits when eligible backing cannot satisfy a reservation.
127
+ Allocation uses earliest expiry, effective time, native creation time and native grant
128
+ ID. One reservation can partially consume a grant and uses at most ten grants.
129
+
130
+ If work definitely never completed, release its uncommitted reservation:
131
+
132
+ ```ts
133
+ await stripe.usage.releaseCredits(ctx, {
134
+ scope,
135
+ reservationId: reservation.reservationId,
136
+ reason: "work_failed", // or "abandoned_before_work"
137
+ });
138
+ ```
139
+
140
+ There is no automatic timeout release. A worker crash does not prove that work
141
+ failed. Resolve the host's job outcome first. Committed, unknown or held usage
142
+ retains its backing and requires an auditable correction.
143
+
144
+ Use the [existing delivery API](./usage-delivery.md). Prepaid delivery also checks
145
+ the original payment, grant, scope, expiry and current native ledger balance.
146
+ Changed backing requires reconciliation. Refund/dispute evidence freezes further
147
+ spending. Delivery does not create a payment or collect an invoice.
148
+
149
+ ## Expiry, rollover and price changes
150
+
151
+ Omitting expiresAt creates non-expiring original-term credits. Explicit expiry
152
+ must cover the current billing period plus 72 hours for finalization.
153
+ Reservations enforce that coverage for their own period. Native credits apply
154
+ at invoice finalization, not when work reserves units.
155
+
156
+ The retain_original_terms policy preserves remaining units across renewal under
157
+ the same original binding until expiry. Different prices, units, currencies,
158
+ modes and plan versions have separate ledgers. There is no automatic conversion,
159
+ promotional grant or reset of consumed units.
160
+
161
+ The live balance is a quantity projection, not money available for withdrawal.
162
+ Reserved and consumed quantities stay separate from native credit application.
163
+ Check eligibility through reserveCredits, since a future expiry may not cover
164
+ the whole billing period even while units remain unexpired.
165
+
166
+ ## Read and reconcile
167
+
168
+ Use getCreditBalance, readCreditGrants and readCreditHistory. Pages accept a limit
169
+ from 1 to 100 and an opaque nullable cursor. History retains purchase, payment,
170
+ grant, reservation, commit, release, native transaction, recovery and closure
171
+ provenance.
172
+
173
+ ```ts
174
+ const state = await stripe.usage.reconcileCreditPurchase(
175
+ ctx,
176
+ purchase,
177
+ provider,
178
+ );
179
+ ```
180
+
181
+ Reconciliation reads grant-filtered native credit balances and transactions.
182
+ Each funded invoice line must match original local quantities, item, period and
183
+ successful delivery. Original price amounts must be covered by native credits.
184
+ Incomplete history, foreign references, proration and unexpected consumption
185
+ hold the projection. After resolving a temporary observation hold, reconcile every
186
+ grant again and call resumeCreditAccount. Resume requires fresh complete proofs
187
+ and cannot release unresolved refunded, disputed or consumed liabilities.
188
+
189
+ The pendingFinalizationAmount separates committed usage from native credit
190
+ application. cashCollection is always none. Invoice payment evidence remains
191
+ not_resolved. Paid status, credit application and previews do not prove new cash
192
+ or authorize seller/affiliate settlement.
193
+
194
+ An invoice void can restore native credit, but does not recreate spent units in
195
+ this ledger. A credit note does not itself restore a Stripe Credit Grant. Both
196
+ require explicit correction provenance. See
197
+ [Stripe's reinstatement rules](https://docs.stripe.com/billing/subscriptions/usage-based/billing-credits#void-invoices-and-issue-credit-notes).
198
+
199
+ Reconciliation is bounded to 100 native transactions and ten invoice proofs per
200
+ grant. Larger or incomplete histories are held, never assumed complete. The
201
+ component retains at most 1,000 purchases and 100,000 audit entries per original
202
+ binding. Quota exhaustion blocks new work without deleting financial history.
203
+ Plan an explicit capacity and archival policy before reaching those bounds.
204
+
205
+ The customer-level capacity guard counts native ledger balances, including local
206
+ consumption awaiting finalization, and outstanding purchase intents. Payment
207
+ creation also checks native inventory before returning a PaymentIntent. That
208
+ proof is bounded to 1,000 listed grants and 100 unexpired balance reads in groups
209
+ of five. Incomplete inventory blocks payment creation. Cancel an unstarted
210
+ purchase or reconcile depleted grants to free its reserved capacity. A captured
211
+ payment waiting for its original grant retains its slot and recovery provenance.
212
+
213
+ Native allocation can differ from local reservation allocation, including native
214
+ creation-time ties. Unproven
215
+ comparisons require reconciliation. External Stripe Dashboard changes can also
216
+ require operator recovery; the local reservation cap does not lock Stripe.
217
+
218
+ ## Cancellation, refunds and closure
219
+
220
+ cancelCreditPurchase cancels only an original unpaid PaymentIntent in a
221
+ supported cancelable state. It never replaces a missing identity or cancels a
222
+ successful payment. Retry ambiguous cancellation under the same purchase.
223
+
224
+ For wholly unused paid credits:
225
+
226
+ 1. Call prepareCreditRefund. It requires current reconciliation and no reserved
227
+ or consumed units. It freezes the grant and confirms native expiration.
228
+ 2. Use BetterStripe's existing createRefund for the returned original
229
+ paymentIntentId, with host authorization and a stable refund idempotency key.
230
+ Preparation returns cashRefund as required; it does not claim money moved.
231
+ 3. Reconcile again to preserve fresh native refund and expiration evidence.
232
+
233
+ Partial consumption, pending work, disputes, invoice voids and partial refunds
234
+ are recovery cases. The component freezes affected units and retains liabilities.
235
+ It does not silently restore units, refund twice or settle consumption as a sale.
236
+
237
+ Close the managed subscription through its normal usage closeout first.
238
+ closeCreditAccount requires no pending purchases/reservations, complete native
239
+ zero-balance evidence and reconciled consumption. Unspent paid credits require a
240
+ verified full refund unless they expired under their original configured terms.
241
+ The general account-closure API checks open prepaid ledgers for payer and realm.
242
+
243
+ ## Verification and agent setup
244
+
245
+ Run pnpm run check:all. Focused tests exercise the public facade and actual Stripe
246
+ SDK transport, database-failure recovery, concurrent reservations, invoice
247
+ provenance, expiration, cancellation and refunds.
248
+
249
+ Use the existing Stripe sandbox and test key. No Metronome account or token is
250
+ required. Keep secrets in the runtime environment and follow the
251
+ [setup guide](./metering-setup.md). The sanitized
252
+ [native finalization evidence](./evidence/native-metering/clock-finalization-run.json)
253
+ demonstrates purchased native credit covering usage without a second usage
254
+ charge. Clock advancement is not ingestion proof. Observe the meter aggregate
255
+ before advancing, then inspect the finalized invoice.
@@ -15,6 +15,13 @@ const receipt = await authorizeUsageRecord(ctx, policy, serverEvent, (event) =>
15
15
  );
16
16
  ```
17
17
 
18
+ The facade accepts strict raw events and the complete canonical prepared record
19
+ returned by `authorizeUsageRecord` or `prepareUsageRecord`. Prepared identity,
20
+ schema version and quantity scaling are validated against a fresh canonical
21
+ preparation; inconsistent derived values, partial prepared shapes and unknown
22
+ fields reject before ledger acceptance.
23
+ Prepared data does not replace host scope or activity authorization.
24
+
18
25
  Acceptance writes an immutable event, durable outbox row and retained-scope counter
19
26
  in one Convex transaction. An optional `dispatch` handle schedules an internal
20
27
  host action in that transaction. Create the handle on the server; never accept it
@@ -0,0 +1,217 @@
1
+ # Included usage and optional usage limits
2
+
3
+ BetterStripe supplies atomic quantity accounting for monthly included usage and
4
+ optional pay-as-you-go caps. Use native Stripe graduated prices for included
5
+ usage, provisioned by the [usage catalog](./usage-catalog.md), and enroll the
6
+ customer through [managed subscriptions](./usage-subscriptions.md). The free
7
+ first tier and original overage rate remain the billing terms. Limits control
8
+ access to work; they do not change the price or collect money.
9
+
10
+ Prepaid uses the separate [payment-backed credit APIs](./usage-credits.md).
11
+ `configureAllowance` rejects prepaid plans. No monetary wallet or extra usage
12
+ charge is created by allowance accounting.
13
+
14
+ ## Configure before accepting usage
15
+
16
+ Authenticate and authorize policy management in a host mutation. Resolve the
17
+ payer, native customer, meter and original terms on the server. Do not accept
18
+ these identities or policy edits directly from an untrusted browser.
19
+
20
+ Use a binding returned by `stripe.usage.ensureSubscription`, `observeSubscription`
21
+ or `getSubscription`. Observe the current native subscription before initializing
22
+ a renewed period. A managed subscription must be active and its period must
23
+ still be open. This works with the supported managed collection methods.
24
+
25
+ ```ts
26
+ const original = subscription.bindings[0];
27
+ await stripe.usage.configureAllowance(ctx, {
28
+ ...original,
29
+ expectedRevision: 0,
30
+ policy: {
31
+ entitled: true,
32
+ reset: "billing_period",
33
+ rollover: "none",
34
+ overage: "allow",
35
+ limit: { mode: "hard", quantity: "12000" },
36
+ },
37
+ });
38
+ ```
39
+
40
+ Configure every metered binding that needs limits. The plan supplies
41
+ `includedQuantity`, unit precision and the original decimal overage rate.
42
+ `limit.quantity` is total usage for the period, including free units, expressed as
43
+ an exact decimal string in that unit. A hard limit of 12000 with 10000 included
44
+ units permits 2000 billable overage units. `overage: "reject"` additionally caps
45
+ usage at the included quantity. The smaller hard cap wins.
46
+
47
+ `limit: { mode: "soft", quantity: "12000" }` reports a warning at the threshold
48
+ and continues accepting usage. `limit: { mode: "none" }` has no separate usage
49
+ threshold. `entitled: false` rejects new reservations. Pay-as-you-go supports
50
+ these optional total-usage thresholds with `overage: "allow"`; it has no free
51
+ included units. Prepaid insufficient-balance enforcement comes from paid grants.
52
+
53
+ This native v1 policy explicitly resets at the original monthly billing-period
54
+ boundary and has no rollover. Carrying free units or resetting on a calendar
55
+ month would disagree with the native price and is rejected. Change billing terms
56
+ at a verified future period, using the subscription lifecycle. Do not mutate an
57
+ existing period's free tier, price, currency, version or units.
58
+
59
+ Setup over existing unaccounted period usage is rejected. Reconcile that history
60
+ and enable the policy at the next verified period rather than granting a fresh
61
+ allowance over work already accepted. An overlapping period, new subscription or
62
+ changed binding cannot reset an existing counter. Once a native payer/meter or
63
+ logical scope has a policy, recording usage without a matching policy reservation
64
+ remains blocked at renewal until the next period is configured.
65
+
66
+ ## Reserve before work, then commit with the ledger
67
+
68
+ Authorize the real activity in the host. Use its stable business identity for
69
+ `sourceEventId`, original occurrence time, and exact unit quantity. Reserve the
70
+ maximum quantity the work is allowed to perform. Commit that exact quantity;
71
+ changing it requires a new, explicitly authorized operation.
72
+
73
+ ```ts
74
+ const event = {
75
+ scope: original.scope,
76
+ binding: original.binding,
77
+ sourceEventId: activity.id,
78
+ quantity: "5",
79
+ occurredAt: activity.occurredAt,
80
+ };
81
+ const reservation = await stripe.usage.reserveAllowance(ctx, {
82
+ event,
83
+ subscription: original.subscription,
84
+ });
85
+ if (reservation.state === "denied") {
86
+ return { allowed: false, reason: reservation.reason };
87
+ }
88
+ if (reservation.state === "released") {
89
+ return { allowed: false, reason: "work_previously_released" };
90
+ }
91
+ if (reservation.state === "reserved") {
92
+ // The worker must deduplicate real work using activity.id across retries.
93
+ await performIdempotentWork(activity.id);
94
+ }
95
+ const receipt = await stripe.usage.record(ctx, {
96
+ event,
97
+ subscription: original.subscription,
98
+ reservationId: reservation.reservationId,
99
+ });
100
+ ```
101
+
102
+ Reserve and record must run from a context that supports component mutations.
103
+ External work belongs in an action or durable worker. A query used to render a
104
+ button never grants permission to run work. Concurrent reservations update the
105
+ same counter transactionally, and hard-cap decisions include both consumed and
106
+ reserved units. Ledger acceptance commits the reservation, immutable event and
107
+ outbox in one transaction. A failed transaction rolls all of them back.
108
+
109
+ Exact reservation and record retries return their prior result. Changed quantity,
110
+ price, subscription, occurrence time or source identity conflicts. A committed
111
+ reservation must not run work again. A released reservation stays released.
112
+ Historical source identities remain reserved across periods and subscriptions.
113
+
114
+ A timeout or unknown worker result retains reserved capacity. Confirm work did
115
+ not happen before releasing it. There is no automatic lease expiry that could
116
+ admit a second job while the original job still runs.
117
+
118
+ ```ts
119
+ await stripe.usage.releaseAllowance(ctx, {
120
+ scope: original.scope,
121
+ reservationId: reservation.reservationId,
122
+ reason: "work_failed", // or "abandoned_before_work"
123
+ });
124
+ ```
125
+
126
+ Release retries with the same reason are idempotent. A different reason conflicts.
127
+ Committed usage cannot be released. Delivery rejection, uncertainty, delayed
128
+ native aggregates or an unpaid invoice do not restore allowance. Corrections
129
+ retain the original event and terms and require an auditable correction outcome;
130
+ never decrement counters based on an invoice preview or an optimistic UI action.
131
+ The correction workflow is documented separately as it becomes available.
132
+
133
+ ## Edit access policy without resetting consumption
134
+
135
+ Read `getAllowanceStatus` and pass its `revision` as `expectedRevision` when changing
136
+ limits or entitlement. An exact policy replay returns the current revision;
137
+ a different policy with a stale revision fails. Cap and entitlement changes keep
138
+ all consumed and reserved units. Lowering a cap below those units denies new work.
139
+ Already reserved work retains its original authorization and can commit once,
140
+ even after entitlement is disabled or the cap is lowered. To cancel that work,
141
+ stop the worker and explicitly release its uncommitted reservation.
142
+
143
+ ```ts
144
+ const status = await stripe.usage.getAllowanceStatus(ctx, original);
145
+ if (status) {
146
+ await stripe.usage.configureAllowance(ctx, {
147
+ ...original,
148
+ expectedRevision: status.revision,
149
+ policy: { ...status.policy, entitled: false },
150
+ });
151
+ }
152
+ ```
153
+
154
+ A new verified billing period gets a new counter. Historical counters and
155
+ reservations remain readable. A late reservation from a closing or old period
156
+ cannot become current-period usage. New acceptance closes 60 seconds before the
157
+ native period ends, matching the managed delivery lifecycle.
158
+
159
+ ## Read status, evidence and reconciliation
160
+
161
+ `getAllowanceStatus(ctx, original)` returns `null` for an unavailable exact binding.
162
+ Otherwise it returns revision, observation time, period, policy, consumed and
163
+ reserved quantities, free units remaining after reservations, committed billable
164
+ overage, soft-limit state and remaining hard-cap capacity. `accepting` also
165
+ checks the current stored managed enrollment and closes on retirement or expiry.
166
+ It is a display observation; only a successful atomic reservation permits work.
167
+ Refresh the managed subscription through its native observation API when provider
168
+ state changes. A cached database view cannot prove a newly changed native state.
169
+
170
+ `committedEstimate` prices only committed usage. `projectedEstimate` also includes
171
+ reservations. Both use the original rate and exact decimal minor currency units.
172
+ They exclude fixed fees, tax, discounts and payment collection. The result always
173
+ reports `cashCollection: "none"`. Do not render estimates as available money,
174
+ paid invoices or seller/affiliate earnings.
175
+
176
+ ```ts
177
+ const local = await stripe.usage.reconcileAllowance(ctx, original);
178
+ const page = await stripe.usage.readAllowanceHistory(ctx, {
179
+ ...original,
180
+ limit: 25,
181
+ cursor: null,
182
+ });
183
+ ```
184
+
185
+ The history reader pages immutable policy, reservation, commit and release evidence
186
+ for the exact binding. Limits are 1–100 rows, with a returned cursor. Evidence is
187
+ retained, with a quota of 100000 history records per period. Accounting mutations
188
+ fail atomically when that retained quota is exhausted.
189
+
190
+ `reconcileAllowance` compares the counter with immutable accepted events and open
191
+ reservations. It returns `matched` only with complete matching local evidence.
192
+ The read is bounded to 500 events and 500 open reservations; larger or conflicting
193
+ histories return `held`, never a false match. It does not repair or restore units.
194
+ Stop new work and investigate a held result through the paged ledger/history
195
+ readers. Native quantity/invoice comparison remains available through
196
+ `getReconciliation`, `getProviderUsage` and `readInvoiceUsage`; those observations do
197
+ not enforce or reset access caps. A native invoice's payment status cannot prove
198
+ new cash collection on its own.
199
+
200
+ ## Developer and agent setup checklist
201
+
202
+ 1. Use an ordinary Stripe test sandbox. No Metronome account or token is needed.
203
+ 2. Follow [sandbox setup](./metering-setup.md), then provision the native catalog
204
+ and managed subscription with the package APIs. Keep secret keys server-side.
205
+ 3. Select the included plan or an optional pay-as-you-go limit. Choose explicit
206
+ entitlement, reset, no-rollover, overage and hard/soft threshold policy.
207
+ 4. Configure each current binding before accepting usage. Observe native renewal,
208
+ then initialize the next period before running more work.
209
+ 5. Authorize activities, reserve, perform idempotent work and record the same
210
+ original event. Start the existing durable delivery workflow for its outbox.
211
+ 6. Expose scoped status/history queries and authorized policy commands. Handle
212
+ denied, released, committed and unknown work states explicitly.
213
+ 7. Test competing last-capacity requests, replay, failed work, policy revision
214
+ conflicts, renewal and stale UI. Compare accounting and native observations
215
+ without turning lag into permission to grant additional units.
216
+
217
+ Native pricing reference: [Stripe usage-based pricing models](https://docs.stripe.com/billing/subscriptions/usage-based/pricing-models).
package/docs/webhooks.md CHANGED
@@ -144,7 +144,11 @@ interface SyncTriggers {
144
144
  subscription?: {
145
145
  onCreate?: (ctx, doc) => Promise<void>;
146
146
  onUpdate?: (ctx, newDoc, oldDoc) => Promise<void>;
147
- onDelete?: (ctx, doc) => Promise<void>;
147
+ onDelete?: (
148
+ ctx,
149
+ doc,
150
+ oldDoc?: StripeComponentSubscription | null,
151
+ ) => Promise<void>;
148
152
  };
149
153
  checkoutSession?: {
150
154
  onCompleted?: (ctx, doc) => Promise<void>;
@@ -179,6 +183,16 @@ interface SyncTriggers {
179
183
  }
180
184
  ```
181
185
 
186
+ `subscription.onDelete` receives the resulting canceled mirror as argument two
187
+ and its exact unique pre-upsert document as argument three, in the same
188
+ transaction. Confirmed absence is `null`. The third argument is optional to
189
+ preserve two-argument consumers and legacy callers; `undefined` does not certify
190
+ absence. Duplicate cached identities reject before upsert, and a missing or
191
+ ambiguous resulting row also rejects. Callback failures roll back both mirror
192
+ and host writes. Metadata can locate host scopes to invalidate; it never proves
193
+ original purchase provenance. With no delete callback, mirror-only behavior is
194
+ unchanged.
195
+
182
196
  ### AsyncHooks
183
197
 
184
198
  Async hooks run after the component's database write commits, in a separate scheduled action. Use these for external API calls (email, Slack, analytics). Failures do not roll back the component write.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fantastic.dev/better-stripe",
3
- "version": "0.56.0",
3
+ "version": "0.58.0",
4
4
  "description": "A Convex component for Stripe V2 Accounts API integration.",
5
5
  "keywords": [
6
6
  "stripe",
@@ -106,6 +106,8 @@
106
106
  "docs/usage-delivery.md",
107
107
  "docs/usage-observations.md",
108
108
  "docs/usage-subscriptions.md",
109
+ "docs/usage-credits.md",
110
+ "docs/usage-limits.md",
109
111
  "docs/evidence/native-metering"
110
112
  ],
111
113
  "scripts": {
@@ -282,3 +282,43 @@ it.each(["o".repeat(300), " opaque owner "])(
282
282
  ]);
283
283
  },
284
284
  );
285
+
286
+ type QualifiedStatus =
287
+ | "requires_payment_method"
288
+ | "requires_confirmation"
289
+ | "requires_action"
290
+ | "processing"
291
+ | "canceled"
292
+ | "succeeded";
293
+
294
+ it.each<QualifiedStatus>([
295
+ "requires_payment_method",
296
+ "requires_confirmation",
297
+ "requires_action",
298
+ "processing",
299
+ "canceled",
300
+ "succeeded",
301
+ ])("returns the closed public status contract for %s", async (status) => {
302
+ const f = fixture();
303
+ f.setup.status = status;
304
+ const observation = await f.client.getSetupIntentFromStripe(f.ctx, f.opts);
305
+ const qualified: QualifiedStatus = observation.status;
306
+ expect(qualified).toBe(status);
307
+ expect(f.requests).toEqual([
308
+ { method: "GET", path: "/v1/setup_intents/seti_original" },
309
+ ]);
310
+ expect(f.realms).toEqual([null]);
311
+ expect("clientSecret" in observation).toBe(status.startsWith("requires_"));
312
+ });
313
+
314
+ it.each([null, undefined, 42, {}, [], "unknown", "toString", "__proto__"])(
315
+ "rejects malformed or unrecognized provider status %j",
316
+ async (status) => {
317
+ const f = fixture();
318
+ Object.assign(f.setup, { status });
319
+ await expect(
320
+ f.client.getSetupIntentFromStripe(f.ctx, f.opts),
321
+ ).rejects.toThrow(/original request/);
322
+ expect(f.requests).toHaveLength(1);
323
+ },
324
+ );
@@ -11,11 +11,32 @@ export type SetupIntentReadOptions = {
11
11
  usage: "on_session" | "off_session";
12
12
  };
13
13
 
14
+ const observationStatuses = {
15
+ requires_payment_method: true,
16
+ requires_confirmation: true,
17
+ requires_action: true,
18
+ processing: true,
19
+ canceled: true,
20
+ succeeded: true,
21
+ };
22
+
23
+ /** Statuses qualified by the exact SetupIntent reader, independent of Stripe's open union. */
24
+ export type SetupIntentObservationStatus = keyof typeof observationStatuses;
25
+
26
+ function isObservationStatus(
27
+ value: unknown,
28
+ ): value is SetupIntentObservationStatus {
29
+ return (
30
+ typeof value === "string" &&
31
+ Object.prototype.hasOwnProperty.call(observationStatuses, value)
32
+ );
33
+ }
34
+
14
35
  export type SetupIntentObservation = {
15
36
  setupIntentId: string;
16
37
  customerAccount: string;
17
38
  usage: "on_session" | "off_session";
18
- status: Stripe.SetupIntent.Status;
39
+ status: SetupIntentObservationStatus;
19
40
  /** Present only for an incomplete confirmation. Never persist or log it. */
20
41
  clientSecret?: string;
21
42
  /** Time of this provider observation, in Unix milliseconds. */
@@ -68,14 +89,7 @@ export async function getSetupIntentFromStripe(
68
89
  setup.customer_account !== opts.customerAccount ||
69
90
  setup.metadata?.userId !== opts.userId ||
70
91
  setup.usage !== opts.usage ||
71
- ![
72
- "requires_payment_method",
73
- "requires_confirmation",
74
- "requires_action",
75
- "processing",
76
- "canceled",
77
- "succeeded",
78
- ].includes(setup.status)
92
+ !isObservationStatus(setup.status)
79
93
  )
80
94
  throw new Error("SetupIntent does not match the original request.");
81
95
  const isIncomplete = [