@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.
- package/CHANGELOG.md +20 -0
- package/README.md +1 -1
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +210 -32
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts +105 -16
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +178 -0
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutSyncTestHelpers.d.ts +89 -0
- package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
- package/dist/client/index.d.ts +6 -0
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +5 -0
- package/dist/client/index.js.map +1 -1
- package/dist/client/products/catalogClient.d.ts +23 -0
- package/dist/client/products/catalogClient.d.ts.map +1 -1
- package/dist/client/products/catalogClient.js +32 -0
- package/dist/client/products/catalogClient.js.map +1 -1
- package/dist/client/products/fixedPrice.d.ts +4 -0
- package/dist/client/products/fixedPrice.d.ts.map +1 -0
- package/dist/client/products/fixedPrice.js +10 -0
- package/dist/client/products/fixedPrice.js.map +1 -0
- package/dist/client/products/products.d.ts.map +1 -1
- package/dist/client/products/products.js +3 -0
- package/dist/client/products/products.js.map +1 -1
- package/dist/client/usage/catalog.d.ts +7 -0
- package/dist/client/usage/catalog.d.ts.map +1 -0
- package/dist/client/usage/catalog.js +55 -0
- package/dist/client/usage/catalog.js.map +1 -0
- package/dist/client/usage/catalogLifecycle.d.ts +25 -0
- package/dist/client/usage/catalogLifecycle.d.ts.map +1 -0
- package/dist/client/usage/catalogLifecycle.js +64 -0
- package/dist/client/usage/catalogLifecycle.js.map +1 -0
- package/dist/client/usage/catalogMath.d.ts +3 -0
- package/dist/client/usage/catalogMath.d.ts.map +1 -0
- package/dist/client/usage/catalogMath.js +21 -0
- package/dist/client/usage/catalogMath.js.map +1 -0
- package/dist/client/usage/catalogPrices.d.ts +5 -0
- package/dist/client/usage/catalogPrices.d.ts.map +1 -0
- package/dist/client/usage/catalogPrices.js +178 -0
- package/dist/client/usage/catalogPrices.js.map +1 -0
- package/dist/client/usage/catalogRead.d.ts +25 -0
- package/dist/client/usage/catalogRead.d.ts.map +1 -0
- package/dist/client/usage/catalogRead.js +71 -0
- package/dist/client/usage/catalogRead.js.map +1 -0
- package/dist/client/usage/catalogTypes.d.ts +97 -0
- package/dist/client/usage/catalogTypes.d.ts.map +1 -0
- package/dist/client/usage/catalogTypes.js +106 -0
- package/dist/client/usage/catalogTypes.js.map +1 -0
- package/dist/client/usage/client.d.ts +37 -0
- package/dist/client/usage/client.d.ts.map +1 -0
- package/dist/client/usage/client.js +59 -0
- package/dist/client/usage/client.js.map +1 -0
- package/dist/client/usage/records.d.ts +1 -1
- package/dist/client/usage/records.d.ts.map +1 -1
- package/dist/client/usage/records.js +1 -1
- package/dist/client/usage/records.js.map +1 -1
- package/dist/client/webhooks/processors.d.ts.map +1 -1
- package/dist/client/webhooks/processors.js +3 -0
- package/dist/client/webhooks/processors.js.map +1 -1
- package/dist/component/_generated/api.d.ts +10 -0
- package/dist/component/_generated/api.d.ts.map +1 -1
- package/dist/component/_generated/api.js.map +1 -1
- package/dist/component/_generated/component.d.ts +141 -0
- package/dist/component/_generated/component.d.ts.map +1 -1
- package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
- package/dist/component/balanceFunding/mutations.d.ts +43 -43
- package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
- package/dist/component/earnings/triggers.d.ts +224 -16
- package/dist/component/earnings/triggers.d.ts.map +1 -1
- package/dist/component/schema.d.ts +89 -0
- package/dist/component/schema.js +7 -0
- package/dist/component/schema.js.map +1 -1
- package/dist/component/usage/helpers.d.ts +13 -0
- package/dist/component/usage/helpers.d.ts.map +1 -0
- package/dist/component/usage/helpers.js +34 -0
- package/dist/component/usage/helpers.js.map +1 -0
- package/dist/component/usage/mutations.d.ts +14 -0
- package/dist/component/usage/mutations.d.ts.map +1 -0
- package/dist/component/usage/mutations.js +124 -0
- package/dist/component/usage/mutations.js.map +1 -0
- package/dist/component/usage/queries.d.ts +62 -0
- package/dist/component/usage/queries.d.ts.map +1 -0
- package/dist/component/usage/queries.js +65 -0
- package/dist/component/usage/queries.js.map +1 -0
- package/dist/component/usage/schema.d.ts +110 -0
- package/dist/component/usage/schema.d.ts.map +1 -0
- package/dist/component/usage/schema.js +54 -0
- package/dist/component/usage/schema.js.map +1 -0
- package/dist/component/usageCatalog/mutations.d.ts +25 -0
- package/dist/component/usageCatalog/mutations.d.ts.map +1 -0
- package/dist/component/usageCatalog/mutations.js +75 -0
- package/dist/component/usageCatalog/mutations.js.map +1 -0
- package/dist/component/usageCatalog/queries.d.ts +33 -0
- package/dist/component/usageCatalog/queries.d.ts.map +1 -0
- package/dist/component/usageCatalog/queries.js +26 -0
- package/dist/component/usageCatalog/queries.js.map +1 -0
- package/dist/component/usageCatalog/schema.d.ts +57 -0
- package/dist/component/usageCatalog/schema.d.ts.map +1 -0
- package/dist/component/usageCatalog/schema.js +22 -0
- package/dist/component/usageCatalog/schema.js.map +1 -0
- package/docs/README.md +5 -1
- package/docs/metered-usage.md +2 -2
- package/docs/metering-setup.md +4 -1
- package/docs/usage-catalog.md +106 -0
- package/docs/usage-ledger.md +62 -0
- package/package.json +4 -2
- package/src/client/index.ts +12 -0
- package/src/client/products/catalogClient.ts +77 -0
- package/src/client/products/fixedPrice.test.ts +57 -0
- package/src/client/products/fixedPrice.ts +13 -0
- package/src/client/products/products.ts +2 -0
- package/src/client/usage/catalog.test.ts +464 -0
- package/src/client/usage/catalog.ts +117 -0
- package/src/client/usage/catalogLifecycle.ts +128 -0
- package/src/client/usage/catalogMath.test.ts +13 -0
- package/src/client/usage/catalogMath.ts +22 -0
- package/src/client/usage/catalogPrices.ts +251 -0
- package/src/client/usage/catalogRead.ts +98 -0
- package/src/client/usage/catalogTypes.ts +170 -0
- package/src/client/usage/client.ts +97 -0
- package/src/client/usage/ledger-client.test.ts +74 -0
- package/src/client/usage/records.ts +1 -1
- package/src/client/webhooks/processors.ts +2 -0
- package/src/component/_generated/api.ts +10 -0
- package/src/component/_generated/component.ts +184 -0
- package/src/component/schema.ts +12 -0
- package/src/component/usage/helpers.ts +33 -0
- package/src/component/usage/ledger.test.ts +310 -0
- package/src/component/usage/mutations.ts +139 -0
- package/src/component/usage/queries.ts +69 -0
- package/src/component/usage/schema.ts +65 -0
- package/src/component/usageCatalog/mutations.ts +79 -0
- package/src/component/usageCatalog/queries.ts +32 -0
- package/src/component/usageCatalog/schema.ts +21 -0
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { expect, it } from "vitest";
|
|
2
|
+
import { scaledUsageRate } from "./catalogMath.js";
|
|
3
|
+
it("scales native per-unit rates exactly without money floats", () => {
|
|
4
|
+
expect(scaledUsageRate("2", 2)).toBe("0.02");
|
|
5
|
+
expect(scaledUsageRate("123.4500", 3)).toBe("0.12345");
|
|
6
|
+
expect(scaledUsageRate("0", 6)).toBe("0");
|
|
7
|
+
expect(scaledUsageRate("999999999999.123456", 6)).toBe("999999.999999123456");
|
|
8
|
+
});
|
|
9
|
+
it("rejects native decimal precision loss rather than rounding", () => {
|
|
10
|
+
expect(() => scaledUsageRate("0.000000000001", 1)).toThrow();
|
|
11
|
+
expect(() => scaledUsageRate("2", 7)).toThrow();
|
|
12
|
+
expect(() => scaledUsageRate("-2", 0)).toThrow();
|
|
13
|
+
});
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** Convert minor currency units per whole unit to a native scaled-unit rate. */
|
|
2
|
+
export function scaledUsageRate(rate: string, precision: number): string {
|
|
3
|
+
if (
|
|
4
|
+
!Number.isInteger(precision) ||
|
|
5
|
+
precision < 0 ||
|
|
6
|
+
precision > 6 ||
|
|
7
|
+
!/^(0|[1-9]\d{0,11})(\.\d{1,12})?$/.test(rate)
|
|
8
|
+
)
|
|
9
|
+
throw new Error("Unsupported native usage rate");
|
|
10
|
+
const [whole, fraction = ""] = rate.split(".");
|
|
11
|
+
const places = fraction.length + precision;
|
|
12
|
+
const digits = (whole + fraction).padStart(places + 1, "0");
|
|
13
|
+
const raw = places
|
|
14
|
+
? `${digits.slice(0, -places)}.${digits.slice(-places)}`
|
|
15
|
+
: digits;
|
|
16
|
+
const [integer, decimal = ""] = raw.split(".");
|
|
17
|
+
const normalized = decimal.replace(/0+$/, "");
|
|
18
|
+
if (normalized.length > 12)
|
|
19
|
+
throw new Error("Unsupported native usage rate precision");
|
|
20
|
+
const base = BigInt(integer).toString();
|
|
21
|
+
return normalized ? `${base}.${normalized}` : base;
|
|
22
|
+
}
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
import Stripe from "stripe";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import type { Component, RunCtx } from "../helpers.js";
|
|
4
|
+
import { componentRef } from "../webhooks/helpers.js";
|
|
5
|
+
import { getChargeCurrencyMetadata } from "../charge-currency.js";
|
|
6
|
+
import { defineUsagePlan, parseUsageQuantity } from "./contracts.js";
|
|
7
|
+
import { scaledUsageRate } from "./catalogMath.js";
|
|
8
|
+
|
|
9
|
+
import {
|
|
10
|
+
UsageCatalogError,
|
|
11
|
+
verifyMeter,
|
|
12
|
+
catalogScope,
|
|
13
|
+
meterKey,
|
|
14
|
+
meterTerms,
|
|
15
|
+
verifyRealm,
|
|
16
|
+
prepareCatalog,
|
|
17
|
+
completeCatalog,
|
|
18
|
+
operationKey,
|
|
19
|
+
permitCreate,
|
|
20
|
+
nativeCall,
|
|
21
|
+
type UsageMeterOptions,
|
|
22
|
+
type UsagePriceOptions,
|
|
23
|
+
} from "./catalogTypes.js";
|
|
24
|
+
import type { Doc } from "../../component/_generated/dataModel.js";
|
|
25
|
+
function incompatible(): never {
|
|
26
|
+
throw new UsageCatalogError(
|
|
27
|
+
"incompatible_terms",
|
|
28
|
+
"Native price has incompatible immutable terms",
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
function decimal(
|
|
32
|
+
value: Stripe.Decimal | string | null | undefined,
|
|
33
|
+
integer: number | null | undefined,
|
|
34
|
+
) {
|
|
35
|
+
const text =
|
|
36
|
+
value?.toString() ??
|
|
37
|
+
(Number.isSafeInteger(integer) && integer !== null && integer !== undefined
|
|
38
|
+
? String(integer)
|
|
39
|
+
: undefined);
|
|
40
|
+
if (text === undefined || !/^\d+(\.\d{1,12})?$/.test(text))
|
|
41
|
+
return incompatible();
|
|
42
|
+
const [whole, fraction = ""] = text.split(".");
|
|
43
|
+
const trimmed = fraction.replace(/0+$/, "");
|
|
44
|
+
const normalized = BigInt(whole).toString();
|
|
45
|
+
return trimmed ? `${normalized}.${trimmed}` : normalized;
|
|
46
|
+
}
|
|
47
|
+
function termsFor(opts: UsagePriceOptions) {
|
|
48
|
+
const plan = defineUsagePlan(opts.plan);
|
|
49
|
+
if (!getChargeCurrencyMetadata(plan.rate.currency)) return incompatible();
|
|
50
|
+
const terms = {
|
|
51
|
+
scope: catalogScope(opts.scope),
|
|
52
|
+
plan,
|
|
53
|
+
meterId: z
|
|
54
|
+
.string()
|
|
55
|
+
.regex(/^mtr_[a-zA-Z0-9_]+$/)
|
|
56
|
+
.max(100)
|
|
57
|
+
.parse(opts.meterId),
|
|
58
|
+
stripeProductId: z
|
|
59
|
+
.string()
|
|
60
|
+
.regex(/^prod_[a-zA-Z0-9]+$/)
|
|
61
|
+
.max(100)
|
|
62
|
+
.parse(opts.stripeProductId),
|
|
63
|
+
lookupKey: z.string().min(1).max(200).parse(opts.lookupKey),
|
|
64
|
+
};
|
|
65
|
+
const rate = scaledUsageRate(
|
|
66
|
+
plan.rate.unitAmountDecimal,
|
|
67
|
+
plan.unit.precision,
|
|
68
|
+
);
|
|
69
|
+
let included: number | undefined;
|
|
70
|
+
if (plan.model === "included_overage") {
|
|
71
|
+
const scaled = BigInt(
|
|
72
|
+
parseUsageQuantity(plan.includedQuantity, plan.unit.precision)
|
|
73
|
+
.scaledQuantity,
|
|
74
|
+
);
|
|
75
|
+
if (scaled < 1n || scaled > BigInt(Number.MAX_SAFE_INTEGER))
|
|
76
|
+
return incompatible();
|
|
77
|
+
included = Number(scaled);
|
|
78
|
+
}
|
|
79
|
+
return { terms, rate, included };
|
|
80
|
+
}
|
|
81
|
+
function verifyPrice(
|
|
82
|
+
price: Stripe.Price,
|
|
83
|
+
opts: UsagePriceOptions,
|
|
84
|
+
rate: string,
|
|
85
|
+
included: number | undefined,
|
|
86
|
+
) {
|
|
87
|
+
const product =
|
|
88
|
+
typeof price.product === "string" ? price.product : price.product.id;
|
|
89
|
+
if (
|
|
90
|
+
!price.active ||
|
|
91
|
+
price.livemode !== opts.scope.livemode ||
|
|
92
|
+
price.lookup_key !== opts.lookupKey ||
|
|
93
|
+
product !== opts.stripeProductId ||
|
|
94
|
+
price.currency !== opts.plan.rate.currency ||
|
|
95
|
+
price.type !== "recurring" ||
|
|
96
|
+
price.recurring?.interval !== "month" ||
|
|
97
|
+
price.recurring.interval_count !== 1 ||
|
|
98
|
+
price.recurring.usage_type !== "metered" ||
|
|
99
|
+
price.recurring.meter !== opts.meterId ||
|
|
100
|
+
price.transform_quantity != null
|
|
101
|
+
)
|
|
102
|
+
return incompatible();
|
|
103
|
+
if (included === undefined) {
|
|
104
|
+
if (
|
|
105
|
+
price.billing_scheme !== "per_unit" ||
|
|
106
|
+
decimal(price.unit_amount_decimal, price.unit_amount) !== rate
|
|
107
|
+
)
|
|
108
|
+
return incompatible();
|
|
109
|
+
} else {
|
|
110
|
+
if (
|
|
111
|
+
price.billing_scheme !== "tiered" ||
|
|
112
|
+
price.tiers_mode !== "graduated" ||
|
|
113
|
+
price.tiers?.length !== 2
|
|
114
|
+
)
|
|
115
|
+
return incompatible();
|
|
116
|
+
const [free, overage] = price.tiers;
|
|
117
|
+
if (
|
|
118
|
+
free.up_to !== included ||
|
|
119
|
+
overage.up_to !== null ||
|
|
120
|
+
decimal(free.unit_amount_decimal, free.unit_amount) !== "0" ||
|
|
121
|
+
decimal(overage.unit_amount_decimal, overage.unit_amount) !== rate
|
|
122
|
+
)
|
|
123
|
+
return incompatible();
|
|
124
|
+
for (const tier of price.tiers)
|
|
125
|
+
if (
|
|
126
|
+
(tier.flat_amount != null && tier.flat_amount !== 0) ||
|
|
127
|
+
(tier.flat_amount_decimal != null &&
|
|
128
|
+
decimal(tier.flat_amount_decimal, 0) !== "0")
|
|
129
|
+
)
|
|
130
|
+
return incompatible();
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
export async function ensureUsagePrice(
|
|
134
|
+
stripe: Stripe,
|
|
135
|
+
component: Component,
|
|
136
|
+
ctx: RunCtx,
|
|
137
|
+
opts: UsagePriceOptions,
|
|
138
|
+
): Promise<Stripe.Price> {
|
|
139
|
+
const { terms, rate, included } = termsFor(opts);
|
|
140
|
+
await verifyRealm(stripe, terms.scope);
|
|
141
|
+
const meterRow = (await ctx.runQuery(
|
|
142
|
+
componentRef(component, "usageCatalog/queries/get"),
|
|
143
|
+
{
|
|
144
|
+
scopeKey: JSON.stringify(terms.scope),
|
|
145
|
+
kind: "meter",
|
|
146
|
+
key: meterKey(terms.plan),
|
|
147
|
+
},
|
|
148
|
+
)) as Doc<"usageCatalog"> | null;
|
|
149
|
+
if (!meterRow || meterRow.providerId !== terms.meterId) return incompatible();
|
|
150
|
+
const meterOpts = meterTerms(
|
|
151
|
+
JSON.parse(meterRow.termsJson) as UsageMeterOptions,
|
|
152
|
+
);
|
|
153
|
+
if (JSON.stringify(meterOpts.plan) !== JSON.stringify(terms.plan))
|
|
154
|
+
return incompatible();
|
|
155
|
+
const meter = await nativeCall(() =>
|
|
156
|
+
stripe.billing.meters.retrieve(terms.meterId),
|
|
157
|
+
);
|
|
158
|
+
if (meter.id !== terms.meterId) return incompatible();
|
|
159
|
+
verifyMeter(meter, meterOpts);
|
|
160
|
+
const product = await nativeCall(() =>
|
|
161
|
+
stripe.products.retrieve(terms.stripeProductId),
|
|
162
|
+
);
|
|
163
|
+
if (
|
|
164
|
+
"deleted" in product ||
|
|
165
|
+
!product.active ||
|
|
166
|
+
product.id !== terms.stripeProductId
|
|
167
|
+
)
|
|
168
|
+
return incompatible();
|
|
169
|
+
const row = await prepareCatalog(
|
|
170
|
+
component,
|
|
171
|
+
ctx,
|
|
172
|
+
"price",
|
|
173
|
+
terms.scope,
|
|
174
|
+
terms.lookupKey,
|
|
175
|
+
terms,
|
|
176
|
+
);
|
|
177
|
+
let price: Stripe.Price | undefined;
|
|
178
|
+
if (row.providerId)
|
|
179
|
+
price = await nativeCall(() =>
|
|
180
|
+
stripe.prices.retrieve(row.providerId!, { expand: ["tiers"] }),
|
|
181
|
+
);
|
|
182
|
+
else {
|
|
183
|
+
const result = await nativeCall(() =>
|
|
184
|
+
stripe.prices.list({
|
|
185
|
+
lookup_keys: [terms.lookupKey],
|
|
186
|
+
limit: 2,
|
|
187
|
+
expand: ["data.tiers"],
|
|
188
|
+
}),
|
|
189
|
+
);
|
|
190
|
+
if (result.has_more || result.data.length > 1)
|
|
191
|
+
throw new UsageCatalogError(
|
|
192
|
+
"ambiguous_lookup",
|
|
193
|
+
"Native price lookup key is ambiguous",
|
|
194
|
+
);
|
|
195
|
+
price = result.data[0];
|
|
196
|
+
}
|
|
197
|
+
if (!price) {
|
|
198
|
+
permitCreate(row);
|
|
199
|
+
const key = await operationKey(terms, "price");
|
|
200
|
+
const params: Stripe.PriceCreateParams = {
|
|
201
|
+
product: terms.stripeProductId,
|
|
202
|
+
currency: terms.plan.rate.currency,
|
|
203
|
+
lookup_key: terms.lookupKey,
|
|
204
|
+
recurring: {
|
|
205
|
+
interval: "month",
|
|
206
|
+
usage_type: "metered",
|
|
207
|
+
meter: terms.meterId,
|
|
208
|
+
},
|
|
209
|
+
expand: ["tiers"],
|
|
210
|
+
...(included === undefined
|
|
211
|
+
? {
|
|
212
|
+
billing_scheme: "per_unit",
|
|
213
|
+
unit_amount_decimal: Stripe.Decimal.from(rate),
|
|
214
|
+
}
|
|
215
|
+
: {
|
|
216
|
+
billing_scheme: "tiered",
|
|
217
|
+
tiers_mode: "graduated",
|
|
218
|
+
tiers: [
|
|
219
|
+
{ up_to: included, unit_amount_decimal: Stripe.Decimal.zero },
|
|
220
|
+
{ up_to: "inf", unit_amount_decimal: Stripe.Decimal.from(rate) },
|
|
221
|
+
],
|
|
222
|
+
}),
|
|
223
|
+
};
|
|
224
|
+
price = await nativeCall(() =>
|
|
225
|
+
stripe.prices.create(params, { idempotencyKey: key }),
|
|
226
|
+
);
|
|
227
|
+
}
|
|
228
|
+
verifyPrice(price, terms, rate, included);
|
|
229
|
+
if (row.providerId && row.providerId !== price.id) return incompatible();
|
|
230
|
+
await completeCatalog(component, ctx, row, price.id, {
|
|
231
|
+
type: "metered_price",
|
|
232
|
+
id: price.id,
|
|
233
|
+
productId: terms.stripeProductId,
|
|
234
|
+
meterId: terms.meterId,
|
|
235
|
+
livemode: price.livemode,
|
|
236
|
+
active: price.active,
|
|
237
|
+
currency: price.currency,
|
|
238
|
+
billingScheme: price.billing_scheme,
|
|
239
|
+
unitAmountDecimal:
|
|
240
|
+
price.billing_scheme === "per_unit"
|
|
241
|
+
? decimal(price.unit_amount_decimal, price.unit_amount)
|
|
242
|
+
: null,
|
|
243
|
+
tiers:
|
|
244
|
+
price.tiers?.map((tier) => ({
|
|
245
|
+
upTo: tier.up_to === null ? null : String(tier.up_to),
|
|
246
|
+
unitAmountDecimal: decimal(tier.unit_amount_decimal, tier.unit_amount),
|
|
247
|
+
})) ?? [],
|
|
248
|
+
interval: "month",
|
|
249
|
+
});
|
|
250
|
+
return price;
|
|
251
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { componentRef } from "../webhooks/helpers.js";
|
|
3
|
+
import { catalogScope } from "./catalogTypes.js";
|
|
4
|
+
import { defineUsagePlan } from "./contracts.js";
|
|
5
|
+
import type { Doc } from "../../component/_generated/dataModel.js";
|
|
6
|
+
import type { Component, RunCtx } from "../helpers.js";
|
|
7
|
+
import type { UsageCatalogScope } from "./catalogTypes.js";
|
|
8
|
+
import type { UsageAvailability } from "./boundaries.js";
|
|
9
|
+
import type { UsagePlan } from "./contracts.js";
|
|
10
|
+
export type UsagePriceBinding = {
|
|
11
|
+
pricingMode: "metered";
|
|
12
|
+
stripePriceId: string;
|
|
13
|
+
stripeProductId: string;
|
|
14
|
+
meterId: string;
|
|
15
|
+
active: boolean;
|
|
16
|
+
currency: string;
|
|
17
|
+
billingScheme: "per_unit" | "tiered";
|
|
18
|
+
unitAmountDecimal: string | null;
|
|
19
|
+
tiers: Array<{ upTo: string | null; unitAmountDecimal: string }>;
|
|
20
|
+
interval: "month";
|
|
21
|
+
plan: UsagePlan;
|
|
22
|
+
};
|
|
23
|
+
const observation = z.strictObject({
|
|
24
|
+
type: z.literal("metered_price"),
|
|
25
|
+
id: z.string(),
|
|
26
|
+
productId: z.string(),
|
|
27
|
+
meterId: z.string(),
|
|
28
|
+
livemode: z.boolean(),
|
|
29
|
+
active: z.boolean(),
|
|
30
|
+
currency: z.string(),
|
|
31
|
+
billingScheme: z.enum(["per_unit", "tiered"]),
|
|
32
|
+
unitAmountDecimal: z.string().nullable(),
|
|
33
|
+
tiers: z.array(
|
|
34
|
+
z.strictObject({
|
|
35
|
+
upTo: z.string().nullable(),
|
|
36
|
+
unitAmountDecimal: z.string(),
|
|
37
|
+
}),
|
|
38
|
+
),
|
|
39
|
+
interval: z.literal("month"),
|
|
40
|
+
});
|
|
41
|
+
export async function getUsagePriceBinding(
|
|
42
|
+
component: Component,
|
|
43
|
+
ctx: RunCtx,
|
|
44
|
+
opts: { scope: UsageCatalogScope; lookupKey: string },
|
|
45
|
+
): Promise<UsageAvailability<UsagePriceBinding>> {
|
|
46
|
+
const scope = catalogScope(opts.scope);
|
|
47
|
+
const key = z.string().min(1).max(200).parse(opts.lookupKey);
|
|
48
|
+
const row = (await ctx.runQuery(
|
|
49
|
+
componentRef(component, "usageCatalog/queries/get"),
|
|
50
|
+
{ scopeKey: JSON.stringify(scope), kind: "price", key },
|
|
51
|
+
)) as Doc<"usageCatalog"> | null;
|
|
52
|
+
if (!row)
|
|
53
|
+
return {
|
|
54
|
+
status: "unavailable",
|
|
55
|
+
reason: "catalog_not_found",
|
|
56
|
+
retryable: false,
|
|
57
|
+
};
|
|
58
|
+
if (!row.observationJson || row.observedAt === undefined)
|
|
59
|
+
return {
|
|
60
|
+
status: "unavailable",
|
|
61
|
+
reason: "catalog_pending",
|
|
62
|
+
retryable: true,
|
|
63
|
+
};
|
|
64
|
+
try {
|
|
65
|
+
const price = observation.parse(JSON.parse(row.observationJson));
|
|
66
|
+
const plan = defineUsagePlan(JSON.parse(row.termsJson).plan);
|
|
67
|
+
if (
|
|
68
|
+
price.id !== row.providerId ||
|
|
69
|
+
price.livemode !== scope.livemode ||
|
|
70
|
+
price.currency !== plan.rate.currency ||
|
|
71
|
+
(price.billingScheme === "per_unit" && price.unitAmountDecimal === null)
|
|
72
|
+
)
|
|
73
|
+
throw new Error("Invalid catalog observation");
|
|
74
|
+
return {
|
|
75
|
+
status: "available",
|
|
76
|
+
observedAt: row.observedAt,
|
|
77
|
+
value: {
|
|
78
|
+
pricingMode: "metered",
|
|
79
|
+
stripePriceId: price.id,
|
|
80
|
+
stripeProductId: price.productId,
|
|
81
|
+
meterId: price.meterId,
|
|
82
|
+
active: price.active,
|
|
83
|
+
currency: price.currency,
|
|
84
|
+
billingScheme: price.billingScheme,
|
|
85
|
+
unitAmountDecimal: price.unitAmountDecimal,
|
|
86
|
+
tiers: price.tiers,
|
|
87
|
+
interval: price.interval,
|
|
88
|
+
plan,
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
} catch {
|
|
92
|
+
return {
|
|
93
|
+
status: "unavailable",
|
|
94
|
+
reason: "invalid_catalog_observation",
|
|
95
|
+
retryable: false,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import type Stripe from "stripe";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import type { Component, RunCtx } from "../helpers.js";
|
|
4
|
+
import { runMutationOrThrow } from "../helpers.js";
|
|
5
|
+
import { componentRef } from "../webhooks/helpers.js";
|
|
6
|
+
import { defineUsagePlan, type UsagePlan } from "./contracts.js";
|
|
7
|
+
import type { Doc } from "../../component/_generated/dataModel.js";
|
|
8
|
+
export type UsageCatalogScope = { stripeAccountId: string; livemode: boolean };
|
|
9
|
+
export type UsageMeterOptions = {
|
|
10
|
+
scope: UsageCatalogScope;
|
|
11
|
+
plan: UsagePlan;
|
|
12
|
+
eventName: string;
|
|
13
|
+
displayName: string;
|
|
14
|
+
};
|
|
15
|
+
export type UsagePriceOptions = {
|
|
16
|
+
scope: UsageCatalogScope;
|
|
17
|
+
plan: UsagePlan;
|
|
18
|
+
meterId: string;
|
|
19
|
+
stripeProductId: string;
|
|
20
|
+
lookupKey: string;
|
|
21
|
+
};
|
|
22
|
+
export class UsageCatalogError extends Error {
|
|
23
|
+
constructor(
|
|
24
|
+
public readonly code:
|
|
25
|
+
| "unsupported_scope"
|
|
26
|
+
| "incompatible_terms"
|
|
27
|
+
| "ambiguous_lookup"
|
|
28
|
+
| "unknown_create_outcome"
|
|
29
|
+
| "provider_unavailable",
|
|
30
|
+
message: string,
|
|
31
|
+
) {
|
|
32
|
+
super(message);
|
|
33
|
+
this.name = "UsageCatalogError";
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
const scopeSchema = z.strictObject({
|
|
37
|
+
stripeAccountId: z
|
|
38
|
+
.string()
|
|
39
|
+
.regex(/^acct_[a-zA-Z0-9]+$/)
|
|
40
|
+
.max(100),
|
|
41
|
+
livemode: z.boolean(),
|
|
42
|
+
});
|
|
43
|
+
export function catalogScope(scope: UsageCatalogScope) {
|
|
44
|
+
return scopeSchema.parse(scope);
|
|
45
|
+
}
|
|
46
|
+
export function meterTerms(opts: UsageMeterOptions) {
|
|
47
|
+
return {
|
|
48
|
+
scope: catalogScope(opts.scope),
|
|
49
|
+
plan: defineUsagePlan(opts.plan),
|
|
50
|
+
eventName: z
|
|
51
|
+
.string()
|
|
52
|
+
.regex(/^[\w.-]{1,100}$/)
|
|
53
|
+
.parse(opts.eventName),
|
|
54
|
+
displayName: z.string().min(1).max(100).parse(opts.displayName),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
export function meterKey(plan: UsagePlan) {
|
|
58
|
+
return JSON.stringify([plan.key, plan.version]);
|
|
59
|
+
}
|
|
60
|
+
export async function nativeCall<T>(call: () => Promise<T>): Promise<T> {
|
|
61
|
+
try {
|
|
62
|
+
return await call();
|
|
63
|
+
} catch {
|
|
64
|
+
throw new UsageCatalogError(
|
|
65
|
+
"provider_unavailable",
|
|
66
|
+
"Native Stripe catalog is unavailable",
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
export async function verifyRealm(stripe: Stripe, scope: UsageCatalogScope) {
|
|
71
|
+
const parsed = catalogScope(scope);
|
|
72
|
+
const [account, balance] = await Promise.all([
|
|
73
|
+
nativeCall(() => stripe.accounts.retrieve(null)),
|
|
74
|
+
nativeCall(() => stripe.balance.retrieve()),
|
|
75
|
+
]);
|
|
76
|
+
if (
|
|
77
|
+
account.id !== parsed.stripeAccountId ||
|
|
78
|
+
balance.livemode !== parsed.livemode
|
|
79
|
+
)
|
|
80
|
+
throw new UsageCatalogError(
|
|
81
|
+
"unsupported_scope",
|
|
82
|
+
"Native catalog scope must match the configured Stripe realm and mode",
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
export async function operationKey(terms: unknown, kind: string) {
|
|
86
|
+
const bytes = new TextEncoder().encode(JSON.stringify(terms));
|
|
87
|
+
const digest = await crypto.subtle.digest("SHA-256", bytes);
|
|
88
|
+
return `bs_usage_${kind}_${Array.from(new Uint8Array(digest), (n) => n.toString(16).padStart(2, "0")).join("")}`;
|
|
89
|
+
}
|
|
90
|
+
export async function prepareCatalog(
|
|
91
|
+
component: Component,
|
|
92
|
+
ctx: RunCtx,
|
|
93
|
+
kind: "meter" | "price",
|
|
94
|
+
scope: UsageCatalogScope,
|
|
95
|
+
key: string,
|
|
96
|
+
terms: unknown,
|
|
97
|
+
): Promise<Doc<"usageCatalog">> {
|
|
98
|
+
return runMutationOrThrow(
|
|
99
|
+
ctx,
|
|
100
|
+
componentRef(component, "usageCatalog/mutations/prepare"),
|
|
101
|
+
{
|
|
102
|
+
scopeKey: JSON.stringify(catalogScope(scope)),
|
|
103
|
+
kind,
|
|
104
|
+
key,
|
|
105
|
+
termsJson: JSON.stringify(terms),
|
|
106
|
+
},
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
export async function completeCatalog(
|
|
110
|
+
component: Component,
|
|
111
|
+
ctx: RunCtx,
|
|
112
|
+
row: Doc<"usageCatalog">,
|
|
113
|
+
providerId: string,
|
|
114
|
+
observation: unknown,
|
|
115
|
+
) {
|
|
116
|
+
return runMutationOrThrow(
|
|
117
|
+
ctx,
|
|
118
|
+
componentRef(component, "usageCatalog/mutations/complete"),
|
|
119
|
+
{
|
|
120
|
+
scopeKey: row.scopeKey,
|
|
121
|
+
kind: row.kind,
|
|
122
|
+
key: row.key,
|
|
123
|
+
providerId,
|
|
124
|
+
observationJson: JSON.stringify(observation),
|
|
125
|
+
},
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
export function permitCreate(row: Doc<"usageCatalog">) {
|
|
129
|
+
if (Date.now() / 1000 - row.firstAttemptAt >= 23 * 3600)
|
|
130
|
+
throw new UsageCatalogError(
|
|
131
|
+
"unknown_create_outcome",
|
|
132
|
+
"Native catalog create requires reconciliation after its safe retry window",
|
|
133
|
+
);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function verifyMeter(
|
|
137
|
+
meter: Stripe.Billing.Meter,
|
|
138
|
+
opts: UsageMeterOptions,
|
|
139
|
+
active = true,
|
|
140
|
+
) {
|
|
141
|
+
if (
|
|
142
|
+
meter.livemode !== opts.scope.livemode ||
|
|
143
|
+
meter.event_name !== opts.eventName ||
|
|
144
|
+
meter.default_aggregation.formula !== "sum" ||
|
|
145
|
+
meter.customer_mapping.type !== "by_id" ||
|
|
146
|
+
meter.customer_mapping.event_payload_key !== "stripe_customer_id" ||
|
|
147
|
+
meter.value_settings.event_payload_key !== "value" ||
|
|
148
|
+
meter.event_time_window !== null ||
|
|
149
|
+
!["active", "inactive"].includes(meter.status) ||
|
|
150
|
+
(active && meter.status !== "active")
|
|
151
|
+
)
|
|
152
|
+
throw new UsageCatalogError(
|
|
153
|
+
"incompatible_terms",
|
|
154
|
+
"Native meter has incompatible immutable terms or status",
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export function meterObservation(meter: Stripe.Billing.Meter) {
|
|
159
|
+
return {
|
|
160
|
+
type: "meter",
|
|
161
|
+
id: meter.id,
|
|
162
|
+
eventName: meter.event_name,
|
|
163
|
+
displayName: meter.display_name,
|
|
164
|
+
active: meter.status === "active",
|
|
165
|
+
livemode: meter.livemode,
|
|
166
|
+
aggregation: meter.default_aggregation.formula,
|
|
167
|
+
customerPayloadKey: meter.customer_mapping.event_payload_key,
|
|
168
|
+
valuePayloadKey: meter.value_settings.event_payload_key,
|
|
169
|
+
};
|
|
170
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import type { Component, RunCtx } from "../helpers.js";
|
|
2
|
+
import { runMutationOrThrow } from "../helpers.js";
|
|
3
|
+
import { componentRef } from "../webhooks/helpers.js";
|
|
4
|
+
import {
|
|
5
|
+
prepareUsageRecord,
|
|
6
|
+
type PreparedUsageRecord,
|
|
7
|
+
type UsageScope,
|
|
8
|
+
type UsageDeliveryState,
|
|
9
|
+
} from "./records.js";
|
|
10
|
+
import {
|
|
11
|
+
validateUsagePageRequest,
|
|
12
|
+
type UsagePageRequest,
|
|
13
|
+
type UsageSubscriptionBinding,
|
|
14
|
+
type UsageReceipt,
|
|
15
|
+
} from "./boundaries.js";
|
|
16
|
+
import type { Doc, Id } from "../../component/_generated/dataModel.js";
|
|
17
|
+
import type { FunctionHandle } from "convex/server";
|
|
18
|
+
export type RecordUsageOptions = {
|
|
19
|
+
event: unknown;
|
|
20
|
+
subscription: UsageSubscriptionBinding;
|
|
21
|
+
reservationId?: Id<"usageReservations">;
|
|
22
|
+
dispatch?: FunctionHandle<"action">;
|
|
23
|
+
quota?: number;
|
|
24
|
+
};
|
|
25
|
+
export type UsageEventView = {
|
|
26
|
+
receipt: UsageReceipt;
|
|
27
|
+
record: PreparedUsageRecord;
|
|
28
|
+
subscription: UsageSubscriptionBinding;
|
|
29
|
+
delivery: UsageDeliveryState;
|
|
30
|
+
};
|
|
31
|
+
type StoredView = { event: Doc<"usageEvents">; delivery: UsageDeliveryState };
|
|
32
|
+
function decode({ event, delivery }: StoredView): UsageEventView {
|
|
33
|
+
return {
|
|
34
|
+
receipt: {
|
|
35
|
+
eventId: event._id,
|
|
36
|
+
identity: event.identity,
|
|
37
|
+
acceptedAt: event.acceptedAt,
|
|
38
|
+
delivery: "queued",
|
|
39
|
+
},
|
|
40
|
+
record: JSON.parse(event.recordJson) as PreparedUsageRecord,
|
|
41
|
+
subscription: JSON.parse(
|
|
42
|
+
event.subscriptionJson,
|
|
43
|
+
) as UsageSubscriptionBinding,
|
|
44
|
+
delivery,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/** Trusted host facade. Authenticate and authorize each exact scope first. */
|
|
48
|
+
export class UsageLedgerClient {
|
|
49
|
+
constructor(private readonly component: Component) {}
|
|
50
|
+
async record(ctx: RunCtx, opts: RecordUsageOptions): Promise<UsageReceipt> {
|
|
51
|
+
const event = prepareUsageRecord(opts.event);
|
|
52
|
+
const input = {
|
|
53
|
+
scope: event.scope,
|
|
54
|
+
binding: event.binding,
|
|
55
|
+
sourceEventId: event.sourceEventId,
|
|
56
|
+
quantity: event.quantity,
|
|
57
|
+
occurredAt: event.occurredAt,
|
|
58
|
+
};
|
|
59
|
+
return runMutationOrThrow(
|
|
60
|
+
ctx,
|
|
61
|
+
componentRef(this.component, "usage/mutations/record"),
|
|
62
|
+
{
|
|
63
|
+
inputJson: JSON.stringify(input),
|
|
64
|
+
subscriptionJson: JSON.stringify(opts.subscription),
|
|
65
|
+
dispatch: opts.dispatch,
|
|
66
|
+
reservationId: opts.reservationId,
|
|
67
|
+
quota: opts.quota,
|
|
68
|
+
},
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
async get(
|
|
72
|
+
ctx: RunCtx,
|
|
73
|
+
opts: { scope: UsageScope; eventId: string },
|
|
74
|
+
): Promise<UsageEventView | null> {
|
|
75
|
+
const result = (await ctx.runQuery(
|
|
76
|
+
componentRef(this.component, "usage/queries/get"),
|
|
77
|
+
opts,
|
|
78
|
+
)) as StoredView | null;
|
|
79
|
+
return result ? decode(result) : null;
|
|
80
|
+
}
|
|
81
|
+
async read(ctx: RunCtx, opts: { scope: UsageScope; page: UsagePageRequest }) {
|
|
82
|
+
const page = validateUsagePageRequest(opts.page);
|
|
83
|
+
const result = (await ctx.runQuery(
|
|
84
|
+
componentRef(this.component, "usage/queries/read"),
|
|
85
|
+
{
|
|
86
|
+
scope: opts.scope,
|
|
87
|
+
period: page.period,
|
|
88
|
+
paginationOpts: { numItems: page.limit, cursor: page.cursor },
|
|
89
|
+
},
|
|
90
|
+
)) as { page: StoredView[]; continueCursor: string; isDone: boolean };
|
|
91
|
+
return {
|
|
92
|
+
events: result.page.map(decode),
|
|
93
|
+
cursor: result.isDone ? null : result.continueCursor,
|
|
94
|
+
isDone: result.isDone,
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
}
|