@fantastic.dev/better-stripe 0.67.0 → 0.67.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,389 +1,207 @@
1
- # Metered usage feasibility
1
+ # Native Stripe metered billing
2
2
 
3
- Status: investigation in progress, reviewed 2026-10-18. BetterStripe does not yet
4
- expose operational metered billing APIs. Configuration and quantity helpers are
5
- available at `@fantastic.dev/better-stripe/usage`. All three models are required. Provider
6
- feasibility must establish a compatible architecture before provider-specific
7
- catalog, delivery or UI implementation.
8
- This document records the native sandbox evidence, repeatable probes and remaining
9
- compatibility questions. Invoice finalization and settlement remain unverified.
3
+ BetterStripe supports pay as you go, included monthly units with overages, and
4
+ paid prepaid credits through native Stripe Billing Meters, subscriptions and
5
+ Billing Credit Grants. The public package owns durable usage, delivery, allowance
6
+ and credit accounting, corrections, original-payment settlement and reusable React
7
+ workflows. Hosts own authentication, billable business activity and billing policy.
10
8
 
11
- ## Existing integration constraints
9
+ Start with [native setup](metering-setup.md), run the
10
+ [three example flows](usage-example.md), then use the
11
+ [verification matrix](usage-verification.md). For an existing application, follow
12
+ [opt-in adoption and rollback](usage-rollout.md). Metronome is optional; it is not a
13
+ credential, dependency or prerequisite for this integration. No Metronome adapter
14
+ is included.
12
15
 
13
- BetterStripe subscriptions use Accounts v2 `customer_account` identities through
14
- the platform Stripe client. See `src/client/billing/subscriptions.ts` and
15
- [financial ownership](financial-ownership.md). Adding a separate v1 Customer is a
16
- new identity/payment-method mapping contract, not an interchangeable identifier.
17
- Existing fixed-price subscriptions, checkout and settlement must keep working.
16
+ ## Choose a model and define units
18
17
 
19
- Hosts authorize actors, payers and sellers and decide which activity is billable.
20
- BetterStripe will own durable acceptance, deduplication, delivery and reconciliation.
21
- A provider receipt cannot authorize a tenant or prove that usage was invoiced.
22
- Seller and affiliate settlement must continue to use verified paid-invoice
23
- proceeds and original payment provenance.
18
+ | Model | Customer behavior | Package accounting |
19
+ | ------------------ | ----------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
20
+ | `pay_as_you_go` | Pays for effective usage on the subscription invoice | Immutable usage plus optional entitlement/cap reservations |
21
+ | `included_overage` | Gets included units each verified monthly period, then pays for overage | Atomic included/overage reservations, hard or soft limits, separate period counters |
22
+ | `prepaid` | Buys units before consumption | Verified original payment and price-scoped grant, atomic reservation/consumption, exhaustion and recovery |
24
23
 
