@fantastic.dev/better-stripe 0.51.0 → 0.53.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 (135) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +1 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +210 -32
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +105 -16
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +178 -0
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +89 -0
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/index.d.ts +6 -0
  12. package/dist/client/index.d.ts.map +1 -1
  13. package/dist/client/index.js +5 -0
  14. package/dist/client/index.js.map +1 -1
  15. package/dist/client/products/catalogClient.d.ts +23 -0
  16. package/dist/client/products/catalogClient.d.ts.map +1 -1
  17. package/dist/client/products/catalogClient.js +32 -0
  18. package/dist/client/products/catalogClient.js.map +1 -1
  19. package/dist/client/products/fixedPrice.d.ts +4 -0
  20. package/dist/client/products/fixedPrice.d.ts.map +1 -0
  21. package/dist/client/products/fixedPrice.js +10 -0
  22. package/dist/client/products/fixedPrice.js.map +1 -0
  23. package/dist/client/products/products.d.ts.map +1 -1
  24. package/dist/client/products/products.js +3 -0
  25. package/dist/client/products/products.js.map +1 -1
  26. package/dist/client/usage/catalog.d.ts +7 -0
  27. package/dist/client/usage/catalog.d.ts.map +1 -0
  28. package/dist/client/usage/catalog.js +55 -0
  29. package/dist/client/usage/catalog.js.map +1 -0
  30. package/dist/client/usage/catalogLifecycle.d.ts +25 -0
  31. package/dist/client/usage/catalogLifecycle.d.ts.map +1 -0
  32. package/dist/client/usage/catalogLifecycle.js +64 -0
  33. package/dist/client/usage/catalogLifecycle.js.map +1 -0
  34. package/dist/client/usage/catalogMath.d.ts +3 -0
  35. package/dist/client/usage/catalogMath.d.ts.map +1 -0
  36. package/dist/client/usage/catalogMath.js +21 -0
  37. package/dist/client/usage/catalogMath.js.map +1 -0
  38. package/dist/client/usage/catalogPrices.d.ts +5 -0
  39. package/dist/client/usage/catalogPrices.d.ts.map +1 -0
  40. package/dist/client/usage/catalogPrices.js +178 -0
  41. package/dist/client/usage/catalogPrices.js.map +1 -0
  42. package/dist/client/usage/catalogRead.d.ts +25 -0
  43. package/dist/client/usage/catalogRead.d.ts.map +1 -0
  44. package/dist/client/usage/catalogRead.js +71 -0
  45. package/dist/client/usage/catalogRead.js.map +1 -0
  46. package/dist/client/usage/catalogTypes.d.ts +97 -0
  47. package/dist/client/usage/catalogTypes.d.ts.map +1 -0
  48. package/dist/client/usage/catalogTypes.js +106 -0
  49. package/dist/client/usage/catalogTypes.js.map +1 -0
  50. package/dist/client/usage/client.d.ts +37 -0
  51. package/dist/client/usage/client.d.ts.map +1 -0
  52. package/dist/client/usage/client.js +59 -0
  53. package/dist/client/usage/client.js.map +1 -0
  54. package/dist/client/usage/records.d.ts +1 -1
  55. package/dist/client/usage/records.d.ts.map +1 -1
  56. package/dist/client/usage/records.js +1 -1
  57. package/dist/client/usage/records.js.map +1 -1
  58. package/dist/client/webhooks/processors.d.ts.map +1 -1
  59. package/dist/client/webhooks/processors.js +3 -0
  60. package/dist/client/webhooks/processors.js.map +1 -1
  61. package/dist/component/_generated/api.d.ts +10 -0
  62. package/dist/component/_generated/api.d.ts.map +1 -1
  63. package/dist/component/_generated/api.js.map +1 -1
  64. package/dist/component/_generated/component.d.ts +141 -0
  65. package/dist/component/_generated/component.d.ts.map +1 -1
  66. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  67. package/dist/component/balanceFunding/mutations.d.ts +43 -43
  68. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  69. package/dist/component/earnings/triggers.d.ts +224 -16
  70. package/dist/component/earnings/triggers.d.ts.map +1 -1
  71. package/dist/component/schema.d.ts +89 -0
  72. package/dist/component/schema.js +7 -0
  73. package/dist/component/schema.js.map +1 -1
  74. package/dist/component/usage/helpers.d.ts +13 -0
  75. package/dist/component/usage/helpers.d.ts.map +1 -0
  76. package/dist/component/usage/helpers.js +34 -0
  77. package/dist/component/usage/helpers.js.map +1 -0
  78. package/dist/component/usage/mutations.d.ts +14 -0
  79. package/dist/component/usage/mutations.d.ts.map +1 -0
  80. package/dist/component/usage/mutations.js +124 -0
  81. package/dist/component/usage/mutations.js.map +1 -0
  82. package/dist/component/usage/queries.d.ts +62 -0
  83. package/dist/component/usage/queries.d.ts.map +1 -0
  84. package/dist/component/usage/queries.js +65 -0
  85. package/dist/component/usage/queries.js.map +1 -0
  86. package/dist/component/usage/schema.d.ts +110 -0
  87. package/dist/component/usage/schema.d.ts.map +1 -0
  88. package/dist/component/usage/schema.js +54 -0
  89. package/dist/component/usage/schema.js.map +1 -0
  90. package/dist/component/usageCatalog/mutations.d.ts +25 -0
  91. package/dist/component/usageCatalog/mutations.d.ts.map +1 -0
  92. package/dist/component/usageCatalog/mutations.js +75 -0
  93. package/dist/component/usageCatalog/mutations.js.map +1 -0
  94. package/dist/component/usageCatalog/queries.d.ts +33 -0
  95. package/dist/component/usageCatalog/queries.d.ts.map +1 -0
  96. package/dist/component/usageCatalog/queries.js +26 -0
  97. package/dist/component/usageCatalog/queries.js.map +1 -0
  98. package/dist/component/usageCatalog/schema.d.ts +57 -0
  99. package/dist/component/usageCatalog/schema.d.ts.map +1 -0
  100. package/dist/component/usageCatalog/schema.js +22 -0
  101. package/dist/component/usageCatalog/schema.js.map +1 -0
  102. package/docs/README.md +5 -1
  103. package/docs/metered-usage.md +2 -2
  104. package/docs/metering-setup.md +4 -1
  105. package/docs/usage-catalog.md +106 -0
  106. package/docs/usage-ledger.md +62 -0
  107. package/package.json +4 -2
  108. package/src/client/index.ts +12 -0
  109. package/src/client/products/catalogClient.ts +77 -0
  110. package/src/client/products/fixedPrice.test.ts +57 -0
  111. package/src/client/products/fixedPrice.ts +13 -0
  112. package/src/client/products/products.ts +2 -0
  113. package/src/client/usage/catalog.test.ts +464 -0
  114. package/src/client/usage/catalog.ts +117 -0
  115. package/src/client/usage/catalogLifecycle.ts +128 -0
  116. package/src/client/usage/catalogMath.test.ts +13 -0
  117. package/src/client/usage/catalogMath.ts +22 -0
  118. package/src/client/usage/catalogPrices.ts +251 -0
  119. package/src/client/usage/catalogRead.ts +98 -0
  120. package/src/client/usage/catalogTypes.ts +170 -0
  121. package/src/client/usage/client.ts +97 -0
  122. package/src/client/usage/ledger-client.test.ts +74 -0
  123. package/src/client/usage/records.ts +1 -1
  124. package/src/client/webhooks/processors.ts +2 -0
  125. package/src/component/_generated/api.ts +10 -0
  126. package/src/component/_generated/component.ts +184 -0
  127. package/src/component/schema.ts +12 -0
  128. package/src/component/usage/helpers.ts +33 -0
  129. package/src/component/usage/ledger.test.ts +310 -0
  130. package/src/component/usage/mutations.ts +139 -0
  131. package/src/component/usage/queries.ts +69 -0
  132. package/src/component/usage/schema.ts +65 -0
  133. package/src/component/usageCatalog/mutations.ts +79 -0
  134. package/src/component/usageCatalog/queries.ts +32 -0
  135. package/src/component/usageCatalog/schema.ts +21 -0
