@fantastic.dev/better-stripe 0.48.1 → 0.50.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 (57) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/invoicePaymentPages.d.ts +2 -5
  4. package/dist/client/billing/invoicePaymentPages.d.ts.map +1 -1
  5. package/dist/client/billing/invoicePaymentPages.js +2 -58
  6. package/dist/client/billing/invoicePaymentPages.js.map +1 -1
  7. package/dist/client/billing/invoicePaymentRead.d.ts +17 -0
  8. package/dist/client/billing/invoicePaymentRead.d.ts.map +1 -0
  9. package/dist/client/billing/invoicePaymentRead.js +25 -0
  10. package/dist/client/billing/invoicePaymentRead.js.map +1 -0
  11. package/dist/client/billing/invoicePaymentShared.d.ts +22 -0
  12. package/dist/client/billing/invoicePaymentShared.d.ts.map +1 -0
  13. package/dist/client/billing/invoicePaymentShared.js +62 -0
  14. package/dist/client/billing/invoicePaymentShared.js.map +1 -0
  15. package/dist/client/billing/setup-intent-read.d.ts +22 -0
  16. package/dist/client/billing/setup-intent-read.d.ts.map +1 -0
  17. package/dist/client/billing/setup-intent-read.js +63 -0
  18. package/dist/client/billing/setup-intent-read.js.map +1 -0
  19. package/dist/client/billing/subscription-payment-method.d.ts +28 -0
  20. package/dist/client/billing/subscription-payment-method.d.ts.map +1 -0
  21. package/dist/client/billing/subscription-payment-method.js +101 -0
  22. package/dist/client/billing/subscription-payment-method.js.map +1 -0
  23. package/dist/client/index.d.ts +9 -0
  24. package/dist/client/index.d.ts.map +1 -1
  25. package/dist/client/index.js +10 -0
  26. package/dist/client/index.js.map +1 -1
  27. package/dist/client/invoiceReads.d.ts +3 -0
  28. package/dist/client/invoiceReads.d.ts.map +1 -1
  29. package/dist/client/invoiceReads.js +5 -0
  30. package/dist/client/invoiceReads.js.map +1 -1
  31. package/dist/component/_generated/component.d.ts +1 -0
  32. package/dist/component/_generated/component.d.ts.map +1 -1
  33. package/dist/component/connect/queries.d.ts +1 -0
  34. package/dist/component/connect/queries.d.ts.map +1 -1
  35. package/dist/component/connect/queries.js +10 -4
  36. package/dist/component/connect/queries.js.map +1 -1
  37. package/dist/component/refundHistory/queries.d.ts +1 -1
  38. package/docs/invoice-payment-pages.md +62 -0
  39. package/docs/react-workflows.md +9 -0
  40. package/docs/read-contracts.md +45 -0
  41. package/docs/setup-intent-recovery.md +27 -0
  42. package/docs/subscription-payment-methods.md +121 -0
  43. package/package.json +4 -2
  44. package/src/client/billing/invoicePaymentPages.ts +9 -74
  45. package/src/client/billing/invoicePaymentRead.test.ts +233 -0
  46. package/src/client/billing/invoicePaymentRead.ts +44 -0
  47. package/src/client/billing/invoicePaymentReadTransport.test.ts +101 -0
  48. package/src/client/billing/invoicePaymentShared.ts +84 -0
  49. package/src/client/billing/setup-intent-read.test.ts +284 -0
  50. package/src/client/billing/setup-intent-read.ts +97 -0
  51. package/src/client/billing/subscription-payment-method.test.ts +460 -0
  52. package/src/client/billing/subscription-payment-method.ts +177 -0
  53. package/src/client/index.ts +39 -0
  54. package/src/client/invoiceReads.ts +9 -0
  55. package/src/component/_generated/component.ts +1 -1
  56. package/src/component/connect/payment-unique.test.ts +195 -0
  57. package/src/component/connect/queries.ts +9 -4
