@fantastic.dev/better-stripe 0.54.0 → 0.56.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 (282) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +3 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +264 -8
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +132 -4
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +264 -8
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +132 -4
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/index.d.ts +9 -0
  12. package/dist/client/index.d.ts.map +1 -1
  13. package/dist/client/index.js +1 -0
  14. package/dist/client/index.js.map +1 -1
  15. package/dist/client/usage/catalogPrices.d.ts +2 -0
  16. package/dist/client/usage/catalogPrices.d.ts.map +1 -1
  17. package/dist/client/usage/catalogPrices.js +15 -0
  18. package/dist/client/usage/catalogPrices.js.map +1 -1
  19. package/dist/client/usage/client.d.ts +2 -2
  20. package/dist/client/usage/client.d.ts.map +1 -1
  21. package/dist/client/usage/client.js +2 -2
  22. package/dist/client/usage/client.js.map +1 -1
  23. package/dist/client/usage/deliveryProvider.d.ts.map +1 -1
  24. package/dist/client/usage/deliveryProvider.js +26 -1
  25. package/dist/client/usage/deliveryProvider.js.map +1 -1
  26. package/dist/client/usage/index.d.ts +9 -0
  27. package/dist/client/usage/index.d.ts.map +1 -1
  28. package/dist/client/usage/index.js +1 -0
  29. package/dist/client/usage/index.js.map +1 -1
  30. package/dist/client/usage/invoiceObservation.d.ts +38 -0
  31. package/dist/client/usage/invoiceObservation.d.ts.map +1 -0
  32. package/dist/client/usage/invoiceObservation.js +157 -0
  33. package/dist/client/usage/invoiceObservation.js.map +1 -0
  34. package/dist/client/usage/observationClient.d.ts +83 -0
  35. package/dist/client/usage/observationClient.d.ts.map +1 -0
  36. package/dist/client/usage/observationClient.js +157 -0
  37. package/dist/client/usage/observationClient.js.map +1 -0
  38. package/dist/client/usage/observationTypes.d.ts +63 -0
  39. package/dist/client/usage/observationTypes.d.ts.map +1 -0
  40. package/dist/client/usage/observationTypes.js +59 -0
  41. package/dist/client/usage/observationTypes.js.map +1 -0
  42. package/dist/client/usage/providerObservation.d.ts +4 -0
  43. package/dist/client/usage/providerObservation.d.ts.map +1 -0
  44. package/dist/client/usage/providerObservation.js +96 -0
  45. package/dist/client/usage/providerObservation.js.map +1 -0
  46. package/dist/client/usage/reconciliation.d.ts +12 -0
  47. package/dist/client/usage/reconciliation.d.ts.map +1 -0
  48. package/dist/client/usage/reconciliation.js +48 -0
  49. package/dist/client/usage/reconciliation.js.map +1 -0
  50. package/dist/client/usage/subscription.fixtures.d.ts +118 -0
  51. package/dist/client/usage/subscription.fixtures.d.ts.map +1 -0
  52. package/dist/client/usage/subscription.fixtures.js +84 -0
  53. package/dist/client/usage/subscription.fixtures.js.map +1 -0
  54. package/dist/client/usage/subscriptionAbandonment.d.ts +8 -0
  55. package/dist/client/usage/subscriptionAbandonment.d.ts.map +1 -0
  56. package/dist/client/usage/subscriptionAbandonment.js +82 -0
  57. package/dist/client/usage/subscriptionAbandonment.js.map +1 -0
  58. package/dist/client/usage/subscriptionCancellation.d.ts +9 -0
  59. package/dist/client/usage/subscriptionCancellation.d.ts.map +1 -0
  60. package/dist/client/usage/subscriptionCancellation.js +39 -0
  61. package/dist/client/usage/subscriptionCancellation.js.map +1 -0
  62. package/dist/client/usage/subscriptionCheckout.d.ts +52 -0
  63. package/dist/client/usage/subscriptionCheckout.d.ts.map +1 -0
  64. package/dist/client/usage/subscriptionCheckout.js +94 -0
  65. package/dist/client/usage/subscriptionCheckout.js.map +1 -0
  66. package/dist/client/usage/subscriptionClient.d.ts +267 -0
  67. package/dist/client/usage/subscriptionClient.d.ts.map +1 -0
  68. package/dist/client/usage/subscriptionClient.js +93 -0
  69. package/dist/client/usage/subscriptionClient.js.map +1 -0
  70. package/dist/client/usage/subscriptionErrors.d.ts +5 -0
  71. package/dist/client/usage/subscriptionErrors.d.ts.map +1 -0
  72. package/dist/client/usage/subscriptionErrors.js +9 -0
  73. package/dist/client/usage/subscriptionErrors.js.map +1 -0
  74. package/dist/client/usage/subscriptionInvoiceSchema.d.ts +203 -0
  75. package/dist/client/usage/subscriptionInvoiceSchema.d.ts.map +1 -0
  76. package/dist/client/usage/subscriptionInvoiceSchema.js +108 -0
  77. package/dist/client/usage/subscriptionInvoiceSchema.js.map +1 -0
  78. package/dist/client/usage/subscriptionLifecycle.d.ts +80 -0
  79. package/dist/client/usage/subscriptionLifecycle.d.ts.map +1 -0
  80. package/dist/client/usage/subscriptionLifecycle.js +87 -0
  81. package/dist/client/usage/subscriptionLifecycle.js.map +1 -0
  82. package/dist/client/usage/subscriptionProvider.d.ts +111 -0
  83. package/dist/client/usage/subscriptionProvider.d.ts.map +1 -0
  84. package/dist/client/usage/subscriptionProvider.js +147 -0
  85. package/dist/client/usage/subscriptionProvider.js.map +1 -0
  86. package/dist/client/usage/subscriptionTerms.d.ts +161 -0
  87. package/dist/client/usage/subscriptionTerms.d.ts.map +1 -0
  88. package/dist/client/usage/subscriptionTerms.js +242 -0
  89. package/dist/client/usage/subscriptionTerms.js.map +1 -0
  90. package/dist/client/usage/subscriptionTransport.fixtures.d.ts +25 -0
  91. package/dist/client/usage/subscriptionTransport.fixtures.d.ts.map +1 -0
  92. package/dist/client/usage/subscriptionTransport.fixtures.js +203 -0
  93. package/dist/client/usage/subscriptionTransport.fixtures.js.map +1 -0
  94. package/dist/client/usage/summary.d.ts +50 -0
  95. package/dist/client/usage/summary.d.ts.map +1 -0
  96. package/dist/client/usage/summary.js +110 -0
  97. package/dist/client/usage/summary.js.map +1 -0
  98. package/dist/client/webhooks/processors.d.ts.map +1 -1
  99. package/dist/client/webhooks/processors.js +2 -0
  100. package/dist/client/webhooks/processors.js.map +1 -1
  101. package/dist/client/webhooks/usageSubscriptions.d.ts +5 -0
  102. package/dist/client/webhooks/usageSubscriptions.d.ts.map +1 -0
  103. package/dist/client/webhooks/usageSubscriptions.js +54 -0
  104. package/dist/client/webhooks/usageSubscriptions.js.map +1 -0
  105. package/dist/component/_generated/api.d.ts +22 -0
  106. package/dist/component/_generated/api.d.ts.map +1 -1
  107. package/dist/component/_generated/api.js.map +1 -1
  108. package/dist/component/_generated/component.d.ts +255 -5
  109. package/dist/component/_generated/component.d.ts.map +1 -1
  110. package/dist/component/accountClosure/mutations.d.ts.map +1 -1
  111. package/dist/component/accountClosure/mutations.js +10 -0
  112. package/dist/component/accountClosure/mutations.js.map +1 -1
  113. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  114. package/dist/component/balanceFunding/mutations.d.ts +16 -16
  115. package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
  116. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  117. package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
  118. package/dist/component/earnings/triggers.d.ts +296 -22
  119. package/dist/component/earnings/triggers.d.ts.map +1 -1
  120. package/dist/component/payoutRelease/queries.d.ts +2 -2
  121. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  122. package/dist/component/refundHistory/queries.d.ts +1 -1
  123. package/dist/component/schema.d.ts +132 -4
  124. package/dist/component/schema.js +8 -0
  125. package/dist/component/schema.js.map +1 -1
  126. package/dist/component/usage/mutations.d.ts.map +1 -1
  127. package/dist/component/usage/mutations.js +5 -0
  128. package/dist/component/usage/mutations.js.map +1 -1
  129. package/dist/component/usage/queries.d.ts +2 -0
  130. package/dist/component/usage/queries.d.ts.map +1 -1
  131. package/dist/component/usage/schema.d.ts +21 -9
  132. package/dist/component/usage/schema.d.ts.map +1 -1
  133. package/dist/component/usage/schema.js +5 -1
  134. package/dist/component/usage/schema.js.map +1 -1
  135. package/dist/component/usageDelivery/fields.d.ts +4 -2
  136. package/dist/component/usageDelivery/fields.d.ts.map +1 -1
  137. package/dist/component/usageDelivery/fields.js +3 -1
  138. package/dist/component/usageDelivery/fields.js.map +1 -1
  139. package/dist/component/usageDelivery/helpers.d.ts +5 -3
  140. package/dist/component/usageDelivery/helpers.d.ts.map +1 -1
  141. package/dist/component/usageDelivery/mutations.d.ts +3 -3
  142. package/dist/component/usageDelivery/mutations.d.ts.map +1 -1
  143. package/dist/component/usageDelivery/mutations.js +8 -1
  144. package/dist/component/usageDelivery/mutations.js.map +1 -1
  145. package/dist/component/usageDelivery/queries.d.ts +19 -3
  146. package/dist/component/usageDelivery/queries.d.ts.map +1 -1
  147. package/dist/component/usageDelivery/queries.js +20 -3
  148. package/dist/component/usageDelivery/queries.js.map +1 -1
  149. package/dist/component/usageDelivery/schema.d.ts +2 -2
  150. package/dist/component/usageDelivery/steps.d.ts +1 -1
  151. package/dist/component/usageDelivery/steps.d.ts.map +1 -1
  152. package/dist/component/usageDelivery/steps.js +20 -2
  153. package/dist/component/usageDelivery/steps.js.map +1 -1
  154. package/dist/component/usageObservations/helpers.d.ts +38 -0
  155. package/dist/component/usageObservations/helpers.d.ts.map +1 -0
  156. package/dist/component/usageObservations/helpers.js +80 -0
  157. package/dist/component/usageObservations/helpers.js.map +1 -0
  158. package/dist/component/usageObservations/history.d.ts +6 -0
  159. package/dist/component/usageObservations/history.d.ts.map +1 -0
  160. package/dist/component/usageObservations/history.js +29 -0
  161. package/dist/component/usageObservations/history.js.map +1 -0
  162. package/dist/component/usageObservations/mutations.d.ts +6 -0
  163. package/dist/component/usageObservations/mutations.d.ts.map +1 -0
  164. package/dist/component/usageObservations/mutations.js +39 -0
  165. package/dist/component/usageObservations/mutations.js.map +1 -0
  166. package/dist/component/usageObservations/queries.d.ts +78 -0
  167. package/dist/component/usageObservations/queries.d.ts.map +1 -0
  168. package/dist/component/usageObservations/queries.js +131 -0
  169. package/dist/component/usageObservations/queries.js.map +1 -0
  170. package/dist/component/usageObservations/schema.d.ts +72 -0
  171. package/dist/component/usageObservations/schema.d.ts.map +1 -0
  172. package/dist/component/usageObservations/schema.js +29 -0
  173. package/dist/component/usageObservations/schema.js.map +1 -0
  174. package/dist/component/usageSubscriptions/abandonment.d.ts +4 -0
  175. package/dist/component/usageSubscriptions/abandonment.d.ts.map +1 -0
  176. package/dist/component/usageSubscriptions/abandonment.js +59 -0
  177. package/dist/component/usageSubscriptions/abandonment.js.map +1 -0
  178. package/dist/component/usageSubscriptions/acceptance.d.ts +11 -0
  179. package/dist/component/usageSubscriptions/acceptance.d.ts.map +1 -0
  180. package/dist/component/usageSubscriptions/acceptance.js +38 -0
  181. package/dist/component/usageSubscriptions/acceptance.js.map +1 -0
  182. package/dist/component/usageSubscriptions/helpers.d.ts +39 -0
  183. package/dist/component/usageSubscriptions/helpers.d.ts.map +1 -0
  184. package/dist/component/usageSubscriptions/helpers.js +28 -0
  185. package/dist/component/usageSubscriptions/helpers.js.map +1 -0
  186. package/dist/component/usageSubscriptions/history.d.ts +46 -0
  187. package/dist/component/usageSubscriptions/history.d.ts.map +1 -0
  188. package/dist/component/usageSubscriptions/history.js +46 -0
  189. package/dist/component/usageSubscriptions/history.js.map +1 -0
  190. package/dist/component/usageSubscriptions/mutations.d.ts +64 -0
  191. package/dist/component/usageSubscriptions/mutations.d.ts.map +1 -0
  192. package/dist/component/usageSubscriptions/mutations.js +252 -0
  193. package/dist/component/usageSubscriptions/mutations.js.map +1 -0
  194. package/dist/component/usageSubscriptions/queries.d.ts +81 -0
  195. package/dist/component/usageSubscriptions/queries.d.ts.map +1 -0
  196. package/dist/component/usageSubscriptions/queries.js +70 -0
  197. package/dist/component/usageSubscriptions/queries.js.map +1 -0
  198. package/dist/component/usageSubscriptions/retirement.d.ts +4 -0
  199. package/dist/component/usageSubscriptions/retirement.d.ts.map +1 -0
  200. package/dist/component/usageSubscriptions/retirement.js +80 -0
  201. package/dist/component/usageSubscriptions/retirement.js.map +1 -0
  202. package/dist/component/usageSubscriptions/schema.d.ts +191 -0
  203. package/dist/component/usageSubscriptions/schema.d.ts.map +1 -0
  204. package/dist/component/usageSubscriptions/schema.js +69 -0
  205. package/dist/component/usageSubscriptions/schema.js.map +1 -0
  206. package/dist/test.d.ts +6 -0
  207. package/dist/test.d.ts.map +1 -0
  208. package/dist/test.js +15 -0
  209. package/dist/test.js.map +1 -0
  210. package/docs/README.md +4 -0
  211. package/docs/evidence/native-metering/clock-finalization-run.json +129 -0
  212. package/docs/evidence/native-metering/clock-lag-run.json +111 -0
  213. package/docs/evidence/native-metering/paid-run.json +107 -0
  214. package/docs/evidence/native-metering/promotional-run.json +103 -0
  215. package/docs/metered-usage.md +14 -0
  216. package/docs/metering-setup.md +7 -1
  217. package/docs/usage-observations.md +152 -0
  218. package/docs/usage-subscriptions.md +278 -0
  219. package/package.json +5 -2
  220. package/src/client/index.ts +26 -0
  221. package/src/client/usage/catalogPrices.ts +21 -0
  222. package/src/client/usage/client.ts +2 -2
  223. package/src/client/usage/deliveryProvider.test.ts +70 -1
  224. package/src/client/usage/deliveryProvider.ts +43 -2
  225. package/src/client/usage/index.ts +27 -0
  226. package/src/client/usage/invoiceObservation.test.ts +195 -0
  227. package/src/client/usage/invoiceObservation.ts +203 -0
  228. package/src/client/usage/observationClient.ts +233 -0
  229. package/src/client/usage/observationTypes.ts +101 -0
  230. package/src/client/usage/providerObservation.test.ts +207 -0
  231. package/src/client/usage/providerObservation.ts +124 -0
  232. package/src/client/usage/reconciliation.test.ts +117 -0
  233. package/src/client/usage/reconciliation.ts +86 -0
  234. package/src/client/usage/subscription.fixtures.ts +84 -0
  235. package/src/client/usage/subscriptionAbandonment.test.ts +124 -0
  236. package/src/client/usage/subscriptionAbandonment.ts +116 -0
  237. package/src/client/usage/subscriptionCancellation.ts +90 -0
  238. package/src/client/usage/subscriptionCheckout.test.ts +31 -0
  239. package/src/client/usage/subscriptionCheckout.ts +152 -0
  240. package/src/client/usage/subscriptionClient.test.ts +316 -0
  241. package/src/client/usage/subscriptionClient.ts +204 -0
  242. package/src/client/usage/subscriptionErrors.ts +14 -0
  243. package/src/client/usage/subscriptionInvoiceSchema.ts +116 -0
  244. package/src/client/usage/subscriptionLifecycle.ts +165 -0
  245. package/src/client/usage/subscriptionProvider.test.ts +48 -0
  246. package/src/client/usage/subscriptionProvider.ts +247 -0
  247. package/src/client/usage/subscriptionTerms.test.ts +158 -0
  248. package/src/client/usage/subscriptionTerms.ts +294 -0
  249. package/src/client/usage/subscriptionTransport.fixtures.ts +241 -0
  250. package/src/client/usage/summary.test.ts +222 -0
  251. package/src/client/usage/summary.ts +188 -0
  252. package/src/client/webhooks/processors.ts +2 -0
  253. package/src/client/webhooks/usageSubscriptions.test.ts +162 -0
  254. package/src/client/webhooks/usageSubscriptions.ts +81 -0
  255. package/src/component/_generated/api.ts +22 -0
  256. package/src/component/_generated/component.ts +335 -0
  257. package/src/component/accountClosure/mutations.ts +12 -0
  258. package/src/component/schema.ts +16 -0
  259. package/src/component/usage/mutations.ts +5 -0
  260. package/src/component/usage/schema.ts +5 -1
  261. package/src/component/usageDelivery/fields.ts +3 -0
  262. package/src/component/usageDelivery/mutations.ts +26 -1
  263. package/src/component/usageDelivery/queries.ts +30 -3
  264. package/src/component/usageDelivery/steps.ts +61 -2
  265. package/src/component/usageObservations/helpers.ts +95 -0
  266. package/src/component/usageObservations/history.test.ts +87 -0
  267. package/src/component/usageObservations/history.ts +39 -0
  268. package/src/component/usageObservations/mutations.ts +39 -0
  269. package/src/component/usageObservations/queries.test.ts +162 -0
  270. package/src/component/usageObservations/queries.ts +145 -0
  271. package/src/component/usageObservations/schema.ts +40 -0
  272. package/src/component/usageSubscriptions/abandonment.ts +80 -0
  273. package/src/component/usageSubscriptions/acceptance.test.ts +122 -0
  274. package/src/component/usageSubscriptions/acceptance.ts +66 -0
  275. package/src/component/usageSubscriptions/helpers.ts +33 -0
  276. package/src/component/usageSubscriptions/history.test.ts +69 -0
  277. package/src/component/usageSubscriptions/history.ts +68 -0
  278. package/src/component/usageSubscriptions/mutations.test.ts +205 -0
  279. package/src/component/usageSubscriptions/mutations.ts +275 -0
  280. package/src/component/usageSubscriptions/queries.ts +78 -0
  281. package/src/component/usageSubscriptions/retirement.ts +105 -0
  282. package/src/component/usageSubscriptions/schema.ts +73 -0