25
- ## Provider comparison
26
-
27
- | Concern | Stripe Billing Meters | Metronome with Stripe |
28
- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
29
- | Provider guidance | Stripe directs new usage integrations to Metronome, including existing flat-rate subscriptions adding usage | Recommended evaluation path for new usage integrations |
30
- | Credentials | Existing Stripe key, subject to permissions and API access | Separate Metronome sandbox/account token and explicit Stripe integration enrollment |
31
- | Payer identity | Guide maps meter payloads to Stripe Customer IDs; installed Stripe 23.0.0 meter types expose `by_id` only | Documented invoice delivery configuration uses `stripe_customer_id` with a `cus_` ID |
32
- | Accounts v2 | Platform sandbox mapping to `cus_`, aggregates and invoice-preview payer identity verified; other modes remain unverified | `customer_account` invoice delivery remains unverified; ingest aliases alone do not establish payment identity |
33
- | Connect | Stripe documents connected-account requests and different rate limits; this does not prove a platform-owned Accounts v2 payer works in that realm | Multi-entity connections are documented; equivalence to Connect destination charges or separate transfers remains unverified |
34
- | Catalog | Meter attached to recurring metered price | Billable metric, product, rate card and customer contract |
35
- | Invoices | Stripe owns subscription invoicing | Metronome rates usage and pushes separate invoices to Stripe, including when recurring subscriptions coexist |
36
- | Cost/access | Confirm account eligibility and current Billing pricing before selection | Confirm enrollment, commercial terms and extra credential acceptance before selection |
37
-
38
- Native Stripe Billing Meters is the default implementation target for BetterStripe.
39
- It uses the existing Stripe integration and credentials, with native sandbox
40
- aggregation and invoice-preview evidence for all three models. Metronome remains an
41
- optional comparison, not a setup prerequisite. See the [developer and AI-agent setup
42
- guide](metering-setup.md). Remaining account/settlement gaps must be verified before
43
- claiming compatibility for those flows.
44
-
45
- ## Required billing models
46
-
47
- BetterStripe must provide simple typed package APIs and reusable UI for:
48
-
49
- - Pay-as-you-go.
50
- - Included monthly usage with overages.
51
- - Prepaid credits.
52
-
53
- Developers configure units, precision, rates, intervals, allowances and credit
54
- policies for their apps. No global first billable unit or single-model choice is
55
- required. Share durable usage acceptance, delivery, scoped readers and
56
- reconciliation across the three models. The example app must demonstrate a
57
- complete runnable flow for each through package APIs and package React components.
58
-
59
- Purchased prepaid credits require verified successful payment before becoming
60
- spendable. Reuse existing payment/funding/recovery contracts where applicable and
61
- avoid a duplicate monetary wallet. Define credit reservation, consumption,
62
- expiration, refund and dispute behavior explicitly. Provider aggregates and invoice
63
- previews are estimates and cannot enforce a strict real-time limit.
64
-
65
- ## Provider feasibility by model
66
-
67
- | Model | Billing Meters candidate | Metronome candidate | Required proof |
68
- | ------------------------------------ | --------------------------------------------------------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------- |
69
- | Pay-as-you-go | Meter, recurring usage price and subscription invoice | Metric, usage rate and contract invoice | Authorized payer, aggregate, rated invoice and original payment |
70
- | Included monthly usage plus overages | Tiered usage price or explicit allowance/rating integration | Contract allowance/credit configuration plus usage rate | Reset, allowance boundary, overage and no double billing |
71
- | Prepaid credits | Billing credit grants applied to eligible metered invoice lines | Payment-gated prepaid commitments | Successful purchase, grant, consumption, exhaustion and refund/dispute recovery |
72
-
73
- The native sandbox has verified aggregation and invoice previews for all three
74
- mechanisms. Finalized billing, complete credit accounting and remaining account
75
- modes still require verification. All three models remain required. Stripe billing credit grants apply to eligible
76
- metered subscription invoices at finalization; they do not themselves implement
77
- an atomic real-time access limit. Verify the provider credit rules against the
78
- existing marketplace settlement contracts before using them for seller flows.
79
-
80
- Stripe documents that Accounts v2 subscription responses include both a mapped
81
- `customer` and `customer_account`, and that `/v1/customers` supports account IDs.
82
- Investigate this provider-owned mapping for meter ingestion instead of provisioning
83
- a separate payer. Verify exact account ownership and provider realm before adoption.
84
-
85
- ## Shared configuration contracts
86
-
87
- `defineUsagePlan` validates and copies a model's terms. It does not provision a
88
- meter, authorize a payer, record usage, enforce limits or charge a customer.
89
- The `rate.unitAmountDecimal` is a decimal string of minor currency units per whole
90
- billable unit. It accepts up to 12 integer and 12 fractional digits. Currency codes
91
- must contain three lowercase letters; adapters must additionally verify actual
92
- currency/provider eligibility. Treat a plan key/version as immutable once used.
24
+ Developers choose the unit, precision, price and policy. This example uses whole
25
+ requests at USD 1 per request. Rates are decimal strings of **minor currency
26
+ units per whole billable unit**, so USD `"100"` means USD 1, not USD 100.
93
27
 
