@fantastic.dev/better-stripe 0.73.0 → 0.75.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 (75) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +1 -1
  3. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +16 -16
  4. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +32 -32
  5. package/dist/client/core/accountCloseOptions.d.ts +21 -0
  6. package/dist/client/core/accountCloseOptions.d.ts.map +1 -0
  7. package/dist/client/core/accountCloseOptions.js +15 -0
  8. package/dist/client/core/accountCloseOptions.js.map +1 -0
  9. package/dist/client/core/accountCloseScope.d.ts +9 -0
  10. package/dist/client/core/accountCloseScope.d.ts.map +1 -0
  11. package/dist/client/core/accountCloseScope.js +49 -0
  12. package/dist/client/core/accountCloseScope.js.map +1 -0
  13. package/dist/client/core/accountClosurePreview.d.ts +40 -0
  14. package/dist/client/core/accountClosurePreview.d.ts.map +1 -0
  15. package/dist/client/core/accountClosurePreview.js +98 -0
  16. package/dist/client/core/accountClosurePreview.js.map +1 -0
  17. package/dist/client/core/accounts.d.ts +3 -6
  18. package/dist/client/core/accounts.d.ts.map +1 -1
  19. package/dist/client/core/accounts.js +21 -5
  20. package/dist/client/core/accounts.js.map +1 -1
  21. package/dist/client/index.d.ts +8 -6
  22. package/dist/client/index.d.ts.map +1 -1
  23. package/dist/client/index.js +7 -0
  24. package/dist/client/index.js.map +1 -1
  25. package/dist/client/products/catalogClient.d.ts +2 -0
  26. package/dist/client/products/catalogClient.d.ts.map +1 -1
  27. package/dist/client/products/catalogClient.js.map +1 -1
  28. package/dist/client/products/products.d.ts +2 -0
  29. package/dist/client/products/products.d.ts.map +1 -1
  30. package/dist/client/products/products.js +3 -1
  31. package/dist/client/products/products.js.map +1 -1
  32. package/dist/client/publicTypes.d.ts +2 -0
  33. package/dist/client/publicTypes.d.ts.map +1 -1
  34. package/dist/client/usage/observationClient.d.ts +2 -2
  35. package/dist/client/usage/observationClient.d.ts.map +1 -1
  36. package/dist/component/_generated/api.d.ts +2 -0
  37. package/dist/component/_generated/api.d.ts.map +1 -1
  38. package/dist/component/_generated/api.js.map +1 -1
  39. package/dist/component/_generated/component.d.ts +14 -0
  40. package/dist/component/_generated/component.d.ts.map +1 -1
  41. package/dist/component/accountClosure/blockers.d.ts +6 -0
  42. package/dist/component/accountClosure/blockers.d.ts.map +1 -0
  43. package/dist/component/accountClosure/blockers.js +43 -0
  44. package/dist/component/accountClosure/blockers.js.map +1 -0
  45. package/dist/component/accountClosure/mutations.d.ts.map +1 -1
  46. package/dist/component/accountClosure/mutations.js +6 -31
  47. package/dist/component/accountClosure/mutations.js.map +1 -1
  48. package/dist/component/accountClosure/queries.d.ts +48 -0
  49. package/dist/component/accountClosure/queries.d.ts.map +1 -1
  50. package/dist/component/accountClosure/queries.js +32 -0
  51. package/dist/component/accountClosure/queries.js.map +1 -1
  52. package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
  53. package/dist/component/payoutRelease/queries.d.ts +2 -2
  54. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  55. package/dist/component/processingCostReconciliation/rollback.d.ts +1 -1
  56. package/docs/client-api.md +74 -0
  57. package/docs/react-workflows.md +31 -0
  58. package/package.json +1 -1
  59. package/src/client/core/account-close-guard.test.ts +349 -0
  60. package/src/client/core/account-closure-preview.test.ts +219 -0
  61. package/src/client/core/accountCloseOptions.ts +23 -0
  62. package/src/client/core/accountCloseScope.ts +87 -0
  63. package/src/client/core/accountClosurePreview.ts +149 -0
  64. package/src/client/core/accounts.ts +33 -7
  65. package/src/client/index.ts +14 -2
  66. package/src/client/products/catalogClient.ts +2 -0
  67. package/src/client/products/product-descriptor-inheritance.test.ts +245 -0
  68. package/src/client/products/products.ts +9 -4
  69. package/src/client/publicTypes.ts +6 -0
  70. package/src/component/_generated/api.ts +2 -0
  71. package/src/component/_generated/component.ts +16 -0
  72. package/src/component/accountClosure/blockers.test.ts +114 -0
  73. package/src/component/accountClosure/blockers.ts +60 -0
  74. package/src/component/accountClosure/mutations.ts +6 -39
  75. package/src/component/accountClosure/queries.ts +41 -1
