@fantastic.dev/better-stripe 0.55.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 (212) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +3 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +216 -38
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +92 -3
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +216 -38
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +92 -3
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/index.d.ts +4 -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 +4 -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/subscription.fixtures.d.ts +118 -0
  31. package/dist/client/usage/subscription.fixtures.d.ts.map +1 -0
  32. package/dist/client/usage/subscription.fixtures.js +84 -0
  33. package/dist/client/usage/subscription.fixtures.js.map +1 -0
  34. package/dist/client/usage/subscriptionAbandonment.d.ts +8 -0
  35. package/dist/client/usage/subscriptionAbandonment.d.ts.map +1 -0
  36. package/dist/client/usage/subscriptionAbandonment.js +82 -0
  37. package/dist/client/usage/subscriptionAbandonment.js.map +1 -0
  38. package/dist/client/usage/subscriptionCancellation.d.ts +9 -0
  39. package/dist/client/usage/subscriptionCancellation.d.ts.map +1 -0
  40. package/dist/client/usage/subscriptionCancellation.js +39 -0
  41. package/dist/client/usage/subscriptionCancellation.js.map +1 -0
  42. package/dist/client/usage/subscriptionCheckout.d.ts +52 -0
  43. package/dist/client/usage/subscriptionCheckout.d.ts.map +1 -0
  44. package/dist/client/usage/subscriptionCheckout.js +94 -0
  45. package/dist/client/usage/subscriptionCheckout.js.map +1 -0
  46. package/dist/client/usage/subscriptionClient.d.ts +267 -0
  47. package/dist/client/usage/subscriptionClient.d.ts.map +1 -0
  48. package/dist/client/usage/subscriptionClient.js +93 -0
  49. package/dist/client/usage/subscriptionClient.js.map +1 -0
  50. package/dist/client/usage/subscriptionErrors.d.ts +5 -0
  51. package/dist/client/usage/subscriptionErrors.d.ts.map +1 -0
  52. package/dist/client/usage/subscriptionErrors.js +9 -0
  53. package/dist/client/usage/subscriptionErrors.js.map +1 -0
  54. package/dist/client/usage/subscriptionInvoiceSchema.d.ts +203 -0
  55. package/dist/client/usage/subscriptionInvoiceSchema.d.ts.map +1 -0
  56. package/dist/client/usage/subscriptionInvoiceSchema.js +108 -0
  57. package/dist/client/usage/subscriptionInvoiceSchema.js.map +1 -0
  58. package/dist/client/usage/subscriptionLifecycle.d.ts +80 -0
  59. package/dist/client/usage/subscriptionLifecycle.d.ts.map +1 -0
  60. package/dist/client/usage/subscriptionLifecycle.js +87 -0
  61. package/dist/client/usage/subscriptionLifecycle.js.map +1 -0
  62. package/dist/client/usage/subscriptionProvider.d.ts +111 -0
  63. package/dist/client/usage/subscriptionProvider.d.ts.map +1 -0
  64. package/dist/client/usage/subscriptionProvider.js +147 -0
  65. package/dist/client/usage/subscriptionProvider.js.map +1 -0
  66. package/dist/client/usage/subscriptionTerms.d.ts +161 -0
  67. package/dist/client/usage/subscriptionTerms.d.ts.map +1 -0
  68. package/dist/client/usage/subscriptionTerms.js +242 -0
  69. package/dist/client/usage/subscriptionTerms.js.map +1 -0
  70. package/dist/client/usage/subscriptionTransport.fixtures.d.ts +25 -0
  71. package/dist/client/usage/subscriptionTransport.fixtures.d.ts.map +1 -0
  72. package/dist/client/usage/subscriptionTransport.fixtures.js +203 -0
  73. package/dist/client/usage/subscriptionTransport.fixtures.js.map +1 -0
  74. package/dist/client/webhooks/processors.d.ts.map +1 -1
  75. package/dist/client/webhooks/processors.js +2 -0
  76. package/dist/client/webhooks/processors.js.map +1 -1
  77. package/dist/client/webhooks/usageSubscriptions.d.ts +5 -0
  78. package/dist/client/webhooks/usageSubscriptions.d.ts.map +1 -0
  79. package/dist/client/webhooks/usageSubscriptions.js +54 -0
  80. package/dist/client/webhooks/usageSubscriptions.js.map +1 -0
  81. package/dist/component/_generated/api.d.ts +14 -0
  82. package/dist/component/_generated/api.d.ts.map +1 -1
  83. package/dist/component/_generated/api.js.map +1 -1
  84. package/dist/component/_generated/component.d.ts +160 -5
  85. package/dist/component/_generated/component.d.ts.map +1 -1
  86. package/dist/component/accountClosure/mutations.d.ts.map +1 -1
  87. package/dist/component/accountClosure/mutations.js +10 -0
  88. package/dist/component/accountClosure/mutations.js.map +1 -1
  89. package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
  90. package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
  91. package/dist/component/earnings/triggers.d.ts +192 -4
  92. package/dist/component/earnings/triggers.d.ts.map +1 -1
  93. package/dist/component/payoutRelease/queries.d.ts +2 -2
  94. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  95. package/dist/component/schema.d.ts +92 -3
  96. package/dist/component/schema.js +5 -0
  97. package/dist/component/schema.js.map +1 -1
  98. package/dist/component/usage/mutations.d.ts.map +1 -1
  99. package/dist/component/usage/mutations.js +5 -0
  100. package/dist/component/usage/mutations.js.map +1 -1
  101. package/dist/component/usage/queries.d.ts +2 -0
  102. package/dist/component/usage/queries.d.ts.map +1 -1
  103. package/dist/component/usage/schema.d.ts +14 -7
  104. package/dist/component/usage/schema.d.ts.map +1 -1
  105. package/dist/component/usage/schema.js +5 -1
  106. package/dist/component/usage/schema.js.map +1 -1
  107. package/dist/component/usageDelivery/fields.d.ts +3 -2
  108. package/dist/component/usageDelivery/fields.d.ts.map +1 -1
  109. package/dist/component/usageDelivery/fields.js +2 -1
  110. package/dist/component/usageDelivery/fields.js.map +1 -1
  111. package/dist/component/usageDelivery/helpers.d.ts +4 -3
  112. package/dist/component/usageDelivery/helpers.d.ts.map +1 -1
  113. package/dist/component/usageDelivery/mutations.d.ts +3 -3
  114. package/dist/component/usageDelivery/queries.d.ts +17 -3
  115. package/dist/component/usageDelivery/queries.d.ts.map +1 -1
  116. package/dist/component/usageDelivery/queries.js +20 -3
  117. package/dist/component/usageDelivery/queries.js.map +1 -1
  118. package/dist/component/usageDelivery/schema.d.ts +2 -2
  119. package/dist/component/usageDelivery/steps.d.ts +1 -1
  120. package/dist/component/usageDelivery/steps.d.ts.map +1 -1
  121. package/dist/component/usageDelivery/steps.js +12 -1
  122. package/dist/component/usageDelivery/steps.js.map +1 -1
  123. package/dist/component/usageSubscriptions/abandonment.d.ts +4 -0
  124. package/dist/component/usageSubscriptions/abandonment.d.ts.map +1 -0
  125. package/dist/component/usageSubscriptions/abandonment.js +59 -0
  126. package/dist/component/usageSubscriptions/abandonment.js.map +1 -0
  127. package/dist/component/usageSubscriptions/acceptance.d.ts +11 -0
  128. package/dist/component/usageSubscriptions/acceptance.d.ts.map +1 -0
  129. package/dist/component/usageSubscriptions/acceptance.js +38 -0
  130. package/dist/component/usageSubscriptions/acceptance.js.map +1 -0
  131. package/dist/component/usageSubscriptions/helpers.d.ts +39 -0
  132. package/dist/component/usageSubscriptions/helpers.d.ts.map +1 -0
  133. package/dist/component/usageSubscriptions/helpers.js +28 -0
  134. package/dist/component/usageSubscriptions/helpers.js.map +1 -0
  135. package/dist/component/usageSubscriptions/history.d.ts +46 -0
  136. package/dist/component/usageSubscriptions/history.d.ts.map +1 -0
  137. package/dist/component/usageSubscriptions/history.js +46 -0
  138. package/dist/component/usageSubscriptions/history.js.map +1 -0
  139. package/dist/component/usageSubscriptions/mutations.d.ts +64 -0
  140. package/dist/component/usageSubscriptions/mutations.d.ts.map +1 -0
  141. package/dist/component/usageSubscriptions/mutations.js +252 -0
  142. package/dist/component/usageSubscriptions/mutations.js.map +1 -0
  143. package/dist/component/usageSubscriptions/queries.d.ts +81 -0
  144. package/dist/component/usageSubscriptions/queries.d.ts.map +1 -0
  145. package/dist/component/usageSubscriptions/queries.js +70 -0
  146. package/dist/component/usageSubscriptions/queries.js.map +1 -0
  147. package/dist/component/usageSubscriptions/retirement.d.ts +4 -0
  148. package/dist/component/usageSubscriptions/retirement.d.ts.map +1 -0
  149. package/dist/component/usageSubscriptions/retirement.js +80 -0
  150. package/dist/component/usageSubscriptions/retirement.js.map +1 -0
  151. package/dist/component/usageSubscriptions/schema.d.ts +191 -0
  152. package/dist/component/usageSubscriptions/schema.d.ts.map +1 -0
  153. package/dist/component/usageSubscriptions/schema.js +69 -0
  154. package/dist/component/usageSubscriptions/schema.js.map +1 -0
  155. package/dist/test.d.ts +6 -0
  156. package/dist/test.d.ts.map +1 -0
  157. package/dist/test.js +15 -0
  158. package/dist/test.js.map +1 -0
  159. package/docs/README.md +2 -0
  160. package/docs/evidence/native-metering/clock-finalization-run.json +129 -0
  161. package/docs/evidence/native-metering/clock-lag-run.json +111 -0
  162. package/docs/evidence/native-metering/paid-run.json +107 -0
  163. package/docs/evidence/native-metering/promotional-run.json +103 -0
  164. package/docs/metered-usage.md +14 -0
  165. package/docs/metering-setup.md +5 -1
  166. package/docs/usage-subscriptions.md +278 -0
  167. package/package.json +4 -2
  168. package/src/client/index.ts +8 -0
  169. package/src/client/usage/catalogPrices.ts +21 -0
  170. package/src/client/usage/client.ts +2 -2
  171. package/src/client/usage/deliveryProvider.test.ts +70 -1
  172. package/src/client/usage/deliveryProvider.ts +43 -2
  173. package/src/client/usage/index.ts +9 -0
  174. package/src/client/usage/subscription.fixtures.ts +84 -0
  175. package/src/client/usage/subscriptionAbandonment.test.ts +124 -0
  176. package/src/client/usage/subscriptionAbandonment.ts +116 -0
  177. package/src/client/usage/subscriptionCancellation.ts +90 -0
  178. package/src/client/usage/subscriptionCheckout.test.ts +31 -0
  179. package/src/client/usage/subscriptionCheckout.ts +152 -0
  180. package/src/client/usage/subscriptionClient.test.ts +316 -0
  181. package/src/client/usage/subscriptionClient.ts +204 -0
  182. package/src/client/usage/subscriptionErrors.ts +14 -0
  183. package/src/client/usage/subscriptionInvoiceSchema.ts +116 -0
  184. package/src/client/usage/subscriptionLifecycle.ts +165 -0
  185. package/src/client/usage/subscriptionProvider.test.ts +48 -0
  186. package/src/client/usage/subscriptionProvider.ts +247 -0
  187. package/src/client/usage/subscriptionTerms.test.ts +158 -0
  188. package/src/client/usage/subscriptionTerms.ts +294 -0
  189. package/src/client/usage/subscriptionTransport.fixtures.ts +241 -0
  190. package/src/client/webhooks/processors.ts +2 -0
  191. package/src/client/webhooks/usageSubscriptions.test.ts +162 -0
  192. package/src/client/webhooks/usageSubscriptions.ts +81 -0
  193. package/src/component/_generated/api.ts +14 -0
  194. package/src/component/_generated/component.ts +200 -0
  195. package/src/component/accountClosure/mutations.ts +12 -0
  196. package/src/component/schema.ts +10 -0
  197. package/src/component/usage/mutations.ts +5 -0
  198. package/src/component/usage/schema.ts +5 -1
  199. package/src/component/usageDelivery/fields.ts +2 -0
  200. package/src/component/usageDelivery/queries.ts +30 -3
  201. package/src/component/usageDelivery/steps.ts +22 -1
  202. package/src/component/usageSubscriptions/abandonment.ts +80 -0
  203. package/src/component/usageSubscriptions/acceptance.test.ts +122 -0
  204. package/src/component/usageSubscriptions/acceptance.ts +66 -0
  205. package/src/component/usageSubscriptions/helpers.ts +33 -0
  206. package/src/component/usageSubscriptions/history.test.ts +69 -0
  207. package/src/component/usageSubscriptions/history.ts +68 -0
  208. package/src/component/usageSubscriptions/mutations.test.ts +205 -0
  209. package/src/component/usageSubscriptions/mutations.ts +275 -0
  210. package/src/component/usageSubscriptions/queries.ts +78 -0
  211. package/src/component/usageSubscriptions/retirement.ts +105 -0
  212. package/src/component/usageSubscriptions/schema.ts +73 -0