94
28
  ```ts
95
- import {
96
- defineUsagePlan,
97
- parseUsageQuantity,
98
- } from "@fantastic.dev/better-stripe/usage";
99
-
100
- const terms = {
101
- key: "api_requests",
29
+ import { defineUsagePlan } from "@fantastic.dev/better-stripe/usage";
30
+ const common = {
31
+ key: "requests",
102
32
  version: "v1",
103
33
  unit: { name: "request", precision: 0 },
104
- rate: { currency: "usd", unitAmountDecimal: "2" },
105
- };
106
- const payAsYouGo = defineUsagePlan({ ...terms, model: "pay_as_you_go" });
34
+ rate: { currency: "usd", unitAmountDecimal: "100" },
35
+ } as const;
36
+ const payAsYouGo = defineUsagePlan({ ...common, model: "pay_as_you_go" });
107
37
  const included = defineUsagePlan({
108
- ...terms,
38
+ ...common,
109
39
  model: "included_overage",
110
- includedQuantity: "1000",
40
+ includedQuantity: "10",
111
41
  reset: "billing_period",
112
42
  });
113
43
  const prepaid = defineUsagePlan({
114
- ...terms,
44
+ ...common,
115
45
  model: "prepaid",
116
46
  insufficientBalance: "reject",
117
47
  });
118
- const exact = parseUsageQuantity("123", payAsYouGo.unit.precision);
119
- // exact.scaledQuantity is "123", a JSON/Convex-safe integer string.
120
48
  ```
121
49
 
122
- The initial shared quantity contract supports 0–6 decimal places, nonnegative
123
- canonical decimal strings, and at most 18 digits in the scaled integer. It rejects
124
- rounding, exponent notation and JavaScript numeric inputs. A provider adapter must
125
- apply its own tighter bounds before accepting usage. `parseUsageQuantity` removes
126
- trailing fractional zeros and preserves exact values beyond JavaScript's safe
127
- integer range. Provider/catalog, delivery and reservation APIs remain unfinished.
50
+ Select one plan for an original binding. Do not submit one activity to all three
51
+ alternatives. Configuration validates terms; it does not provision resources,
52
+ authorize a caller or fund credits. Use a new version, event name and price lookup
53
+ key for changed terms. Preserve old prices and original activity bindings.
128
54
 
129
- ## Native event scope and identity
55
+ ## Provision the original binding
130
56
 
131
- `prepareUsageRecord` validates and snapshots a native event before persistence.
132
- Its scope contains `stripeAccountId` for the Stripe realm, `customerAccount` for
133
- the Accounts v2 payer, `meterId`, and `livemode`. The binding preserves the mapped
134
- `stripeCustomerId`, `stripePriceId`, native `eventName`, pinned API version and
135
- full plan/version terms. The host must authorize and verify these references on
136
- the server. Passing validation does not prove ownership or provider eligibility.
57
+ In an authenticated host action, authorize the issuer realm, product and Accounts
58
+ v2 payer. Resolve the payer's provider-owned mapped `cus_` identity; do not create
59
+ an unrelated Customer to hide a mapping error.
137
60
 