@@ -0,0 +1,149 @@
1
+ import type Stripe from "stripe";
2
+ import { z } from "zod";
3
+ import type { Component, RunCtx } from "../helpers.js";
4
+ import type { AccountBalance } from "../connect/payouts.js";
5
+ import { getAccountBalance } from "../connect/payouts.js";
6
+ import { getCheckoutSessionPageFromStripe } from "../billing/checkoutPages.js";
7
+ import { componentRef } from "../webhooks/helpers.js";
8
+ import { closureConfigurations } from "./accountCloseOptions.js";
9
+ import type { ClosureBlocker } from "../../component/accountClosure/blockers.js";
10
+ import type { AppliedConfiguration } from "../../component/core/validators.js";
11
+
12
+ export type ClosureObservation<T> =
13
+ { status: "observed"; value: T } | { status: "unknown" };
14
+ export type AccountClosurePreview = {
15
+ stripeAccountId: string;
16
+ observedAt: number;
17
+ financialCoverage: "unknown";
18
+ account: ClosureObservation<{
19
+ appliedConfigurations: AppliedConfiguration[];
20
+ closed: boolean;
21
+ }>;
22
+ balances: ClosureObservation<AccountBalance[]>;
23
+ openSessions: ClosureObservation<{ sessionIds: string[]; hasMore: boolean }>;
24
+ componentBlockers: ClosureObservation<ClosureBlocker[]>;
25
+ knownBlockers: string[];
26
+ unknownReasons: string[];
27
+ };
28
+ export type AccountClosurePreviewOptions = {
29
+ stripeAccountId: string;
30
+ sessionLimit?: number;
31
+ };
32
+ export const accountClosurePreviewOptionsSchema = z
33
+ .object({
34
+ stripeAccountId: z
35
+ .string()
36
+ .regex(/^acct_[A-Za-z0-9_]+$/)
37
+ .max(128),
38
+ sessionLimit: z.number().int().min(1).max(100).optional(),
39
+ })
40
+ .strict();
41
+
42
+ /** Point-in-time known blockers; never a positive closure authorization. */
43
+ export async function previewAccountClosure(
44
+ stripe: Stripe,
45
+ component: Component,
46
+ ctx: RunCtx,
47
+ input: AccountClosurePreviewOptions,
48
+ ): Promise<AccountClosurePreview> {
49
+ const opts = accountClosurePreviewOptionsSchema.parse(input);
50
+ const [account, balances, openSessions, componentBlockers] =
51
+ await Promise.all([
52
+ observe(async () => {
53
+ const account = z
54
+ .object({
55
+ id: z.literal(opts.stripeAccountId),
56
+ closed: z.boolean(),
57
+ applied_configurations: closureConfigurations,
58
+ })
59
+ .passthrough()
60
+ .parse(await stripe.v2.core.accounts.retrieve(opts.stripeAccountId));
61
+ return {
62
+ appliedConfigurations: account.applied_configurations,
63
+ closed: account.closed,
64
+ };
65
+ }),
66
+ observe(async () =>
67
+ z
68
+ .array(
69
+ z
70
+ .object({
71
+ available: z.number().int().safe(),
72
+ pending: z.number().int().safe(),
73
+ currency: z.string().regex(/^[a-z]{3}$/),
74
+ })
75
+ .strict(),
76
+ )
77
+ .parse(
78
+ await getAccountBalance(stripe, {
79
+ stripeAccountId: opts.stripeAccountId,
80
+ }),
81
+ ),
82
+ ),
83
+ observe(async () => {
84
+ const page = await getCheckoutSessionPageFromStripe(stripe, {
85
+ customerAccount: opts.stripeAccountId,
86
+ status: "open",
87
+ limit: opts.sessionLimit ?? 25,
88
+ });
89
+ return {
90
+ sessionIds: page.page.map((session) => session.id),
91
+ hasMore: page.hasMore,
92
+ };
93
+ }),
94
+ observe(async () =>
95
+ z
96
+ .array(
97
+ z.enum(["usageCorrections", "prepaidCredits", "usageEnrollment"]),
98
+ )
99
+ .max(3)
100
+ .parse(
101
+ await ctx.runQuery(
102
+ componentRef(component, "accountClosure/queries/knownBlockers"),
103
+ { stripeAccountId: opts.stripeAccountId },
104
+ ),
105
+ ),
106
+ ),
107
+ ]);
108
+ const knownBlockers: string[] =
109
+ componentBlockers.status === "observed" ? [...componentBlockers.value] : [];
110
+ const unknownReasons = ["financial_coverage_unknown"];
111
+ if (account.status === "unknown") unknownReasons.push("account_unavailable");
112
+ if (balances.status === "unknown")
113
+ unknownReasons.push("balances_unavailable");
114
+ else if (
115
+ balances.value.some((item) => item.available !== 0 || item.pending !== 0)
116
+ )
117
+ knownBlockers.push("nonzero_balance");
118
+ if (openSessions.status === "unknown")
119
+ unknownReasons.push("open_sessions_unavailable");
120
+ else {
121
+ if (openSessions.value.sessionIds.length)
122
+ knownBlockers.push("open_checkout_sessions");
123
+ if (openSessions.value.hasMore)
124
+ unknownReasons.push("open_sessions_truncated");
125
+ }
126
+ if (componentBlockers.status === "unknown")
127
+ unknownReasons.push("component_blockers_unavailable");
128
+ return {
129
+ stripeAccountId: opts.stripeAccountId,
130
+ observedAt: Date.now(),
131
+ financialCoverage: "unknown",
132
+ account,
133
+ balances,
134
+ openSessions,
135
+ componentBlockers,
136
+ knownBlockers,
137
+ unknownReasons,
138
+ };
139
+ }
140
+
141
+ async function observe<T>(
142
+ read: () => Promise<T>,
143
+ ): Promise<ClosureObservation<T>> {
144
+ try {
145
+ return { status: "observed", value: await read() };
146
+ } catch {
147
+ return { status: "unknown" };
148
+ }
149
+ }
@@ -1,6 +1,15 @@
1
1
  import type { AccountByStripeIdOptions } from "../originalIdReadOptions.js";