@@ -0,0 +1,74 @@
1
+ import { componentsGeneric, type FunctionReference } from "convex/server";
2
+ import { expect, it } from "vitest";
3
+ import { initConvexTest } from "../setup.test.js";
4
+ import schema from "../../component/schema.js";
5
+ import { modules } from "../../test.js";
6
+ import { BetterStripe } from "../index.js";
7
+ import type { Component, RunCtx } from "../helpers.js";
8
+ it("records and reads through the public facade without resolving a Stripe secret", async () => {
9
+ const t = initConvexTest();
10
+ t.registerComponent("betterStripe", schema, modules);
11
+ const stripe = new BetterStripe(
12
+ componentsGeneric().betterStripe as unknown as Component,
13
+ );
14
+ const ctx = {
15
+ runQuery: (
16
+ ref: FunctionReference<"query">,
17
+ args: Record<string, unknown>,
18
+ ) => t.query(ref, args),
19
+ runMutation: (
20
+ ref: FunctionReference<"mutation">,
21
+ args: Record<string, unknown>,
22
+ ) => t.mutation(ref, args),
23
+ } as RunCtx;
24
+ const now = Math.floor(Date.now() / 1000);
25
+ const scope = {
26
+ stripeAccountId: "acct_platform",
27
+ customerAccount: "acct_buyer",
28
+ meterId: "mtr_calls",
29
+ livemode: false,
30
+ };
31
+ const event = {
32
+ scope,
33
+ binding: {
34
+ stripeCustomerId: "cus_buyer",
35
+ stripePriceId: "price_calls",
36
+ eventName: "calls",
37
+ plan: {
38
+ key: "calls",
39
+ version: "v1",
40
+ model: "pay_as_you_go",
41
+ unit: { name: "call", precision: 0 },
42
+ rate: { currency: "usd", unitAmountDecimal: "2" },
43
+ },
44
+ },
45
+ sourceEventId: "activity_1",
46
+ quantity: "1",
47
+ occurredAt: now,
48
+ };
49
+ const result = await stripe.usage.record(ctx, {
50
+ event,
51
+ subscription: {
52
+ subscriptionId: "sub_calls",
53
+ subscriptionItemId: "si_calls",
54
+ stripePriceId: "price_calls",
55
+ period: { start: now - 1, end: now + 100 },
56
+ interval: "month",
57
+ },
58
+ });
59
+ expect(result).toMatchObject({ delivery: "queued" });
60
+ expect(
61
+ await stripe.usage.get(ctx, { scope, eventId: result.eventId }),
62
+ ).toMatchObject({
63
+ record: { sourceEventId: "activity_1" },
64
+ delivery: "queued",
65
+ });
66
+ const page = await stripe.usage.read(ctx, {
67
+ scope,
68
+ page: { period: { start: now - 1, end: now + 2 }, limit: 10, cursor: null },
69
+ });
70
+ expect(page).toMatchObject({
71
+ isDone: true,
72
+ events: [{ record: { quantity: "1" }, delivery: "queued" }],
73
+ });
74
+ });
@@ -7,7 +7,7 @@ import {
7
7
  type UsagePlan,
8
8
  } from "./contracts.js";