@@ -0,0 +1,233 @@
1
+ import { afterEach, expect, it, vi } from "vitest";
2
+
3
+ import { getStripeClient } from "../helpers.js";
4
+ import { BetterStripe } from "../index.js";
5
+
6
+ afterEach(() => vi.restoreAllMocks());
7
+
8
+ function fixture() {
9
+ const key = `sk_test_exact_invoice_payment_${crypto.randomUUID()}`;
10
+ const stripe = getStripeClient(key);
11
+ const client = new BetterStripe({} as never, { STRIPE_SECRET_KEY: key });
12
+ const ctx = { runQuery: vi.fn() };
13
+ const scope = {
14
+ stripeInvoiceId: "in_original",
15
+ customerAccount: "acct_original",
16
+ stripeSubscriptionId: "sub_original",
17
+ };
18
+ const invoice = {
19
+ id: scope.stripeInvoiceId,
20
+ customer_account: scope.customerAccount,
21
+ parent: {
22
+ type: "subscription_details",
23
+ subscription_details: { subscription: scope.stripeSubscriptionId },
24
+ },
25
+ };
26
+ const payment = {
27
+ id: "inpay_original",
28
+ object: "invoice_payment",
29
+ invoice: scope.stripeInvoiceId,
30
+ amount_paid: 0,
31
+ amount_requested: 1200,
32
+ currency: "jpy",
33
+ status: "open",
34
+ payment: { type: "payment_intent", payment_intent: "pi_original" },
35
+ };
36
+ const invoiceRead = vi
37
+ .spyOn(stripe.invoices, "retrieve")
38
+ .mockResolvedValue(invoice as never);
39
+ const list = vi.spyOn(stripe.invoicePayments, "list").mockResolvedValue({
40
+ data: [payment],
41
+ has_more: false,
42
+ } as never);
43
+ const retrieve = vi
44
+ .spyOn(stripe.invoicePayments, "retrieve")
45
+ .mockResolvedValue(payment as never);
46
+ return { client, ctx, scope, invoice, invoiceRead, payment, list, retrieve };
47
+ }
48
+
49
+ it("retains the real public page reader and exact original zero units as a positive control", async () => {
50
+ const f = fixture();
51
+ const result = await f.client.getInvoicePaymentPageFromStripe(f.ctx, f.scope);
52
+ expect(result.page).toEqual([
53
+ {
54
+ invoicePayment: f.payment,
55
+ paymentIntentId: "pi_original",
56
+ referenceStatus: "payment_intent",
57
+ },
58
+ ]);
59
+ expect(f.list).toHaveBeenCalledOnce();
60
+ expect(f.retrieve).not.toHaveBeenCalled();
61
+ });
62
+
63
+ it("reads the exact original payment with zero paid units without enumerating", async () => {
64
+ const f = fixture();
65
+ const result = await f.client.getInvoicePaymentFromStripe(f.ctx, {
66
+ ...f.scope,
67
+ stripeInvoicePaymentId: f.payment.id,
68
+ });
69
+ expect(result).toEqual({
70
+ scope: f.scope,
71
+ invoicePayment: f.payment,
72
+ paymentIntentId: "pi_original",
73
+ referenceStatus: "payment_intent",
74
+ });
75
+ expect(f.retrieve).toHaveBeenCalledExactlyOnceWith("inpay_original");
76
+ expect(f.invoiceRead).toHaveBeenCalledExactlyOnceWith("in_original");
77
+ expect(f.list).not.toHaveBeenCalled();
78
+ });
79
+
80
+ it.each([
81
+ { stripeInvoicePaymentId: "bad" },
82
+ { stripeInvoiceId: "bad" },
83
+ { customerAccount: "cus_wrong" },
84
+ { stripeSubscriptionId: "bad" },
85
+ { connectedAccountId: "acct_other" },
86
+ ])(
87
+ "rejects invalid/unsupported selectors before provider access %#",
88
+ async (change) => {
89
+ const f = fixture();
90
+ await expect(
91
+ f.client.getInvoicePaymentFromStripe(f.ctx, {
92
+ ...f.scope,
93
+ stripeInvoicePaymentId: f.payment.id,
94
+ ...change,
95
+ }),
96
+ ).rejects.toThrow();
97
+ expect(f.invoiceRead).not.toHaveBeenCalled();
98
+ expect(f.retrieve).not.toHaveBeenCalled();
99
+ },
100
+ );
101
+
102
+ it.each([
103
+ { id: "in_other" },
104
+ { customer_account: "acct_other" },
105
+ { parent: null },
106
+ {
107
+ parent: {
108
+ type: "subscription_details",
109
+ subscription_details: { subscription: "sub_other" },
110
+ },
111
+ },
112
+ ])("holds foreign or missing original invoice binding %#", async (change) => {
113
+ const f = fixture();
114
+ f.invoiceRead.mockResolvedValue({ ...f.invoice, ...change } as never);
115
+ await expect(
116
+ f.client.getInvoicePaymentFromStripe(f.ctx, {
117
+ ...f.scope,
118
+ stripeInvoicePaymentId: f.payment.id,
119
+ }),
120
+ ).rejects.toThrow();
121
+ expect(f.retrieve).not.toHaveBeenCalled();
122
+ });
123
+
124
+ it.each([
125
+ null,
126
+ { id: "inpay_other" },
127
+ { invoice: "in_other" },
128
+ { object: "payment_intent" },
129
+ { payment: null },
130
+ { amount_requested: Number.MAX_SAFE_INTEGER + 1 },
131
+ { amount_paid: -1 },
132
+ { amount_paid: 1.5 },
133
+ { currency: "invalid" },
134
+ ])(
135
+ "rejects missing, mismatched or malformed exact provider evidence %#",
136
+ async (change) => {
137
+ const f = fixture();
138
+ f.retrieve.mockResolvedValue(
139
+ change === null
140
+ ? (null as never)
141
+ : ({ ...f.payment, ...change } as never),
142
+ );
143
+ await expect(
144
+ f.client.getInvoicePaymentFromStripe(f.ctx, {
145
+ ...f.scope,
146
+ stripeInvoicePaymentId: f.payment.id,
147
+ }),
148
+ ).rejects.toThrow();
149
+ expect(f.list).not.toHaveBeenCalled();
150
+ },
151
+ );
152
+
153
+ it.each([
154
+ {
155
+ type: "payment_intent",
156
+ payment_intent: { id: "pi_expanded" },
157
+ expected: "payment_intent",
158
+ id: "pi_expanded",
159
+ },
160
+ {
161
+ type: "payment_intent",
162
+ payment_intent: null,
163
+ expected: "unavailable",
164
+ id: null,
165
+ },
166
+ {
167
+ type: "payment_intent",
168
+ payment_intent: "malformed",
169
+ expected: "unavailable",
170
+ id: null,
171
+ },
172
+ { type: "charge", charge: "ch_original", expected: "unsupported", id: null },
173
+ { type: "future_reference", expected: "unsupported", id: null },
174
+ ])(
175
+ "preserves original exact row and honest reference distinction %#",
176
+ async ({ expected, id, ...payment }) => {
177
+ const f = fixture();
178
+ const row = {
179
+ ...f.payment,
180
+ invoice: { id: f.scope.stripeInvoiceId },
181
+ amount_paid: null,
182
+ status: "canceled",
183
+ payment,
184
+ };
185
+ f.retrieve.mockResolvedValue(row as never);
186
+ const result = await f.client.getInvoicePaymentFromStripe(f.ctx, {
187
+ ...f.scope,
188
+ stripeInvoicePaymentId: f.payment.id,
189
+ });
190
+ expect(result.invoicePayment).toEqual(row);
191
+ expect(result.referenceStatus).toBe(expected);
192
+ expect(result.paymentIntentId).toBe(id);
193
+ },
194
+ );
195
+
196
+ it.each(["invoice", "payment"])(
197
+ "propagates %s provider outage without empty fallback",
198
+ async (source) => {
199
+ const f = fixture();
200
+ const error = new Error("synthetic provider unavailable");
201
+ (source === "invoice" ? f.invoiceRead : f.retrieve).mockRejectedValue(
202
+ error,
203
+ );
204
+ await expect(
205
+ f.client.getInvoicePaymentFromStripe(f.ctx, {
206
+ ...f.scope,
207
+ stripeInvoicePaymentId: f.payment.id,
208
+ }),
209
+ ).rejects.toBe(error);
210
+ expect(f.list).not.toHaveBeenCalled();
211
+ },
212
+ );
213
+
214
+ it("freezes primitive original selectors before awaiting the invoice provider response", async () => {
215
+ const f = fixture();
216
+ const options = { ...f.scope, stripeInvoicePaymentId: f.payment.id };
217
+ let release = () => {};
218
+ f.invoiceRead.mockImplementation(async () => {
219
+ await new Promise<void>((resolve) => {
220
+ release = resolve;
221
+ });
222
+ return f.invoice as never;
223
+ });
224
+ const pending = f.client.getInvoicePaymentFromStripe(f.ctx, options);
225
+ options.stripeInvoiceId = "in_replaced";
226
+ options.stripeInvoicePaymentId = "inpay_replaced";
227
+ options.customerAccount = "acct_replaced";
228
+ options.stripeSubscriptionId = "sub_replaced";
229
+ release();
230
+ const result = await pending;
231
+ expect(f.retrieve).toHaveBeenCalledExactlyOnceWith("inpay_original");
232
+ expect(result.scope).toEqual(f.scope);
233
+ });
@@ -0,0 +1,44 @@
1
+ import type Stripe from "stripe";
2
+ import { z } from "zod";
3
+ import {
4
+ assertInvoicePaymentScope,
5
+ invoicePaymentScopeSchema,
6
+ paymentReference,
7
+ referenceId,
8
+ type InvoicePaymentScope,
9
+ type ProviderInvoicePaymentReference,
10
+ } from "./invoicePaymentShared.js";
11
+
12
+ const optionsSchema = invoicePaymentScopeSchema
13
+ .extend({
14
+ stripeInvoicePaymentId: z
15
+ .string()
16
+ .max(128)
17
+ .regex(/^inpay_[A-Za-z0-9_]+$/),
18
+ })
19
+ .strict();
20
+
21
+ export type InvoicePaymentReadOptions = z.input<typeof optionsSchema>;
22
+ export type ProviderInvoicePaymentRead = ProviderInvoicePaymentReference & {
23
+ scope: InvoicePaymentScope;
24
+ };
25
+
26
+ /** Exact platform read, without page enumeration or refund-eligibility inference. */
27
+ export async function getInvoicePaymentFromStripe(
28
+ stripe: Stripe,
29
+ input: InvoicePaymentReadOptions,
30
+ ): Promise<ProviderInvoicePaymentRead> {
31
+ const { stripeInvoicePaymentId, ...scope } = optionsSchema.parse(input);
32
+ await assertInvoicePaymentScope(stripe, scope);
33
+ const row = await stripe.invoicePayments.retrieve(stripeInvoicePaymentId);
34
+ if (
35
+ !row ||
36
+ row.object !== "invoice_payment" ||
37
+ row.id !== stripeInvoicePaymentId ||
38
+ referenceId(row.invoice) !== scope.stripeInvoiceId ||
39
+ !row.payment ||
40
+ typeof row.payment.type !== "string"
41
+ )
42
+ throw new Error("Invalid provider exact invoice payment scope or record");
43
+ return { scope, ...paymentReference(row) };
44
+ }
@@ -0,0 +1,101 @@
1
+ import type Stripe from "stripe";
2
+ import { expect, it, vi } from "vitest";
3
+ import { BetterStripe } from "../index.js";
4
+ import { getStripeClient } from "../helpers.js";
5
+
6
+ function fixture(failure = false) {
7
+ const key = `sk_test_exact_invoice_http_${crypto.randomUUID()}`;
8
+ const client = new BetterStripe({} as never, { STRIPE_SECRET_KEY: key });
9
+ const calls: { method: string; path: string; realm: string | undefined }[] =
10
+ [];
11
+ const sdk = getStripeClient(key);
12
+ const invoice = {
13
+ id: "in_original",
14
+ customer_account: "acct_original",
15
+ parent: {
16
+ type: "subscription_details",
17
+ subscription_details: { subscription: { id: "sub_original" } },
18
+ },
19
+ };
20
+ const row = {
21
+ id: "inpay_original",
22
+ object: "invoice_payment",
23
+ invoice: { id: "in_original" },
24
+ amount_paid: null,
25
+ amount_requested: 1200,
26
+ currency: "jpy",
27
+ status: "open",
28
+ payment: { type: "payment_intent", payment_intent: { id: "pi_original" } },
29
+ };
30
+ (
31
+ sdk as unknown as { _setApiField: (key: string, value: unknown) => void }
32
+ )._setApiField("httpClient", {
33
+ getClientName: () => "exact-invoice-payment-test",
34
+ makeRequest: async (
35
+ ...[, , path, method, headers]: Parameters<
36
+ ReturnType<typeof Stripe.createNodeHttpClient>["makeRequest"]
37
+ >
38
+ ) => {
39
+ calls.push({
40
+ method,
41
+ path,
42
+ realm: headers["Stripe-Account"] as string | undefined,
43
+ });
44
+ const isExact = path === "/v1/invoice_payments/inpay_original";
45
+ const data =
46
+ failure && isExact
47
+ ? {
48
+ error: {
49
+ type: "invalid_request_error",
50
+ message: "synthetic inaccessible payment",
51
+ },
52
+ }
53
+ : isExact
54
+ ? row
55
+ : invoice;
56
+ return {
57
+ getStatusCode: () => (failure && isExact ? 404 : 200),
58
+ getHeaders: () => ({}),
59
+ getRawResponse: () => ({}),
60
+ toJSON: async () => data,
61
+ toStream: () => {
62
+ throw new Error("Unexpected stream");
63
+ },
64
+ };
65
+ },
66
+ });
67
+ const ctx = { runQuery: vi.fn(), runMutation: vi.fn() };
68
+ const options = {
69
+ stripeInvoicePaymentId: "inpay_original",
70
+ stripeInvoiceId: "in_original",
71
+ customerAccount: "acct_original",
72
+ stripeSubscriptionId: "sub_original",
73
+ };
74
+ return { client, calls, ctx, options, row };
75
+ }
76
+
77
+ it("uses exact platform GET paths through the actual Stripe HTTP boundary, without list or writes", async () => {
78
+ const f = fixture();
79
+ const result = await f.client.getInvoicePaymentFromStripe(f.ctx, f.options);
80
+ expect(result.invoicePayment).toEqual(f.row);
81
+ expect(result.paymentIntentId).toBe("pi_original");
82
+ expect(f.calls).toEqual([
83
+ { method: "GET", path: "/v1/invoices/in_original", realm: undefined },
84
+ {
85
+ method: "GET",
86
+ path: "/v1/invoice_payments/inpay_original",
87
+ realm: undefined,
88
+ },
89
+ ]);
90
+ expect(f.ctx.runQuery).not.toHaveBeenCalled();
91
+ expect(f.ctx.runMutation).not.toHaveBeenCalled();
92
+ });
93
+
94
+ it("propagates an actual Stripe HTTP resource error rather than an empty result", async () => {
95
+ const f = fixture(true);
96
+ await expect(
97
+ f.client.getInvoicePaymentFromStripe(f.ctx, f.options),
98
+ ).rejects.toMatchObject({ statusCode: 404 });
99
+ expect(f.calls).toHaveLength(2);
100
+ expect(f.ctx.runMutation).not.toHaveBeenCalled();
101
+ });
@@ -0,0 +1,84 @@
1
+ import type Stripe from "stripe";
2
+ import { z } from "zod";
3
+
4
+ export const invoicePaymentScopeSchema = z
5
+ .object({
6
+ stripeInvoiceId: z
7
+ .string()
8
+ .max(128)
9
+ .regex(/^in_[A-Za-z0-9_]+$/),
10
+ customerAccount: z
11
+ .string()
12
+ .max(128)
13
+ .regex(/^acct_[A-Za-z0-9_]+$/),
14
+ stripeSubscriptionId: z
15
+ .string()
16
+ .max(128)
17
+ .regex(/^sub_[A-Za-z0-9_]+$/),
18
+ })
19
+ .strict();
20
+ export type InvoicePaymentScope = z.infer<typeof invoicePaymentScopeSchema>;
21
+ export type ProviderInvoicePaymentReference = {
22
+ invoicePayment: Stripe.InvoicePayment;
23
+ paymentIntentId: string | null;
24
+ referenceStatus: "payment_intent" | "unsupported" | "unavailable";
25
+ };
26
+
27
+ /** Normalize provider references without inferring missing identifiers. */
28
+ export function referenceId(value: string | { id: string } | null | undefined) {
29
+ return typeof value === "string" ? value : value?.id;
30
+ }
31
+ /** Keep financial evidence exact; reject units that JavaScript cannot safely represent. */
32
+ function assertRepresentableUnits(row: Stripe.InvoicePayment) {
33
+ const amounts = [
34
+ row.amount_requested,
35
+ ...(row.amount_paid === null ? [] : [row.amount_paid]),
36
+ ];
37
+ if (
38
+ amounts.some((amount) => !Number.isSafeInteger(amount) || amount < 0) ||
39
+ !/^[a-z]{3}$/.test(row.currency)
40
+ ) {
41
+ throw new Error("Invalid provider invoice payment units or currency");
42
+ }
43
+ }
44
+ /** Retain unsupported rows while distinguishing canonical and unavailable references. */
45
+ export function paymentReference(
46
+ invoicePayment: Stripe.InvoicePayment,
47
+ ): ProviderInvoicePaymentReference {
48
+ assertRepresentableUnits(invoicePayment);
49
+ const type = invoicePayment.payment.type;
50
+ const id =
51
+ type === "payment_intent"
52
+ ? referenceId(invoicePayment.payment.payment_intent)
53
+ : undefined;
54
+ const paymentIntentId = id && /^pi_[A-Za-z0-9_]+$/.test(id) ? id : null;
55
+ return {
56
+ invoicePayment,
57
+ paymentIntentId,
58
+ referenceStatus:
59
+ type !== "payment_intent"
60
+ ? "unsupported"
61
+ : paymentIntentId
62
+ ? "payment_intent"
63
+ : "unavailable",
64
+ };
65
+ }
66
+
67
+ /** Provider observation only; the caller still authorizes original host scope. */
68
+ export async function assertInvoicePaymentScope(
69
+ stripe: Stripe,
70
+ scope: InvoicePaymentScope,
71
+ ) {
72
+ const invoice = await stripe.invoices.retrieve(scope.stripeInvoiceId);
73
+ const parent = invoice.parent;
74
+ if (
75
+ invoice.id !== scope.stripeInvoiceId ||
76
+ invoice.customer_account !== scope.customerAccount ||
77
+ parent?.type !== "subscription_details" ||
78
+ referenceId(parent.subscription_details?.subscription) !==
79
+ scope.stripeSubscriptionId
80
+ )
81
+ throw new Error(
82
+ "Invalid provider invoice payment buyer or subscription scope",
83
+ );
84
+ }