@fantastic.dev/better-stripe 0.54.0 → 0.55.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 (122) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +1 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +112 -34
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +40 -1
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +112 -34
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +40 -1
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/index.d.ts +5 -0
  12. package/dist/client/index.d.ts.map +1 -1
  13. package/dist/client/usage/client.d.ts +2 -2
  14. package/dist/client/usage/client.d.ts.map +1 -1
  15. package/dist/client/usage/client.js +2 -2
  16. package/dist/client/usage/client.js.map +1 -1
  17. package/dist/client/usage/index.d.ts +5 -0
  18. package/dist/client/usage/index.d.ts.map +1 -1
  19. package/dist/client/usage/invoiceObservation.d.ts +38 -0
  20. package/dist/client/usage/invoiceObservation.d.ts.map +1 -0
  21. package/dist/client/usage/invoiceObservation.js +157 -0
  22. package/dist/client/usage/invoiceObservation.js.map +1 -0
  23. package/dist/client/usage/observationClient.d.ts +83 -0
  24. package/dist/client/usage/observationClient.d.ts.map +1 -0
  25. package/dist/client/usage/observationClient.js +157 -0
  26. package/dist/client/usage/observationClient.js.map +1 -0
  27. package/dist/client/usage/observationTypes.d.ts +63 -0
  28. package/dist/client/usage/observationTypes.d.ts.map +1 -0
  29. package/dist/client/usage/observationTypes.js +59 -0
  30. package/dist/client/usage/observationTypes.js.map +1 -0
  31. package/dist/client/usage/providerObservation.d.ts +4 -0
  32. package/dist/client/usage/providerObservation.d.ts.map +1 -0
  33. package/dist/client/usage/providerObservation.js +96 -0
  34. package/dist/client/usage/providerObservation.js.map +1 -0
  35. package/dist/client/usage/reconciliation.d.ts +12 -0
  36. package/dist/client/usage/reconciliation.d.ts.map +1 -0
  37. package/dist/client/usage/reconciliation.js +48 -0
  38. package/dist/client/usage/reconciliation.js.map +1 -0
  39. package/dist/client/usage/summary.d.ts +50 -0
  40. package/dist/client/usage/summary.d.ts.map +1 -0
  41. package/dist/client/usage/summary.js +110 -0
  42. package/dist/client/usage/summary.js.map +1 -0
  43. package/dist/component/_generated/api.d.ts +8 -0
  44. package/dist/component/_generated/api.d.ts.map +1 -1
  45. package/dist/component/_generated/api.js.map +1 -1
  46. package/dist/component/_generated/component.d.ts +95 -0
  47. package/dist/component/_generated/component.d.ts.map +1 -1
  48. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  49. package/dist/component/balanceFunding/mutations.d.ts +16 -16
  50. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  51. package/dist/component/earnings/triggers.d.ts +104 -18
  52. package/dist/component/earnings/triggers.d.ts.map +1 -1
  53. package/dist/component/refundHistory/queries.d.ts +1 -1
  54. package/dist/component/schema.d.ts +40 -1
  55. package/dist/component/schema.js +3 -0
  56. package/dist/component/schema.js.map +1 -1
  57. package/dist/component/usage/schema.d.ts +7 -2
  58. package/dist/component/usage/schema.d.ts.map +1 -1
  59. package/dist/component/usageDelivery/fields.d.ts +1 -0
  60. package/dist/component/usageDelivery/fields.d.ts.map +1 -1
  61. package/dist/component/usageDelivery/fields.js +1 -0
  62. package/dist/component/usageDelivery/fields.js.map +1 -1
  63. package/dist/component/usageDelivery/helpers.d.ts +1 -0
  64. package/dist/component/usageDelivery/helpers.d.ts.map +1 -1
  65. package/dist/component/usageDelivery/mutations.d.ts.map +1 -1
  66. package/dist/component/usageDelivery/mutations.js +8 -1
  67. package/dist/component/usageDelivery/mutations.js.map +1 -1
  68. package/dist/component/usageDelivery/queries.d.ts +2 -0
  69. package/dist/component/usageDelivery/queries.d.ts.map +1 -1
  70. package/dist/component/usageDelivery/steps.d.ts.map +1 -1
  71. package/dist/component/usageDelivery/steps.js +8 -1
  72. package/dist/component/usageDelivery/steps.js.map +1 -1
  73. package/dist/component/usageObservations/helpers.d.ts +38 -0
  74. package/dist/component/usageObservations/helpers.d.ts.map +1 -0
  75. package/dist/component/usageObservations/helpers.js +80 -0
  76. package/dist/component/usageObservations/helpers.js.map +1 -0
  77. package/dist/component/usageObservations/history.d.ts +6 -0
  78. package/dist/component/usageObservations/history.d.ts.map +1 -0
  79. package/dist/component/usageObservations/history.js +29 -0
  80. package/dist/component/usageObservations/history.js.map +1 -0
  81. package/dist/component/usageObservations/mutations.d.ts +6 -0
  82. package/dist/component/usageObservations/mutations.d.ts.map +1 -0
  83. package/dist/component/usageObservations/mutations.js +39 -0
  84. package/dist/component/usageObservations/mutations.js.map +1 -0
  85. package/dist/component/usageObservations/queries.d.ts +78 -0
  86. package/dist/component/usageObservations/queries.d.ts.map +1 -0
  87. package/dist/component/usageObservations/queries.js +131 -0
  88. package/dist/component/usageObservations/queries.js.map +1 -0
  89. package/dist/component/usageObservations/schema.d.ts +72 -0
  90. package/dist/component/usageObservations/schema.d.ts.map +1 -0
  91. package/dist/component/usageObservations/schema.js +29 -0
  92. package/dist/component/usageObservations/schema.js.map +1 -0
  93. package/docs/README.md +2 -0
  94. package/docs/metering-setup.md +2 -0
  95. package/docs/usage-observations.md +152 -0
  96. package/package.json +3 -2
  97. package/src/client/index.ts +18 -0
  98. package/src/client/usage/client.ts +2 -2
  99. package/src/client/usage/index.ts +18 -0
  100. package/src/client/usage/invoiceObservation.test.ts +195 -0
  101. package/src/client/usage/invoiceObservation.ts +203 -0
  102. package/src/client/usage/observationClient.ts +233 -0
  103. package/src/client/usage/observationTypes.ts +101 -0
  104. package/src/client/usage/providerObservation.test.ts +207 -0
  105. package/src/client/usage/providerObservation.ts +124 -0
  106. package/src/client/usage/reconciliation.test.ts +117 -0
  107. package/src/client/usage/reconciliation.ts +86 -0
  108. package/src/client/usage/summary.test.ts +222 -0
  109. package/src/client/usage/summary.ts +188 -0
  110. package/src/component/_generated/api.ts +8 -0
  111. package/src/component/_generated/component.ts +135 -0
  112. package/src/component/schema.ts +6 -0
  113. package/src/component/usageDelivery/fields.ts +1 -0
  114. package/src/component/usageDelivery/mutations.ts +26 -1
  115. package/src/component/usageDelivery/steps.ts +39 -1
  116. package/src/component/usageObservations/helpers.ts +95 -0
  117. package/src/component/usageObservations/history.test.ts +87 -0
  118. package/src/component/usageObservations/history.ts +39 -0
  119. package/src/component/usageObservations/mutations.ts +39 -0
  120. package/src/component/usageObservations/queries.test.ts +162 -0
  121. package/src/component/usageObservations/queries.ts +145 -0
  122. package/src/component/usageObservations/schema.ts +40 -0