138
- Use one stable `sourceEventId` per real activity. The deduplication identity covers
139
- test/live mode, realm, payer, meter and that source ID. Plan changes, mapped-customer
140
- changes and quantity/time corrections do not create a new identity; acceptance must
141
- compare the original immutable event and reject conflicting replay. Occurrence
142
- time is Unix seconds. Adapters must enforce Stripe's supported event windows and
143
- retain original time, rather than replacing it with the retry time.
144
-
145
- `UsageDeliveryState` distinguishes queued, sending, provider-accepted, rejected,
146
- unknown and held delivery. Locally recorded acceptance is the ledger transaction;
147
- provider acceptance is only a receipt. Aggregation and invoicing require independent
148
- reconciliation evidence. An adjustment retains the original event and receipts.
149
- A finalized/paid invoice is not inferred from a delivery state or preview. These
150
- contracts prepare the shared ledger/delivery work; they do not implement it.
151
-
152
- ## Access preflight
153
-
154
- From the repository root, inject a sandbox key as `STRIPE_SECRET_KEY` and run:
155
-
156
- ```sh
157
- node scripts/metering-feasibility.mjs
158
- ```
159
-
160
- Use `op run` from one persistent authorized terminal when the key is in 1Password.
161
- Do not print or save the key. The script rejects non-test secret keys before making
162
- any request. It makes one platform-realm GET to `/v1/billing/meters?limit=1`, pins
163
- the repository's Stripe version and prints only status and verification flags.
164
- It creates no meters, customers, events, subscriptions, invoices or charges.
165
-
166
- A successful response establishes endpoint access only. A 401 or 403 is an access
167
- failure, not evidence that a billing identity or model is unsupported. The script
168
- has no connected-account selector and does not test that realm. It is a development
169
- tool in the repository, not a public package API.
170
-
171
- ## Three-model sandbox runner
172
-
173
- ```sh
174
- node scripts/metering-sandbox.mjs
175
- # Explicit optional test-card purchase proof, refunded during cleanup:
176
- node scripts/metering-sandbox.mjs --verify-test-payment
61
+ ```ts
62
+ const meter = await stripe.ensureUsageMeter(ctx, {
63
+ scope: { stripeAccountId: issuerId, livemode: false },
64
+ plan: selectedPlan,
65
+ eventName: "requests_v1",
66
+ displayName: "Requests v1",
67
+ });
68
+ const price = await stripe.ensureUsagePrice(ctx, {
69
+ scope: { stripeAccountId: issuerId, livemode: false },
70
+ plan: selectedPlan,
71
+ meterId: meter.id,
72
+ stripeProductId: authorizedProductId,
73
+ lookupKey: "requests_v1_usd",
74
+ });
75
+ const enrollment = await stripe.usage.ensureSubscription(
76
+ ctx,
77
+ {
78
+ requestId: originalSignupId,
79
+ meters: [
80
+ {
81
+ scope: {
82
+ stripeAccountId: issuerId,
83
+ customerAccount: payerId,
84
+ meterId: meter.id,
85
+ livemode: false,
86
+ },
87
+ binding: {
88
+ stripeCustomerId: mappedCustomerId,
89
+ stripePriceId: price.stripePriceId,
90
+ eventName: meter.event_name,
91
+ plan: selectedPlan,
92
+ },
93
+ },
94
+ ],
95
+ fixedPriceIds: [],
96
+ collection: { method: "send_invoice", daysUntilDue: 30 },
97
+ },
98
+ { stripeSecretKey },
99
+ );
177
100
  ```
178
101
 
179
- Inject a test key into the process environment. Both paths reject live keys before
180
- networking. Each run creates an isolated Accounts v2 payer and three independent
181
- meter/product/price/subscription sets. It verifies the provider-owned customer
182
- mapping, sends 15 units twice with one event/idempotency identity and polls bounded
183
- usage summaries before previewing each invoice. No invoice is explicitly finalized.
102
+ Persist and reuse the verified `enrollment.bindings` and original signup identity.
103
+ Read native status and period before admitting work. See
104
+ [catalog](usage-catalog.md) and [subscriptions](usage-subscriptions.md) for Checkout,
105
+ automatic collection, supported native shapes and bounded recovery.
184
106
 
185
- The default credit grant is promotional, so it does not prove a paid purchase.
186
- The optional flag creates a 100-cent sandbox PaymentIntent with Stripe's test card.
187
- Only a verified succeeded payment for the exact payer, currency and received amount
188
- permits a paid credit grant. Cleanup expires credits, refunds the successful test
189
- payment, cancels subscriptions without invoicing/proration, archives prices/products
190
- and deactivates meters. Test payer records and historical provider evidence remain.
191
- Cleanup success means the corresponding API request succeeded, not that an
192
- asynchronous refund has settled. A failed run can leave test resources requiring
193
- operator cleanup; never rerun an old operation as a new live payment.
107
+ ## Admit work through the component
194
108
 
195
- ## Sandbox acceptance matrix
109
+ For pay as you go and included usage, configure the original verified period with
110
+ `configureAllowance`. Choose entitlement, `overage`, and a `none`, `soft` or `hard`
111
+ limit. `reserveAllowance` enforces that policy before work; included units and
112
+ billable overage derive from the immutable plan. See [limits](usage-limits.md).
196
113
 
197
- Run the following with sandbox credentials and the confirmed three-model scope. Capture
198
- sanitized request shapes, API versions, timestamps, status codes and assertions.
199
- Keep secrets and raw customer/provider payloads out of evidence and workflow state.
114
+ For prepaid, call `purchaseCredits` with a stable business purchase ID and the
115
+ original credit binding. Send its `clientSecret` only to the authenticated
116
+ purchaser's payment UI. After payment, call `observeCreditPurchase`; only its
117
+ verified ready grant makes units spendable. `reserveCredits` rejects insufficient
118
+ or unreconciled backing. Consumption never creates another cash charge. See
119
+ [paid credits](usage-credits.md). Credits cover the issuer's own services, not a
120
+ third-party seller wallet or reseller redemption.
200
121
 
201
- | Scenario | Required proof | Current result |
202
- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------- |
203
- | Platform Accounts v2 payer | Meter/contract creation, ingestion, aggregate and invoice all refer to the authorized payer | Unverified |
204
- | Connected seller | Prove catalog/event realm and payer ownership, destination/transfer economics and paid-invoice provenance | Unverified |
205
- | Non-Connect account | Prove identity and invoice flow without silently provisioning an alternative payer | Unverified |
206
- | Duplicate delivery | Same source event and provider identifier produce one aggregate contribution | Unverified |
207
- | Shared meter | Two subscriptions for one customer show the actual aggregation boundary; no inferred per-subscription event targeting | Unverified |
208
- | Correction | Original event, reason and receipt retained; provider cancellation window and finalized-invoice behavior demonstrated | Unverified |
209
- | Invoice closeout | Original event time, delayed aggregate, finalized invoice line and payment/processing costs reconcile | Unverified |
210
- | Test clocks | Determine which provider clock drives event timestamps and invoice periods, without assuming virtual time advances ingestion | Unverified |
211
- | Packed consumer | Verify eventual public contracts from the built tarball with linked guides present | Configuration helpers verified; operational APIs pending |
212
-
213
- For Billing Meters, event uniqueness is enforced for at least a rolling 24-hour
214
- window. Acceptance permits timestamps within 35 calendar days in the past or five
215
- minutes in the future. Cancellation is limited to events sent within 24 hours.
216
- Aggregation is asynchronous. Accepted late events can appear in summaries without
217
- changing a finalized invoice. Preserve local deduplication and an explicit unknown
218
- delivery state beyond the safe retry window. Events have no subscription selector.
219
-
220
- Metronome's quickstart uses a customer UUID or ingest alias and transaction ID,
221
- string-valued numerical properties and a 34-day backdating window. Confirm exact
222
- retention, correction and retry guarantees for the chosen API and account before
223
- encoding them as constants. Its invoice integration documentation and Stripe's
224
- integration overview use different metadata names for invoice mapping. Inspect the
225
- actual sandbox invoice rather than trusting a single assumed metadata key.
226
-
227
- ## Evidence recorded so far
228
-
229
- On 2026-10-18 the platform sandbox returned HTTP 200 for the meter access preflight.
230
- The three-model run on `2026-09-30.endive` verified the provider-owned Accounts v2
231
- mapping, catalog/subscription creation, event acceptance, an aggregate of exactly
232
- 15 units after identical retries, and invoice-preview payer identity for each model.
233
- Preview totals were 30 cents for pay-as-you-go at 2 cents/unit, 10 cents after a
234
- 10-unit free tier, and zero after a 100-cent promotional grant.
235
-
236
- All thirteen requested cleanup operations succeeded. No real customer email was
237
- used. These observations are platform-scope test evidence. They do not prove
238
- Connect seller flows, non-Connect preview enrollment, paid purchases, finalized
239
- invoices, payment/processing costs, corrections or marketplace settlement. The
240
- optional purchase probe is separate and must be recorded explicitly when run.
241
- Metronome is optional and has not been provisioned. Native Stripe is the implementation target; all three models remain in scope.
242
-
243
- The configuration/quantity tests cover all three models, invalid terms, exact
244
- values beyond safe integers and caller-mutation isolation. A packed consumer test
245
- loads the real `./usage` export and exercises the same three configurations.
246
-
247
- ## Primary sources
248
-
249
- - [Stripe usage-based billing](https://docs.stripe.com/billing/usage-based)
250
- - [Stripe's guidance on recording usage](https://docs.stripe.com/billing/subscriptions/usage-based/recording-usage)
251
- - [Record usage with the API](https://docs.stripe.com/billing/subscriptions/usage-based/recording-usage-api)
252
- - [Create a meter event](https://docs.stripe.com/api/billing/meter-event/create)
253
- - [Configure meters and corrections](https://docs.stripe.com/billing/subscriptions/usage-based/meters/configure)
254
- - [How Metronome works with Stripe](https://docs.stripe.com/billing/how-metronome-works-with-stripe)
255
- - [Metronome API quickstart](https://docs.metronome.com/guides/get-started/api-quickstart)
256
- - [Metronome invoice integration](https://docs.metronome.com/integrations/invoice-integrations/stripe)
257
-
258
- - [Accounts v2 customer interoperability](https://docs.stripe.com/accounts-v2/use-accounts-as-customers)
259
- - [Stripe billing credits](https://docs.stripe.com/billing/subscriptions/usage-based/billing-credits)
260
-
261
- A later optional purchase run verified a succeeded 100-cent sandbox payment for
262
- the exact payer/currency, created a paid grant and requested its refund. All 14
263
- cleanup calls succeeded. Its prepaid aggregate was 15 and preview total was zero;
264
- its included-usage aggregation did not catch up before the polling bound. This
265
- later run is not a second complete three-model aggregation proof. Neither run
266
- finalized a metered invoice or verified seller settlement.
267
-
268
- ## Host authorization and observation contracts
269
-
270
- `authorizeUsageRecord` prepares a server-resolved event, invokes the host's
271
- `authorize` callback for its exact scope, then `authorizeActivity` for the source
272
- activity, and only then calls the supplied acceptance function. A denial throws
273
- before acceptance. Resolve bindings and activity identity on the server; copying
274
- browser-supplied payer, price or quantity into the helper is not authorization.
275
- The component APIs are trusted host boundaries. Never export their mutations as
276
- unauthenticated application endpoints.
122
+ The host resolves the immutable business activity and authorizes it before this
123
+ shared mutation pattern:
277
124
 
278
125
  ```ts