9
9
 
10
- const scopeSchema = z.strictObject({
10
+ export const scopeSchema = z.strictObject({
11
11
  stripeAccountId: z.string().regex(/^acct_[a-zA-Z0-9]+$/),
12
12
  customerAccount: z.string().regex(/^acct_[a-zA-Z0-9]+$/),
13
13
  meterId: z.string().regex(/^mtr_[a-zA-Z0-9_]+$/),
@@ -1,3 +1,4 @@
1
+ import { isFixedPrice } from "../products/fixedPrice.js";
1
2
  import { handleRefundEvent } from "./refundDelivery.js";
2
3
  import { handlePayoutEvent } from "./payoutReconciliation.js";
3
4
  import { reconcileDisputeMoney } from "./disputeRecovery.js";
@@ -157,6 +158,7 @@ async function handlePriceEvent(
157
158
  whCtx: WebhookContext,
158
159
  price: Stripe.Price,
159
160
  ): Promise<void> {
161
+ if (!isFixedPrice(price)) return;
160
162
  const { ctx, component, stripe } = whCtx;
161
163
  const stripeProductId: string =
162
164
  typeof price.product === "string"
@@ -162,6 +162,11 @@ import type * as settlement_clawbackSchema from "../settlement/clawbackSchema.js
162
162
  import type * as settlement_clawbacks from "../settlement/clawbacks.js";
163
163
  import type * as settlement_mutations from "../settlement/mutations.js";
164
164
  import type * as settlement_queries from "../settlement/queries.js";
165
+ import type * as usage_helpers from "../usage/helpers.js";
166
+ import type * as usage_mutations from "../usage/mutations.js";
167
+ import type * as usage_queries from "../usage/queries.js";
168
+ import type * as usageCatalog_mutations from "../usageCatalog/mutations.js";
169
+ import type * as usageCatalog_queries from "../usageCatalog/queries.js";
165
170
  import type * as webhooks_mutations from "../webhooks/mutations.js";
166
171
  import type * as webhooks_queries from "../webhooks/queries.js";
167
172
  import type * as webhooks_validators from "../webhooks/validators.js";
@@ -328,6 +333,11 @@ const fullApi: ApiFromModules<{
328
333
  "settlement/clawbacks": typeof settlement_clawbacks;
329
334
  "settlement/mutations": typeof settlement_mutations;
330
335
  "settlement/queries": typeof settlement_queries;
336
+ "usage/helpers": typeof usage_helpers;
337
+ "usage/mutations": typeof usage_mutations;
338
+ "usage/queries": typeof usage_queries;
339
+ "usageCatalog/mutations": typeof usageCatalog_mutations;
340
+ "usageCatalog/queries": typeof usageCatalog_queries;
331
341
  "webhooks/mutations": typeof webhooks_mutations;
332
342
  "webhooks/queries": typeof webhooks_queries;
333
343
  "webhooks/validators": typeof webhooks_validators;
@@ -8270,6 +8270,190 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
8270
8270
  >;
8271
8271
  };
8272
8272
  };
8273
+ usage: {
8274
+ mutations: {
8275
+ record: FunctionReference<
8276
+ "mutation",
8277
+ "internal",
8278
+ {
8279
+ dispatch?: string;
8280
+ inputJson: string;
8281
+ quota?: number;
8282
+ reservationId?: string;
8283
+ subscriptionJson: string;
8284
+ },
8285
+ {
8286
+ acceptedAt: number;
8287
+ delivery: "queued";
8288
+ eventId: string;
8289
+ identity: string;
8290
+ },
8291
+ Name
8292
+ >;
8293
+ };
8294
+ queries: {
8295
+ get: FunctionReference<
8296
+ "query",
8297
+ "internal",
8298
+ {
8299
+ eventId: string;
8300
+ scope: {
8301
+ customerAccount: string;
8302
+ livemode: boolean;
8303
+ meterId: string;
8304
+ stripeAccountId: string;
8305
+ };
8306
+ },
8307
+ {
8308
+ delivery:
8309
+ | "queued"
8310
+ | "sending"
8311
+ | "provider_accepted"
8312
+ | "rejected"
8313
+ | "unknown"
8314
+ | "held";
8315
+ event: {
8316
+ _creationTime: number;
8317
+ _id: string;
8318
+ acceptedAt: number;
8319
+ identity: string;
8320
+ occurredAt: number;
8321
+ recordJson: string;
8322
+ reservationId?: string;
8323
+ scopeKey: string;
8324
+ subscriptionJson: string;
8325
+ };
8326
+ } | null,
8327
+ Name
8328
+ >;
8329
+ read: FunctionReference<
8330
+ "query",
8331
+ "internal",
8332
+ {
8333
+ paginationOpts: {
8334
+ cursor: string | null;
8335
+ endCursor?: string | null;
8336
+ id?: number;
8337
+ maximumBytesRead?: number;
8338
+ maximumRowsRead?: number;
8339
+ numItems: number;
8340
+ };
8341
+ period: { end: number; start: number };
8342
+ scope: {
8343
+ customerAccount: string;
8344
+ livemode: boolean;
8345
+ meterId: string;
8346
+ stripeAccountId: string;
8347
+ };
8348
+ },
8349
+ {
8350
+ continueCursor: string;
8351
+ isDone: boolean;
8352
+ page: Array<{
8353
+ delivery:
8354
+ | "queued"
8355
+ | "sending"
8356
+ | "provider_accepted"
8357
+ | "rejected"
8358
+ | "unknown"
8359
+ | "held";
8360
+ event: {
8361
+ _creationTime: number;
8362
+ _id: string;
8363
+ acceptedAt: number;
8364
+ identity: string;
8365
+ occurredAt: number;
8366
+ recordJson: string;
8367
+ reservationId?: string;
8368
+ scopeKey: string;
8369
+ subscriptionJson: string;
8370
+ };
8371
+ }>;
8372
+ pageStatus?: "SplitRecommended" | "SplitRequired" | null;
8373
+ splitCursor?: string | null;
8374
+ },
8375
+ Name
8376
+ >;
8377
+ };
8378
+ };
8379
+ usageCatalog: {
8380
+ mutations: {
8381
+ complete: FunctionReference<
8382
+ "mutation",
8383
+ "internal",
8384
+ {
8385
+ key: string;
8386
+ kind: "meter" | "price";
8387
+ observationJson: string;
8388
+ providerId: string;
8389
+ scopeKey: string;
8390
+ },
8391
+ null,
8392
+ Name
8393
+ >;
8394
+ prepare: FunctionReference<
8395
+ "mutation",
8396
+ "internal",
8397
+ {
8398
+ key: string;
8399
+ kind: "meter" | "price";
8400
+ scopeKey: string;
8401
+ termsJson: string;
8402
+ },
8403
+ {
8404
+ _creationTime: number;
8405
+ _id: string;
8406
+ firstAttemptAt: number;
8407
+ key: string;
8408
+ kind: "meter" | "price";
8409
+ observationJson?: string;
8410
+ observedAt?: number;
8411
+ providerId?: string;
8412
+ scopeKey: string;
8413
+ termsJson: string;
8414
+ },
8415
+ Name
8416
+ >;
8417
+ };
8418
+ queries: {
8419
+ get: FunctionReference<
8420
+ "query",
8421
+ "internal",
8422
+ { key: string; kind: "meter" | "price"; scopeKey: string },
8423
+ {
8424
+ _creationTime: number;
8425
+ _id: string;
8426
+ firstAttemptAt: number;
8427
+ key: string;
8428
+ kind: "meter" | "price";
8429
+ observationJson?: string;
8430
+ observedAt?: number;
8431
+ providerId?: string;
8432
+ scopeKey: string;
8433
+ termsJson: string;
8434
+ } | null,
8435
+ Name
8436
+ >;
8437
+ getByProvider: FunctionReference<
8438
+ "query",
8439
+ "internal",
8440
+ { kind: "meter" | "price"; providerId: string; scopeKey: string },
8441
+ {
8442
+ _creationTime: number;
8443
+ _id: string;
8444
+ firstAttemptAt: number;
8445
+ key: string;
8446
+ kind: "meter" | "price";
8447
+ observationJson?: string;
8448
+ observedAt?: number;
8449
+ providerId?: string;
8450
+ scopeKey: string;
8451
+ termsJson: string;
8452
+ } | null,
8453
+ Name
8454
+ >;
8455
+ };
8456
+ };
8273
8457
  webhooks: {
8274
8458
  mutations: {
8275
8459
  insertWebhookEvent: FunctionReference<
@@ -68,7 +68,14 @@ import {
68
68
  commissionTermsTable,
69
69
  commissionDecisionsTable,
70
70
  } from "./settlement/schema";
71
+ import { usageCatalogTable } from "./usageCatalog/schema.js";
71
72
  import { defineSchema } from "convex/server";
73
+ import {
74
+ usageEventsTable,
75
+ usageOutboxTable,
76
+ usageScopeCountersTable,
77
+ usageReservationsTable,
78
+ } from "./usage/schema.js";
72
79
 
73
80
  import {
74
81
  checkoutSessionsTable,
@@ -89,6 +96,11 @@ import { pricesTable, productsTable } from "./products/schema";
89
96
  import { webhookEventsTable } from "./webhooks/schema";
90
97
 
91
98
  export default defineSchema({
99
+ usageCatalog: usageCatalogTable,
100
+ usageEvents: usageEventsTable,
101
+ usageOutbox: usageOutboxTable,
102
+ usageScopeCounters: usageScopeCountersTable,
103
+ usageReservations: usageReservationsTable,
92
104
  refundSyncClaims: refundSyncClaimsTable,
93
105
  processingCostReconciliationOperations,
94
106
  recoveryWorkflowOperations,
@@ -0,0 +1,33 @@
1
+ import { z } from "zod";
2
+ import { scopeSchema } from "../../client/usage/records.js";
3
+ import type { UsageScope } from "../../client/usage/records.js";
4
+ export function scopeKey(input: UsageScope) {
5
+ const key = JSON.stringify(scopeSchema.parse(input));
6
+ if (key.length > 512) throw new Error("Usage scope exceeds size limit");
7
+ return key;
8
+ }
9
+ const seconds = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
10
+ const subscriptionSchema = z.strictObject({
11
+ subscriptionId: z
12
+ .string()
13
+ .regex(/^sub_[a-zA-Z0-9]+$/)
14
+ .max(100),
15
+ subscriptionItemId: z
16
+ .string()
17
+ .regex(/^si_[a-zA-Z0-9]+$/)
18
+ .max(100),
19
+ stripePriceId: z
20
+ .string()
21
+ .regex(/^price_[a-zA-Z0-9]+$/)
22
+ .max(100),
23
+ period: z.strictObject({ start: seconds, end: seconds }),
24
+ interval: z.literal("month"),
25
+ });
26
+ export function subscriptionSnapshot(json: string) {
27
+ if (new TextEncoder().encode(json).length > 2048)
28
+ throw new Error("Usage subscription exceeds size limit");
29
+ const subscription = subscriptionSchema.parse(JSON.parse(json));
30
+ if (subscription.period.end <= subscription.period.start)
31
+ throw new Error("Invalid usage subscription period");
32
+ return subscription;
33
+ }
@@ -0,0 +1,310 @@
1
+ import { convexTest } from "convex-test";
2
+ import { makeFunctionReference } from "convex/server";
3
+ import { expect, it } from "vitest";
4
+ import { record as registeredRecord } from "./mutations.js";
5
+ import type { MutationCtx } from "../_generated/server.js";
6
+ import { schema, modules } from "../../test.js";
7
+
8
+ // Codegen runs after the first failing tests; these are genuine function refs.
9
+ const record = makeFunctionReference<"mutation">("usage/mutations:record");
10
+ const read = makeFunctionReference<"query">("usage/queries:read");
11
+ const get = makeFunctionReference<"query">("usage/queries:get");
12
+ const now = Math.floor(Date.now() / 1000);
13
+ const scope = {
14
+ stripeAccountId: "acct_platform",
15
+ customerAccount: "acct_buyer",
16
+ meterId: "mtr_calls",
17
+ livemode: false,
18
+ };
19
+ const event = {
20
+ scope,
21
+ binding: {
22
+ stripeCustomerId: "cus_buyer",
23
+ stripePriceId: "price_calls",
24
+ eventName: "calls",
25
+ plan: {
26
+ key: "calls",
27
+ version: "v1",
28
+ model: "pay_as_you_go",
29
+ unit: { name: "call", precision: 2 },
30
+ rate: { currency: "usd", unitAmountDecimal: "2" },
31
+ },
32
+ },
33
+ sourceEventId: "activity_1",
34
+ quantity: "1.20",
35
+ occurredAt: now,
36
+ };
37
+ const subscription = {
38
+ subscriptionId: "sub_calls",
39
+ subscriptionItemId: "si_calls",
40
+ stripePriceId: "price_calls",
41
+ period: { start: now - 100, end: now + 1000 },
42
+ interval: "month",
43
+ };
44
+ const args = (input = event) => ({
45
+ inputJson: JSON.stringify(input),
46
+ subscriptionJson: JSON.stringify(subscription),
47
+ });
48
+ it("atomically persists a single immutable event and outbox for competing identical replays", async () => {
49
+ const t = convexTest(schema, modules);
50
+ const results = await Promise.all([
51
+ t.mutation(record, args()),
52
+ t.mutation(record, args({ ...event, quantity: "1.2" })),
53
+ ]);
54
+ expect(results[0]).toEqual(results[1]);
55
+ await t.run(async (ctx) => {
56
+ const events = await ctx.db.query("usageEvents").take(10);
57
+ const outbox = await ctx.db.query("usageOutbox").take(10);
58
+ expect(events).toHaveLength(1);
59
+ expect(outbox).toHaveLength(1);
60
+ expect(outbox[0].eventId).toBe(events[0]._id);
61
+ expect(JSON.parse(events[0].recordJson).scaledQuantity).toBe("120");
62
+ expect(await ctx.db.query("usageScopeCounters").first()).toMatchObject({
63
+ count: 1,
64
+ });
65
+ });
66
+ });
67
+ it("rejects changed versions, amounts, timestamps and subscription bindings without rewriting history", async () => {
68
+ const t = convexTest(schema, modules);
69
+ await t.mutation(record, args());
70
+ for (const changed of [
71
+ { ...event, quantity: "2" },
72
+ { ...event, occurredAt: now - 1 },
73
+ {
74
+ ...event,
75
+ binding: {
76
+ ...event.binding,
77
+ plan: { ...event.binding.plan, version: "v2" },
78
+ },
79
+ },
80
+ ])
81
+ await expect(t.mutation(record, args(changed))).rejects.toThrow(
82
+ "Conflicting usage replay",
83
+ );
84
+ await expect(
85
+ t.mutation(record, {
86
+ ...args(),
87
+ subscriptionJson: JSON.stringify({
88
+ ...subscription,
89
+ subscriptionId: "sub_other",
90
+ }),
91
+ }),
92
+ ).rejects.toThrow("Conflicting usage replay");
93
+ });
94
+ it("isolates payer/meter/realm/mode and currency snapshots", async () => {
95
+ const t = convexTest(schema, modules);
96
+ for (const changed of [
97
+ event,
98
+ { ...event, scope: { ...scope, customerAccount: "acct_other" } },
99
+ { ...event, scope: { ...scope, meterId: "mtr_other" } },
100
+ { ...event, scope: { ...scope, stripeAccountId: "acct_other" } },
101
+ { ...event, scope: { ...scope, livemode: true } },
102
+ ])
103
+ await t.mutation(record, args(changed));
104
+ await expect(
105
+ t.mutation(
106
+ record,
107
+ args({
108
+ ...event,
109
+ binding: {
110
+ ...event.binding,
111
+ plan: {
112
+ ...event.binding.plan,
113
+ rate: { currency: "eur", unitAmountDecimal: "2" },
114
+ },
115
+ },
116
+ }),
117
+ ),
118
+ ).rejects.toThrow("Conflicting usage replay");
119
+ expect(
120
+ await t.run((ctx) => ctx.db.query("usageEvents").take(10)),
121
+ ).toHaveLength(5);
122
+ });
123
+ it("rejects out-of-window/period input, oversized payloads and quota exhaustion but returns original replay", async () => {
124
+ const t = convexTest(schema, modules);
125
+ for (const occurredAt of [
126
+ now - 35 * 86400 - 10,
127
+ now + 600,
128
+ subscription.period.end,
129
+ ])
130
+ await expect(
131
+ t.mutation(record, args({ ...event, occurredAt })),
132
+ ).rejects.toThrow();
133
+ await expect(
134
+ t.mutation(record, { ...args(), inputJson: " ".repeat(8193) }),
135
+ ).rejects.toThrow();
136
+ const first = await t.mutation(record, { ...args(), quota: 1 });
137
+ expect(await t.mutation(record, { ...args(), quota: 1 })).toEqual(first);
138
+ await expect(
139
+ t.mutation(record, {
140
+ ...args({ ...event, sourceEventId: "activity_2" }),
141
+ quota: 1,
142
+ }),
143
+ ).rejects.toThrow("Usage scope quota exhausted");
144
+ });
145
+ it("rolls back event, counter and reservation commit if scheduling fails", async () => {
146
+ const t = convexTest(schema, modules);
147
+ const reservationId = await t.run((ctx) =>
148
+ ctx.db.insert("usageReservations", {
149
+ scopeKey: JSON.stringify(scope),
150
+ sourceEventId: event.sourceEventId,
151
+ planJson: JSON.stringify(event.binding.plan),
152
+ scaledQuantity: "120",
153
+ state: "reserved",
154
+ }),
155
+ );
156
+ await expect(
157
+ t.run((ctx) => {
158
+ const handler = (
159
+ registeredRecord as unknown as {
160
+ _handler: (
161
+ ctx: MutationCtx,
162
+ args: {
163
+ inputJson: string;
164
+ subscriptionJson: string;
165
+ dispatch?: string;
166
+ reservationId?: import("../_generated/dataModel.js").Id<"usageReservations">;
167
+ },
168
+ ) => Promise<unknown>;
169
+ }
170
+ )._handler;
171
+ return handler(
172
+ {
173
+ ...ctx,
174
+ scheduler: {
175
+ ...ctx.scheduler,
176
+ runAfter: async () => {
177
+ throw new Error("Scheduling unavailable");
178
+ },
179
+ },
180
+ } as MutationCtx,
181
+ {
182
+ ...args(),
183
+ dispatch: "function://;usage/delivery:dispatch",
184
+ reservationId,
185
+ },
186
+ );
187
+ }),
188
+ ).rejects.toThrow("Scheduling unavailable");
189
+ expect(await t.run((ctx) => ctx.db.query("usageEvents").take(10))).toEqual(
190
+ [],
191
+ );
192
+ expect(await t.run((ctx) => ctx.db.query("usageOutbox").take(10))).toEqual(
193
+ [],
194
+ );
195
+ expect(
196
+ await t.run((ctx) => ctx.db.query("usageScopeCounters").take(10)),
197
+ ).toEqual([]);
198
+ expect(
199
+ await t.run((ctx) => ctx.db.get("usageReservations", reservationId)),
200
+ ).toMatchObject({ state: "reserved" });
201
+ });
202
+ it("requires and atomically commits the exact prepaid reservation", async () => {
203
+ const t = convexTest(schema, modules);
204
+ const input = {
205
+ ...event,
206
+ binding: {
207
+ ...event.binding,
208
+ plan: {
209
+ ...event.binding.plan,
210
+ model: "prepaid",
211
+ insufficientBalance: "reject",
212
+ },
213
+ },
214
+ };
215
+ await expect(t.mutation(record, args(input))).rejects.toThrow(
216
+ "A matching usage reservation is required",
217
+ );
218
+ const reservationId = await t.run((ctx) =>
219
+ ctx.db.insert("usageReservations", {
220
+ scopeKey: JSON.stringify(scope),
221
+ sourceEventId: input.sourceEventId,
222
+ planJson: JSON.stringify(input.binding.plan),
223
+ scaledQuantity: "120",
224
+ state: "reserved",
225
+ }),
226
+ );
227
+ await t.mutation(record, { ...args(input), reservationId });
228
+ expect(
229
+ await t.run((ctx) => ctx.db.get("usageReservations", reservationId)),
230
+ ).toMatchObject({ state: "committed" });
231
+ const secondReservation = await t.run((ctx) =>
232
+ ctx.db.insert("usageReservations", {
233
+ scopeKey: JSON.stringify(scope),
234
+ sourceEventId: input.sourceEventId,
235
+ planJson: JSON.stringify(input.binding.plan),
236
+ scaledQuantity: "120",
237
+ state: "reserved",
238
+ }),
239
+ );
240
+ await expect(
241
+ t.mutation(record, { ...args(input), reservationId: secondReservation }),
242
+ ).rejects.toThrow("Conflicting usage reservation replay");
243
+ });
244
+
245
+ it("pages an explicit period without exposing guessed or cross-scope events", async () => {
246
+ const t = convexTest(schema, modules);
247
+ const first = await t.mutation(record, args());
248
+ await t.mutation(
249
+ record,
250
+ args({ ...event, sourceEventId: "activity_2", occurredAt: now + 1 }),
251
+ );
252
+ expect(
253
+ await t.query(get, {
254
+ scope: { ...scope, customerAccount: "acct_other" },
255
+ eventId: first.eventId,
256
+ }),
257
+ ).toBeNull();
258
+ const request = {
259
+ scope,
260
+ period: { start: now, end: now + 2 },
261
+ paginationOpts: { numItems: 1, cursor: null },
262
+ };
263
+ const page = await t.query(read, request);
264
+ expect(page.page).toHaveLength(1);
265
+ expect(page.isDone).toBe(false);
266
+ const next = await t.query(read, {
267
+ ...request,
268
+ paginationOpts: { numItems: 1, cursor: page.continueCursor },
269
+ });
270
+ expect(next.page).toHaveLength(1);
271
+ expect(next.page[0].event._id).not.toBe(page.page[0].event._id);
272
+ const empty = await t.query(read, {
273
+ ...request,
274
+ period: { start: now - 2, end: now },
275
+ });
276
+ expect(empty.page).toEqual([]);
277
+ await expect(
278
+ t.query(read, {
279
+ ...request,
280
+ paginationOpts: { numItems: 101, cursor: null },
281
+ }),
282
+ ).rejects.toThrow();
283
+ });
284
+
285
+ it("rejects a supplied missing reservation even for pay-as-you-go", async () => {
286
+ const t = convexTest(schema, modules);
287
+ const reservationId = await t.run(async (ctx) => {
288
+ const id = await ctx.db.insert("usageReservations", {
289
+ scopeKey: JSON.stringify(scope),
290
+ sourceEventId: event.sourceEventId,
291
+ planJson: JSON.stringify(event.binding.plan),
292
+ scaledQuantity: "120",
293
+ state: "reserved",
294
+ });
295
+ await ctx.db.delete("usageReservations", id);
296
+ return id;
297
+ });
298
+ await expect(
299
+ t.mutation(record, { ...args(), reservationId }),
300
+ ).rejects.toThrow("Usage reservation is unavailable");
301
+ expect(await t.run((ctx) => ctx.db.query("usageEvents").take(10))).toEqual(
302
+ [],
303
+ );
304
+ expect(await t.run((ctx) => ctx.db.query("usageOutbox").take(10))).toEqual(
305
+ [],
306
+ );
307
+ expect(
308
+ await t.run((ctx) => ctx.db.query("usageScopeCounters").take(10)),
309
+ ).toEqual([]);
310
+ });