@fantastic.dev/better-stripe 0.50.3 → 0.51.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.
@@ -0,0 +1,136 @@
1
+ import { expect, it } from "vitest";
2
+ import { assertUsageReplay, validateUsagePageRequest } from "./boundaries.js";
3
+ import { prepareUsageRecord } from "./records.js";
4
+ import { authorizeUsageRecord, type UsageAuthorization } from "./boundaries.js";
5
+
6
+ const event = {
7
+ scope: {
8
+ stripeAccountId: "acct_platform",
9
+ customerAccount: "acct_buyer",
10
+ meterId: "mtr_calls",
11
+ livemode: false,
12
+ },
13
+ binding: {
14
+ stripeCustomerId: "cus_buyer",
15
+ stripePriceId: "price_calls",
16
+ eventName: "calls",
17
+ plan: {
18
+ key: "calls",
19
+ version: "v1",
20
+ model: "pay_as_you_go",
21
+ unit: { name: "call", precision: 2 },
22
+ rate: { currency: "usd", unitAmountDecimal: "2" },
23
+ },
24
+ },
25
+ sourceEventId: "request_1",
26
+ quantity: "1.20",
27
+ occurredAt: 100,
28
+ };
29
+ it("bounds page requests and uses half-open explicit periods", () => {
30
+ expect(
31
+ validateUsagePageRequest({
32
+ period: { start: 0, end: 100 },
33
+ limit: 100,
34
+ cursor: null,
35
+ }),
36
+ ).toEqual({ period: { start: 0, end: 100 }, limit: 100, cursor: null });
37
+ for (const input of [
38
+ { period: { start: 0, end: 0 }, limit: 10, cursor: null },
39
+ { period: { start: 10, end: 9 }, limit: 10, cursor: null },
40
+ { period: { start: 0, end: 1.1 }, limit: 10, cursor: null },
41
+ { period: { start: 0, end: 100 }, limit: 101, cursor: null },
42
+ { period: { start: 0, end: 100 }, limit: 0, cursor: null },
43
+ { period: { start: 0, end: 100 }, limit: 10, cursor: "x".repeat(2049) },
44
+ ])
45
+ expect(() => validateUsagePageRequest(input)).toThrow();
46
+ });
47
+ it("accepts an exact replay after normalizing quantities", () => {
48
+ expect(() =>
49
+ assertUsageReplay(
50
+ prepareUsageRecord(event),
51
+ prepareUsageRecord({ ...event, quantity: "1.2" }),
52
+ ),
53
+ ).not.toThrow();
54
+ });
55
+ it("rejects replay changes to historical terms, routing, time or quantity", () => {
56
+ const original = prepareUsageRecord(event);
57
+ for (const changed of [
58
+ { ...event, quantity: "1.21" },
59
+ { ...event, occurredAt: 101 },
60
+ { ...event, binding: { ...event.binding, stripeCustomerId: "cus_other" } },
61
+ {
62
+ ...event,
63
+ binding: {
64
+ ...event.binding,
65
+ plan: { ...event.binding.plan, version: "v2" },
66
+ },
67
+ },
68
+ {
69
+ ...event,
70
+ binding: {
71
+ ...event.binding,
72
+ plan: {
73
+ ...event.binding.plan,
74
+ rate: { currency: "eur", unitAmountDecimal: "2" },
75
+ },
76
+ },
77
+ },
78
+ ])
79
+ expect(() =>
80
+ assertUsageReplay(original, prepareUsageRecord(changed)),
81
+ ).toThrow("Conflicting usage replay");
82
+ });
83
+
84
+ it("runs host authorization and activity policy before accepting any model", async () => {
85
+ const order: string[] = [];
86
+ const policy: UsageAuthorization<{ userId: string }> = {
87
+ async authorize(ctx, request) {
88
+ expect(ctx.userId).toBe("user_1");
89
+ expect(request.operation).toBe("record");
90
+ order.push("authorize");
91
+ },
92
+ async authorizeActivity() {
93
+ order.push("activity");
94
+ },
95
+ };
96
+ for (const plan of [
97
+ event.binding.plan,
98
+ {
99
+ ...event.binding.plan,
100
+ model: "included_overage",
101
+ includedQuantity: "10",
102
+ reset: "billing_period",
103
+ },
104
+ { ...event.binding.plan, model: "prepaid", insufficientBalance: "reject" },
105
+ ]) {
106
+ await authorizeUsageRecord(
107
+ { userId: "user_1" },
108
+ policy,
109
+ { ...event, binding: { ...event.binding, plan } },
110
+ async (record) => {
111
+ order.push("accept");
112
+ return record.identity;
113
+ },
114
+ );
115
+ }
116
+ expect(order).toEqual(
117
+ Array(3).fill(["authorize", "activity", "accept"]).flat(),
118
+ );
119
+ order.length = 0;
120
+ await expect(
121
+ authorizeUsageRecord(
122
+ { userId: "user_1" },
123
+ {
124
+ ...policy,
125
+ async authorizeActivity() {
126
+ throw new Error("Not billable");
127
+ },
128
+ },
129
+ event,
130
+ async () => {
131
+ order.push("accept");
132
+ },
133
+ ),
134
+ ).rejects.toThrow("Not billable");
135
+ expect(order).toEqual(["authorize"]);
136
+ });
@@ -0,0 +1,182 @@
1
+ import type { PreparedUsageRecord, UsageScope } from "./records.js";
2
+ import { prepareUsageRecord } from "./records.js";
3
+ import { z } from "zod";
4
+ import { defineUsagePlan } from "./contracts.js";
5
+
6
+ export type UsagePeriod = { start: number; end: number };
7
+ export type UsagePageRequest = {
8
+ period: UsagePeriod;
9
+ limit: number;
10
+ cursor: string | null;
11
+ };
12
+ export type UsageAvailability<T> =
13
+ | { status: "available"; value: T; observedAt: number }
14
+ | {
15
+ status: "unavailable" | "unsupported";
16
+ reason: string;
17
+ retryable: boolean;
18
+ };
19
+ export type UsageAuthorization<Context> = {
20
+ /** Throw on denial. Resolve identity and tenant ownership in the host. */
21
+ authorize(
22
+ ctx: Context,
23
+ request: {
24
+ scope: UsageScope;
25
+ operation: "record" | "read" | "reconcile" | "correct" | "configure";
26
+ },
27
+ ): Promise<void>;
28
+ /** Throw when the server-verified activity is not billable. */
29
+ authorizeActivity(ctx: Context, record: PreparedUsageRecord): Promise<void>;
30
+ };
31
+
32
+ /** Independent observations; none is inferred from another field. */
33
+ export type UsageObservations = {
34
+ localAcceptedQuantity: string;
35
+ providerAcceptedQuantity: string;
36
+ aggregate: UsageAvailability<{ quantity: string; complete: boolean }>;
37
+ estimate: UsageAvailability<{ amountDecimal: string; currency: string }>;
38
+ invoice: UsageAvailability<{
39
+ invoiceId: string;
40
+ status: "draft" | "open" | "paid" | "void" | "uncollectible";
41
+ amount: string;
42
+ currency: string;
43
+ }>;
44
+ };
45
+ export type UsageCorrectionRequest = {
46
+ scope: UsageScope;
47
+ sourceEventId: string;
48
+ correctionId: string;
49
+ reason: string;
50
+ /** Cancellation preserves the original event. Replacement is a new event. */
51
+ operation: "cancel";
52
+ };
53
+ export type UsageRetentionPolicy = {
54
+ /** Financial evidence has no automatic deletion path. */
55
+ financialEvidence: "retain";
56
+ /** Execution payload cleanup must never erase event/payment/correction history. */
57
+ executionJournalDays: number;
58
+ };
59
+ export type UsageTransitionRequest = {
60
+ scope: UsageScope;
61
+ fromVersion: string;
62
+ toVersion: string;
63
+ effectiveAt: number;
64
+ pendingUsage: "drain_before_transition";
65
+ reservations: "resolve_before_transition";
66
+ existingCredits: "retain_original_terms";
67
+ };
68
+ export type UsageSubscriptionBinding = {
69
+ subscriptionId: string;
70
+ subscriptionItemId: string;
71
+ stripePriceId: string;
72
+ period: UsagePeriod;
73
+ interval: "month";
74
+ };
75
+ export type UsageCreditProvenance = {
76
+ grantId: string;
77
+ purchasePaymentIntentId: string;
78
+ currency: string;
79
+ originalAmount: string;
80
+ /** Quantity projections retain their original plan version and unit. */
81
+ planVersion: string;
82
+ reservationId: string;
83
+ scaledQuantity: string;
84
+ };
85
+ export type UsageCorrectionOutcome = {
86
+ correctionId: string;
87
+ sourceEventId: string;
88
+ state:
89
+ | "requested"
90
+ | "provider_accepted"
91
+ | "confirmed"
92
+ | "held"
93
+ | "unsupported"
94
+ | "invoice_adjustment_required";
95
+ providerAdjustmentId: string | null;
96
+ reason: string;
97
+ };
98
+ export type UsageReceipt = {
99
+ eventId: string;
100
+ identity: string;
101
+ acceptedAt: number;
102
+ delivery: import("./records.js").UsageDeliveryState;
103
+ };
104
+ export type UsageHistoryPage = {
105
+ events: Array<{ receipt: UsageReceipt; record: PreparedUsageRecord }>;
106
+ cursor: string | null;
107
+ isDone: boolean;
108
+ };
109
+ export type UsageProviderCapabilities = {
110
+ aggregation: "sum";
111
+ scaledIntegerQuantities: true;
112
+ realTimeBalance: false;
113
+ eventCancellation: "provider_window";
114
+ invoiceFinalization: "asynchronous";
115
+ };
116
+ /** Contract for host adapters; this interface does not supply a billing engine. */
117
+ export interface UsageContractPort {
118
+ record(record: PreparedUsageRecord): Promise<UsageReceipt>;
119
+ read(request: {
120
+ scope: UsageScope;
121
+ page: UsagePageRequest;
122
+ }): Promise<UsageHistoryPage>;
123
+ reconcile(request: {
124
+ scope: UsageScope;
125
+ period: UsagePeriod;
126
+ }): Promise<UsageAvailability<UsageObservations>>;
127
+ capabilities(
128
+ scope: UsageScope,
129
+ ): Promise<UsageAvailability<UsageProviderCapabilities>>;
130
+ }
131
+
132
+ const seconds = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
133
+ const pageSchema = z.strictObject({
134
+ period: z.strictObject({ start: seconds, end: seconds }),
135
+ limit: z.number().int().min(1).max(100),
136
+ cursor: z.string().min(1).max(2048).nullable(),
137
+ });
138
+
139
+ export function validateUsagePageRequest(input: unknown): UsagePageRequest {
140
+ const request = pageSchema.parse(input);
141
+ if (request.period.end <= request.period.start)
142
+ throw new Error("Usage period must have a positive duration");
143
+ return request;
144
+ }
145
+
146
+ export function assertUsageReplay(
147
+ original: PreparedUsageRecord,
148
+ candidate: PreparedUsageRecord,
149
+ ): void {
150
+ const signature = (record: PreparedUsageRecord) =>
151
+ JSON.stringify([
152
+ record.schemaVersion,
153
+ record.identity,
154
+ record.sourceEventId,
155
+ record.scope.livemode,
156
+ record.scope.stripeAccountId,
157
+ record.scope.customerAccount,
158
+ record.scope.meterId,
159
+ record.quantity,
160
+ record.scaledQuantity,
161
+ record.occurredAt,
162
+ record.binding.stripeCustomerId,
163
+ record.binding.stripePriceId,
164
+ record.binding.eventName,
165
+ record.binding.apiVersion,
166
+ defineUsagePlan(record.binding.plan),
167
+ ]);
168
+ if (signature(original) !== signature(candidate))
169
+ throw new Error("Conflicting usage replay");
170
+ }
171
+
172
+ export async function authorizeUsageRecord<Context, Result>(
173
+ ctx: Context,
174
+ policy: UsageAuthorization<Context>,
175
+ input: unknown,
176
+ accept: (record: PreparedUsageRecord) => Promise<Result>,
177
+ ): Promise<Result> {
178
+ const record = prepareUsageRecord(input);
179
+ await policy.authorize(ctx, { scope: record.scope, operation: "record" });
180
+ await policy.authorizeActivity(ctx, record);
181
+ return accept(record);
182
+ }
@@ -0,0 +1,145 @@
1
+ import { expect, it } from "vitest";
2
+ import { defineUsagePlan, parseUsageQuantity } from "./contracts.js";
3
+
4
+ const base = {
5
+ key: "api_requests",
6
+ version: "v1",
7
+ unit: { name: "request", precision: 3 },
8
+ rate: { currency: "usd", unitAmountDecimal: "0.02" },
9
+ };
10
+ it.each([
11
+ { ...base, model: "pay_as_you_go" },
12
+ {
13
+ ...base,
14
+ model: "included_overage",
15
+ includedQuantity: "1000",
16
+ reset: "billing_period",
17
+ },
18
+ { ...base, model: "prepaid", insufficientBalance: "reject" },
19
+ ])("validates a serializable plan for $model", (input) => {
20
+ expect(defineUsagePlan(input)).toEqual(input);
21
+ expect(JSON.parse(JSON.stringify(defineUsagePlan(input)))).toEqual(input);
22
+ });
23
+ it("rejects invalid or ambiguous model configuration", () => {
24
+ for (const input of [
25
+ { ...base, model: "unknown" },
26
+ { ...base, model: "pay_as_you_go", includedQuantity: "5" },
27
+ {
28
+ ...base,
29
+ model: "included_overage",
30
+ includedQuantity: "1.0001",
31
+ reset: "billing_period",
32
+ },
33
+ { ...base, model: "prepaid", insufficientBalance: "allow" },
34
+ { ...base, model: "prepaid" },
35
+ {
36
+ ...base,
37
+ model: "pay_as_you_go",
38
+ rate: { currency: "USD", unitAmountDecimal: "0.1" },
39
+ },
40
+ {
41
+ ...base,
42
+ model: "pay_as_you_go",
43
+ rate: { currency: "usd", unitAmountDecimal: 0.1 },
44
+ },
45
+ ])
46
+ expect(() => defineUsagePlan(input)).toThrow();
47
+ });
48
+ it("represents exact quantities beyond JavaScript's safe integer range", () => {
49
+ expect(parseUsageQuantity("9007199254740993.01", 2)).toEqual({
50
+ quantity: "9007199254740993.01",
51
+ scaledQuantity: "900719925474099301",
52
+ precision: 2,
53
+ });
54
+ expect(parseUsageQuantity("1.2300", 4)).toEqual({
55
+ quantity: "1.23",
56
+ scaledQuantity: "12300",
57
+ precision: 4,
58
+ });
59
+ expect(parseUsageQuantity("0.000", 3)).toEqual({
60
+ quantity: "0",
61
+ scaledQuantity: "0",
62
+ precision: 3,
63
+ });
64
+ });
65
+ it("rejects rounding, noncanonical numbers, excessive precision and unsafe input", () => {
66
+ for (const value of [
67
+ "-1",
68
+ "+1",
69
+ "1e3",
70
+ "01",
71
+ "1.",
72
+ ".1",
73
+ " 1",
74
+ "1.0001",
75
+ "NaN",
76
+ 1,
77
+ Infinity,
78
+ null,
79
+ ])
80
+ expect(() => parseUsageQuantity(value, 3)).toThrow();
81
+ for (const precision of [-1, 1.5, 7, NaN])
82
+ expect(() => parseUsageQuantity("1", precision)).toThrow();
83
+ expect(() => parseUsageQuantity("1000000000000000000", 0)).toThrow();
84
+ });
85
+ it("copies configuration so caller mutation cannot change validated terms", () => {
86
+ const input = {
87
+ ...base,
88
+ unit: { ...base.unit },
89
+ rate: { ...base.rate },
90
+ model: "pay_as_you_go",
91
+ };
92
+ const plan = defineUsagePlan(input);
93
+ input.rate.unitAmountDecimal = "999";
94
+ expect(plan.rate.unitAmountDecimal).toBe("0.02");
95
+ });
96
+
97
+ it("keeps event identity scoped and independent of plan revisions", async () => {
98
+ const { prepareUsageRecord } = await import("./records.js");
99
+ const input = {
100
+ scope: {
101
+ stripeAccountId: "acct_platform",
102
+ customerAccount: "acct_buyer",
103
+ meterId: "mtr_requests",
104
+ livemode: false,
105
+ },
106
+ binding: {
107
+ stripeCustomerId: "cus_mapped",
108
+ eventName: "requests_v1",
109
+ stripePriceId: "price_requests",
110
+ plan: { ...base, model: "pay_as_you_go" },
111
+ },
112
+ sourceEventId: "job_123",
113
+ quantity: "1.230",
114
+ occurredAt: 1000,
115
+ };
116
+ const first = prepareUsageRecord(input);
117
+ expect(first.quantity).toBe("1.23");
118
+ expect(first.scaledQuantity).toBe("1230");
119
+ expect(
120
+ prepareUsageRecord({
121
+ ...input,
122
+ binding: {
123
+ ...input.binding,
124
+ plan: { ...input.binding.plan, version: "v2" },
125
+ },
126
+ }).identity,
127
+ ).toBe(first.identity);
128
+ expect(
129
+ prepareUsageRecord({
130
+ ...input,
131
+ scope: { ...input.scope, customerAccount: "acct_other" },
132
+ }).identity,
133
+ ).not.toBe(first.identity);
134
+ expect(
135
+ prepareUsageRecord({ ...input, scope: { ...input.scope, livemode: true } })
136
+ .identity,
137
+ ).not.toBe(first.identity);
138
+ expect(() => prepareUsageRecord({ ...input, occurredAt: 1.5 })).toThrow();
139
+ expect(() =>
140
+ prepareUsageRecord({
141
+ ...input,
142
+ binding: { ...input.binding, stripeCustomerId: "acct_buyer" },
143
+ }),
144
+ ).toThrow();
145
+ });
@@ -0,0 +1,79 @@
1
+ import { z } from "zod";
2
+
3
+ const unit = z.strictObject({
4
+ name: z.string().min(1).max(100),
5
+ precision: z.number().int().min(0).max(6),
6
+ });
7
+ const rate = z.strictObject({
8
+ currency: z.string().regex(/^[a-z]{3}$/),
9
+ // Decimal minor currency units per whole billable unit, never a JS float.
10
+ unitAmountDecimal: z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,12})?$/),
11
+ });
12
+ const common = {
13
+ key: z.string().min(1).max(100),
14
+ version: z.string().min(1).max(100),
15
+ unit,
16
+ rate,
17
+ };
18
+ const planSchema = z.discriminatedUnion("model", [
19
+ z.strictObject({ ...common, model: z.literal("pay_as_you_go") }),
20
+ z.strictObject({
21
+ ...common,
22
+ model: z.literal("included_overage"),
23
+ includedQuantity: z.string(),
24
+ reset: z.literal("billing_period"),
25
+ }),
26
+ z.strictObject({
27
+ ...common,
28
+ model: z.literal("prepaid"),
29
+ insufficientBalance: z.literal("reject"),
30
+ }),
31
+ ]);
32
+
33
+ /** Configuration contracts only. Validating a plan does not enable billing. */
34
+ export type UsagePlan = z.infer<typeof planSchema>;
35
+ export type UsageBillingModel = UsagePlan["model"];
36
+ export type ExactUsageQuantity = {
37
+ quantity: string;
38
+ scaledQuantity: string;
39
+ precision: number;
40
+ };
41
+
42
+ /**
43
+ * Parse a nonnegative decimal quantity without rounding. The shared contract
44
+ * supports 0–6 decimal places and at most 18 scaled digits. A provider adapter
45
+ * must additionally enforce its own supported bounds before accepting usage.
46
+ */
47
+ export function parseUsageQuantity(
48
+ value: unknown,
49
+ precision: number,
50
+ ): ExactUsageQuantity {
51
+ if (!Number.isInteger(precision) || precision < 0 || precision > 6)
52
+ throw new Error("Usage precision must be an integer between 0 and 6");
53
+ if (
54
+ typeof value !== "string" ||
55
+ value.length > 25 ||
56
+ !/^(0|[1-9]\d*)(\.\d+)?$/.test(value)
57
+ )
58
+ throw new Error("Usage quantity must be a nonnegative decimal string");
59
+ const [whole, fraction = ""] = value.split(".");
60
+ if (fraction.length > precision)
61
+ throw new Error("Usage quantity exceeds configured precision");
62
+ const scaled = BigInt(whole + fraction.padEnd(precision, "0"));
63
+ if (scaled > 999_999_999_999_999_999n)
64
+ throw new Error("Usage quantity exceeds the shared scaled bound");
65
+ const normalizedFraction = fraction.replace(/0+$/, "");
66
+ return {
67
+ quantity: normalizedFraction ? `${whole}.${normalizedFraction}` : whole,
68
+ scaledQuantity: scaled.toString(),
69
+ precision,
70
+ };
71
+ }
72
+
73
+ /** Validate and copy terms; provider provisioning and host authorization are separate. */
74
+ export function defineUsagePlan(input: unknown): UsagePlan {
75
+ const plan = planSchema.parse(input);
76
+ if (plan.model === "included_overage")
77
+ parseUsageQuantity(plan.includedQuantity, plan.unit.precision);
78
+ return plan;
79
+ }
@@ -0,0 +1,34 @@
1
+ export { defineUsagePlan, parseUsageQuantity } from "./contracts.js";
2
+ export type {
3
+ UsagePlan,
4
+ UsageBillingModel,
5
+ ExactUsageQuantity,
6
+ } from "./contracts.js";
7
+ export { prepareUsageRecord } from "./records.js";
8
+ export type {
9
+ UsageScope,
10
+ PreparedUsageRecord,
11
+ UsageDeliveryState,
12
+ } from "./records.js";
13
+ export {
14
+ assertUsageReplay,
15
+ validateUsagePageRequest,
16
+ authorizeUsageRecord,
17
+ } from "./boundaries.js";
18
+ export type {
19
+ UsagePeriod,
20
+ UsagePageRequest,
21
+ UsageAvailability,
22
+ UsageAuthorization,
23
+ UsageObservations,
24
+ UsageCorrectionRequest,
25
+ UsageRetentionPolicy,
26
+ UsageTransitionRequest,
27
+ UsageSubscriptionBinding,
28
+ UsageCreditProvenance,
29
+ UsageCorrectionOutcome,
30
+ UsageReceipt,
31
+ UsageHistoryPage,
32
+ UsageProviderCapabilities,
33
+ UsageContractPort,
34
+ } from "./boundaries.js";
@@ -0,0 +1,76 @@
1
+ import { z } from "zod";
2
+ import { STRIPE_API_VERSION } from "../constants.js";
3
+ import { STRIPE_CUSTOMER_PREVIEW_API_VERSION } from "../apiVersion.js";
4
+ import {
5
+ defineUsagePlan,
6
+ parseUsageQuantity,
7
+ type UsagePlan,
8
+ } from "./contracts.js";
9
+
10
+ const scopeSchema = z.strictObject({
11
+ stripeAccountId: z.string().regex(/^acct_[a-zA-Z0-9]+$/),
12
+ customerAccount: z.string().regex(/^acct_[a-zA-Z0-9]+$/),
13
+ meterId: z.string().regex(/^mtr_[a-zA-Z0-9_]+$/),
14
+ livemode: z.boolean(),
15
+ });
16
+ const recordSchema = z.strictObject({
17
+ scope: scopeSchema,
18
+ binding: z.strictObject({
19
+ stripeCustomerId: z.string().regex(/^cus_[a-zA-Z0-9]+$/),
20
+ stripePriceId: z.string().regex(/^price_[a-zA-Z0-9]+$/),
21
+ eventName: z.string().min(1).max(100),
22
+ apiVersion: z
23
+ .enum([STRIPE_API_VERSION, STRIPE_CUSTOMER_PREVIEW_API_VERSION])
24
+ .default(STRIPE_API_VERSION),
25
+ plan: z.unknown(),
26
+ }),
27
+ sourceEventId: z.string().min(1).max(200),
28
+ quantity: z.unknown(),
29
+ occurredAt: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
30
+ });
31
+
32
+ /** The exact Stripe realm, Accounts v2 payer, meter and test/live scope. */
33
+ export type UsageScope = z.infer<typeof scopeSchema>;
34
+ export type PreparedUsageRecord = Omit<
35
+ z.infer<typeof recordSchema>,
36
+ "quantity" | "binding"
37
+ > & {
38
+ schemaVersion: 1;
39
+ identity: string;
40
+ quantity: string;
41
+ scaledQuantity: string;
42
+ binding: Omit<z.infer<typeof recordSchema>["binding"], "plan"> & {
43
+ plan: UsagePlan;
44
+ };
45
+ };
46
+ export type UsageDeliveryState =
47
+ "queued" | "sending" | "provider_accepted" | "rejected" | "unknown" | "held";
48
+
49
+ /**
50
+ * Validate and snapshot a record before acceptance. This pure helper does not
51
+ * authorize an actor, verify provider ownership, persist or deliver anything.
52
+ * Occurrence time is Unix seconds; native provider windows are enforced by the
53
+ * acceptance/delivery implementation, not by changing historical event time.
54
+ */
55
+ export function prepareUsageRecord(input: unknown): PreparedUsageRecord {
56
+ const record = recordSchema.parse(input);
57
+ const plan = defineUsagePlan(record.binding.plan);
58
+ const quantity = parseUsageQuantity(record.quantity, plan.unit.precision);
59
+ const scope = record.scope;
60
+ return {
61
+ ...record,
62
+ schemaVersion: 1,
63
+ quantity: quantity.quantity,
64
+ scaledQuantity: quantity.scaledQuantity,
65
+ binding: { ...record.binding, plan },
66
+ // A plan/version/quantity change must conflict with the original source
67
+ // event, so these are deliberately outside the deduplication identity.
68
+ identity: JSON.stringify([
69
+ scope.livemode,
70
+ scope.stripeAccountId,
71
+ scope.customerAccount,
72
+ scope.meterId,
73
+ record.sourceEventId,
74
+ ]),
75
+ };
76
+ }