@@ -0,0 +1,316 @@
1
+ import { expect, it } from "vitest";
2
+ import { BetterStripe } from "../index.js";
3
+ import type { RunCtx } from "../helpers.js";
4
+ import { fixture } from "./subscriptionTransport.fixtures.js";
5
+ import { request, nativeSubscription } from "./subscription.fixtures.js";
6
+ const ref = {
7
+ scope: {
8
+ stripeAccountId: "acct_platform",
9
+ customerAccount: "acct_buyer",
10
+ livemode: false,
11
+ },
12
+ requestId: "signup1",
13
+ };
14
+ it("exposes managed lifecycle through the public facade and retains original invoice provenance", async () => {
15
+ const f = fixture(),
16
+ client = new BetterStripe(f.component),
17
+ options = {
18
+ stripeSecretKey: "sk_test_subscription",
19
+ httpClient: f.httpClient,
20
+ };
21
+ await f.t.action((ctx) =>
22
+ client.usage.ensureSubscription(ctx as RunCtx, request, options),
23
+ );
24
+ expect(
25
+ await f.t.query((ctx) => client.usage.getSubscription(ctx as RunCtx, ref)),
26
+ ).toMatchObject({
27
+ status: "available",
28
+ value: {
29
+ subscriptionId: "sub_calls",
30
+ items: [
31
+ { meterId: "mtr_calls", unitAmountDecimal: null },
32
+ { meterId: null, quantity: "1" },
33
+ ],
34
+ },
35
+ });
36
+ const cancel = { ...ref, operationId: "cancel1", cancelAtPeriodEnd: true };
37
+ expect(
38
+ await f.t.action((ctx) =>
39
+ client.usage.setCancelAtPeriodEnd(ctx as RunCtx, cancel, options),
40
+ ),
41
+ ).toMatchObject({ cancelAtPeriodEnd: true });
42
+ await f.t.action((ctx) =>
43
+ client.usage.setCancelAtPeriodEnd(ctx as RunCtx, cancel, options),
44
+ );
45
+ expect(
46
+ f.calls.filter(
47
+ (c) => c.path === "/v1/subscriptions/sub_calls" && c.method === "POST",
48
+ ),
49
+ ).toHaveLength(1);
50
+ await f.t.action((ctx) =>
51
+ client.usage.setCancelAtPeriodEnd(
52
+ ctx as RunCtx,
53
+ { ...ref, operationId: "reactivate2", cancelAtPeriodEnd: false },
54
+ options,
55
+ ),
56
+ );
57
+ expect(
58
+ f.calls.filter(
59
+ (c) => c.path === "/v1/subscriptions/sub_calls" && c.method === "POST",
60
+ ),
61
+ ).toHaveLength(2);
62
+ const invoice = await f.t.action((ctx) =>
63
+ client.usage.observeSubscriptionInvoice(
64
+ ctx as RunCtx,
65
+ { ...ref, invoiceId: "in_closeout" },
66
+ options,
67
+ ),
68
+ );
69
+ expect(invoice[0].observation).toMatchObject({
70
+ status: "available",
71
+ value: {
72
+ finalized: true,
73
+ total: "1010",
74
+ paymentEvidence: "not_resolved",
75
+ lines: [{ amount: "10", quantity: "15", stripePriceId: "price_calls" }],
76
+ },
77
+ });
78
+ const history = await f.t.query((ctx) =>
79
+ client.usage.readSubscriptionHistory(ctx as RunCtx, {
80
+ ...ref,
81
+ kind: "invoice",
82
+ limit: 10,
83
+ cursor: null,
84
+ }),
85
+ );
86
+ expect(history.records).toHaveLength(1);
87
+ f.state.native!.status = "canceled";
88
+ expect(
89
+ await f.t.action((ctx) =>
90
+ client.usage.retireSubscription(
91
+ ctx as RunCtx,
92
+ { ...ref, invoiceId: "in_closeout" },
93
+ options,
94
+ ),
95
+ ),
96
+ ).toMatchObject({
97
+ retired: true,
98
+ creditTreatment: "retain_original_terms",
99
+ billingReconciliation: "required",
100
+ });
101
+ expect(
102
+ (
103
+ await f.t.query((ctx) =>
104
+ client.usage.readSubscriptionHistory(ctx as RunCtx, {
105
+ ...ref,
106
+ kind: "retirement",
107
+ limit: 10,
108
+ cursor: null,
109
+ }),
110
+ )
111
+ ).records,
112
+ ).toHaveLength(1);
113
+ });
114
+ it("pins Checkout sessions without recreating expired signup", async () => {
115
+ const f = fixture(),
116
+ client = new BetterStripe(f.component),
117
+ options = {
118
+ stripeSecretKey: "sk_test_subscription",
119
+ httpClient: f.httpClient,
120
+ };
121
+ const input = {
122
+ ...request,
123
+ collection: {
124
+ method: "checkout" as const,
125
+ successUrl: "https://example.test/success",
126
+ cancelUrl: "https://example.test/cancel",
127
+ },
128
+ };
129
+ expect(
130
+ await f.t.action((ctx) =>
131
+ client.usage.ensureCheckout(ctx as RunCtx, input, options),
132
+ ),
133
+ ).toMatchObject({ status: "open", subscription: null });
134
+ await f.t.action((ctx) =>
135
+ client.usage.ensureCheckout(ctx as RunCtx, input, options),
136
+ );
137
+ expect(
138
+ f.calls.filter(
139
+ (c) => c.path === "/v1/checkout/sessions" && c.method === "POST",
140
+ ),
141
+ ).toHaveLength(1);
142
+ f.state.session!.status = "expired";
143
+ expect(
144
+ await f.t.action((ctx) =>
145
+ client.usage.ensureCheckout(ctx as RunCtx, input, options),
146
+ ),
147
+ ).toMatchObject({ status: "expired", url: null });
148
+ expect(
149
+ f.calls.filter(
150
+ (c) => c.path === "/v1/checkout/sessions" && c.method === "POST",
151
+ ),
152
+ ).toHaveLength(1);
153
+ });
154
+ it("rejects foreign scoped reads, missing credentials and absent pinned provider IDs", async () => {
155
+ const f = fixture(),
156
+ client = new BetterStripe(f.component),
157
+ options = {
158
+ stripeSecretKey: "sk_test_subscription",
159
+ httpClient: f.httpClient,
160
+ };
161
+ await expect(
162
+ f.t.action((ctx) =>
163
+ client.usage.ensureSubscription(ctx as RunCtx, request, {}),
164
+ ),
165
+ ).rejects.toThrow(/credentials/);
166
+ await f.t.action((ctx) =>
167
+ client.usage.ensureSubscription(ctx as RunCtx, request, options),
168
+ );
169
+ await expect(
170
+ f.t.query((ctx) =>
171
+ client.usage.getSubscription(ctx as RunCtx, {
172
+ ...ref,
173
+ scope: { ...ref.scope, customerAccount: "acct_foreign" },
174
+ }),
175
+ ),
176
+ ).rejects.toThrow(/scope/);
177
+ f.state.missingNative = true;
178
+ await expect(
179
+ f.t.action((ctx) =>
180
+ client.usage.observeSubscription(ctx as RunCtx, ref, options),
181
+ ),
182
+ ).rejects.toThrow("Native usage subscription unavailable");
183
+ await expect(
184
+ f.t.action((ctx) =>
185
+ client.usage.ensureSubscription(ctx as RunCtx, request, options),
186
+ ),
187
+ ).rejects.toThrow("Native usage subscription unavailable");
188
+ expect(
189
+ f.calls.filter(
190
+ (c) => c.path === "/v1/subscriptions" && c.method === "POST",
191
+ ),
192
+ ).toHaveLength(1);
193
+ });
194
+
195
+ it("adopts the completed original Checkout subscription and reports unsupported key realms", async () => {
196
+ const f = fixture(),
197
+ client = new BetterStripe(f.component),
198
+ options = {
199
+ stripeSecretKey: "sk_test_subscription",
200
+ httpClient: f.httpClient,
201
+ };
202
+ const input = {
203
+ ...request,
204
+ collection: {
205
+ method: "checkout" as const,
206
+ successUrl: "https://example.test/success",
207
+ cancelUrl: "https://example.test/cancel",
208
+ },
209
+ };
210
+ await f.t.action((ctx) =>
211
+ client.usage.ensureCheckout(ctx as RunCtx, input, options),
212
+ );
213
+ f.state.native = {
214
+ ...nativeSubscription(),
215
+ collection_method: "charge_automatically",
216
+ days_until_due: null,
217
+ metadata: f.state.session!.metadata as Record<string, string>,
218
+ };
219
+ f.state.session!.status = "complete";
220
+ f.state.session!.subscription = "sub_calls";
221
+ expect(
222
+ await f.t.action((ctx) =>
223
+ client.usage.ensureCheckout(ctx as RunCtx, input, options),
224
+ ),
225
+ ).toMatchObject({
226
+ status: "complete",
227
+ url: null,
228
+ subscription: { subscriptionId: "sub_calls" },
229
+ });
230
+ expect(
231
+ await f.t.action((ctx) =>
232
+ client.usage.observeSubscription(ctx as RunCtx, ref, options),
233
+ ),
234
+ ).toMatchObject({ subscriptionId: "sub_calls" });
235
+ expect(
236
+ f.calls.filter(
237
+ (call) => call.path === "/v1/subscriptions" && call.method === "POST",
238
+ ),
239
+ ).toHaveLength(0);
240
+ f.state.realmId = "acct_other";
241
+ await expect(
242
+ f.t.action((ctx) =>
243
+ client.usage.observeSubscription(ctx as RunCtx, ref, options),
244
+ ),
245
+ ).rejects.toMatchObject({ code: "unsupported_scope" });
246
+ });
247
+
248
+ it("rejects a retrieved Checkout subscription ID that differs from the completed session", async () => {
249
+ const f = fixture(),
250
+ client = new BetterStripe(f.component),
251
+ options = {
252
+ stripeSecretKey: "sk_test_subscription",
253
+ httpClient: f.httpClient,
254
+ };
255
+ const input = {
256
+ ...request,
257
+ collection: {
258
+ method: "checkout" as const,
259
+ successUrl: "https://example.test/success",
260
+ cancelUrl: "https://example.test/cancel",
261
+ },
262
+ };
263
+ await f.t.action((ctx) =>
264
+ client.usage.ensureCheckout(ctx as RunCtx, input, options),
265
+ );
266
+ f.state.native = {
267
+ ...nativeSubscription(),
268
+ id: "sub_other",
269
+ metadata: f.state.session!.metadata as Record<string, string>,
270
+ };
271
+ f.state.session!.status = "complete";
272
+ f.state.session!.subscription = "sub_calls";
273
+ await expect(
274
+ f.t.action((ctx) =>
275
+ client.usage.ensureCheckout(ctx as RunCtx, input, options),
276
+ ),
277
+ ).rejects.toThrow("Native Checkout subscription identity mismatch");
278
+ });
279
+
280
+ it("records terminal cancellation refusal without leaving a lock that prevents closeout", async () => {
281
+ const f = fixture(),
282
+ client = new BetterStripe(f.component),
283
+ options = {
284
+ stripeSecretKey: "sk_test_subscription",
285
+ httpClient: f.httpClient,
286
+ };
287
+ await f.t.action((ctx) =>
288
+ client.usage.ensureSubscription(ctx as RunCtx, request, options),
289
+ );
290
+ f.state.native!.status = "canceled";
291
+ f.state.native!.cancel_at_period_end = true;
292
+ const command = {
293
+ ...ref,
294
+ operationId: "late-reactivation",
295
+ cancelAtPeriodEnd: false,
296
+ };
297
+ await expect(
298
+ f.t.action((ctx) =>
299
+ client.usage.setCancelAtPeriodEnd(ctx as RunCtx, command, options),
300
+ ),
301
+ ).rejects.toThrow(/cannot be reactivated/);
302
+ await expect(
303
+ f.t.action((ctx) =>
304
+ client.usage.setCancelAtPeriodEnd(ctx as RunCtx, command, options),
305
+ ),
306
+ ).rejects.toThrow(/cannot be reactivated/);
307
+ expect(
308
+ await f.t.action((ctx) =>
309
+ client.usage.retireSubscription(
310
+ ctx as RunCtx,
311
+ { ...ref, invoiceId: "in_closeout" },
312
+ options,
313
+ ),
314
+ ),
315
+ ).toMatchObject({ retired: true });
316
+ });
@@ -0,0 +1,204 @@
1
+ import { abandonManagedSignup } from "./subscriptionAbandonment.js";
2
+ import Stripe from "stripe";
3
+ import type { RunCtx } from "../helpers.js";
4
+ import type { StripeApiVersion } from "../stripe-types.js";
5
+ import { componentRef } from "../webhooks/helpers.js";
6
+ import { UsageObservationClient } from "./observationClient.js";
7
+ import {
8
+ ensureManagedSubscription,
9
+ UsageSubscriptionError,
10
+ } from "./subscriptionProvider.js";
11
+ import { ensureManagedCheckout } from "./subscriptionCheckout.js";
12
+ import { changeManagedCancellation } from "./subscriptionCancellation.js";
13
+ import {
14
+ getSubscriptionIntent,
15
+ refreshManagedSubscription,
16
+ observeManagedInvoice,
17
+ retireManagedSubscription,
18
+ type UsageSubscriptionRef,
19
+ } from "./subscriptionLifecycle.js";
20
+ import {
21
+ subscriptionTerms,
22
+ type UsageSubscriptionOptions,
23
+ type UsageSubscriptionView,
24
+ } from "./subscriptionTerms.js";
25
+ import type { UsageDeliveryProviderOptions } from "./deliveryProvider.js";
26
+ import type { UsageAvailability } from "./boundaries.js";
27
+ import { validateUsagePageRequest } from "./boundaries.js";
28
+ import type { Doc } from "../../component/_generated/dataModel.js";
29
+ function provider(version: string, options: UsageDeliveryProviderOptions) {
30
+ if (!options.stripeSecretKey)
31
+ throw new UsageSubscriptionError(
32
+ "provider_unavailable",
33
+ "Native usage subscription credentials unavailable",
34
+ );
35
+ return new Stripe(options.stripeSecretKey, {
36
+ apiVersion: version as StripeApiVersion,
37
+ maxNetworkRetries: 0,
38
+ timeout: 15000,
39
+ ...(options.httpClient ? { httpClient: options.httpClient } : {}),
40
+ });
41
+ }
42
+ /** Trusted host authorizes the full payer/realm and every original meter first. */
43
+ export class UsageSubscriptionClient extends UsageObservationClient {
44
+ async ensureSubscription(
45
+ ctx: RunCtx,
46
+ input: UsageSubscriptionOptions,
47
+ options: UsageDeliveryProviderOptions,
48
+ ) {
49
+ const terms = subscriptionTerms(input);
50
+ return ensureManagedSubscription(
51
+ provider(terms.meters[0].binding.apiVersion, options),
52
+ this.component,
53
+ ctx,
54
+ terms,
55
+ );
56
+ }
57
+ async ensureCheckout(
58
+ ctx: RunCtx,
59
+ input: UsageSubscriptionOptions,
60
+ options: UsageDeliveryProviderOptions,
61
+ ) {
62
+ const terms = subscriptionTerms(input);
63
+ return ensureManagedCheckout(
64
+ provider(terms.meters[0].binding.apiVersion, options),
65
+ this.component,
66
+ ctx,
67
+ terms,
68
+ );
69
+ }
70
+ async getSubscription(
71
+ ctx: RunCtx,
72
+ input: UsageSubscriptionRef,
73
+ ): Promise<UsageAvailability<UsageSubscriptionView>> {
74
+ const row = await getSubscriptionIntent(this.component, ctx, input);
75
+ return row.viewJson && row.startedAt !== undefined
76
+ ? {
77
+ status: "available",
78
+ observedAt: Math.floor(row.startedAt / 1000),
79
+ value: JSON.parse(row.viewJson) as UsageSubscriptionView,
80
+ }
81
+ : {
82
+ status: "unavailable",
83
+ reason: "subscription_not_observed",
84
+ retryable: true,
85
+ };
86
+ }
87
+ async observeSubscription(
88
+ ctx: RunCtx,
89
+ input: UsageSubscriptionRef,
90
+ options: UsageDeliveryProviderOptions,
91
+ ) {
92
+ const row = await getSubscriptionIntent(this.component, ctx, input),
93
+ terms = subscriptionTerms(JSON.parse(row.termsJson));
94
+ return refreshManagedSubscription(
95
+ provider(terms.meters[0].binding.apiVersion, options),
96
+ this.component,
97
+ ctx,
98
+ row,
99
+ );
100
+ }
101
+ async setCancelAtPeriodEnd(
102
+ ctx: RunCtx,
103
+ input: UsageSubscriptionRef & {
104
+ operationId: string;
105
+ cancelAtPeriodEnd: boolean;
106
+ },
107
+ options: UsageDeliveryProviderOptions,
108
+ ) {
109
+ const row = await getSubscriptionIntent(this.component, ctx, input),
110
+ terms = subscriptionTerms(JSON.parse(row.termsJson));
111
+ return changeManagedCancellation(
112
+ provider(terms.meters[0].binding.apiVersion, options),
113
+ this.component,
114
+ ctx,
115
+ row,
116
+ {
117
+ operationId: input.operationId,
118
+ cancelAtPeriodEnd: input.cancelAtPeriodEnd,
119
+ },
120
+ );
121
+ }
122
+ async observeSubscriptionInvoice(
123
+ ctx: RunCtx,
124
+ input: UsageSubscriptionRef & { invoiceId: string },
125
+ options: UsageDeliveryProviderOptions,
126
+ ) {
127
+ const row = await getSubscriptionIntent(this.component, ctx, input),
128
+ terms = subscriptionTerms(JSON.parse(row.termsJson));
129
+ return observeManagedInvoice(
130
+ provider(terms.meters[0].binding.apiVersion, options),
131
+ this.component,
132
+ ctx,
133
+ row,
134
+ input.invoiceId,
135
+ );
136
+ }
137
+ async retireSubscription(
138
+ ctx: RunCtx,
139
+ input: UsageSubscriptionRef & { invoiceId: string },
140
+ options: UsageDeliveryProviderOptions,
141
+ ) {
142
+ const row = await getSubscriptionIntent(this.component, ctx, input),
143
+ terms = subscriptionTerms(JSON.parse(row.termsJson));
144
+ return retireManagedSubscription(
145
+ provider(terms.meters[0].binding.apiVersion, options),
146
+ this.component,
147
+ ctx,
148
+ row,
149
+ input.invoiceId,
150
+ );
151
+ }
152
+ async abandonSignup(
153
+ ctx: RunCtx,
154
+ input: UsageSubscriptionRef,
155
+ options: UsageDeliveryProviderOptions,
156
+ ) {
157
+ const row = await getSubscriptionIntent(this.component, ctx, input),
158
+ terms = subscriptionTerms(JSON.parse(row.termsJson));
159
+ return abandonManagedSignup(
160
+ provider(terms.meters[0].binding.apiVersion, options),
161
+ this.component,
162
+ ctx,
163
+ row,
164
+ );
165
+ }
166
+ async readSubscriptionHistory(
167
+ ctx: RunCtx,
168
+ input: UsageSubscriptionRef & {
169
+ kind: "subscription" | "invoice" | "retirement";
170
+ limit: number;
171
+ cursor: string | null;
172
+ },
173
+ ) {
174
+ const page = validateUsagePageRequest({
175
+ period: { start: 0, end: 1 },
176
+ limit: input.limit,
177
+ cursor: input.cursor,
178
+ });
179
+ await getSubscriptionIntent(this.component, ctx, input);
180
+ const result = (await ctx.runQuery(
181
+ componentRef(this.component, "usageSubscriptions/queries/history"),
182
+ {
183
+ scope: input.scope,
184
+ requestId: input.requestId,
185
+ kind: input.kind,
186
+ paginationOpts: { numItems: page.limit, cursor: page.cursor },
187
+ },
188
+ )) as {
189
+ page: Doc<"usageSubscriptionHistory">[];
190
+ isDone: boolean;
191
+ continueCursor: string;
192
+ };
193
+ return {
194
+ records: result.page.map((row) => ({
195
+ kind: row.kind,
196
+ resourceId: row.resourceId,
197
+ observedAt: Math.floor(row.startedAt / 1000),
198
+ observation: JSON.parse(row.observationJson) as unknown,
199
+ })),
200
+ isDone: result.isDone,
201
+ cursor: result.isDone ? null : result.continueCursor,
202
+ };
203
+ }
204
+ }
@@ -0,0 +1,14 @@
1
+ export class UsageSubscriptionError extends Error {
2
+ constructor(
3
+ public readonly code:
4
+ | "unsupported_scope"
5
+ | "overlapping_enrollment"
6
+ | "incompatible_terms"
7
+ | "unknown_create_outcome"
8
+ | "provider_unavailable",
9
+ message: string,
10
+ ) {
11
+ super(message);
12
+ this.name = "UsageSubscriptionError";
13
+ }
14
+ }
@@ -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
+ ]);