2
2
  import { addCustomerConfiguration } from "./accountConfigurations.js";
3
3
  import { idempotencyOptions } from "./idempotency.js";
4
+ import {
5
+ closeAccountOptionsSchema,
6
+ type CloseAccountOptions,
7
+ } from "./accountCloseOptions.js";
8
+ import {
9
+ confirmedClosureScope,
10
+ guardedAccountIsClosed,
11
+ assertGuardedCloseAcknowledgement,
12
+ } from "./accountCloseScope.js";
4
13
  export type CreateAccountOptions = {
5
14
  userId: string;
6
15
  email?: string;
@@ -432,25 +441,39 @@ export async function closeAccount(
432
441
  stripe: Stripe,
433
442
  component: Component,
434
443
  ctx: RunCtx,
435
- opts: { stripeAccountId: string },
444
+ opts: CloseAccountOptions,
436
445
  ): Promise<{ closed: boolean }> {
446
+ const isGuarded = opts.expectedAppliedConfigurations !== undefined;
447
+ if (isGuarded) closeAccountOptionsSchema.parse(opts);
448
+ const originalOptions = isGuarded
449
+ ? { stripeAccountId: opts.stripeAccountId }
450
+ : opts;
437
451
  const { closure, isRetry } = await runMutationOrThrow(
438
452
  ctx,
439
453
  componentRef(component, "accountClosure/mutations/prepare"),
440
- opts,
454
+ originalOptions,
441
455
  );
456
+ if (isGuarded) confirmedClosureScope(opts, closure);
442
457
  if (closure.state === "closed") return { closed: true };
443
458
  let appliedConfigs = closure.appliedConfigurations;
444
459
  let isProviderClosed = false;
445
- if (isRetry || appliedConfigs === undefined) {
460
+ if (isGuarded) {
461
+ isProviderClosed = await guardedAccountIsClosed(
462
+ stripe,
463
+ component,
464
+ ctx,
465
+ opts,
466
+ closure,
467
+ );
468
+ } else if (isRetry || appliedConfigs === undefined) {
446
469
  const account = await stripe.v2.core.accounts.retrieve(
447
470
  opts.stripeAccountId,
448
471
  );
449
472
  appliedConfigs ??= account.applied_configurations ?? [];
450
473
  isProviderClosed = account.closed === true;
451
474
  }
452
- if (!isProviderClosed)
453
- await stripe.v2.core.accounts.close(
475
+ if (!isProviderClosed) {
476
+ const response = await stripe.v2.core.accounts.close(
454
477
  opts.stripeAccountId,
455
478
  {
456
479
  applied_configurations: (appliedConfigs ??
@@ -458,10 +481,13 @@ export async function closeAccount(
458
481
  },
459
482
  { idempotencyKey: `betterstripe-close:${opts.stripeAccountId}` },
460
483
  );
484
+ if (isGuarded)
485
+ assertGuardedCloseAcknowledgement(response, opts.stripeAccountId);
486
+ }
461
487
  await runMutationOrThrow(
462
488
  ctx,
463
489
  componentRef(component, "accountClosure/mutations/complete"),
464
- opts,
490
+ originalOptions,
465
491
  );
466
492
 
467
493
  return { closed: true };
@@ -471,7 +497,7 @@ export async function restartAccountOnboarding(
471
497
  stripe: Stripe,
472
498
  component: Component,
473
499
  ctx: RunCtx,
474
- opts: { stripeAccountId: string },
500
+ opts: CloseAccountOptions,
475
501
  ): Promise<{ closed: boolean }> {
476
502
  return closeAccount(stripe, component, ctx, opts);
477
503
  }
@@ -35,6 +35,13 @@ export type {
35
35
  export type { RefundSyncScope } from "./connect/refundSyncValidation.js";
36
36
  import * as personalAccountMappingImpl from "./core/personalAccountMapping.js";
37
37
  export type * from "./publicTypes.js";
38
+ export { closeAccountOptionsSchema } from "./core/accountCloseOptions.js";
39
+ export { accountClosurePreviewOptionsSchema } from "./core/accountClosurePreview.js";
40
+ import type { CloseAccountOptions } from "./core/accountCloseOptions.js";
41
+ import {
42
+ previewAccountClosure,
43
+ type AccountClosurePreviewOptions,
44
+ } from "./core/accountClosurePreview.js";
38
45
  export * from "./financialOutcomes/index.js";
39
46
  export * from "./processingCostDeficit/index.js";
40
47
  import * as accountClosuresImpl from "./core/accountClosures.js";
@@ -506,16 +513,21 @@ export class BetterStripe extends PaymentSourceClient {
506
513
  return accountsImpl.listStripeAccounts(this.stripe(), ctx, opts);
507
514
  }
508
515
 
516
+ /** Known point-in-time blockers only. Host authentication and independent clearance remain required. */
517
+ async previewAccountClosure(ctx: RunCtx, opts: AccountClosurePreviewOptions) {
518
+ return previewAccountClosure(this.stripe(), this.component, ctx, opts);
519
+ }
520
+
509
521
  async closeAccount(
510
522
  ctx: RunCtx,
511
- opts: { stripeAccountId: string },
523
+ opts: CloseAccountOptions,
512
524
  ): Promise<{ closed: boolean }> {
513
525
  return accountsImpl.closeAccount(this.stripe(), this.component, ctx, opts);
514
526
  }
515
527
 
516
528
  async restartAccountOnboarding(
517
529
  ctx: RunCtx,
518
- opts: { stripeAccountId: string },
530
+ opts: CloseAccountOptions,
519
531
  ): Promise<{ closed: boolean }> {
520
532
  return accountsImpl.restartAccountOnboarding(
521
533
  this.stripe(),
@@ -121,6 +121,8 @@ export abstract class CatalogClient extends BillingPortalClient {
121
121
  metadata?: Record<string, string>;
122
122
  /** Explicit string overrides store defaults; null clears the descriptor. */
123
123
  statementDescriptor?: string | null;
124
+ /** False disables inherited defaults; explicit string/null still apply. */
125
+ inheritStatementDescriptor?: boolean;
124
126
  /** Reuse only for identical retries of the same provider SET. */
125
127
  idempotencyKey?: string;
126
128
  },
@@ -0,0 +1,245 @@
1
+ import { componentsGeneric } from "convex/server";
2
+ import Stripe from "stripe";
3
+ import { expect, expectTypeOf, it, vi } from "vitest";
4
+
5
+ import { STRIPE_API_VERSION } from "../constants.js";
6
+ import type { Component, RunCtx } from "../helpers.js";
7
+ import { BetterStripe } from "../index.js";
8
+
9
+ function fixture(storeDescriptor: string | undefined = "ORIGINAL STORE") {
10
+ const requests: { path: string; key: string | null; form: string }[] = [];
11
+ const state: {
12
+ accountId: string;
13
+ storeDescriptor: string | undefined;
14
+ hasLostReply: boolean;
15
+ failure?: { status: number; type: string; code?: string };
16
+ } = { accountId: "acct_original", storeDescriptor, hasLostReply: false };
17
+ const provider = new Stripe("sk_test_descriptor_inheritance_synthetic", {
18
+ apiVersion: STRIPE_API_VERSION,
19
+ maxNetworkRetries: 0,
20
+ httpClient: Stripe.createFetchHttpClient(async (url, init) => {
21
+ expect(init?.method).toBe("POST");
22
+ expect(new URL(String(url)).origin).toBe("https://api.stripe.com");
23
+ requests.push({
24
+ path: new URL(String(url)).pathname,
25
+ key: new Headers(init?.headers).get("Idempotency-Key"),
26
+ form: String(init?.body ?? ""),
27
+ });
28
+ if (state.hasLostReply) throw new Error("Synthetic lost SET reply");
29
+ return new Response(
30
+ JSON.stringify(
31
+ state.failure
32
+ ? { error: { ...state.failure, message: "Synthetic SET failure" } }
33
+ : { id: "prod_original", object: "product", active: true },
34
+ ),
35
+ {
36
+ status: state.failure?.status ?? 200,
37
+ headers: { "content-type": "application/json" },
38
+ },
39
+ );
40
+ }),
41
+ });
42
+ class Client extends BetterStripe {
43
+ protected override stripe() {
44
+ return provider;
45
+ }
46
+ }
47
+ const client = new Client(
48
+ componentsGeneric().betterStripe as unknown as Component,
49
+ {
50
+ STRIPE_SECRET_KEY: "sk_test_descriptor_inheritance_synthetic",
51
+ statementDescriptorSuffix: "PLATFORM",
52
+ },
53
+ );
54
+ const ctx: RunCtx = {
55
+ runQuery: vi
56
+ .fn()
57
+ .mockImplementation(async (_ref, args) =>
58
+ args.stripeProductId
59
+ ? { accountId: state.accountId }
60
+ : { statementDescriptor: state.storeDescriptor },
61
+ ),
62
+ };
63
+ return { client, ctx, requests, state };
64
+ }
65
+
66
+ it("omits the inherited descriptor without reading ambient product or account defaults", async () => {
67
+ const f = fixture();
68
+ const input = {
69
+ stripeProductId: "prod_original",
70
+ name: "OriginalEdit",
71
+ inheritStatementDescriptor: false,
72
+ idempotencyKey: "descriptor-omission:original",
73
+ };
74
+ await f.client.updateProduct(f.ctx, input);
75
+ expect(
76
+ new URLSearchParams(f.requests[0]?.form).has("statement_descriptor"),
77
+ f.requests[0]?.form,
78
+ ).toBe(false);
79
+ expect(f.ctx.runQuery).not.toHaveBeenCalled();
80
+ expect(f.requests).toEqual([
81
+ {
82
+ path: "/v1/products/prod_original",
83
+ key: "descriptor-omission:original",
84
+ form: "name=OriginalEdit",
85
+ },
86
+ ]);
87
+ });
88
+
89
+ it.each([" EXPLICIT STORE ", null])(
90
+ "keeps explicit descriptor %j precedence with inheritance disabled",
91
+ async (statementDescriptor) => {
92
+ const f = fixture();
93
+ const input = {
94
+ stripeProductId: "prod_original",
95
+ inheritStatementDescriptor: false,
96
+ statementDescriptor,
97
+ };
98
+ await f.client.updateProduct(f.ctx, input);
99
+ expect(f.requests).toHaveLength(1);
100
+ expect(
101
+ new URLSearchParams(f.requests[0]?.form).get("statement_descriptor"),
102
+ ).toBe(statementDescriptor === null ? "" : "EXPLICIT STORE");
103
+ expect(f.ctx.runQuery).not.toHaveBeenCalled();
104
+ },
105
+ );
106
+
107
+ it("rejects an invalid explicit descriptor before HTTP or ambient reads when inheritance is disabled", async () => {
108
+ const f = fixture();
109
+ const input = {
110
+ stripeProductId: "prod_original",
111
+ inheritStatementDescriptor: false,
112
+ statementDescriptor: "BAD*NAME",
113
+ };
114
+ await expect(f.client.updateProduct(f.ctx, input)).rejects.toThrow(
115
+ /statement descriptor/i,
116
+ );
117
+ expect(f.requests).toHaveLength(0);
118
+ expect(f.ctx.runQuery).not.toHaveBeenCalled();
119
+ });
120
+
121
+ it.each(
122
+ [undefined, true].flatMap((inheritStatementDescriptor) =>
123
+ [undefined, "LEGACY STORE"].map((storeDescriptor) => ({
124
+ inheritStatementDescriptor,
125
+ storeDescriptor,
126
+ })),
127
+ ),
128
+ )(
129
+ "keeps legacy inheritance $inheritStatementDescriptor and fallback $storeDescriptor",
130
+ async ({ inheritStatementDescriptor, storeDescriptor }) => {
131
+ const f = fixture();
132
+ f.state.storeDescriptor = storeDescriptor;
133
+ const input = {
134
+ stripeProductId: "prod_original",
135
+ ...(inheritStatementDescriptor === undefined
136
+ ? {}
137
+ : { inheritStatementDescriptor }),
138
+ };
139
+ await f.client.updateProduct(f.ctx, input);
140
+ expect(f.ctx.runQuery).toHaveBeenCalledTimes(2);
141
+ expect(
142
+ new URLSearchParams(f.requests[0]?.form).get("statement_descriptor"),
143
+ ).toBe(storeDescriptor ?? "PLATFORM");
144
+ },
145
+ );
146
+
147
+ it("reuses identical immutable input and key after a lost reply despite ambient retargeting", async () => {
148
+ const f = fixture();
149
+ const input = Object.freeze({
150
+ stripeProductId: "prod_original",
151
+ name: "OriginalEdit",
152
+ metadata: Object.freeze({ communityId: "original" }),
153
+ inheritStatementDescriptor: false,
154
+ idempotencyKey: "descriptor-omission:original",
155
+ });
156
+ f.state.hasLostReply = true;
157
+ await expect(f.client.updateProduct(f.ctx, input)).rejects.toBeInstanceOf(
158
+ Stripe.errors.StripeConnectionError,
159
+ );
160
+ f.state.hasLostReply = false;
161
+ f.state.accountId = "acct_retargeted";
162
+ f.state.storeDescriptor = "RETARGETED STORE";
163
+ await f.client.updateProduct(f.ctx, input);
164
+ expect(f.requests).toHaveLength(2);
165
+ expect(f.requests[1]).toEqual(f.requests[0]);
166
+ expect(f.requests[0]?.key).toBe(input.idempotencyKey);
167
+ expect(
168
+ new URLSearchParams(f.requests[0]?.form).has("statement_descriptor"),
169
+ ).toBe(false);
170
+ expect(
171
+ new URLSearchParams(f.requests[0]?.form).get("metadata[communityId]"),
172
+ ).toBe("original");
173
+ expect(f.ctx.runQuery).not.toHaveBeenCalled();
174
+ });
175
+
176
+ it("keeps independent original products and caller keys separate", async () => {
177
+ const f = fixture();
178
+ for (const suffix of ["one", "two"]) {
179
+ const input = {
180
+ stripeProductId: `prod_${suffix}`,
181
+ name: `Plan${suffix}`,
182
+ inheritStatementDescriptor: false,
183
+ idempotencyKey: `descriptor-omission:${suffix}`,
184
+ };
185
+ await f.client.updateProduct(f.ctx, input);
186
+ }
187
+ expect(f.requests.map(({ path, key, form }) => [path, key, form])).toEqual([
188
+ ["/v1/products/prod_one", "descriptor-omission:one", "name=Planone"],
189
+ ["/v1/products/prod_two", "descriptor-omission:two", "name=Plantwo"],
190
+ ]);
191
+ expect(f.ctx.runQuery).not.toHaveBeenCalled();
192
+ });
193
+
194
+ it.each([400, 409, 500])(
195
+ "preserves HTTP%i and the original omission/key with one transport attempt",
196
+ async (status) => {
197
+ const f = fixture();
198
+ f.state.failure = {
199
+ status,
200
+ type: status === 500 ? "api_error" : "idempotency_error",
201
+ code: status === 409 ? "idempotency_key_in_use" : undefined,
202
+ };
203
+ const input = {
204
+ stripeProductId: "prod_original",
205
+ name: "OriginalEdit",
206
+ inheritStatementDescriptor: false,
207
+ idempotencyKey: "descriptor-omission:error",
208
+ };
209
+ const result = f.client.updateProduct(f.ctx, input);
210
+ await expect(result).rejects.toBeInstanceOf(
211
+ status === 400
212
+ ? Stripe.errors.StripeIdempotencyError
213
+ : Stripe.errors.StripeAPIError,
214
+ );
215
+ await expect(result).rejects.toMatchObject({
216
+ statusCode: status,
217
+ code: status === 409 ? "idempotency_key_in_use" : undefined,
218
+ });
219
+ expect(f.requests).toEqual([
220
+ {
221
+ path: "/v1/products/prod_original",
222
+ key: "descriptor-omission:error",
223
+ form: "name=OriginalEdit",
224
+ },
225
+ ]);
226
+ expect(f.ctx.runQuery).not.toHaveBeenCalled();
227
+ },
228
+ );
229
+
230
+ it("exposes only an optional boolean on the public update type", () => {
231
+ type Input = Parameters<BetterStripe["updateProduct"]>[1];
232
+ expectTypeOf<Input>()
233
+ .toHaveProperty("inheritStatementDescriptor")
234
+ .toEqualTypeOf<boolean | undefined>();
235
+ expectTypeOf<{
236
+ stripeProductId: string;
237
+ inheritStatementDescriptor: string;
238
+ }>().not.toExtend<Input>();
239
+ expectTypeOf<
240
+ Parameters<BetterStripe["createProduct"]>[1]
241
+ >().not.toHaveProperty("inheritStatementDescriptor");
242
+ expectTypeOf<
243
+ Parameters<BetterStripe["deactivateProduct"]>[1]
244
+ >().not.toHaveProperty("inheritStatementDescriptor");
245
+ });
@@ -139,6 +139,8 @@ export async function updateProduct(
139
139
  defaultStatementDescriptorSuffix?: string;
140
140
  /** String overrides store defaults; null clears without restoring a fallback. */
141
141
  statementDescriptor?: string | null;
142
+ /** False disables inherited defaults; explicit string/null still apply. */
143
+ inheritStatementDescriptor?: boolean;
142
144
  /** Caller-owned stable key for identical retries of this provider SET. */
143
145
  idempotencyKey?: string;
144
146
  },
@@ -157,10 +159,13 @@ export async function updateProduct(
157
159
  // from the stored product record so a store that set/changed its descriptor
158
160
  // propagates to its products' first-invoice charges. Re-set only when a value
159
161
  // resolves (never clears an existing descriptor).
160
- const stored = (await ctx.runQuery(
161
- componentRef(component, "products/queries/getProductByStripeId"),
162
- { stripeProductId: opts.stripeProductId },
163
- )) as { accountId?: string } | null;
162
+ const stored =
163
+ opts.inheritStatementDescriptor === false
164
+ ? null
165
+ : ((await ctx.runQuery(
166
+ componentRef(component, "products/queries/getProductByStripeId"),
167
+ { stripeProductId: opts.stripeProductId },
168
+ )) as { accountId?: string } | null);
164
169
  const statementDescriptor = await resolveProductStatementDescriptor(
165
170
  component,
166
171
  ctx,
@@ -1,4 +1,10 @@
1
1
  export type { StripeAccountClosure } from "./core/accountClosures.js";
2
+ export type { CloseAccountOptions } from "./core/accountCloseOptions.js";
3
+ export type {
4
+ AccountClosurePreview,
5
+ AccountClosurePreviewOptions,
6
+ ClosureObservation,
7
+ } from "./core/accountClosurePreview.js";
2
8
  export type {
3
9
  BetterStripeOptions,
4
10
  FeeOverride,
@@ -8,6 +8,7 @@
8
8
  * @module
9
9
  */
10
10
 
11
+ import type * as accountClosure_blockers from "../accountClosure/blockers.js";
11
12
  import type * as accountClosure_helpers from "../accountClosure/helpers.js";
12
13
  import type * as accountClosure_mutations from "../accountClosure/mutations.js";
13
14
  import type * as accountClosure_queries from "../accountClosure/queries.js";
@@ -226,6 +227,7 @@ import type {
226
227
  import { anyApi, componentsGeneric } from "convex/server";
227
228
 
228
229
  const fullApi: ApiFromModules<{
230
+ "accountClosure/blockers": typeof accountClosure_blockers;
229
231
  "accountClosure/helpers": typeof accountClosure_helpers;
230
232
  "accountClosure/mutations": typeof accountClosure_mutations;
231
233
  "accountClosure/queries": typeof accountClosure_queries;
@@ -55,6 +55,15 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
55
55
  >;
56
56
  };
57
57
  queries: {
58
+ currentOwner: FunctionReference<
59
+ "query",
60
+ "internal",
61
+ { stripeAccountId: string },
62
+ | { status: "missing" }
63
+ | { status: "ambiguous" }
64
+ | { orgId?: string; status: "unique"; userId: string },
65
+ Name
66
+ >;
58
67
  getClosedAccountByStripeId: FunctionReference<
59
68
  "query",
60
69
  "internal",
@@ -73,6 +82,13 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
73
82
  } | null,
74
83
  Name
75
84
  >;
85
+ knownBlockers: FunctionReference<
86
+ "query",
87
+ "internal",
88
+ { stripeAccountId: string },
89
+ Array<"usageCorrections" | "prepaidCredits" | "usageEnrollment">,
90
+ Name
91
+ >;
76
92
  listClosedAccountsByUserId: FunctionReference<
77
93
  "query",
78
94
  "internal",