@fantastic.dev/better-stripe 0.39.0 → 0.40.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 (53) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +1 -1
  3. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +16 -16
  4. package/dist/client/connect/payoutSyncTestHelpers.d.ts +16 -16
  5. package/dist/client/costRecovery-invoices.d.ts.map +1 -1
  6. package/dist/client/costRecovery-invoices.js +3 -5
  7. package/dist/client/costRecovery-invoices.js.map +1 -1
  8. package/dist/client/index.d.ts +3 -2
  9. package/dist/client/index.d.ts.map +1 -1
  10. package/dist/client/index.js +2 -2
  11. package/dist/client/index.js.map +1 -1
  12. package/dist/client/paymentSource/client.d.ts +21 -0
  13. package/dist/client/paymentSource/client.d.ts.map +1 -0
  14. package/dist/client/paymentSource/client.js +8 -0
  15. package/dist/client/paymentSource/client.js.map +1 -0
  16. package/dist/client/paymentSource/contracts.d.ts +30 -0
  17. package/dist/client/paymentSource/contracts.d.ts.map +1 -0
  18. package/dist/client/paymentSource/contracts.js +16 -0
  19. package/dist/client/paymentSource/contracts.js.map +1 -0
  20. package/dist/client/paymentSource/economics.d.ts +12 -0
  21. package/dist/client/paymentSource/economics.d.ts.map +1 -0
  22. package/dist/client/paymentSource/economics.js +13 -0
  23. package/dist/client/paymentSource/economics.js.map +1 -0
  24. package/dist/client/paymentSource/funding.d.ts +10 -0
  25. package/dist/client/paymentSource/funding.d.ts.map +1 -0
  26. package/dist/client/paymentSource/funding.js +12 -0
  27. package/dist/client/paymentSource/funding.js.map +1 -0
  28. package/dist/client/paymentSource/history.d.ts +13 -0
  29. package/dist/client/paymentSource/history.d.ts.map +1 -0
  30. package/dist/client/paymentSource/history.js +41 -0
  31. package/dist/client/paymentSource/history.js.map +1 -0
  32. package/dist/client/paymentSource/resolver.d.ts +6 -0
  33. package/dist/client/paymentSource/resolver.d.ts.map +1 -0
  34. package/dist/client/paymentSource/resolver.js +222 -0
  35. package/dist/client/paymentSource/resolver.js.map +1 -0
  36. package/dist/client/settlement/verifiedSale.d.ts.map +1 -1
  37. package/dist/client/settlement/verifiedSale.js +4 -6
  38. package/dist/client/settlement/verifiedSale.js.map +1 -1
  39. package/dist/component/balanceFunding/mutations.d.ts +16 -16
  40. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  41. package/dist/component/earnings/triggers.d.ts +16 -16
  42. package/docs/settlement.md +48 -0
  43. package/package.json +1 -1
  44. package/src/client/costRecovery-invoices.ts +3 -7
  45. package/src/client/index.ts +6 -2
  46. package/src/client/paymentSource/client.ts +13 -0
  47. package/src/client/paymentSource/contracts.ts +33 -0
  48. package/src/client/paymentSource/economics.ts +20 -0
  49. package/src/client/paymentSource/funding.ts +23 -0
  50. package/src/client/paymentSource/history.ts +48 -0
  51. package/src/client/paymentSource/resolver.test.ts +582 -0
  52. package/src/client/paymentSource/resolver.ts +350 -0
  53. package/src/client/settlement/verifiedSale.ts +4 -10
