@fantastic.dev/better-stripe 0.47.1 → 0.48.1

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 (110) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/historyPages.d.ts +22 -0
  4. package/dist/client/billing/historyPages.d.ts.map +1 -0
  5. package/dist/client/billing/historyPages.js +8 -0
  6. package/dist/client/billing/historyPages.js.map +1 -0
  7. package/dist/client/billing/subscriptions.d.ts +2 -3
  8. package/dist/client/billing/subscriptions.d.ts.map +1 -1
  9. package/dist/client/billing/subscriptions.js.map +1 -1
  10. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +10 -0
  11. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  12. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +5 -0
  13. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  14. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +10 -0
  15. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  16. package/dist/client/connect/payoutSyncTestHelpers.d.ts +5 -0
  17. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  18. package/dist/client/core/accounts.d.ts +2 -3
  19. package/dist/client/core/accounts.d.ts.map +1 -1
  20. package/dist/client/core/accounts.js.map +1 -1
  21. package/dist/client/index.d.ts +3 -6
  22. package/dist/client/index.d.ts.map +1 -1
  23. package/dist/client/index.js.map +1 -1
  24. package/dist/client/originalIdReadOptions.d.ts +10 -0
  25. package/dist/client/originalIdReadOptions.d.ts.map +1 -0
  26. package/dist/client/originalIdReadOptions.js +2 -0
  27. package/dist/client/originalIdReadOptions.js.map +1 -0
  28. package/dist/client/publicTypes.d.ts +2 -0
  29. package/dist/client/publicTypes.d.ts.map +1 -1
  30. package/dist/client/readContracts.d.ts +4 -0
  31. package/dist/client/readContracts.d.ts.map +1 -1
  32. package/dist/client/readContracts.js +8 -0
  33. package/dist/client/readContracts.js.map +1 -1
  34. package/dist/client/webhooks/handler.d.ts.map +1 -1
  35. package/dist/client/webhooks/handler.js +6 -3
  36. package/dist/client/webhooks/handler.js.map +1 -1
  37. package/dist/client/webhooks/processors.d.ts.map +1 -1
  38. package/dist/client/webhooks/processors.js +3 -65
  39. package/dist/client/webhooks/processors.js.map +1 -1
  40. package/dist/client/webhooks/refundDelivery.d.ts +5 -0
  41. package/dist/client/webhooks/refundDelivery.d.ts.map +1 -0
  42. package/dist/client/webhooks/refundDelivery.js +28 -0
  43. package/dist/client/webhooks/refundDelivery.js.map +1 -0
  44. package/dist/client/webhooks/refundRecovery.d.ts +5 -0
  45. package/dist/client/webhooks/refundRecovery.d.ts.map +1 -0
  46. package/dist/client/webhooks/refundRecovery.js +36 -0
  47. package/dist/client/webhooks/refundRecovery.js.map +1 -0
  48. package/dist/component/_generated/api.d.ts +4 -0
  49. package/dist/component/_generated/api.d.ts.map +1 -1
  50. package/dist/component/_generated/api.js.map +1 -1
  51. package/dist/component/_generated/component.d.ts +102 -0
  52. package/dist/component/_generated/component.d.ts.map +1 -1
  53. package/dist/component/billing/queries.d.ts +1 -0
  54. package/dist/component/billing/queries.d.ts.map +1 -1
  55. package/dist/component/billing/queries.js +10 -4
  56. package/dist/component/billing/queries.js.map +1 -1
  57. package/dist/component/billing/schema.d.ts +5 -0
  58. package/dist/component/billing/schema.d.ts.map +1 -1
  59. package/dist/component/billing/schema.js +13 -0
  60. package/dist/component/billing/schema.js.map +1 -1
  61. package/dist/component/billingHistory/queries.d.ts +97 -0
  62. package/dist/component/billingHistory/queries.d.ts.map +1 -0
  63. package/dist/component/billingHistory/queries.js +65 -0
  64. package/dist/component/billingHistory/queries.js.map +1 -0
  65. package/dist/component/billingHistory/scope.d.ts +23 -0
  66. package/dist/component/billingHistory/scope.d.ts.map +1 -0
  67. package/dist/component/billingHistory/scope.js +54 -0
  68. package/dist/component/billingHistory/scope.js.map +1 -0
  69. package/dist/component/core/queries.d.ts +1 -0
  70. package/dist/component/core/queries.d.ts.map +1 -1
  71. package/dist/component/core/queries.js +7 -4
  72. package/dist/component/core/queries.js.map +1 -1
  73. package/dist/component/earnings/triggers.d.ts +10 -0
  74. package/dist/component/earnings/triggers.d.ts.map +1 -1
  75. package/dist/component/processingCostReconciliation/rollback.d.ts +1 -1
  76. package/dist/component/refundHistory/queries.d.ts +1 -1
  77. package/dist/component/refundSync/mutations.d.ts +1 -1
  78. package/dist/component/refundSync/mutations.d.ts.map +1 -1
  79. package/dist/component/schema.d.ts +5 -0
  80. package/docs/billing-history.md +13 -0
  81. package/docs/personal-account-mapping.md +30 -0
  82. package/docs/refund-context.md +42 -9
  83. package/package.json +2 -1
  84. package/src/client/billing/historyPages.test.ts +58 -0
  85. package/src/client/billing/historyPages.ts +48 -0
  86. package/src/client/billing/subscriptions.ts +2 -1
  87. package/src/client/core/accounts.ts +2 -1
  88. package/src/client/index.ts +6 -2
  89. package/src/client/originalIdReadOptions.test.ts +63 -0
  90. package/src/client/originalIdReadOptions.ts +10 -0
  91. package/src/client/publicTypes.ts +12 -0
  92. package/src/client/readContracts.ts +16 -0
  93. package/src/client/webhooks/handler.ts +7 -3
  94. package/src/client/webhooks/processors.test.ts +9 -7
  95. package/src/client/webhooks/processors.ts +3 -88
  96. package/src/client/webhooks/refund-delivery.test.ts +512 -0
  97. package/src/client/webhooks/refundDelivery.ts +42 -0
  98. package/src/client/webhooks/refundRecovery.ts +52 -0
  99. package/src/client/webhooks.test.ts +35 -42
  100. package/src/component/_generated/api.ts +4 -0
  101. package/src/component/_generated/component.ts +130 -2
  102. package/src/component/billing/queries.ts +9 -4
  103. package/src/component/billing/schema.ts +13 -0
  104. package/src/component/billingHistory/guards.test.ts +235 -0
  105. package/src/component/billingHistory/options.test.ts +35 -0
  106. package/src/component/billingHistory/pages.test.ts +74 -0
  107. package/src/component/billingHistory/queries.ts +88 -0
  108. package/src/component/billingHistory/scope.ts +77 -0
  109. package/src/component/core/original-id-unique.test.ts +209 -0
  110. package/src/component/core/queries.ts +6 -4