@@ -0,0 +1,116 @@
1
+ import { z } from "zod";
2
+ const id = z.string().min(1).max(100),
3
+ seconds = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
4
+ const integer = z.string().regex(/^-?\d{1,30}$/),
5
+ decimal = z.string().regex(/^\d{1,30}(\.\d{1,18})?$/);
6
+ const currency = z.string().regex(/^[a-z]{3}$/);
7
+ const unavailable = z.strictObject({
8
+ status: z.enum(["unavailable", "unsupported"]),
9
+ reason: z.enum([
10
+ "provider_binding_mismatch",
11
+ "invoice_binding_mismatch",
12
+ "invoice_unavailable",
13
+ "unsupported_scope",
14
+ "invoice_history_incomplete",
15
+ "ambiguous_invoice_items",
16
+ "metered_lines_not_observed",
17
+ ]),
18
+ retryable: z.boolean(),
19
+ });
20
+ const meterAmount = z.union([
21
+ unavailable,
22
+ z.strictObject({
23
+ status: z.literal("available"),
24
+ observedAt: seconds,
25
+ value: z.strictObject({ amount: integer, currency }),
26
+ }),
27
+ ]);
28
+ export const managedInvoiceObservationSchema = z.union([
29
+ unavailable,
30
+ z.strictObject({
31
+ status: z.literal("available"),
32
+ observedAt: seconds,
33
+ value: z.strictObject({
34
+ kind: z.literal("invoice"),
35
+ invoiceId: id,
36
+ status: z.enum(["draft", "open", "paid", "void", "uncollectible"]),
37
+ finalized: z.boolean(),
38
+ amountDue: integer,
39
+ amountPaid: integer,
40
+ total: integer,
41
+ currency,
42
+ linesComplete: z.boolean(),
43
+ paymentEvidence: z.literal("not_resolved"),
44
+ meterAmount,
45
+ lines: z
46
+ .array(
47
+ z.strictObject({
48
+ lineId: id,
49
+ stripePriceId: id,
50
+ subscriptionItemId: id,
51
+ amount: integer,
52
+ currency,
53
+ quantity: decimal.nullable(),
54
+ providerQuantityDecimal: decimal.nullable(),
55
+ unitAmountDecimal: decimal.nullable(),
56
+ creditAppliedAmount: integer,
57
+ nativePeriod: z.strictObject({ start: seconds, end: seconds }),
58
+ proration: z.boolean(),
59
+ }),
60
+ )
61
+ .max(100),
62
+ }),
63
+ }),
64
+ ]);
65
+ export const managedInvoiceSchema = z
66
+ .array(
67
+ z.strictObject({
68
+ meterId: id,
69
+ subscriptionItemId: id,
70
+ observation: managedInvoiceObservationSchema,
71
+ }),
72
+ )
73
+ .min(1)
74
+ .max(10);
75
+ export type UsageSubscriptionInvoice = z.infer<typeof managedInvoiceSchema>;
76
+
77
+ export const retirementProof = z.strictObject({
78
+ invoiceId: id,
79
+ stripeAccountId: id,
80
+ customerAccount: id,
81
+ stripeCustomerId: id,
82
+ livemode: z.boolean(),
83
+ subscriptionId: id,
84
+ status: z.enum(["open", "paid", "uncollectible"]),
85
+ finalizedAt: seconds,
86
+ billingReason: z.literal("subscription_cycle"),
87
+ periodEnd: seconds,
88
+ });
89
+
90
+ const abandonmentCommon = {
91
+ stripeAccountId: id,
92
+ customerAccount: id,
93
+ stripeCustomerId: id,
94
+ livemode: z.boolean(),
95
+ nativeId: id,
96
+ };
97
+ export const abandonmentProof = z.discriminatedUnion("kind", [
98
+ z.strictObject({
99
+ ...abandonmentCommon,
100
+ kind: z.literal("checkout"),
101
+ status: z.literal("expired"),
102
+ subscription: z.null(),
103
+ paymentIntent: z.null(),
104
+ setupIntent: z.null(),
105
+ paymentStatus: z.enum(["unpaid", "no_payment_required"]),
106
+ }),
107
+ z.strictObject({
108
+ ...abandonmentCommon,
109
+ kind: z.literal("subscription"),
110
+ status: z.literal("incomplete_expired"),
111
+ invoiceId: id,
112
+ invoiceStatus: z.literal("void"),
113
+ invoiceAmountPaid: z.literal("0"),
114
+ billingReason: z.literal("subscription_create"),
115
+ }),
116
+ ]);
@@ -0,0 +1,165 @@
1
+ import { retirementProof } from "./subscriptionInvoiceSchema.js";
2
+ import type Stripe from "stripe";
3
+ import type { Component, RunCtx } from "../helpers.js";
4
+ import { runMutationOrThrow } from "../helpers.js";
5
+ import { componentRef } from "../webhooks/helpers.js";
6
+ import type { Doc } from "../../component/_generated/dataModel.js";
7
+ import {
8
+ subscriptionScopeSchema,
9
+ subscriptionTerms,
10
+ type UsageSubscriptionView,
11
+ } from "./subscriptionTerms.js";
12
+ import {
13
+ saveSubscription,
14
+ subscriptionCall,
15
+ UsageSubscriptionError,
16
+ verifySubscriptionRealm,
17
+ } from "./subscriptionProvider.js";
18
+ import { observeUsageInvoice } from "./invoiceObservation.js";
19
+ import {
20
+ managedInvoiceSchema,
21
+ type UsageSubscriptionInvoice,
22
+ } from "./subscriptionInvoiceSchema.js";
23
+ export type UsageSubscriptionRef = {
24
+ scope: {
25
+ stripeAccountId: string;
26
+ customerAccount: string;
27
+ livemode: boolean;
28
+ };
29
+ requestId: string;
30
+ };
31
+ export async function getSubscriptionIntent(
32
+ component: Component,
33
+ ctx: RunCtx,
34
+ input: UsageSubscriptionRef,
35
+ ) {
36
+ const scope = subscriptionScopeSchema.parse(input.scope);
37
+ const row = (await ctx.runQuery(
38
+ componentRef(component, "usageSubscriptions/queries/get"),
39
+ { scope, requestId: input.requestId },
40
+ )) as Doc<"usageSubscriptionIntents"> | null;
41
+ if (!row)
42
+ throw new UsageSubscriptionError(
43
+ "incompatible_terms",
44
+ "Managed subscription scope unavailable",
45
+ );
46
+ return row;
47
+ }
48
+ export async function refreshManagedSubscription(
49
+ stripe: Stripe,
50
+ component: Component,
51
+ ctx: RunCtx,
52
+ row: Doc<"usageSubscriptionIntents">,
53
+ ) {
54
+ const terms = subscriptionTerms(JSON.parse(row.termsJson)),
55
+ startedAt = Date.now();
56
+ return subscriptionCall(async () => {
57
+ if (!row.providerId)
58
+ throw new UsageSubscriptionError(
59
+ "incompatible_terms",
60
+ "Managed subscription not yet observed",
61
+ );
62
+ await verifySubscriptionRealm(stripe, terms);
63
+ const sub = await stripe.subscriptions.retrieve(row.providerId);
64
+ if (sub.id !== row.providerId)
65
+ throw new UsageSubscriptionError(
66
+ "incompatible_terms",
67
+ "Pinned subscription identity changed",
68
+ );
69
+ return saveSubscription(component, ctx, row.key, sub, terms, startedAt);
70
+ });
71
+ }
72
+ export async function observeManagedInvoice(
73
+ stripe: Stripe,
74
+ component: Component,
75
+ ctx: RunCtx,
76
+ row: Doc<"usageSubscriptionIntents">,
77
+ invoiceId: string,
78
+ ): Promise<UsageSubscriptionInvoice> {
79
+ const startedAt = Date.now();
80
+ return subscriptionCall(async () => {
81
+ // Historical terms come from the retained snapshot, never the current price.
82
+ const view = row.viewJson
83
+ ? (JSON.parse(row.viewJson) as UsageSubscriptionView)
84
+ : await refreshManagedSubscription(stripe, component, ctx, row);
85
+ const observations = [];
86
+ for (const source of view.bindings)
87
+ observations.push({
88
+ meterId: source.scope.meterId,
89
+ subscriptionItemId: source.subscription.subscriptionItemId,
90
+ observation: await observeUsageInvoice(
91
+ stripe,
92
+ { ...source, period: source.subscription.period },
93
+ invoiceId,
94
+ ),
95
+ });
96
+ const parsed = managedInvoiceSchema.parse(observations);
97
+ await runMutationOrThrow(
98
+ ctx,
99
+ componentRef(component, "usageSubscriptions/mutations/saveInvoice"),
100
+ {
101
+ key: row.key,
102
+ invoiceId,
103
+ observationsJson: JSON.stringify(parsed),
104
+ startedAt,
105
+ },
106
+ );
107
+ return parsed;
108
+ });
109
+ }
110
+
111
+ export async function retireManagedSubscription(
112
+ stripe: Stripe,
113
+ component: Component,
114
+ ctx: RunCtx,
115
+ row: Doc<"usageSubscriptionIntents">,
116
+ invoiceId: string,
117
+ ) {
118
+ return subscriptionCall(async () => {
119
+ const view = await refreshManagedSubscription(stripe, component, ctx, row);
120
+ if (view.status !== "canceled")
121
+ throw new UsageSubscriptionError(
122
+ "incompatible_terms",
123
+ "Retirement requires native period-end cancellation",
124
+ );
125
+ const terms = subscriptionTerms(JSON.parse(row.termsJson)),
126
+ first = terms.meters[0];
127
+ const invoice = await stripe.invoices.retrieve(invoiceId);
128
+ const proof = retirementProof.parse({
129
+ invoiceId: invoice.id,
130
+ stripeAccountId: first.scope.stripeAccountId,
131
+ customerAccount: invoice.customer_account,
132
+ stripeCustomerId:
133
+ typeof invoice.customer === "string"
134
+ ? invoice.customer
135
+ : invoice.customer?.id,
136
+ livemode: invoice.livemode,
137
+ subscriptionId:
138
+ typeof invoice.parent?.subscription_details?.subscription === "string"
139
+ ? invoice.parent.subscription_details.subscription
140
+ : invoice.parent?.subscription_details?.subscription?.id,
141
+ status: invoice.status,
142
+ finalizedAt: invoice.status_transitions?.finalized_at,
143
+ billingReason: invoice.billing_reason,
144
+ periodEnd: invoice.period_end,
145
+ });
146
+ if (invoice.id !== invoiceId)
147
+ throw new UsageSubscriptionError(
148
+ "incompatible_terms",
149
+ "Native retirement invoice identity mismatch",
150
+ );
151
+ const current = { ...row, viewJson: JSON.stringify(view) };
152
+ await observeManagedInvoice(stripe, component, ctx, current, invoiceId);
153
+ await runMutationOrThrow(
154
+ ctx,
155
+ componentRef(component, "usageSubscriptions/mutations/retire"),
156
+ { key: row.key, proofJson: JSON.stringify(proof) },
157
+ );
158
+ return {
159
+ retired: true as const,
160
+ invoiceId,
161
+ creditTreatment: "retain_original_terms" as const,
162
+ billingReconciliation: "required" as const,
163
+ };
164
+ });
165
+ }
@@ -0,0 +1,48 @@
1
+ import { expect, it } from "vitest";
2
+ import type { RunCtx } from "../helpers.js";
3
+ import { ensureManagedSubscription } from "./subscriptionProvider.js";
4
+ import { request } from "./subscription.fixtures.js";
5
+ import { fixture } from "./subscriptionTransport.fixtures.js";
6
+ it("creates flexible mixed subscriptions without metered quantity and replays the pinned native identity", async () => {
7
+ const f = fixture();
8
+ const result = await f.t.action((ctx) =>
9
+ ensureManagedSubscription(f.stripe, f.component, ctx as RunCtx, request),
10
+ );
11
+ expect(result.bindings[0].subscription.subscriptionItemId).toBe("si_calls");
12
+ const writes = f.calls.filter((c) => c.method === "POST");
13
+ expect(writes).toHaveLength(1);
14
+ expect(writes[0].body.get("billing_mode[type]")).toBe("flexible");
15
+ expect(writes[0].body.get("items[0][quantity]")).toBeNull();
16
+ expect(writes[0].body.get("customer_account")).toBe("acct_buyer");
17
+ expect(writes[0].key).toMatch(/^bs_usage_sub_/);
18
+ const again = await f.t.action((ctx) =>
19
+ ensureManagedSubscription(f.stripe, f.component, ctx as RunCtx, request),
20
+ );
21
+ expect(again.subscriptionId).toBe(result.subscriptionId);
22
+ expect(f.calls.filter((c) => c.method === "POST")).toHaveLength(1);
23
+ });
24
+ it("refuses another active subscription sharing native customer/meter without creating anything", async () => {
25
+ const f = fixture(true);
26
+ await expect(
27
+ f.t.action((ctx) =>
28
+ ensureManagedSubscription(f.stripe, f.component, ctx as RunCtx, request),
29
+ ),
30
+ ).rejects.toThrow(/overlap/i);
31
+ expect(f.calls.some((c) => c.method === "POST")).toBe(false);
32
+ });
33
+ it("redacts ambiguous provider failures and retains the same durable request for recovery", async () => {
34
+ const f = fixture(false, true);
35
+ await expect(
36
+ f.t.action((ctx) =>
37
+ ensureManagedSubscription(f.stripe, f.component, ctx as RunCtx, request),
38
+ ),
39
+ ).rejects.toThrow("Native usage subscription unavailable");
40
+ await expect(
41
+ f.t.action((ctx) =>
42
+ ensureManagedSubscription(f.stripe, f.component, ctx as RunCtx, request),
43
+ ),
44
+ ).rejects.toThrow("Native usage subscription unavailable");
45
+ const writes = f.calls.filter((c) => c.method === "POST");
46
+ expect(writes).toHaveLength(2);
47
+ expect(writes[0].key).toBe(writes[1].key);
48
+ });
@@ -0,0 +1,247 @@
1
+ import type Stripe from "stripe";
2
+ import type { Component, RunCtx } from "../helpers.js";
3
+ import { runMutationOrThrow } from "../helpers.js";
4
+ import { componentRef } from "../webhooks/helpers.js";
5
+ import type { Doc } from "../../component/_generated/dataModel.js";
6
+ import { verifyRealm, verifyMeter, UsageCatalogError } from "./catalogTypes.js";
7
+ import { verifyPinnedUsagePrice } from "./catalogPrices.js";
8
+ import {
9
+ subscriptionTerms,
10
+ subscriptionEvidence,
11
+ subscriptionView,
12
+ type UsageSubscriptionTerms,
13
+ type UsageSubscriptionOptions,
14
+ } from "./subscriptionTerms.js";
15
+ import { UsageSubscriptionError } from "./subscriptionErrors.js";
16
+ export { UsageSubscriptionError } from "./subscriptionErrors.js";
17
+ export async function subscriptionCall<T>(fn: () => Promise<T>): Promise<T> {
18
+ try {
19
+ return await fn();
20
+ } catch (error) {
21
+ if (error instanceof UsageSubscriptionError) throw error;
22
+ if (
23
+ error instanceof UsageCatalogError &&
24
+ ["unsupported_scope", "incompatible_terms"].includes(error.code)
25
+ )
26
+ throw new UsageSubscriptionError(
27
+ error.code as "unsupported_scope" | "incompatible_terms",
28
+ "Native usage subscription scope or pricing is unsupported",
29
+ );
30
+ throw new UsageSubscriptionError(
31
+ "provider_unavailable",
32
+ "Native usage subscription unavailable",
33
+ );
34
+ }
35
+ }
36
+ export async function verifySubscriptionRealm(
37
+ stripe: Stripe,
38
+ terms: UsageSubscriptionTerms,
39
+ ) {
40
+ const first = terms.meters[0];
41
+ await verifyRealm(stripe, {
42
+ stripeAccountId: first.scope.stripeAccountId,
43
+ livemode: first.scope.livemode,
44
+ });
45
+ const customer = await stripe.customers.retrieve(first.scope.customerAccount);
46
+ if (
47
+ customer.deleted ||
48
+ customer.id !== first.binding.stripeCustomerId ||
49
+ customer.customer_account !== first.scope.customerAccount ||
50
+ customer.livemode !== first.scope.livemode
51
+ )
52
+ throw new UsageSubscriptionError(
53
+ "unsupported_scope",
54
+ "Native usage subscription payer mismatch",
55
+ );
56
+ }
57
+ export async function verifySubscriptionPrices(
58
+ stripe: Stripe,
59
+ terms: UsageSubscriptionTerms,
60
+ ) {
61
+ for (const { scope, binding } of terms.meters) {
62
+ const [meter, price] = await Promise.all([
63
+ stripe.billing.meters.retrieve(scope.meterId),
64
+ stripe.prices.retrieve(binding.stripePriceId, { expand: ["tiers"] }),
65
+ ]);
66
+ if (meter.id !== scope.meterId || price.id !== binding.stripePriceId)
67
+ throw new UsageSubscriptionError(
68
+ "incompatible_terms",
69
+ "Native usage subscription price mismatch",
70
+ );
71
+ verifyMeter(meter, {
72
+ scope,
73
+ plan: binding.plan,
74
+ eventName: binding.eventName,
75
+ displayName: meter.display_name,
76
+ });
77
+ verifyPinnedUsagePrice(
78
+ price,
79
+ { stripeAccountId: scope.stripeAccountId, livemode: scope.livemode },
80
+ binding.plan,
81
+ scope.meterId,
82
+ );
83
+ }
84
+ for (const id of terms.fixedPriceIds) {
85
+ const price = await stripe.prices.retrieve(id);
86
+ if (
87
+ price.id !== id ||
88
+ !price.active ||
89
+ price.livemode !== terms.meters[0].scope.livemode ||
90
+ price.currency !== terms.meters[0].binding.plan.rate.currency ||
91
+ price.recurring?.interval !== "month" ||
92
+ price.recurring.interval_count !== 1 ||
93
+ price.recurring.usage_type !== "licensed" ||
94
+ price.transform_quantity != null ||
95
+ price.billing_scheme !== "per_unit" ||
96
+ !Number.isSafeInteger(price.unit_amount)
97
+ )
98
+ throw new UsageSubscriptionError(
99
+ "incompatible_terms",
100
+ "Native fixed subscription price is unsupported",
101
+ );
102
+ }
103
+ }
104
+ export async function discoverSubscription(
105
+ stripe: Stripe,
106
+ terms: UsageSubscriptionTerms,
107
+ key: string,
108
+ ) {
109
+ let cursor: string | undefined, found: Stripe.Subscription | undefined;
110
+ for (let page = 0; page < 10; page++) {
111
+ const result = await stripe.subscriptions.list({
112
+ customer_account: terms.meters[0].scope.customerAccount,
113
+ status: "all",
114
+ limit: 100,
115
+ ...(cursor ? { starting_after: cursor } : {}),
116
+ });
117
+ if (result.data.length > 100)
118
+ throw new UsageSubscriptionError(
119
+ "incompatible_terms",
120
+ "Native subscription inventory exceeds page budget",
121
+ );
122
+ for (const sub of result.data) {
123
+ if (
124
+ sub.customer_account !== terms.meters[0].scope.customerAccount ||
125
+ sub.livemode !== terms.meters[0].scope.livemode ||
126
+ sub.items.has_more
127
+ )
128
+ throw new UsageSubscriptionError(
129
+ "incompatible_terms",
130
+ "Native subscription inventory is incomplete or mismatched",
131
+ );
132
+ if (sub.metadata?.bsUsageIntent === key) {
133
+ if (found)
134
+ throw new UsageSubscriptionError(
135
+ "overlapping_enrollment",
136
+ "Duplicate native usage subscription identity",
137
+ );
138
+ found = sub;
139
+ } else if (
140
+ !["canceled", "incomplete_expired"].includes(sub.status) &&
141
+ sub.items.data.some((item) =>
142
+ terms.meters.some(
143
+ (meter) => item.price.recurring?.meter === meter.scope.meterId,
144
+ ),
145
+ )
146
+ )
147
+ throw new UsageSubscriptionError(
148
+ "overlapping_enrollment",
149
+ "Native customer/meter subscription overlap",
150
+ );
151
+ }
152
+ if (!result.has_more) return found;
153
+ const next = result.data[result.data.length - 1]?.id;
154
+ if (!next || next === cursor) break;
155
+ cursor = next;
156
+ }
157
+ throw new UsageSubscriptionError(
158
+ "incompatible_terms",
159
+ "Native subscription inventory exceeds bounded history",
160
+ );
161
+ }
162
+ export async function saveSubscription(
163
+ component: Component,
164
+ ctx: RunCtx,
165
+ key: string,
166
+ native: Stripe.Subscription,
167
+ terms: UsageSubscriptionTerms,
168
+ startedAt: number,
169
+ ) {
170
+ const evidence = subscriptionEvidence(native),
171
+ view = subscriptionView(evidence, terms);
172
+ await runMutationOrThrow(
173
+ ctx,
174
+ componentRef(component, "usageSubscriptions/mutations/save"),
175
+ { key, nativeJson: JSON.stringify(evidence), startedAt },
176
+ );
177
+ return view;
178
+ }
179
+ export async function prepareSubscription(
180
+ component: Component,
181
+ ctx: RunCtx,
182
+ terms: UsageSubscriptionTerms,
183
+ method: "direct" | "checkout",
184
+ ) {
185
+ return runMutationOrThrow(
186
+ ctx,
187
+ componentRef(component, "usageSubscriptions/mutations/prepare"),
188
+ { termsJson: JSON.stringify(terms), method },
189
+ ) as Promise<Doc<"usageSubscriptionIntents">>;
190
+ }
191
+ export async function ensureManagedSubscription(
192
+ stripe: Stripe,
193
+ component: Component,
194
+ ctx: RunCtx,
195
+ input: UsageSubscriptionOptions,
196
+ ) {
197
+ const terms = subscriptionTerms(input),
198
+ startedAt = Date.now();
199
+ return subscriptionCall(async () => {
200
+ if (terms.collection.method === "checkout")
201
+ throw new UsageSubscriptionError(
202
+ "incompatible_terms",
203
+ "Use the managed Checkout API for Checkout collection",
204
+ );
205
+ await verifySubscriptionRealm(stripe, terms);
206
+ const row = await prepareSubscription(component, ctx, terms, "direct");
207
+ if (!row.providerId) await verifySubscriptionPrices(stripe, terms);
208
+ let sub = row.providerId
209
+ ? await stripe.subscriptions.retrieve(row.providerId)
210
+ : await discoverSubscription(stripe, terms, row.key);
211
+ if (row.providerId && sub?.id !== row.providerId)
212
+ throw new UsageSubscriptionError(
213
+ "incompatible_terms",
214
+ "Pinned subscription identity changed",
215
+ );
216
+ if (!sub) {
217
+ if (Date.now() / 1000 - row.firstAttemptAt >= 23 * 3600)
218
+ throw new UsageSubscriptionError(
219
+ "unknown_create_outcome",
220
+ "Native subscription create requires reconciliation after safe retry window",
221
+ );
222
+ sub = await stripe.subscriptions.create(
223
+ {
224
+ customer_account: terms.meters[0].scope.customerAccount,
225
+ billing_mode: { type: "flexible" },
226
+ items: [
227
+ ...terms.meters.map((m) => ({ price: m.binding.stripePriceId })),
228
+ ...terms.fixedPriceIds.map((price) => ({ price, quantity: 1 })),
229
+ ],
230
+ ...(terms.collection.method === "send_invoice"
231
+ ? {
232
+ collection_method: "send_invoice" as const,
233
+ days_until_due: terms.collection.daysUntilDue,
234
+ }
235
+ : {
236
+ collection_method: "charge_automatically" as const,
237
+ default_payment_method: terms.collection.defaultPaymentMethod,
238
+ payment_behavior: "default_incomplete" as const,
239
+ }),
240
+ metadata: { bsUsageIntent: row.key },
241
+ },
242
+ { idempotencyKey: `bs_usage_sub_${row.key}` },
243
+ );
244
+ }
245
+ return saveSubscription(component, ctx, row.key, sub, terms, startedAt);
246
+ });
247
+ }