@@ -0,0 +1,222 @@
1
+ import { expect, it } from "vitest";
2
+ import { summarizeUsageRecords } from "./summary.js";
3
+ import { prepareUsageRecord } from "./records.js";
4
+ const scope = {
5
+ stripeAccountId: "acct_platform",
6
+ customerAccount: "acct_buyer",
7
+ meterId: "mtr_calls",
8
+ livemode: false,
9
+ };
10
+ const period = { start: 600, end: 1200 };
11
+ const subscription = {
12
+ subscriptionId: "sub_calls",
13
+ subscriptionItemId: "si_calls",
14
+ stripePriceId: "price_calls",
15
+ period,
16
+ interval: "month" as const,
17
+ };
18
+ function view(model = "pay_as_you_go", quantity = "1.25", currency = "usd") {
19
+ const record = prepareUsageRecord({
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,
29
+ unit: { name: "call", precision: 2 },
30
+ rate: { currency, unitAmountDecimal: "2" },
31
+ ...(model === "included_overage"
32
+ ? { includedQuantity: "1", reset: "billing_period" }
33
+ : model === "prepaid"
34
+ ? { insufficientBalance: "reject" }
35
+ : {}),
36
+ },
37
+ },
38
+ sourceEventId: "one",
39
+ quantity,
40
+ occurredAt: 700,
41
+ });
42
+ return {
43
+ record,
44
+ subscription,
45
+ delivery: "provider_accepted" as const,
46
+ hasValidationError: false,
47
+ };
48
+ }
49
+ it("keeps exact accepted and transport-accepted quantities and separate currencies", () => {
50
+ const local = summarizeUsageRecords(
51
+ [
52
+ view(),
53
+ {
54
+ ...view("pay_as_you_go", "2.5", "eur"),
55
+ record: {
56
+ ...view("pay_as_you_go", "2.5", "eur").record,
57
+ binding: {
58
+ ...view("pay_as_you_go", "2.5", "eur").record.binding,
59
+ stripeCustomerId: "cus_eur",
60
+ },
61
+ },
62
+ delivery: "queued",
63
+ },
64
+ ],
65
+ { period, complete: true, observedAt: 1201 },
66
+ );
67
+ expect(local).toMatchObject({
68
+ complete: true,
69
+ eventCount: 2,
70
+ groups: [
71
+ {
72
+ acceptedQuantity: "1.25",
73
+ providerAcceptedQuantity: "1.25",
74
+ estimate: {
75
+ status: "available",
76
+ value: { amountDecimal: "2.5", currency: "usd" },
77
+ },
78
+ },
79
+ {
80
+ acceptedQuantity: "2.5",
81
+ providerAcceptedQuantity: "0",
82
+ estimate: {
83
+ status: "available",
84
+ value: { amountDecimal: "5", currency: "eur" },
85
+ },
86
+ },
87
+ ],
88
+ });
89
+ });
90
+ it("applies included units only to a complete original billing period", () => {
91
+ expect(
92
+ summarizeUsageRecords([view("included_overage")], {
93
+ period,
94
+ complete: true,
95
+ observedAt: 1201,
96
+ }),
97
+ ).toMatchObject({
98
+ groups: [
99
+ {
100
+ included: {
101
+ status: "available",
102
+ value: { consumed: "1.25", remaining: "0", overage: "0.25" },
103
+ },
104
+ estimate: { status: "available", value: { amountDecimal: "0.5" } },
105
+ },
106
+ ],
107
+ });
108
+ expect(
109
+ summarizeUsageRecords([view("included_overage")], {
110
+ period: { start: 700, end: 900 },
111
+ complete: true,
112
+ observedAt: 1201,
113
+ }),
114
+ ).toMatchObject({
115
+ groups: [
116
+ {
117
+ included: { status: "unavailable", reason: "partial_billing_period" },
118
+ estimate: { status: "unavailable" },
119
+ },
120
+ ],
121
+ });
122
+ });
123
+ it("does not fabricate prepaid balances or complete estimates from incomplete history", () => {
124
+ expect(
125
+ summarizeUsageRecords([view("prepaid")], {
126
+ period,
127
+ complete: true,
128
+ observedAt: 1201,
129
+ }),
130
+ ).toMatchObject({
131
+ groups: [
132
+ {
133
+ credits: {
134
+ status: "unavailable",
135
+ reason: "credit_accounting_not_configured",
136
+ },
137
+ estimate: { status: "unavailable" },
138
+ },
139
+ ],
140
+ });
141
+ expect(
142
+ summarizeUsageRecords([view()], {
143
+ period,
144
+ complete: false,
145
+ observedAt: 1201,
146
+ }),
147
+ ).toMatchObject({
148
+ complete: false,
149
+ groups: [
150
+ {
151
+ estimate: { status: "unavailable", reason: "local_history_incomplete" },
152
+ },
153
+ ],
154
+ });
155
+ });
156
+
157
+ it("does not estimate invoice usage across overlapping native subscription items", () => {
158
+ const first = view(),
159
+ second = {
160
+ ...view(),
161
+ subscription: { ...subscription, subscriptionItemId: "si_other" },
162
+ };
163
+ const result = summarizeUsageRecords([first, second], {
164
+ period,
165
+ complete: true,
166
+ observedAt: 1201,
167
+ });
168
+ expect(
169
+ result.groups.every(
170
+ (group) =>
171
+ group.estimate.status === "unavailable" &&
172
+ group.estimate.reason === "ambiguous_subscription_binding",
173
+ ),
174
+ ).toBe(true);
175
+ });
176
+
177
+ it("withholds allowance estimates across same-item price transitions", () => {
178
+ const first = view("included_overage", "0.75");
179
+ const second = structuredClone(first);
180
+ second.record.binding.plan.version = "v2";
181
+ second.record.binding.stripePriceId = "price_v2";
182
+ second.subscription = { ...subscription, stripePriceId: "price_v2" };
183
+ const result = summarizeUsageRecords([first, second], {
184
+ period,
185
+ complete: true,
186
+ observedAt: 1201,
187
+ });
188
+ expect(result.groups).toHaveLength(2);
189
+ for (const group of result.groups) {
190
+ expect(group.acceptedQuantity).toBe("0.75");
191
+ expect(group.included).toMatchObject({
192
+ status: "unavailable",
193
+ reason: "ambiguous_subscription_binding",
194
+ });
195
+ expect(group.estimate).toMatchObject({
196
+ status: "unavailable",
197
+ reason: "ambiguous_subscription_binding",
198
+ });
199
+ }
200
+ });
201
+
202
+ it("combines semantically identical snapshots regardless of property order", () => {
203
+ const first = view("included_overage", "0.75");
204
+ const second = structuredClone(first);
205
+ second.subscription = {
206
+ interval: subscription.interval,
207
+ period: { end: period.end, start: period.start },
208
+ stripePriceId: subscription.stripePriceId,
209
+ subscriptionItemId: subscription.subscriptionItemId,
210
+ subscriptionId: subscription.subscriptionId,
211
+ };
212
+ const result = summarizeUsageRecords([first, second], {
213
+ period,
214
+ complete: true,
215
+ observedAt: 1201,
216
+ });
217
+ expect(result.groups).toHaveLength(1);
218
+ expect(result.groups[0].included).toMatchObject({
219
+ status: "available",
220
+ value: { consumed: "1.5", overage: "0.5" },
221
+ });
222
+ });
@@ -0,0 +1,188 @@
1
+ import { convexToJson } from "convex/values";
2
+ import type { PreparedUsageRecord, UsageDeliveryState } from "./records.js";
3
+ import { parseUsageQuantity } from "./contracts.js";
4
+ import type {
5
+ UsageAvailability,
6
+ UsagePeriod,
7
+ UsageSubscriptionBinding,
8
+ } from "./boundaries.js";
9
+ export type UsageSummaryEvent = {
10
+ record: PreparedUsageRecord;
11
+ subscription: UsageSubscriptionBinding;
12
+ delivery: UsageDeliveryState;
13
+ hasValidationError: boolean;
14
+ };
15
+ export type UsageCreditSummary = {
16
+ availableQuantity: string;
17
+ reservedQuantity: string;
18
+ consumedQuantity: string;
19
+ expiredQuantity: string;
20
+ };
21
+ export type UsageLocalGroup = {
22
+ binding: PreparedUsageRecord["binding"];
23
+ subscription: UsageSubscriptionBinding;
24
+ acceptedScaledQuantity: string;
25
+ providerAcceptedScaledQuantity: string;
26
+ acceptedQuantity: string;
27
+ providerAcceptedQuantity: string;
28
+ eventCount: number;
29
+ validationErrorEventCount: number;
30
+ deliveryQuantities: Record<UsageDeliveryState, string>;
31
+ estimate: UsageAvailability<{ amountDecimal: string; currency: string }>;
32
+ included: UsageAvailability<{
33
+ included: string;
34
+ consumed: string;
35
+ remaining: string;
36
+ overage: string;
37
+ }>;
38
+ credits: UsageAvailability<UsageCreditSummary>;
39
+ };
40
+ export type UsageLocalSummary = {
41
+ period: UsagePeriod;
42
+ observedAt: number;
43
+ complete: boolean;
44
+ eventCount: number;
45
+ groups: UsageLocalGroup[];
46
+ };
47
+ export function decimalFromScaled(value: bigint, precision: number): string {
48
+ if (precision === 0) return value.toString();
49
+ const digits = value.toString().padStart(precision + 1, "0"),
50
+ whole = digits.slice(0, -precision),
51
+ fraction = digits.slice(-precision).replace(/0+$/, "");
52
+ return fraction ? `${whole}.${fraction}` : whole;
53
+ }
54
+ function rateAmount(quantity: bigint, record: PreparedUsageRecord) {
55
+ const [whole, fraction = ""] =
56
+ record.binding.plan.rate.unitAmountDecimal.split(".");
57
+ return decimalFromScaled(
58
+ quantity * BigInt(whole + fraction),
59
+ record.binding.plan.unit.precision + fraction.length,
60
+ );
61
+ }
62
+ const unavailable = (reason: string) => ({
63
+ status: "unavailable" as const,
64
+ reason,
65
+ retryable: false,
66
+ });
67
+ const states: UsageDeliveryState[] = [
68
+ "queued",
69
+ "sending",
70
+ "provider_accepted",
71
+ "rejected",
72
+ "unknown",
73
+ "held",
74
+ ];
75
+ export function summarizeUsageRecords(
76
+ events: UsageSummaryEvent[],
77
+ options: { period: UsagePeriod; complete: boolean; observedAt: number },
78
+ ): UsageLocalSummary {
79
+ const grouped = new Map<string, UsageSummaryEvent[]>();
80
+ for (const event of events) {
81
+ const key = JSON.stringify(
82
+ convexToJson([event.record.binding, event.subscription]),
83
+ );
84
+ const group = grouped.get(key) ?? [];
85
+ group.push(event);
86
+ grouped.set(key, group);
87
+ }
88
+ const groups: UsageLocalGroup[] = [];
89
+ for (const values of grouped.values()) {
90
+ const { record, subscription } = values[0],
91
+ plan = record.binding.plan,
92
+ precision = plan.unit.precision;
93
+ const sums = Object.fromEntries(
94
+ states.map((state) => [state, 0n]),
95
+ ) as Record<UsageDeliveryState, bigint>;
96
+ for (const value of values)
97
+ sums[value.delivery] += BigInt(value.record.scaledQuantity);
98
+ const accepted = states.reduce((sum, state) => sum + sums[state], 0n);
99
+ const fullPeriod =
100
+ options.period.start === subscription.period.start &&
101
+ options.period.end === subscription.period.end;
102
+ const eligible =
103
+ options.complete && (plan.model !== "included_overage" || fullPeriod);
104
+ let chargeable = accepted;
105
+ let included: UsageLocalGroup["included"] = unavailable(
106
+ plan.model === "included_overage"
107
+ ? options.complete
108
+ ? "partial_billing_period"
109
+ : "local_history_incomplete"
110
+ : "not_included_model",
111
+ );
112
+ if (plan.model === "included_overage" && eligible) {
113
+ const allowance = BigInt(
114
+ parseUsageQuantity(plan.includedQuantity, precision).scaledQuantity,
115
+ );
116
+ chargeable = accepted > allowance ? accepted - allowance : 0n;
117
+ included = {
118
+ status: "available",
119
+ observedAt: options.observedAt,
120
+ value: {
121
+ included: decimalFromScaled(allowance, precision),
122
+ consumed: decimalFromScaled(accepted, precision),
123
+ remaining: decimalFromScaled(
124
+ allowance > accepted ? allowance - accepted : 0n,
125
+ precision,
126
+ ),
127
+ overage: decimalFromScaled(chargeable, precision),
128
+ },
129
+ };
130
+ }
131
+ groups.push({
132
+ binding: record.binding,
133
+ subscription,
134
+ acceptedScaledQuantity: accepted.toString(),
135
+ providerAcceptedScaledQuantity: sums.provider_accepted.toString(),
136
+ acceptedQuantity: decimalFromScaled(accepted, precision),
137
+ providerAcceptedQuantity: decimalFromScaled(
138
+ sums.provider_accepted,
139
+ precision,
140
+ ),
141
+ eventCount: values.length,
142
+ validationErrorEventCount: values.filter((v) => v.hasValidationError)
143
+ .length,
144
+ deliveryQuantities: Object.fromEntries(
145
+ states.map((state) => [
146
+ state,
147
+ decimalFromScaled(sums[state], precision),
148
+ ]),
149
+ ) as Record<UsageDeliveryState, string>,
150
+ included,
151
+ estimate: !options.complete
152
+ ? unavailable("local_history_incomplete")
153
+ : plan.model === "prepaid"
154
+ ? unavailable("credit_accounting_not_configured")
155
+ : !eligible
156
+ ? unavailable("partial_billing_period")
157
+ : {
158
+ status: "available",
159
+ observedAt: options.observedAt,
160
+ value: {
161
+ amountDecimal: rateAmount(chargeable, record),
162
+ currency: plan.rate.currency,
163
+ },
164
+ },
165
+ credits: unavailable(
166
+ plan.model === "prepaid"
167
+ ? "credit_accounting_not_configured"
168
+ : "not_prepaid_model",
169
+ ),
170
+ });
171
+ }
172
+ for (const group of groups) {
173
+ if (
174
+ groups.some(
175
+ (other) =>
176
+ other !== group &&
177
+ other.binding.stripeCustomerId === group.binding.stripeCustomerId &&
178
+ other.subscription.period.start < group.subscription.period.end &&
179
+ other.subscription.period.end > group.subscription.period.start,
180
+ )
181
+ ) {
182
+ group.estimate = unavailable("ambiguous_subscription_binding");
183
+ if (group.binding.plan.model === "included_overage")
184
+ group.included = unavailable("ambiguous_subscription_binding");
185
+ }
186
+ }
187
+ return { ...options, eventCount: events.length, groups };
188
+ }
@@ -174,6 +174,10 @@ import type * as usageDelivery_mutations from "../usageDelivery/mutations.js";
174
174
  import type * as usageDelivery_queries from "../usageDelivery/queries.js";