@@ -13,6 +13,7 @@ import type {
13
13
  // We can't call registerRoutes directly because it needs HttpRouter.
14
14
  // Instead, import the module and extract handleWebhookRequest via registerRoutes.
15
15
  import { registerRoutes } from "./webhooks.js";
16
+ import { mockQualifiedRefund } from "../../tests/fixtures/qualified-refund.js";
16
17
 
17
18
  // ---------------------------------------------------------------------------
18
19
  // Mock Stripe SDK
@@ -22,6 +23,7 @@ const mockConstructEventAsync = vi.fn();
22
23
  const mockParseEventNotification = vi.fn();
23
24
  const mockParseEventNotificationAsync = vi.fn();
24
25
  const mockAccountRetrieve = vi.fn();
26
+ const mockRefundRetrieve = vi.fn();
25
27
 
26
28
  vi.mock("stripe", () => {
27
29
  return {
@@ -31,6 +33,7 @@ vi.mock("stripe", () => {
31
33
  parseEventNotificationAsync = mockParseEventNotificationAsync;
32
34
  v2 = { core: { accounts: { retrieve: mockAccountRetrieve } } };
33
35
  products = { retrieve: vi.fn() };
36
+ refunds = { retrieve: mockRefundRetrieve };
34
37
  },
35
38
  };
36
39
  });
@@ -177,28 +180,6 @@ function makeV2ThinEvent(overrides?: Partial<V2ThinEvent>): V2ThinEvent {
177
180
  };
178
181
  }
179
182
 
180
- /**
181
- * Capture the webhook handler by calling registerRoutes with a fake HttpRouter.
182
- * Returns a function that calls the handler directly.
183
- */
184
- function _setupHandler(
185
- config?: RegisterRoutesConfig,
186
- ): (ctx: WebhookActionCtx, request: Request) => Promise<Response> {
187
- let handler: any;
188
- const fakeRouter = {
189
- route: (opts: any) => {
190
- handler = opts.handler;
191
- },
192
- };
193
-
194
- registerRoutes(
195
- fakeRouter as any,
196
- createMockComponent(),
197
- config ?? makeBaseConfig(),
198
- );
199
- return handler;
200
- }
201
-
202
183
  async function parseJson(response: Response): Promise<any> {
203
184
  return JSON.parse(await response.text());
204
185
  }
@@ -1029,7 +1010,7 @@ describe("webhooks", () => {
1029
1010
  );
1030
1011
  });