279
- import {
280
- authorizeUsageRecord,
281
- type UsageAuthorization,
282
- type PreparedUsageRecord,
283
- } from "@fantastic.dev/better-stripe/usage";
284
-
285
- type Context = { userId: string; customerAccount: string; activityId: string };
286
- const policy: UsageAuthorization<Context> = {
287
- async authorize(ctx, { scope }) {
288
- if (!ctx.userId || ctx.customerAccount !== scope.customerAccount)
289
- throw new Error("Unauthorized usage scope");
290
- },
291
- async authorizeActivity(ctx, record) {
292
- if (record.sourceEventId !== ctx.activityId || record.quantity !== "1")
293
- throw new Error("Activity is not billable under these terms");
126
+ const receipt = await authorizeUsageRecord(
127
+ ctx,
128
+ policy,
129
+ serverEvent,
130
+ async (event) => {
131
+ const reservation =
132
+ event.binding.plan.model === "prepaid"
133
+ ? await stripe.usage.reserveCredits(ctx, { event, subscription })
134
+ : await stripe.usage.reserveAllowance(ctx, { event, subscription });
135
+ if (reservation.state === "denied" || reservation.state === "released")
136
+ throw new Error("Usage is not admitted");
137
+ const receipt = await stripe.usage.record(ctx, {
138
+ event,
139
+ subscription,
140
+ reservationId: reservation.reservationId,
141
+ });
142
+ await applyDatabaseWorkOnce(ctx, originalActivityId, receipt);
143
+ return receipt;
294
144
  },
295
- };
296
- declare const ctx: Context;
297
- // Resolve this from authenticated activity and verified native billing bindings.
298
- declare const serverRecord: unknown;
299
- // Supply the component's atomic acceptance adapter when implementing the ledger.
300
- declare const accept: (record: PreparedUsageRecord) => Promise<string>;
301
- const eventId = await authorizeUsageRecord(ctx, policy, serverRecord, accept);
145
+ );
302
146
  ```
303
147
 
304
- The same adapter handles each of the three configurations above. Hosts own actor,
305
- tenant, entitlement and billable-activity policy. The component owns deduplication,
306
- financial history, delivery and credit accounting. Credentials remain in host
307
- internal actions. They must never enter records, workflow arguments or receipts.
308
-
309
- `UsagePageRequest` uses a half-open `[start, end)` period in Unix seconds, an opaque
310
- cursor and a limit of 1–100. `validateUsagePageRequest` rejects invalid intervals,
311
- unsafe timestamps and oversized cursors. Every page must reauthorize the original
312
- scope and period. Readers must distinguish an incomplete scan from a complete
313
- zero total; never sum different currencies or pricing versions implicitly.
314
-
315
- `UsageObservations` keeps local acceptance, provider acceptance, aggregation,
316
- estimates and invoice observations separate. `UsageAvailability` explicitly
317
- represents unsupported and unavailable provider/account modes, reason and retry
318
- policy. Missing observations are not zero. `observedAt` is Unix seconds;
319
- acceptance timestamps are assigned by the component, independently of original
320
- occurrence time. Native v1 delivery uses sum aggregation and integer scaled units;
321
- price conversion must preserve the configured whole-unit rate exactly or reject
322
- unsupported precision. A provider acceptance receipt is not aggregation or payment.
323
-
324
- ## Corrections, retention and transitions
325
-
326
- `UsageCorrectionRequest` identifies the original scope/source event, an immutable
327
- correction ID and reason. Cancellation retains the original quantity, timestamp,
328
- provider event identifier and every receipt. A replacement uses a new source event
329
- only after cancellation is confirmed; finalized invoice changes require explicit
330
- billing adjustments rather than silently rewriting usage. Native cancellation
331
- windows and uncertain responses can produce unsupported or held results. No
332
- financial outcome follows merely from requesting a correction.
333
-
334
- `UsageRetentionPolicy` retains financial evidence. Retention of temporary execution
335
- payloads may be configured separately, but cleanup must preserve event identities,
336
- pricing snapshots, unresolved receipts, payments, reservations and correction
337
- links. There is no automatic financial-history deletion contract. Bounded pages
338
- and per-scope quotas apply before acceptance; an exhausted quota rejects new work
339
- without deleting old evidence. Large-volume exports retain original identities
340
- and must be reconciled before any future explicit archival feature.
341
-
342
- `UsageTransitionRequest` drains pending usage and resolves reservations before an
343
- explicit effective boundary. Versions are immutable. A model/rate/unit/currency
344
- change creates a new version and native price; existing credit grants retain their
345
- original terms. No implicit currency conversion, credit conversion, subscription
346
- migration or historical re-rating is permitted. `assertUsageReplay` compares
347
- normalized immutable terms and rejects changed replay on the original identity,
348
- including time, currency, mapped customer and version. A transition must never
349
- turn a prepaid consumption into a new pay-as-you-go charge.
350
-
351
- These are shared contracts and host-boundary helpers. The [atomic ledger](usage-ledger.md) implements acceptance and local history.
352
- Catalog, delivery, correction and transition adapters follow in subsequent tickets.
353
-
354
- `UsageContractPort` defines shared `record`, paginated `read`, `reconcile` and
355
- `capabilities` requests/results for host adapters. `record` is an atomic local
356
- acceptance receipt; `read` returns bounded history, not provider completeness;
357
- `reconcile` returns independent observations and never resends events to repair a
358
- mismatch. Check capabilities and availability for the selected scope. These
359
- interfaces specify the adapters being implemented, not an available engine.
360
-
361
- `UsageSubscriptionBinding` ties the verified native subscription/item and monthly
362
- period to its price. Store it as immutable routing provenance when accepting
363
- usage. Invoice IDs are later observations because the invoice may not exist at
364
- acceptance. `UsageCreditProvenance` ties a reservation/allocation to its original
365
- grant, verified purchase PaymentIntent, currency, amount, unit quantity and plan
366
- version. A grant may cover multiple events; an event may allocate several grants.
367
- Never fabricate one purchase/grant from a local balance total.
368
-
369
- `UsageCorrectionOutcome` distinguishes request, provider acceptance, confirmed
370
- cancellation, held/unsupported cases and required invoice adjustment. Confirmed
371
- cancellation is an adjustment observation linked to the original event, rather
372
- than overwriting its original delivery or invoice receipt. A requested or
373
- provider-accepted correction must not release spendable credits until confirmed.
374
-
375
- The [packed consumer fixture](https://github.com/FantasticDevHQ/better-stripe/blob/main/scripts/fixtures/usage-consumer.ts) compiles concrete authorization and activity callbacks plus record/read/reconcile adapters for all three models against the actual package tarball. It returns alternative model paths and never submits one activity to multiple models.
376
-
377
- ## Native lifecycle verification, 2026-10-18
378
-
379
- The [managed subscription guide](usage-subscriptions.md) now covers native
380
- metered/mixed subscriptions, Checkout, closeout and retained lifecycle history.
381
- The [test-clock run](evidence/native-metering/clock-finalization-run.json) verified
382
- Accounts v2 payer mapping, all three 15-unit aggregates and finalized invoice
383
- totals of 30/10/0 USD cents for pay-as-you-go/included-overage/prepaid. The prepaid
384
- purchase was a separate verified 100-cent test payment. All 15 cleanup requests
385
- succeeded, including grant expiry, the test refund request and clock deletion.
386
- The [prior lag run](evidence/native-metering/clock-lag-run.json) remains visible;
387
- it stopped before advancement while prepaid aggregation was pending. These
388
- results supplement the earlier investigation table. They do not prove production
389
- billing, non-Connect modes, strict credit accounting or seller settlement.
148
+ Import `authorizeUsageRecord` from the `/usage` entry point. `policy`,
149
+ `serverEvent`, `subscription` and `applyDatabaseWorkOnce` are authenticated host
150
+ adapters. The business adapter must read a completion marker keyed by the
151
+ original business activity and apply work once in this same Convex transaction.
152
+ Usage replay alone does not make arbitrary application work idempotent. Keep the
153
+ original reservation reference for completed work; do not re-reserve new capacity
154
+ under another ID after closing its account. External effects require a durable,
155
+ idempotent work protocol rather than a database-only transaction.
156
+
157
+ Recording atomically commits usage, reservation consumption and an outbox. It
158
+ performs no provider I/O. Schedule `usage.startDelivery` after commit, or provide
159
+ its supported transactional dispatch handle. The host's internal provider action
160
+ uses `usageDeliveryArgs` / `usageDeliveryResult` and delegates to `usage.deliver`
161
+ with execution-time credentials. See [ledger](usage-ledger.md),
162
+ [delivery and callbacks](usage-delivery.md), and [authorization](usage-security.md).
163
+
164
+ ## Read, display and settle
165
+
166
+ Use `getSummary` for bounded local totals, `observeProviderUsage` / `reconcile` for
167
+ native aggregation, and `readInvoiceUsage` for original invoice lines. A delivery
168
+ receipt is not aggregation or payment. A preview or estimate is not a finalized
169
+ invoice. Missing, stale, partial or unknown evidence remains unavailable or held.
170
+
171
+ The `/react` entry point supplies `UsageConfiguration`, `UsagePriceRow`,
172
+ `UsageBilling`, `UsageSummary`, `UsageAllowance`, `UsageCredits` and paginated
173
+ `UsageHistory`. Bind them to authenticated host readers; browser view keys are
174
+ cache identities, not authorization. Server types also have neutral exports from
175
+ `/usage`. See [React views](usage-react.md) and
176
+ [configuration UI](usage-configuration.md).
177
+
178
+ For pay as you go and included overage, `getInvoiceSale` verifies original paid
179
+ proceeds before `settleInvoice`. For prepaid, use `getCreditPurchaseRevenue` and
180
+ `settleCreditPurchase` on the original purchase. A zero-dollar usage invoice must
181
+ not create another sale or affiliate commission. Actual processing fees,
182
+ recipient eligibility, refunds and disputes retain their original sources. See
183
+ [settlement](usage-settlement.md) and [corrections](usage-corrections.md).
184
+
185
+ ## Precision, windows and retained limits
186
+
187
+ Quantities are canonical decimal strings with 0–6 fractional digits and at most
188
+ 18 scaled integer digits. Never round or pass JS floating-point quantities. Native
189
+ catalog/credit adapters apply tighter bounds where required. Occurrence time is
190
+ original business time in Unix seconds, within the immutable half-open period and
191
+ Stripe's 35-day past / five-minute future window. Retrying does not change time.
192
+
193
+ Provider aggregation is asynchronous. Unknown sends cannot be blindly retried,
194
+ even inside provider deduplication windows. Native creation recovery stops blind
195
+ writes after 23 hours. Correction, cancellation and late invoice-adjustment
196
+ windows are separately documented in [corrections](usage-corrections.md).
197
+
198
+ Local retained-event quotas are bounded at 100,000 per scope; read pages contain
199
+ 1–100 rows. Other audit, purchase and native-proof bounds have explicit held/error
200
+ states in their domain guides. There is no financial-history deletion/reset API.
201
+ Keep original IDs, prices, API/definition versions and worker handlers available
202
+ while operations can resume. Follow [rollout and recovery](usage-rollout.md).
203
+
204
+ The [verification matrix](usage-verification.md) records exact tested account
205
+ modes, actual fees and transfer proof, future-test-clock limits, injected failures
206
+ and unverified live-money/throughput cases. Historical feasibility probes remain
207
+ in the repository; they do not replace the package's ledger or paid-source proof.