175
175
  import type * as usageDelivery_steps from "../usageDelivery/steps.js";
176
176
  import type * as usageDelivery_workflow from "../usageDelivery/workflow.js";
177
+ import type * as usageObservations_helpers from "../usageObservations/helpers.js";
178
+ import type * as usageObservations_history from "../usageObservations/history.js";
179
+ import type * as usageObservations_mutations from "../usageObservations/mutations.js";
180
+ import type * as usageObservations_queries from "../usageObservations/queries.js";
177
181
  import type * as webhooks_mutations from "../webhooks/mutations.js";
178
182
  import type * as webhooks_queries from "../webhooks/queries.js";
179
183
  import type * as webhooks_validators from "../webhooks/validators.js";
@@ -352,6 +356,10 @@ const fullApi: ApiFromModules<{
352
356
  "usageDelivery/queries": typeof usageDelivery_queries;
353
357
  "usageDelivery/steps": typeof usageDelivery_steps;
354
358
  "usageDelivery/workflow": typeof usageDelivery_workflow;
359
+ "usageObservations/helpers": typeof usageObservations_helpers;
360
+ "usageObservations/history": typeof usageObservations_history;
361
+ "usageObservations/mutations": typeof usageObservations_mutations;
362
+ "usageObservations/queries": typeof usageObservations_queries;
355
363
  "webhooks/mutations": typeof webhooks_mutations;
356
364
  "webhooks/queries": typeof webhooks_queries;
357
365
  "webhooks/validators": typeof webhooks_validators;
@@ -8727,6 +8727,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
8727
8727
  eventId: string;
8728
8728
  firstSendAt?: number;
8729
8729
  held?: boolean;
8730
+ historySequence?: number;
8730
8731
  leaseUntil?: number;
8731
8732
  nextAttemptAt: number;
8732
8733
  provider?: string;
@@ -8756,6 +8757,140 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
8756
8757
  >;
8757
8758
  };