1031
1012
 
1032
- it("refund events: upserts refund with payment intent + charge link", async () => {
1013
+ it("refund events: qualifies current refund with payment intent + charge link", async () => {
1033
1014
  const event = makeV1Event("refund.created", {
1034
1015
  id: "re_123",
1035
1016
  payment_intent: "pi_abc",
@@ -1041,28 +1022,34 @@ describe("webhooks", () => {
1041
1022
  metadata: { note: "partial" },
1042
1023
  });
1043
1024
  mockConstructEventAsync.mockResolvedValue(event);
1025
+ const refund = mockQualifiedRefund(
1026
+ ctx,
1027
+ mockRefundRetrieve,
1028
+ event.data.object,
1029
+ );
1044
1030
 
1045
1031
  const request = makeRequest({ type: "refund.created" });
1046
1032
  const response = await handler(ctx, request);
1047
1033
  expect(response.status).toBe(200);
1048
1034
 
1049
1035
  expect(ctx.runMutation).toHaveBeenCalledWith(
1050
- component.connect.mutations.upsertRefund,
1036
+ makeRef("refundSync/mutations/finish"),
1051
1037
  expect.objectContaining({
1052
- stripeRefundId: "re_123",
1053
- stripePaymentIntentId: "pi_abc",
1054
- stripeChargeId: "ch_xyz",
1055
- amount: 500,
1056
- currency: "usd",
1057
- status: "succeeded",
1058
- reason: "requested_by_customer",
1038
+ generation: 1,
1039
+ apiContext: "platform",
1040
+ refund: expect.objectContaining(refund),
1059
1041
  }),
1060
1042
  );
1043
+ expect(ctx.runMutation).not.toHaveBeenCalledWith(
1044
+ component.connect.mutations.upsertRefund,
1045
+ expect.anything(),
1046
+ );
1061
1047
  });
1062
1048
 
1063
- it("refund events: clamps an unknown status to pending and drops unknown reason", async () => {
1049
+ it("refund events: holds invalid current status instead of clamping a raw snapshot", async () => {
1064
1050
  const event = makeV1Event("refund.updated", {
1065
1051
  id: "re_456",
1052
+ object: "refund",
1066
1053
  payment_intent: "pi_abc",
1067
1054
  charge: "ch_xyz",
1068
1055
  amount: 500,
@@ -1071,17 +1058,23 @@ describe("webhooks", () => {
1071
1058
  reason: "not_a_real_reason",
1072
1059
  });
1073
1060
  mockConstructEventAsync.mockResolvedValue(event);
1074
-
1075
- const request = makeRequest({ type: "refund.updated" });
1076
- await handler(ctx, request);
1077
-
1078
- const call = (ctx.runMutation as Mock).mock.calls.find(
1079
- ([ref]) =>
1080
- ref?.[TO_REFERENCE_PATH] ===
1081
- component.connect.mutations.upsertRefund[TO_REFERENCE_PATH],
1061
+ mockRefundRetrieve.mockResolvedValue(event.data.object);
1062
+ (ctx.runMutation as Mock)
1063
+ .mockResolvedValueOnce("inserted")
1064
+ .mockResolvedValueOnce(1);
1065
+ const response = await handler(
1066
+ ctx,
1067
+ makeRequest({ type: "refund.updated" }),
1068
+ );
1069
+ expect(response.status).toBe(500);
1070
+ expect(ctx.runMutation).not.toHaveBeenCalledWith(
1071
+ component.connect.mutations.upsertRefund,
1072
+ expect.anything(),
1073
+ );
1074
+ expect(ctx.runMutation).toHaveBeenCalledWith(
1075
+ component.webhooks.mutations.markWebhookEventFailed,
1076
+ expect.objectContaining({ stripeEventId: event.id }),
1082
1077
  );
1083
- expect(call?.[1]).toMatchObject({ status: "pending" });
1084
- expect(call?.[1].reason).toBeUndefined();
1085
1078
  });
1086
1079
 
1087
1080
  it("dispute events: upserts dispute and records the originating event suffix", async () => {
@@ -38,6 +38,8 @@ import type * as balanceFunding_workflowValidators from "../balanceFunding/workf
38
38
  import type * as billing_mutations from "../billing/mutations.js";
39
39
  import type * as billing_queries from "../billing/queries.js";
40
40
  import type * as billing_validators from "../billing/validators.js";
41
+ import type * as billingHistory_queries from "../billingHistory/queries.js";
42
+ import type * as billingHistory_scope from "../billingHistory/scope.js";
41
43
  import type * as connect_mutations from "../connect/mutations.js";
42
44
  import type * as connect_payoutWrites from "../connect/payoutWrites.js";
43
45
  import type * as connect_queries from "../connect/queries.js";
@@ -202,6 +204,8 @@ const fullApi: ApiFromModules<{
202
204
  "billing/mutations": typeof billing_mutations;
203
205
  "billing/queries": typeof billing_queries;
204
206
  "billing/validators": typeof billing_validators;
207
+ "billingHistory/queries": typeof billingHistory_queries;
208
+ "billingHistory/scope": typeof billingHistory_scope;
205
209
  "connect/mutations": typeof connect_mutations;
206
210
  "connect/payoutWrites": typeof connect_payoutWrites;
207
211
  "connect/queries": typeof connect_queries;
@@ -2072,7 +2072,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
2072
2072
  getSubscriptionByStripeId: FunctionReference<
2073
2073
  "query",
2074
2074
  "internal",
2075
- { stripeSubscriptionId: string },
2075
+ { requireUnique?: boolean; stripeSubscriptionId: string },
2076
2076
  {
2077
2077
  _creationTime: number;
2078
2078
  _id: string;
@@ -2479,6 +2479,134 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
2479
2479
  >;
2480
2480
  };
2481
2481
  };
2482
+ billingHistory: {
2483
+ queries: {
2484
+ paginateCheckoutSessions: FunctionReference<
2485
+ "query",
2486
+ "internal",
2487
+ {
2488
+ accountId?: string;
2489
+ paginationOpts: {
2490
+ cursor: string | null;
2491
+ endCursor?: string | null;
2492
+ id?: number;
2493
+ maximumBytesRead?: number;
2494
+ maximumRowsRead?: number;
2495
+ numItems: number;
2496
+ };
2497
+ status?: "open" | "complete" | "expired";
2498
+ userId: string;
2499
+ },
2500
+ {
2501
+ continueCursor: string;
2502
+ isDone: boolean;
2503
+ page: Array<{
2504
+ _creationTime: number;
2505
+ _id: string;
2506
+ accountId?: string;
2507
+ applicationFeeAmount?: number;
2508
+ applicationFeePercent?: number;
2509
+ chargeType?: "destination" | "separate";
2510
+ clientSecret?: string;
2511
+ currency?: string;
2512
+ destinationAccountId?: string;
2513
+ feeCollectedAmount?: number;
2514
+ feeRefundedAmount?: number;
2515
+ metadata?: any;
2516
+ mode: "payment" | "subscription" | "setup";
2517
+ orgId?: string;
2518
+ priceId?: string;
2519
+ splitRecipients?: Array<{
2520
+ amount?: number;
2521
+ destinationAccountId: string;
2522
+ percent?: number;
2523
+ role: "store" | "affiliate" | "other";
2524
+ }>;
2525
+ status: "open" | "complete" | "expired";
2526
+ stripeSessionId: string;
2527
+ url?: string;
2528
+ userId: string;
2529
+ }>;
2530
+ pageStatus?: "SplitRecommended" | "SplitRequired" | null;
2531
+ splitCursor?: string | null;
2532
+ },
2533
+ Name
2534
+ >;
2535
+ paginateSubscriptions: FunctionReference<
2536
+ "query",
2537
+ "internal",
2538
+ {
2539
+ accountId?: string;
2540
+ paginationOpts: {
2541
+ cursor: string | null;
2542
+ endCursor?: string | null;
2543
+ id?: number;
2544
+ maximumBytesRead?: number;
2545
+ maximumRowsRead?: number;
2546
+ numItems: number;
2547
+ };
2548
+ status?:
2549
+ | "active"
2550
+ | "trialing"
2551
+ | "past_due"
2552
+ | "canceled"
2553
+ | "incomplete"
2554
+ | "incomplete_expired"
2555
+ | "unpaid"
2556
+ | "paused";
2557
+ userId: string;
2558
+ },
2559
+ {
2560
+ continueCursor: string;
2561
+ isDone: boolean;
2562
+ page: Array<{
2563
+ _creationTime: number;
2564
+ _id: string;
2565
+ accountId?: string;
2566
+ applicationFeeAmount?: number;
2567
+ applicationFeePercent?: number;
2568
+ cancelAtPeriodEnd: boolean;
2569
+ canceledAt?: string;
2570
+ chargeType?: "destination" | "separate";
2571
+ currency?: string;
2572
+ currentPeriodEnd?: string;
2573
+ currentPeriodStart?: string;
2574
+ destinationAccountId?: string;
2575
+ feeCollectedAmount?: number;
2576
+ feeRefundedAmount?: number;
2577
+ isCollectionPaused?: boolean;
2578
+ isTrialing: boolean;
2579
+ metadata?: any;
2580
+ orgId?: string;
2581
+ priceId?: string;
2582
+ quantity?: number;
2583
+ splitRecipients?: Array<{
2584
+ amount?: number;
2585
+ destinationAccountId: string;
2586
+ percent?: number;
2587
+ role: "store" | "affiliate" | "other";
2588
+ }>;
2589
+ status:
2590
+ | "active"
2591
+ | "trialing"
2592
+ | "past_due"
2593
+ | "canceled"
2594
+ | "incomplete"
2595
+ | "incomplete_expired"
2596
+ | "unpaid"
2597
+ | "paused";
2598
+ stripeSubscriptionId: string;
2599
+ trialEnd?: string;
2600
+ trialStart?: string;
2601
+ userId: string;
2602
+ }>;
2603
+ pageStatus?: "SplitRecommended" | "SplitRequired" | null;
2604
+ splitCursor?: string | null;
2605
+ },
2606
+ Name
2607
+ >;
2608
+ };
2609
+ };
2482
2610
  connect: {
2483
2611
  mutations: {
2484
2612
  claimReversalSlices: FunctionReference<
@@ -3400,7 +3528,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
3400
3528
  getAccountByStripeId: FunctionReference<
3401
3529
  "query",
3402
3530
  "internal",
3403
- { stripeAccountId: string },
3531
+ { requireUnique?: boolean; stripeAccountId: string },
3404
3532
  {
3405
3533
  _creationTime: number;
3406
3534
  _id: string;
@@ -24,15 +24,20 @@ export const getSubscription = query({
24
24
  });
25
25
 
26
26
  export const getSubscriptionByStripeId = query({
27
- args: { stripeSubscriptionId: v.string() },
27
+ args: {
28
+ stripeSubscriptionId: v.string(),
29
+ requireUnique: v.optional(v.boolean()),
30
+ },
28
31
  returns: v.union(subscriptionDocValidator, v.null()),
29
32
  handler: async (ctx, args) => {
30
- return await ctx.db
33
+ const rows = ctx.db
31
34
  .query("subscriptions")
32
35
  .withIndex("by_stripe_subscription_id", (q) =>
33
36
  q.eq("stripeSubscriptionId", args.stripeSubscriptionId),
34
- )
35
- .first();
37
+ );
38
+ if (!args.requireUnique) return await rows.first();
39
+ const matches = await rows.take(2);
40
+ return matches.length === 1 ? (matches[0] ?? null) : null;
36
41
  },
37
42
  });
38
43
 
@@ -13,6 +13,13 @@ export const subscriptionsTable = defineTable(subscriptionFields)
13
13
  .index("by_stripe_subscription_id", ["stripeSubscriptionId"])
14
14
  .index("by_price_id", ["priceId"])
15
15
  .index("by_user_id", ["userId"])
16
+ .index("by_userId_and_status", ["userId", "status"])
17
+ .index("by_userId_and_accountId", ["userId", "accountId"])
18
+ .index("by_userId_and_accountId_and_status", [
19
+ "userId",
20
+ "accountId",
21
+ "status",
22
+ ])
16
23
  .index("by_org_id", ["orgId"])
17
24
  .index("by_status", ["status"])
18
25
  .index("by_account_id", ["accountId"])
@@ -24,6 +31,12 @@ export const subscriptionsTable = defineTable(subscriptionFields)
24
31
  export const checkoutSessionsTable = defineTable(checkoutSessionFields)
25
32
  .index("by_stripe_session_id", ["stripeSessionId"])
26
33
  .index("by_user_id", ["userId"])
34
+ .index("by_userId_and_accountId", ["userId", "accountId"])
35
+ .index("by_userId_and_accountId_and_status", [
36
+ "userId",
37
+ "accountId",
38
+ "status",
39
+ ])
27
40
  .index("by_account_id", ["accountId"])
28
41
  .index("by_user_status", ["userId", "status"]);
29
42
 
@@ -0,0 +1,235 @@
1
+ // @vitest-environment edge-runtime
2
+ import { convexTest } from "convex-test";
3
+ import { expect, it } from "vitest";
4
+ import { api } from "../_generated/api.js";
5
+ import { schema, modules } from "../../test.js";
6
+
7
+ async function fixture() {
8
+ const t = convexTest(schema, modules);
9
+ for (const userId of ["original", "foreign"])
10
+ for (let i = 0; i < 6; i++) {
11
+ await t.mutation(api.billing.mutations.upsertCheckoutSession, {
12
+ stripeSessionId: `cs_${userId}_${i}`,
13
+ userId,
14
+ ...(i > 1 ? { accountId: i > 3 ? "acct_other" : "acct_original" } : {}),
15
+ mode: "payment",
16
+ status: i % 2 ? "complete" : "open",
17
+ });
18
+ await t.mutation(api.billing.mutations.upsertSubscription, {
19
+ stripeSubscriptionId: `sub_${userId}_${i}`,
20
+ userId,
21
+ ...(i > 1 ? { accountId: i > 3 ? "acct_other" : "acct_original" } : {}),
22
+ status: i % 2 ? "active" : "trialing",
23
+ isTrialing: i % 2 === 0,
24
+ cancelAtPeriodEnd: false,
25
+ });
26
+ }
27
+ return t;
28
+ }
29
+
30
+ it("uses conjunctive original buyer/account/status scope and retains accountless user rows", async () => {
31
+ const t = await fixture();
32
+ const checkout = await t.query(
33
+ api.billingHistory.queries.paginateCheckoutSessions,
34
+ {
35
+ userId: "original",
36
+ accountId: "acct_original",
37
+ status: "complete",
38
+ paginationOpts: { cursor: null, numItems: 10 },
39
+ },
40
+ );
41
+ expect(checkout.page.map((row) => row.stripeSessionId)).toEqual([
42
+ "cs_original_3",
43
+ ]);
44
+ const subscriptions = await t.query(
45
+ api.billingHistory.queries.paginateSubscriptions,
46
+ {
47
+ userId: "original",
48
+ accountId: "acct_original",
49
+ status: "trialing",
50
+ paginationOpts: { cursor: null, numItems: 10 },
51
+ },
52
+ );
53
+ expect(subscriptions.page.map((row) => row.stripeSubscriptionId)).toEqual([
54
+ "sub_original_2",
55
+ ]);
56
+ const legacy = await t.query(
57
+ api.billingHistory.queries.paginateSubscriptions,
58
+ {
59
+ userId: "original",
60
+ paginationOpts: { cursor: null, numItems: 10 },
61
+ },
62
+ );
63
+ expect(legacy.page).toHaveLength(6);
64
+ expect(legacy.page.filter((row) => row.accountId === undefined)).toHaveLength(
65
+ 2,
66
+ );
67
+ });
68
+
69
+ it("rejects exchanged kinds and changed user/account/status continuation scopes", async () => {
70
+ const t = await fixture();
71
+ const args = {
72
+ userId: "original",
73
+ paginationOpts: { cursor: null, numItems: 1 },
74
+ };
75
+ const first = await t.query(
76
+ api.billingHistory.queries.paginateCheckoutSessions,
77
+ args,
78
+ );
79
+ expect(first.isDone).toBe(false);
80
+ const paginationOpts = { cursor: first.continueCursor, numItems: 1 };
81
+ for (const changed of [
82
+ { userId: "foreign" },
83
+ { accountId: "acct_original" },
84
+ { status: "complete" as const },
85
+ ])
86
+ await expect(
87
+ t.query(api.billingHistory.queries.paginateCheckoutSessions, {
88
+ ...args,
89
+ ...changed,
90
+ paginationOpts,
91
+ }),
92
+ ).rejects.toThrow("cursor or scope");
93
+ await expect(
94
+ t.query(api.billingHistory.queries.paginateSubscriptions, {
95
+ userId: "original",
96
+ paginationOpts,
97
+ }),
98
+ ).rejects.toThrow("cursor or scope");
99
+ });
100
+
101
+ it.each([0, -1, 101, 1.5])(
102
+ "rejects invalid page size %s without returning a preview",
103
+ async (numItems) => {
104
+ const t = convexTest(schema, modules);
105
+ await expect(
106
+ t.query(api.billingHistory.queries.paginateSubscriptions, {
107
+ userId: "original",
108
+ paginationOpts: { cursor: null, numItems },
109
+ }),
110
+ ).rejects.toThrow("selector or page size");
111
+ },
112
+ );
113
+
114
+ it("rejects empty ownership selectors and malformed cursors", async () => {
115
+ const t = convexTest(schema, modules);
116
+ for (const args of [
117
+ { userId: "" },
118
+ { userId: " " },
119
+ { userId: "original", accountId: "" },
120
+ ])
121
+ await expect(
122
+ t.query(api.billingHistory.queries.paginateCheckoutSessions, {
123
+ ...args,
124
+ paginationOpts: { cursor: null, numItems: 1 },
125
+ }),
126
+ ).rejects.toThrow("selector or page size");
127
+ await expect(
128
+ t.query(api.billingHistory.queries.paginateCheckoutSessions, {
129
+ userId: "original",
130
+ paginationOpts: { cursor: "not-a-cursor", numItems: 1 },
131
+ }),
132
+ ).rejects.toThrow("cursor or scope");
133
+ });
134
+
135
+ it("returns an explicit exhausted empty page for an authorized empty buyer scope", async () => {
136
+ const t = await fixture();
137
+ const result = await t.query(
138
+ api.billingHistory.queries.paginateSubscriptions,
139
+ {
140
+ userId: "empty",
141
+ paginationOpts: { cursor: null, numItems: 10 },
142
+ },
143
+ );
144
+ expect(result).toMatchObject({ page: [], isDone: true });
145
+ });
146
+
147
+ it("preserves native pinned range growth and scope-bound split continuation", async () => {
148
+ const t = await fixture();
149
+ const scope = { userId: "original" };
150
+ const first = await t.query(
151
+ api.billingHistory.queries.paginateCheckoutSessions,
152
+ {
153
+ ...scope,
154
+ paginationOpts: { cursor: null, numItems: 2 },
155
+ },
156
+ );
157
+ for (let i = 0; i < 220; i++)
158
+ await t.mutation(api.billing.mutations.upsertCheckoutSession, {
159
+ stripeSessionId: `cs_growth_${i}`,
160
+ userId: "original",
161
+ mode: "payment",
162
+ status: "complete",
163
+ });
164
+ const grown = await t.query(
165
+ api.billingHistory.queries.paginateCheckoutSessions,
166
+ {
167
+ ...scope,
168
+ paginationOpts: {
169
+ cursor: null,
170
+ endCursor: first.continueCursor,
171
+ numItems: 2,
172
+ },
173
+ },
174
+ );
175
+ expect(grown.pageStatus).toBe("SplitRequired");
176
+ expect(grown.splitCursor).toBeTruthy();
177
+ const prefix = await t.query(
178
+ api.billingHistory.queries.paginateCheckoutSessions,
179
+ {
180
+ ...scope,
181
+ paginationOpts: {
182
+ cursor: null,
183
+ endCursor: grown.splitCursor,
184
+ numItems: 2,
185
+ },
186
+ },
187
+ );
188
+ const suffix = await t.query(
189
+ api.billingHistory.queries.paginateCheckoutSessions,
190
+ {
191
+ ...scope,
192
+ paginationOpts: {
193
+ cursor: grown.splitCursor!,
194
+ endCursor: first.continueCursor,
195
+ numItems: 2,
196
+ },
197
+ },
198
+ );
199
+ expect(
200
+ new Set([...prefix.page, ...suffix.page].map((row) => row.stripeSessionId))
201
+ .size,
202
+ ).toBe(222);
203
+ await expect(
204
+ t.query(api.billingHistory.queries.paginateCheckoutSessions, {
205
+ userId: "foreign",
206
+ paginationOpts: {
207
+ cursor: null,
208
+ endCursor: grown.splitCursor,
209
+ numItems: 2,
210
+ },
211
+ }),
212
+ ).rejects.toThrow("cursor or scope");
213
+ });
214
+
215
+ it("preserves exact Unicode and longer legacy buyer IDs without inventing a new length cap", async () => {
216
+ const t = convexTest(schema, modules);
217
+ for (const userId of ["buyer_東京", `legacy_${"a".repeat(600)}`]) {
218
+ await t.mutation(api.billing.mutations.upsertSubscription, {
219
+ stripeSubscriptionId: `sub_${userId}`,
220
+ userId,
221
+ status: "active",
222
+ isTrialing: false,
223
+ cancelAtPeriodEnd: false,
224
+ });
225
+ const result = await t.query(
226
+ api.billingHistory.queries.paginateSubscriptions,
227
+ {
228
+ userId,
229
+ paginationOpts: { cursor: null, numItems: 1 },
230
+ },
231
+ );
232
+ expect(result.page).toHaveLength(1);
233
+ expect(result.page[0]?.userId).toBe(userId);
234
+ }
235
+ });
@@ -0,0 +1,35 @@
1
+ import { expect, it } from "vitest";
2
+ import { historyOptions } from "./scope.js";
3
+ const scope = { kind: "subscriptions" as const, userId: "original" };
4
+ it("preserves stricter caller read ceilings rather than increasing the read budget", () => {
5
+ expect(
6
+ historyOptions(scope, {
7
+ cursor: null,
8
+ numItems: 10,
9
+ maximumRowsRead: 1,
10
+ maximumBytesRead: 256,
11
+ }),
12
+ ).toMatchObject({ maximumRowsRead: 1, maximumBytesRead: 256 });
13
+ });
14
+ it("rejects empty pinned cursors rather than forwarding a raw native cursor", () => {
15
+ expect(() =>
16
+ historyOptions(scope, { cursor: null, endCursor: "", numItems: 10 }),
17
+ ).toThrow();
18
+ });
19
+ it.each([0, -1, 1.5, Infinity])(
20
+ "rejects invalid caller read ceiling %s",
21
+ (maximumRowsRead) => {
22
+ expect(() =>
23
+ historyOptions(scope, { cursor: null, numItems: 10, maximumRowsRead }),
24
+ ).toThrow();
25
+ },
26
+ );
27
+
28
+ it.each([" original", "original ", "original\nline", "original\u007f"])(
29
+ "rejects noncanonical original selector %j",
30
+ (userId) => {
31
+ expect(() =>
32
+ historyOptions({ ...scope, userId }, { cursor: null, numItems: 10 }),
33
+ ).toThrow();
34
+ },
35
+ );