@@ -0,0 +1,582 @@
1
+ import type Stripe from "stripe";
2
+ import { componentsGeneric } from "convex/server";
3
+ import { expect, it } from "vitest";
4
+ import { BetterStripe } from "../index.js";
5
+ import { getStripeClient, type Component, type RunCtx } from "../helpers.js";
6
+
7
+ function fixture() {
8
+ const key = `sk_test_source_${crypto.randomUUID()}`;
9
+ const apiVersion = "2026-09-30.preview";
10
+ const client = new BetterStripe(
11
+ componentsGeneric().betterStripe as unknown as Component,
12
+ {
13
+ STRIPE_SECRET_KEY: key,
14
+ stripeApiVersion: apiVersion,
15
+ },
16
+ );
17
+ const transaction = {
18
+ id: "txn_source",
19
+ object: "balance_transaction",
20
+ source: "ch_source",
21
+ amount: 1000,
22
+ fee: 50,
23
+ net: 950,
24
+ currency: "usd",
25
+ };
26
+ const payment = {
27
+ id: "pi_source",
28
+ object: "payment_intent",
29
+ status: "succeeded",
30
+ amount: 1000,
31
+ amount_received: 1000,
32
+ currency: "usd",
33
+ customer_account: "acct_customer",
34
+ livemode: false,
35
+ metadata: { stripePriceId: "price_untrusted" },
36
+ latest_charge: {
37
+ id: "ch_source",
38
+ object: "charge",
39
+ payment_intent: "pi_source",
40
+ amount: 1000,
41
+ amount_captured: 1000,
42
+ currency: "usd",
43
+ paid: true,
44
+ captured: true,
45
+ status: "succeeded",
46
+ amount_refunded: 0,
47
+ disputed: false,
48
+ livemode: false,
49
+ balance_transaction: transaction,
50
+ },
51
+ };
52
+ const invoice = {
53
+ id: "in_source",
54
+ object: "invoice",
55
+ status: "paid",
56
+ currency: "usd",
57
+ amount_paid: 1000,
58
+ amount_due: 1000,
59
+ amount_remaining: 0,
60
+ total: 1000,
61
+ amount_overpaid: 0,
62
+ starting_balance: 0,
63
+ ending_balance: 0,
64
+ customer_account: "acct_customer",
65
+ livemode: false,
66
+ parent: {
67
+ type: "subscription_details",
68
+ subscription_details: { subscription: "sub_source" },
69
+ },
70
+ };
71
+ const funding = {
72
+ id: "inpay_source",
73
+ object: "invoice_payment",
74
+ invoice: "in_source",
75
+ status: "paid",
76
+ currency: "usd",
77
+ amount_paid: 1000,
78
+ amount_requested: 1000,
79
+ livemode: false,
80
+ payment: { type: "payment_intent", payment_intent: "pi_source" },
81
+ };
82
+ const line = {
83
+ id: "il_source",
84
+ object: "line_item",
85
+ invoice: "in_source",
86
+ currency: "usd",
87
+ amount: 1000,
88
+ quantity: 1,
89
+ livemode: false,
90
+ parent: {
91
+ type: "subscription_item_details",
92
+ subscription_item_details: {
93
+ subscription: "sub_source",
94
+ subscription_item: "si_source",
95
+ proration: false,
96
+ },
97
+ },
98
+ pricing: {
99
+ type: "price_details",
100
+ price_details: { price: "price_original", product: "prod_original" },
101
+ unit_amount_decimal: "1000",
102
+ },
103
+ };
104
+ const subscription = {
105
+ id: "sub_source",
106
+ object: "subscription",
107
+ customer_account: "acct_customer",
108
+ livemode: false,
109
+ metadata: { sellerId: "untrusted" },
110
+ items: {
111
+ data: [{ price: { id: "price_current", product: "prod_current" } }],
112
+ },
113
+ };
114
+ const history = { inverse: [funding], funding: [funding], lines: [line] };
115
+ const pages = new Map<string, { data: unknown[]; has_more: boolean }>();
116
+ const requests: {
117
+ path: string;
118
+ method: string;
119
+ version: string;
120
+ account: string;
121
+ }[] = [];
122
+ const sdk = getStripeClient(key, apiVersion);
123
+ (
124
+ sdk as unknown as { _setApiField: (name: string, value: unknown) => void }
125
+ )._setApiField("httpClient", {
126
+ getClientName: () => "verified-source-contract",
127
+ makeRequest: async (
128
+ ...[, , path, method, headers]: Parameters<
129
+ ReturnType<typeof Stripe.createNodeHttpClient>["makeRequest"]
130
+ >
131
+ ) => {
132
+ requests.push({
133
+ path,
134
+ method,
135
+ version: String(headers["Stripe-Version"]),
136
+ account: String(headers["Stripe-Account"]),
137
+ });
138
+ const url = new URL(path, "https://stripe.test");
139
+ const phase = url.pathname.endsWith("/lines")
140
+ ? "lines"
141
+ : url.searchParams.has("invoice")
142
+ ? "funding"
143
+ : "inverse";
144
+ const override = pages.get(
145
+ phase + ":" + (url.searchParams.get("starting_after") ?? ""),
146
+ );
147
+ const data =
148
+ url.pathname === "/v1/payment_intents/pi_source"
149
+ ? payment
150
+ : url.pathname === "/v1/invoices/in_source"
151
+ ? invoice
152
+ : url.pathname === "/v1/subscriptions/sub_source"
153
+ ? subscription
154
+ : {
155
+ object: "list",
156
+ url: url.pathname,
157
+ has_more: override?.has_more ?? false,
158
+ data:
159
+ override?.data ??
160
+ (phase === "lines"
161
+ ? history.lines
162
+ : phase === "funding"
163
+ ? history.funding
164
+ : history.inverse),
165
+ };
166
+ return {
167
+ getStatusCode: () => 200,
168
+ getHeaders: () => ({}),
169
+ getRawResponse: () => ({}),
170
+ toJSON: async () => data,
171
+ toStream: () => {
172
+ throw new Error("Unexpected stream");
173
+ },
174
+ };
175
+ },
176
+ });
177
+ const options = {
178
+ paymentIntentId: "pi_source",
179
+ customerAccountId: "acct_customer",
180
+ stripeAccountId: "acct_connected",
181
+ gross: 1000,
182
+ currency: "usd",
183
+ };
184
+ const resolve = (
185
+ overrides: Partial<typeof options> & {
186
+ maxHistoryPages?: number;
187
+ maxHistoryItems?: number;
188
+ } = {},
189
+ ) => {
190
+ return client.getVerifiedPaymentSource({} as RunCtx, {
191
+ ...options,
192
+ ...overrides,
193
+ });
194
+ };
195
+ return {
196
+ resolve,
197
+ client,
198
+ options,
199
+ payment,
200
+ invoice,
201
+ funding,
202
+ line,
203
+ subscription,
204
+ history,
205
+ requests,
206
+ pages,
207
+ };
208
+ }
209
+
210
+ it("resolves a complete original invoice price through the inherited SDK method, ignoring current prices and metadata", async () => {
211
+ const s = fixture();
212
+ expect(await s.resolve()).toEqual({
213
+ status: "ready",
214
+ value: {
215
+ paymentIntentId: "pi_source",
216
+ chargeId: "ch_source",
217
+ invoiceId: "in_source",
218
+ invoicePaymentId: "inpay_source",
219
+ subscriptionId: "sub_source",
220
+ customerAccountId: "acct_customer",
221
+ stripeAccountId: "acct_connected",
222
+ stripePriceId: "price_original",
223
+ stripeProductId: "prod_original",
224
+ gross: 1000,
225
+ processingFee: 50,
226
+ currency: "usd",
227
+ livemode: false,
228
+ },
229
+ });
230
+ expect(s.requests).toHaveLength(6);
231
+ expect(
232
+ s.requests.every(
233
+ (r) =>
234
+ r.method === "GET" &&
235
+ r.version === "2026-09-30.preview" &&
236
+ r.account === "acct_connected",
237
+ ),
238
+ ).toBe(true);
239
+ });
240
+
241
+ type Fixture = ReturnType<typeof fixture>;
242
+ const terminal = (reason: string) => ({
243
+ status: "rejected",
244
+ reason,
245
+ retryable: false,
246
+ });
247
+ const conflict = {
248
+ status: "conflict",
249
+ reason: "identity_changed",
250
+ retryable: false,
251
+ };
252
+ const incomplete = {
253
+ status: "unknown",
254
+ reason: "history_incomplete",
255
+ retryable: false,
256
+ };
257
+ it.each([
258
+ [
259
+ "foreign payment",
260
+ (s: Fixture): unknown => (s.payment.id = "pi_foreign"),
261
+ conflict,
262
+ ],
263
+ [
264
+ "foreign charge",
265
+ (s: Fixture): unknown =>
266
+ (s.payment.latest_charge.payment_intent = "pi_foreign"),
267
+ conflict,
268
+ ],
269
+ [
270
+ "foreign invoice",
271
+ (s: Fixture): unknown => (s.invoice.id = "in_foreign"),
272
+ conflict,
273
+ ],
274
+ [
275
+ "foreign customer",
276
+ (s: Fixture): unknown => (s.invoice.customer_account = "acct_foreign"),
277
+ conflict,
278
+ ],
279
+ [
280
+ "foreign subscription",
281
+ (s: Fixture): unknown => (s.subscription.id = "sub_foreign"),
282
+ conflict,
283
+ ],
284
+ [
285
+ "foreign invoice line",
286
+ (s: Fixture): unknown => (s.line.invoice = "in_foreign"),
287
+ conflict,
288
+ ],
289
+ [
290
+ "foreign funding row",
291
+ (s: Fixture): unknown => (s.funding.invoice = "in_foreign"),
292
+ conflict,
293
+ ],
294
+ [
295
+ "foreign balance transaction",
296
+ (s: Fixture): unknown =>
297
+ (s.payment.latest_charge.balance_transaction.source = "ch_foreign"),
298
+ conflict,
299
+ ],
300
+ [
301
+ "invoice currency",
302
+ (s: Fixture): unknown => (s.invoice.currency = "eur"),
303
+ terminal("currency_mismatch"),
304
+ ],
305
+ [
306
+ "funding currency",
307
+ (s: Fixture): unknown => (s.funding.currency = "eur"),
308
+ terminal("currency_mismatch"),
309
+ ],
310
+ [
311
+ "line currency",
312
+ (s: Fixture): unknown => (s.line.currency = "eur"),
313
+ terminal("currency_mismatch"),
314
+ ],
315
+ [
316
+ "balance currency",
317
+ (s: Fixture): unknown =>
318
+ (s.payment.latest_charge.balance_transaction.currency = "eur"),
319
+ terminal("currency_mismatch"),
320
+ ],
321
+ [
322
+ "partial payment",
323
+ (s: Fixture): unknown => (s.funding.amount_paid = 900),
324
+ terminal("unsupported_source"),
325
+ ],
326
+ [
327
+ "credit-funded invoice",
328
+ (s: Fixture): unknown => (s.invoice.total = 1100),
329
+ terminal("unsupported_source"),
330
+ ],
331
+ [
332
+ "unsafe amount",
333
+ (s: Fixture): unknown =>
334
+ (s.payment.amount_received = Number.MAX_SAFE_INTEGER + 1),
335
+ terminal("unsupported_source"),
336
+ ],
337
+ [
338
+ "negative fee",
339
+ (s: Fixture): unknown =>
340
+ (s.payment.latest_charge.balance_transaction.fee = -1),
341
+ terminal("unsupported_source"),
342
+ ],
343
+ [
344
+ "unreconciled transaction",
345
+ (s: Fixture): unknown =>
346
+ (s.payment.latest_charge.balance_transaction.net = 999),
347
+ terminal("unsupported_source"),
348
+ ],
349
+ [
350
+ "missing original price",
351
+ (s: Fixture): void => {
352
+ Object.assign(s.line, { pricing: null });
353
+ },
354
+ terminal("unsupported_source"),
355
+ ],
356
+ [
357
+ "multiple invoice lines",
358
+ (s: Fixture): void => {
359
+ s.history.lines.push({ ...s.line, id: "il_second" });
360
+ },
361
+ terminal("unsupported_source"),
362
+ ],
363
+ [
364
+ "multiple paid allocations",
365
+ (s: Fixture): void => {
366
+ s.history.funding.push({ ...s.funding, id: "inpay_second" });
367
+ },
368
+ terminal("unsupported_source"),
369
+ ],
370
+ ] as const)(
371
+ "refuses %s without guessing source economics",
372
+ async (_name, mutate, expected) => {
373
+ const s = fixture();
374
+ mutate(s);
375
+ expect(await s.resolve()).toEqual(expected);
376
+ },
377
+ );
378
+
379
+ it("preserves refunded/disputed original funding as cost provenance", async () => {
380
+ const s = fixture();
381
+ s.payment.latest_charge.amount_refunded = 1000;
382
+ s.payment.latest_charge.disputed = true;
383
+ expect(await s.resolve()).toMatchObject({
384
+ status: "ready",
385
+ value: { gross: 1000, processingFee: 50, stripePriceId: "price_original" },
386
+ });
387
+ });
388
+ it("keeps missing fees explicit while accepting provider-verified zero fees", async () => {
389
+ const missing = fixture();
390
+ Object.assign(missing.payment.latest_charge, { balance_transaction: null });
391
+ expect(await missing.resolve()).toEqual({
392
+ status: "not_ready",
393
+ reason: "fee_pending",
394
+ retryable: true,
395
+ });
396
+ const zero = fixture();
397
+ zero.payment.latest_charge.balance_transaction.fee = 0;
398
+ zero.payment.latest_charge.balance_transaction.net = 1000;
399
+ expect(await zero.resolve()).toMatchObject({
400
+ status: "ready",
401
+ value: { processingFee: 0 },
402
+ });
403
+ });
404
+ it.each([0, -1, 1.5, Infinity, 21])(
405
+ "rejects invalid history page cap %s before provider reads",
406
+ async (maxHistoryPages) => {
407
+ const s = fixture();
408
+ expect(await s.resolve({ maxHistoryPages })).toEqual(
409
+ terminal("invalid_scope"),
410
+ );
411
+ expect(s.requests).toHaveLength(0);
412
+ },
413
+ );
414
+ it.each(["inverse", "funding", "lines"])(
415
+ "holds incomplete %s history at the hard cap",
416
+ async (phase) => {
417
+ const s = fixture();
418
+ s.pages.set(phase + ":", {
419
+ data: [phase === "lines" ? s.line : s.funding],
420
+ has_more: true,
421
+ });
422
+ expect(await s.resolve({ maxHistoryPages: 1 })).toEqual(incomplete);
423
+ },
424
+ );
425
+ it("rejects duplicate history across pages rather than claiming unique funding", async () => {
426
+ const s = fixture();
427
+ s.pages.set("inverse:", { data: [s.funding], has_more: true });
428
+ s.pages.set("inverse:inpay_source", { data: [s.funding], has_more: false });
429
+ expect(await s.resolve()).toEqual(incomplete);
430
+ });
431
+ it("holds oversized and non-progressing provider envelopes", async () => {
432
+ const large = fixture();
433
+ large.pages.set("inverse:", {
434
+ data: Array.from({ length: 101 }, (_, i) => ({
435
+ ...large.funding,
436
+ id: "inpay_" + i,
437
+ })),
438
+ has_more: false,
439
+ });
440
+ expect(await large.resolve()).toEqual(incomplete);
441
+ const empty = fixture();
442
+ empty.pages.set("inverse:", { data: [], has_more: true });
443
+ expect(await empty.resolve()).toEqual(incomplete);
444
+ });
445
+
446
+ it.each([
447
+ [
448
+ "charge ID",
449
+ (s: Fixture): void => {
450
+ s.payment.latest_charge.id = "";
451
+ s.payment.latest_charge.balance_transaction.source = "";
452
+ },
453
+ ],
454
+ [
455
+ "balance ID",
456
+ (s: Fixture): unknown =>
457
+ (s.payment.latest_charge.balance_transaction.id = ""),
458
+ ],
459
+ ["payment object", (s: Fixture): unknown => (s.payment.object = "customer")],
460
+ [
461
+ "charge object",
462
+ (s: Fixture): unknown => (s.payment.latest_charge.object = "customer"),
463
+ ],
464
+ [
465
+ "balance object",
466
+ (s: Fixture): unknown =>
467
+ (s.payment.latest_charge.balance_transaction.object = "customer"),
468
+ ],
469
+ ["invoice object", (s: Fixture): unknown => (s.invoice.object = "customer")],
470
+ [
471
+ "subscription object",
472
+ (s: Fixture): unknown => (s.subscription.object = "customer"),
473
+ ],
474
+ ["line object", (s: Fixture): unknown => (s.line.object = "customer")],
475
+ ] as const)("refuses malformed %s identity", async (_name, mutate) => {
476
+ const s = fixture();
477
+ mutate(s);
478
+ expect(await s.resolve()).toEqual(conflict);
479
+ });
480
+
481
+ it("resolves original expanded price identifiers without consulting its current amount", async () => {
482
+ const s = fixture();
483
+ Object.assign(s.line.pricing.price_details, {
484
+ price: { id: "price_original", object: "price", unit_amount: 9999 },
485
+ });
486
+ expect(await s.resolve()).toMatchObject({
487
+ status: "ready",
488
+ value: { stripePriceId: "price_original", gross: 1000 },
489
+ });
490
+ });
491
+
492
+ it("finishes all funding pages before choosing a unique paid allocation", async () => {
493
+ const s = fixture();
494
+ const open = {
495
+ ...s.funding,
496
+ id: "inpay_open",
497
+ status: "open",
498
+ amount_paid: 0,
499
+ };
500
+ for (const phase of ["inverse", "funding"]) {
501
+ s.pages.set(phase + ":", { data: [open], has_more: true });
502
+ s.pages.set(phase + ":inpay_open", { data: [s.funding], has_more: false });
503
+ }
504
+ expect(
505
+ await s.resolve({ maxHistoryPages: 2, maxHistoryItems: 2 }),
506
+ ).toMatchObject({ status: "ready" });
507
+ const paginated = s.requests.filter((r) =>
508
+ r.path.includes("starting_after="),
509
+ );
510
+ expect(paginated).toHaveLength(2);
511
+ expect(
512
+ paginated.every((r) => r.path.includes("starting_after=inpay_open")),
513
+ ).toBe(true);
514
+ expect(s.requests.every((r) => !r.path.includes("status="))).toBe(true);
515
+ });
516
+
517
+ it.each(["inverse", "funding", "lines"])(
518
+ "holds %s history at the item limit",
519
+ async (phase) => {
520
+ const s = fixture();
521
+ s.pages.set(phase + ":", {
522
+ data: [phase === "lines" ? s.line : s.funding],
523
+ has_more: true,
524
+ });
525
+ expect(await s.resolve({ maxHistoryItems: 1 })).toEqual(incomplete);
526
+ },
527
+ );
528
+
529
+ it.each([0, -1, 1.5, Infinity, 2001])(
530
+ "rejects invalid item limit %s before reads",
531
+ async (maxHistoryItems) => {
532
+ const s = fixture();
533
+ expect(await s.resolve({ maxHistoryItems })).toEqual(
534
+ terminal("invalid_scope"),
535
+ );
536
+ expect(s.requests).toHaveLength(0);
537
+ },
538
+ );
539
+
540
+ it("distinguishes pending from non-payable payment state", async () => {
541
+ const pending = fixture();
542
+ pending.payment.status = "processing";
543
+ expect(await pending.resolve()).toEqual({
544
+ status: "not_ready",
545
+ reason: "provider_pending",
546
+ retryable: true,
547
+ });
548
+ const canceled = fixture();
549
+ canceled.payment.status = "canceled";
550
+ expect(await canceled.resolve()).toEqual(terminal("payment_not_payable"));
551
+ });
552
+
553
+ it("requires every supplied expected binding to match provider evidence", async () => {
554
+ for (const overrides of [
555
+ { customerAccountId: "acct_foreign" },
556
+ { invoiceId: "in_foreign" },
557
+ { subscriptionId: "sub_foreign" },
558
+ ]) {
559
+ const s = fixture();
560
+ expect(
561
+ await s.client.getVerifiedPaymentSource({} as RunCtx, {
562
+ ...s.options,
563
+ ...overrides,
564
+ }),
565
+ ).toEqual(conflict);
566
+ }
567
+ });
568
+
569
+ it("rejects malformed expanded original price IDs", async () => {
570
+ const s = fixture();
571
+ Object.assign(s.line.pricing.price_details, { price: { id: 123 } });
572
+ expect(await s.resolve()).toEqual(terminal("unsupported_source"));
573
+ });
574
+
575
+ it("requires original line subscription binding and refuses proration", async () => {
576
+ const mismatch = fixture();
577
+ mismatch.line.parent.subscription_item_details.subscription = "sub_foreign";
578
+ expect(await mismatch.resolve()).toEqual(conflict);
579
+ const prorated = fixture();
580
+ prorated.line.parent.subscription_item_details.proration = true;
581
+ expect(await prorated.resolve()).toEqual(terminal("unsupported_source"));
582
+ });