8758
8759
  };
8760
+ usageObservations: {
8761
+ mutations: {
8762
+ save: FunctionReference<
8763
+ "mutation",
8764
+ "internal",
8765
+ { observationJson: string; sourceJson: string; startedAt: number },
8766
+ null,
8767
+ Name
8768
+ >;
8769
+ };
8770
+ queries: {
8771
+ cached: FunctionReference<
8772
+ "query",
8773
+ "internal",
8774
+ { sourceJson: string },
8775
+ string | null,
8776
+ Name
8777
+ >;
8778
+ deliveryHistory: FunctionReference<
8779
+ "query",
8780
+ "internal",
8781
+ {
8782
+ eventId: string;
8783
+ paginationOpts: {
8784
+ cursor: string | null;
8785
+ endCursor?: string | null;
8786
+ id?: number;
8787
+ maximumBytesRead?: number;
8788
+ maximumRowsRead?: number;
8789
+ numItems: number;
8790
+ };
8791
+ scope: {
8792
+ customerAccount: string;
8793
+ livemode: boolean;
8794
+ meterId: string;
8795
+ stripeAccountId: string;
8796
+ };
8797
+ },
8798
+ {
8799
+ continueCursor: string;
8800
+ isDone: boolean;
8801
+ legacyHistoryMissing: boolean;
8802
+ page: Array<{
8803
+ _creationTime: number;
8804
+ _id: string;
8805
+ attempt: number;
8806
+ created?: number;
8807
+ eventId: string;
8808
+ identity: string;
8809
+ phase:
8810
+ | "started"
8811
+ | "accepted"
8812
+ | "rate_limited"
8813
+ | "unavailable"
8814
+ | "unknown"
8815
+ | "rejected"
8816
+ | "held"
8817
+ | "resumed"
8818
+ | "window_expired"
8819
+ | "retry_exhausted";
8820
+ recordedAt: number;
8821
+ scopeKey: string;
8822
+ sequence: number;
8823
+ }>;
8824
+ pageStatus?: "SplitRecommended" | "SplitRequired" | null;
8825
+ splitCursor?: string | null;
8826
+ },
8827
+ Name
8828
+ >;
8829
+ summary: FunctionReference<
8830
+ "query",
8831
+ "internal",
8832
+ {
8833
+ maxRecords: number;
8834
+ period: { end: number; start: number };
8835
+ scope: {
8836
+ customerAccount: string;
8837
+ livemode: boolean;
8838
+ meterId: string;
8839
+ stripeAccountId: string;
8840
+ };
8841
+ },
8842
+ string,
8843
+ Name
8844
+ >;
8845
+ validationHistory: FunctionReference<
8846
+ "query",
8847
+ "internal",
8848
+ {
8849
+ eventId: string;
8850
+ paginationOpts: {
8851
+ cursor: string | null;
8852
+ endCursor?: string | null;
8853
+ id?: number;
8854
+ maximumBytesRead?: number;
8855
+ maximumRowsRead?: number;
8856
+ numItems: number;
8857
+ };
8858
+ scope: {
8859
+ customerAccount: string;
8860
+ livemode: boolean;
8861
+ meterId: string;
8862
+ stripeAccountId: string;
8863
+ };
8864
+ },
8865
+ {
8866
+ continueCursor: string;
8867
+ isDone: boolean;
8868
+ page: Array<{
8869
+ _creationTime: number;
8870
+ _id: string;
8871
+ code:
8872
+ | "meter_event_customer_not_found"
8873
+ | "meter_event_no_customer_defined"
8874
+ | "meter_event_dimension_count_too_high"
8875
+ | "archived_meter"
8876
+ | "timestamp_too_far_in_past"
8877
+ | "timestamp_in_future"
8878
+ | "meter_event_value_not_found"
8879
+ | "meter_event_invalid_value"
8880
+ | "no_meter";
8881
+ dedupe: string;
8882
+ eventId: string;
8883
+ observedAt: number;
8884
+ providerEventId: string;
8885
+ scopeKey: string;
8886
+ }>;
8887
+ pageStatus?: "SplitRecommended" | "SplitRequired" | null;
8888
+ splitCursor?: string | null;
8889
+ },
8890
+ Name
8891
+ >;
8892
+ };
8893
+ };
8759
8894
  webhooks: {
8760
8895
  mutations: {
8761
8896
  insertWebhookEvent: FunctionReference<
@@ -1,3 +1,7 @@
1
+ import {
2
+ historyTable as usageDeliveryHistory,
3
+ observationsTable as usageProviderObservations,
4
+ } from "./usageObservations/schema.js";
1
5
  import {
2
6
  errorsTable as usageDeliveryErrors,
3
7
  locksTable as usageDeliveryLocks,
@@ -100,6 +104,8 @@ import { pricesTable, productsTable } from "./products/schema";
100
104
  import { webhookEventsTable } from "./webhooks/schema";
101
105
 
102
106
  export default defineSchema({
107
+ usageProviderObservations,
108
+ usageDeliveryHistory,
103
109
  usageDeliveryLocks,
104
110
  usageDeliveryErrors,
105
111
  usageCatalog: usageCatalogTable,
@@ -12,6 +12,7 @@ export const reason = v.union(
12
12
  );
13
13
  export { usageDeliveryOutcomeValidator as outcome } from "../../client/usage/deliveryProtocol.js";
14
14
  export const deliveryFields = {
15
+ historySequence: v.optional(v.number()),
15
16
  provider: v.optional(v.string()),
16
17
  workflowId: v.optional(v.string()),
17
18
  definitionVersion: v.optional(v.literal(1)),
@@ -1,3 +1,4 @@
1
+ import { appendDeliveryHistory } from "../usageObservations/history.js";
1
2
  import { errorCode } from "./fields.js";
2
3
  import type { PreparedUsageRecord } from "../../client/usage/records.js";
3
4
  import { mutation } from "../_generated/server.js";
@@ -81,6 +82,14 @@ export const hold = mutation({
81
82
  ? { state: "held" as const, reason: "administrative_hold" as const }
82
83
  : {}),
83
84
  });
85
+ if (!outbox.held)
86
+ await appendDeliveryHistory(
87
+ ctx,
88
+ args.eventId,
89
+ "held",
90
+ outbox.attempts,
91
+ `control:${(outbox.historySequence ?? 0) + 1}:held`,
92
+ );
84
93
  return await currentStatus(ctx, (await read(ctx, args)).outbox);
85
94
  },
86
95
  });
@@ -94,8 +103,16 @@ export const resume = mutation({
94
103
  ["provider_accepted", "rejected"].includes(outbox.state) ||
95
104
  outbox.reason === "delivery_window_expired"
96
105
  ) {
97
- if (outbox.held)
106
+ if (outbox.held) {
98
107
  await ctx.db.patch("usageOutbox", outbox._id, { held: false });
108
+ await appendDeliveryHistory(
109
+ ctx,
110
+ args.eventId,
111
+ "resumed",
112
+ outbox.attempts,
113
+ `control:${(outbox.historySequence ?? 0) + 1}:resumed`,
114
+ );
115
+ }
99
116
  return await currentStatus(ctx, (await read(ctx, args)).outbox);
100
117
  }
101
118
  if (!outbox.provider)
@@ -105,6 +122,14 @@ export const resume = mutation({
105
122
  state: outbox.state === "sending" ? "sending" : "queued",
106
123
  reason: undefined,
107
124
  });
125
+ if (outbox.held || outbox.state === "held")
126
+ await appendDeliveryHistory(
127
+ ctx,
128
+ args.eventId,
129
+ "resumed",
130
+ outbox.attempts,
131
+ `control:${(outbox.historySequence ?? 0) + 1}:resumed`,
132
+ );
108
133
  await launch(ctx, args, outbox);
109
134
  return await currentStatus(ctx, (await read(ctx, args)).outbox);
110
135
  },