@fantastic.dev/better-stripe 0.61.0 → 0.63.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +6 -2
  3. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +32 -32
  4. package/dist/client/connect/payoutSyncTestHelpers.d.ts +16 -16
  5. package/dist/client/paymentSource/resolver.d.ts +1 -0
  6. package/dist/client/paymentSource/resolver.d.ts.map +1 -1
  7. package/dist/client/paymentSource/resolver.js +11 -2
  8. package/dist/client/paymentSource/resolver.js.map +1 -1
  9. package/dist/client/paymentSource/zeroTierLines.d.ts +4 -0
  10. package/dist/client/paymentSource/zeroTierLines.d.ts.map +1 -0
  11. package/dist/client/paymentSource/zeroTierLines.js +35 -0
  12. package/dist/client/paymentSource/zeroTierLines.js.map +1 -0
  13. package/dist/client/usage/configuration.d.ts +13 -0
  14. package/dist/client/usage/configuration.d.ts.map +1 -0
  15. package/dist/client/usage/configuration.js +2 -0
  16. package/dist/client/usage/configuration.js.map +1 -0
  17. package/dist/client/usage/deliveryProvider.d.ts.map +1 -1
  18. package/dist/client/usage/deliveryProvider.js +16 -0
  19. package/dist/client/usage/deliveryProvider.js.map +1 -1
  20. package/dist/client/usage/index.d.ts +2 -0
  21. package/dist/client/usage/index.d.ts.map +1 -1
  22. package/dist/client/usage/invoiceSale.d.ts.map +1 -1
  23. package/dist/client/usage/invoiceSale.js +15 -2
  24. package/dist/client/usage/invoiceSale.js.map +1 -1
  25. package/dist/client/usage/observationClient.d.ts +2 -2
  26. package/dist/client/usage/observationClient.d.ts.map +1 -1
  27. package/dist/client/usage/views.d.ts +24 -0
  28. package/dist/client/usage/views.d.ts.map +1 -0
  29. package/dist/client/usage/views.js +2 -0
  30. package/dist/client/usage/views.js.map +1 -0
  31. package/dist/component/balanceFunding/mutations.d.ts +16 -16
  32. package/dist/component/payoutRelease/queries.d.ts +2 -2
  33. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  34. package/dist/react/index.d.ts +5 -0
  35. package/dist/react/index.d.ts.map +1 -1
  36. package/dist/react/index.js +3 -0
  37. package/dist/react/index.js.map +1 -1
  38. package/dist/react/workflows/Usage.types.d.ts +2 -23
  39. package/dist/react/workflows/Usage.types.d.ts.map +1 -1
  40. package/dist/react/workflows/Usage.types.js.map +1 -1
  41. package/dist/react/workflows/UsageConfiguration.d.ts +4 -0
  42. package/dist/react/workflows/UsageConfiguration.d.ts.map +1 -0
  43. package/dist/react/workflows/UsageConfiguration.js +19 -0
  44. package/dist/react/workflows/UsageConfiguration.js.map +1 -0
  45. package/dist/react/workflows/UsageConfiguration.types.d.ts +57 -0
  46. package/dist/react/workflows/UsageConfiguration.types.d.ts.map +1 -0
  47. package/dist/react/workflows/UsageConfiguration.types.js +2 -0
  48. package/dist/react/workflows/UsageConfiguration.types.js.map +1 -0
  49. package/dist/react/workflows/UsagePriceRow.d.ts +26 -0
  50. package/dist/react/workflows/UsagePriceRow.d.ts.map +1 -0
  51. package/dist/react/workflows/UsagePriceRow.js +40 -0
  52. package/dist/react/workflows/UsagePriceRow.js.map +1 -0
  53. package/dist/react/workflows/usage-configuration-validation.d.ts +4 -0
  54. package/dist/react/workflows/usage-configuration-validation.d.ts.map +1 -0
  55. package/dist/react/workflows/usage-configuration-validation.js +116 -0
  56. package/dist/react/workflows/usage-configuration-validation.js.map +1 -0
  57. package/dist/react/workflows/useUsageConfiguration.d.ts +4 -0
  58. package/dist/react/workflows/useUsageConfiguration.d.ts.map +1 -0
  59. package/dist/react/workflows/useUsageConfiguration.js +84 -0
  60. package/dist/react/workflows/useUsageConfiguration.js.map +1 -0
  61. package/docs/README.md +4 -0
  62. package/docs/react-api.md +2 -0
  63. package/docs/usage-configuration.md +154 -0
  64. package/docs/usage-delivery.md +4 -0
  65. package/docs/usage-example.md +246 -0
  66. package/docs/usage-react.md +4 -0
  67. package/docs/usage-settlement.md +8 -3
  68. package/package.json +4 -2
  69. package/src/client/paymentSource/resolver.ts +14 -2
  70. package/src/client/paymentSource/zeroTierLines.ts +42 -0
  71. package/src/client/usage/configuration.ts +9 -0
  72. package/src/client/usage/deliveryProvider.test.ts +77 -37
  73. package/src/client/usage/deliveryProvider.ts +19 -0
  74. package/src/client/usage/index.ts +4 -0
  75. package/src/client/usage/invoiceSale.test.ts +68 -0
  76. package/src/client/usage/invoiceSale.ts +20 -2
  77. package/src/client/usage/views.ts +23 -0
  78. package/src/react/index.ts +16 -0
  79. package/src/react/workflows/Usage.types.ts +5 -29
  80. package/src/react/workflows/UsageConfiguration.test.tsx +393 -0
  81. package/src/react/workflows/UsageConfiguration.tsx +135 -0
  82. package/src/react/workflows/UsageConfiguration.types.ts +59 -0
  83. package/src/react/workflows/UsagePriceRow.test.tsx +140 -0
  84. package/src/react/workflows/UsagePriceRow.tsx +109 -0
  85. package/src/react/workflows/usage-configuration-validation.test.ts +107 -0
  86. package/src/react/workflows/usage-configuration-validation.ts +152 -0
  87. package/src/react/workflows/useUsageConfiguration.ts +99 -0
@@ -0,0 +1,84 @@
1
+ "use client";
2
+ import { useState } from "react";
3
+ import { defineUsagePlan } from "../../client/usage/contracts.js";
4
+ import { useWorkflowAction } from "./useWorkflowAction.js";
5
+ import { configurationFields, validateConfiguration, } from "./usage-configuration-validation.js";
6
+ /** Shared form lifecycle for component and HTTP adapters. Server authorization is mandatory. */
7
+ export function useUsageConfiguration(props) {
8
+ const key = JSON.stringify([props.scope, props.initial, props.meters]);
9
+ const initial = {
10
+ key,
11
+ meterId: props.initial.meterId ?? "",
12
+ fields: configurationFields(props.initial),
13
+ };
14
+ const [state, setState] = useState(initial);
15
+ if (state.key !== key)
16
+ setState(initial);
17
+ const disabled = !props.scope.canConfigure || props.scope.capability !== "issuer_native";
18
+ const immutable = state.meterId !== "";
19
+ const action = useWorkflowAction(async () => {
20
+ if (disabled)
21
+ throw new Error("Configuration is read-only for this scope.");
22
+ let value = validateConfiguration(state.fields, state.meterId);
23
+ if (immutable) {
24
+ const meter = props.meters.find((item) => item.id === state.meterId);
25
+ if (!meter?.active ||
26
+ JSON.stringify(validateConfiguration(configurationFields(meter.configuration), meter.id)) !== JSON.stringify(value))
27
+ throw new Error("Select an active managed meter with unchanged original terms.");
28
+ // Native intent fingerprints retain the original lexical decimal snapshot.
29
+ value = {
30
+ ...value,
31
+ plan: defineUsagePlan(meter.configuration.plan),
32
+ ...(value.creditPackage
33
+ ? {
34
+ creditPackage: {
35
+ ...value.creditPackage,
36
+ quantity: meter.configuration.creditPackage?.quantity ??
37
+ value.creditPackage.quantity,
38
+ },
39
+ }
40
+ : {}),
41
+ };
42
+ }
43
+ try {
44
+ await props.onSave(value);
45
+ }
46
+ catch {
47
+ throw new Error("Configuration could not be saved. Retry the same terms or ask an administrator to reconcile the operation.");
48
+ }
49
+ return "Configuration version saved. Existing subscriptions keep their original prices.";
50
+ }, key);
51
+ return {
52
+ fields: state.fields,
53
+ meterId: state.meterId,
54
+ immutable,
55
+ disabled,
56
+ isPending: action.isPending,
57
+ error: action.error,
58
+ message: action.result,
59
+ save: action.run,
60
+ setField: (field, value) => {
61
+ if (disabled || immutable || action.isPending)
62
+ return;
63
+ action.reset();
64
+ setState((current) => ({
65
+ ...current,
66
+ fields: { ...current.fields, [field]: value },
67
+ }));
68
+ },
69
+ selectMeter: (meterId) => {
70
+ if (disabled || action.isPending)
71
+ return;
72
+ const meter = props.meters.find((item) => item.id === meterId);
73
+ if (meterId && !meter?.active)
74
+ return;
75
+ action.reset();
76
+ setState({
77
+ key,
78
+ meterId,
79
+ fields: configurationFields(meter?.configuration ?? props.initial),
80
+ });
81
+ },
82
+ };
83
+ }
84
+ //# sourceMappingURL=useUsageConfiguration.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useUsageConfiguration.js","sourceRoot":"","sources":["../../../src/react/workflows/useUsageConfiguration.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AACb,OAAO,EAAE,QAAQ,EAAE,MAAM,O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AI,SAAS,IAAI,MAAM,CAAC,SAAS;gBAAE,OAAO;YACtD,MAAM,CAAC,KAAK,EAAE,CAAC;YACf,QAAQ,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;gBACrB,GAAG,OAAO;gBACV,MAAM,EAAE,EAAE,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE;aAC9C,CAAC,CAAC,CAAC;QACN,CAAC;QACD,WAAW,EAAE,CAAC,OAAO,EAAE,EAAE;YACvB,IAAI,QAAQ,IAAI,MAAM,CAAC,SAAS;gBAAE,OAAO;YACzC,MAAM,KAAK,GAAG,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,EAAE,KAAK,OAAO,CAAC,CAAC;YAC/D,IAAI,OAAO,IAAI,CAAC,KAAK,EAAE,MAAM;gBAAE,OAAO;YACtC,MAAM,CAAC,KAAK,EAAE,CAAC;YACf,QAAQ,CAAC;gBACP,GAAG;gBACH,OAAO;gBACP,MAAM,EAAE,mBAAmB,CAAC,KAAK,EAAE,aAAa,IAAI,KAAK,CAAC,OAAO,CAAC;aACnE,CAAC,CAAC;QACL,CAAC;KACF,CAAC;AACJ,CAAC"}
package/docs/README.md CHANGED
@@ -78,3 +78,7 @@ Start with the [native Stripe setup guide](metering-setup.md), then read the
78
78
  - [Metered billing authorization](./usage-security.md) covers server ownership, work deduplication, native proof limits and retained recovery liabilities.
79
79
 
80
80
  - [Reusable metered billing UI](usage-react.md) covers all three models, render props, authenticated adapters and bounded history.
81
+
82
+ - [Native usage configuration UI](usage-configuration.md) covers reusable forms, managed meter selection, price rows and authorized adapters.
83
+
84
+ - [Native metered billing example](usage-example.md), three runnable models, paid evidence and scoped cleanup.
package/docs/react-api.md CHANGED
@@ -286,3 +286,5 @@ function SellerDisputes({ stripeAccountId }: { stripeAccountId: string }) {
286
286
  ## Metered billing
287
287
 
288
288
  See [reusable metered billing UI](usage-react.md) for `UsageBilling`, `UsageSummary`, `UsageAllowance`, `UsageCredits`, `UsageHistory` and their hooks.
289
+
290
+ See [native usage configuration UI](usage-configuration.md) for `UsageConfiguration`, `useUsageConfiguration` and `UsagePriceRow`.
@@ -0,0 +1,154 @@
1
+ # Configure native usage billing in React
2
+
3
+ `UsageConfiguration`, `useUsageConfiguration` and `UsagePriceRow` are reusable,
4
+ unstyled package UI. Both component-backed Convex actions and authenticated HTTP
5
+ adapters use the same contract. No Metronome account or credentials are required.
6
+ Read [native catalog provisioning](usage-catalog.md), [usage views](usage-react.md)
7
+ and [authorization boundaries](usage-security.md) before wiring the adapter.
8
+
9
+ ```tsx
10
+ import {
11
+ UsageConfiguration,
12
+ type UsageConfigurationValue,
13
+ } from "@fantastic.dev/better-stripe/react";
14
+
15
+ const initial: UsageConfigurationValue = {
16
+ plan: {
17
+ key: "api-calls",
18
+ version: "v1",
19
+ model: "pay_as_you_go",
20
+ unit: { name: "call", precision: 0 },
21
+ rate: { currency: "usd", unitAmountDecimal: "2" },
22
+ },
23
+ eventName: "api_calls_v1",
24
+ displayName: "API calls",
25
+ };
26
+
27
+ <UsageConfiguration
28
+ scope={authorizedConfigurationScope}
29
+ initial={initial}
30
+ meters={authorizedManagedMeters}
31
+ onSave={saveAuthorizedConfiguration}
32
+ />;
33
+ ```
34
+
35
+ `scope` contains opaque `identityKey`, `accountKey` and `productKey`, a display
36
+ `ownershipLabel`, `role: "admin" | "seller"`, `canConfigure` and
37
+ `capability: "issuer_native" | "unsupported"`. Derive these on the host from the
38
+ signed-in actor and verified issuer account. They control browser state and
39
+ presentation. They do not authorize a server operation. Include actor changes in
40
+ `identityKey`, even if two actors share an account.
41
+
42
+ The form has no owner selector, provider secret input or browser Stripe callback.
43
+ The native APIs currently operate in the configured key's issuer realm, without
44
+ connected-account headers. Seller adapters must authorize the seller's product
45
+ within that supported realm; a role label does not enable arbitrary Connect
46
+ billing. A host must return unsupported for an ineligible provider/account setup.
47
+ These are BetterStripe components, not Stripe embedded catalog components.
48
+
49
+ ## Supported settings
50
+
51
+ The billing model selects the relevant fields:
52
+
53
+ - **Pay as you go:** exact price per whole unit, currency, billable unit and
54
+ quantity precision from 0 through 6.
55
+ - **Included monthly units plus overages:** the same rate as an overage rate,
56
+ positive included units, and a reset at the original monthly billing period.
57
+ Native pricing uses a graduated free first tier followed by an infinite paid
58
+ tier. This does not add a monthly subscription fee or authorize work.
59
+ - **Prepaid paid credits:** a paid credit package quantity, manual top-up and
60
+ reject-on-insufficient-credit policy. The package must have positive whole minor currency backing within the native
61
+ payment bound and supported charge increments. Each later reservation must
62
+ also have exact whole-minor backing. Fractional rates are supported when work
63
+ uses suitable batches; fractional-minor consumption is rejected without rounding. Original terms
64
+ remain attached to credits. Automatic top-up and a monetary wallet are not
65
+ supported. Credit purchases fund only the issuer's own services.
66
+
67
+ Rates shown in the form are **major currency units per whole billable unit**.
68
+ The submitted `plan.rate.unitAmountDecimal` is an exact string in **minor currency
69
+ units per whole billable unit**. For example, `0.00125 USD` becomes `"0.125"` minor
70
+ units. Precision 2 gives Stripe a scaled-unit rate of `"0.00125"` minor units.
71
+ The form uses the existing plan, quantity, native rate and credit cost validators.
72
+ It rejects excessive precision and bounds rather than rounding. Provider account,
73
+ minimum payment, currency and payment-method eligibility still require server
74
+ validation and native observations.
75
+
76
+ Monthly interval and sum aggregation are the current supported configuration.
77
+ Other intervals, count/last aggregation, general tiers and transformed quantities
78
+ need an explicit supported server adapter. The form does not imply support by
79
+ accepting those settings.
80
+
81
+ ## Immutable meter selection and versions
82
+
83
+ `meters` is an authorized subset/page of managed meters. Each entry contains `id`,
84
+ `active` and its original `configuration`. Do not pass arbitrary native meters
85
+ without first verifying/adopting them through the package. Do not describe a
86
+ partial page as complete inventory. Hosts can page or search their managed catalog
87
+ and replace the supplied subset.
88
+
89
+ Selecting an active meter loads its immutable original terms and disables edits.
90
+ Inactive meters cannot be selected. Choose **Create new meter version** to edit
91
+ new terms. The server must require a new plan version, event name and price lookup
92
+ key for changed terms. Saving does not migrate, cancel or reprice existing
93
+ subscriptions. Those keep their original price until an explicit authorized host
94
+ operation changes them.
95
+
96
+ Server adapters can import the `UsageConfigurationValue` type from
97
+ `@fantastic.dev/better-stripe/usage` without loading React types. The React entry
98
+ point continues to re-export it for UI consumers.
99
+
100
+ `onSave` receives `{ plan, eventName, displayName, meterId?, creditPackage? }`.
101
+ For prepaid, `creditPackage` is `{ quantity, topUp: "manual" }`. It is configuration
102
+ only. Saving does not create a payment, grant credits or authorize consumption.
103
+ The host must:
104
+
105
+ 1. Authenticate the actor and authorize admin/seller access to the product.
106
+ 2. Resolve the Stripe realm, mode, product and permitted immutable plan identity
107
+ on the server. Ignore client attempts to choose financial ownership.
108
+ 3. Revalidate the plan and selected original meter. Call `ensureUsageMeter` or
109
+ verify/adopt the selected meter, then `ensureUsagePrice` with a stable lookup
110
+ key. Persist the validated package policy in the host's authorized product
111
+ configuration, not a second usage ledger.
112
+ 4. For later purchases, use the package's [credit workflow](usage-credits.md),
113
+ deriving `ownership: "issuer"` and `rollover: "retain_original_terms"` on the
114
+ server. Verify payment before granting spending capacity.
115
+ 5. Return only sanitized results. An uncertain create outcome must be reconciled
116
+ using the original keys. Do not invent new identities to retry.
117
+
118
+ The package catalog persists intents and verifies immutable provider terms. A
119
+ browser duplicate-submit lock is only a UI convenience. Host authorization and
120
+ package idempotency remain mandatory after reloads or across tabs.
121
+
122
+ ## State, styling and recovery
123
+
124
+ Inputs and save controls disable during submission. Validation errors identify
125
+ unsupported values. Provider errors use a sanitized retry/reconciliation message;
126
+ raw provider messages are not shown by the default UI. A successful save shows a
127
+ version confirmation. Changing scope, authoritative initial terms or meter choices
128
+ resets edits and discards delayed results. A read-only or unsupported host cannot
129
+ submit through the hook either.
130
+
131
+ Use `className`, `[data-better-stripe="usage-configuration"]`, ordinary semantic
132
+ HTML and associated labels to style the default form. A `children(state)` render
133
+ prop, or `useUsageConfiguration(props)`, exposes `fields`, `setField`, `meterId`,
134
+ `selectMeter`, `immutable`, `disabled`, `isPending`, `save`, `error` and `message`.
135
+ Keep immutable/disabled controls and error/status announcements accessible when
136
+ customizing. The hook retains the same validation and submission lifecycle.
137
+
138
+ `UsagePriceRow` accepts a discriminated `value`:
139
+
140
+ - `{ kind: "fixed", price }` reuses `PriceCard` formatting. Pass observed usage,
141
+ billing-scheme and transformation metadata when available. Metered, tiered,
142
+ transformed, missing amounts or unsupported charge units cannot masquerade as
143
+ fixed zero prices.
144
+ - `{ kind: "metered", price }` uses the managed `UsagePriceBinding` returned by
145
+ `getUsagePrice`. It displays the original plan version, exact whole-unit rate,
146
+ model, monthly interval, aggregation, precision and active state. Included
147
+ tiers and prepaid credit backing have separate explanations.
148
+ - `{ kind: "unsupported", reason: "tiered" | "transformed" | "other" }` labels
149
+ other observed terms explicitly. It never infers a free price from a null
150
+ amount.
151
+
152
+ Use `productName`, `className` or `children(value)` for the catalog row. It is
153
+ read-only. The form, catalog row and usage views share package contracts; the
154
+ example should compose them rather than implementing another pricing engine.
@@ -92,6 +92,10 @@ window. Automatic sends also stop 23 hours after the first send attempt. Stripe
92
92
  retains deduplication for at least 24 hours, not forever. A historical acceptance
93
93
  receipt remains valid after these windows expire, but does not authorize replay.
94
94
  The adapter never changes the original occurrence time to make an event eligible.
95
+ For a sandbox subscription attached to a test clock, delivery additionally reads
96
+ the native clock and checks its 35-day past/5-minute future window. An advancing
97
+ or unavailable clock holds delivery. A timestamp outside its native window is
98
+ rejected before sending. Production source timestamps remain unchanged.
95
99
 
96
100
  ## Status and operational controls
97
101
 
@@ -0,0 +1,246 @@
1
+ # Run all three native billing models
2
+
3
+ The example at `/demo/metered-usage` uses the public BetterStripe package against a
4
+ Stripe sandbox. It provisions a dedicated Accounts v2 customer, test clock,
5
+ product, meter, price and managed subscription per persona and model. Usage,
6
+ delivery, allowance reservations, credits, corrections and settlement live in the
7
+ component. The example stores fixture provenance and synthetic application work.
8
+
9
+ Start with [sandbox setup](metering-setup.md). Use your existing Stripe sandbox;
10
+ no Metronome account or token is needed. Run the example backend and frontend
11
+ from the `example` directory with `pnpm dev`. Keep test keys in the backend
12
+ Convex environment. Do not copy secret values into commands, screenshots, source
13
+ files or browser storage.
14
+
15
+ ## Demo security model
16
+
17
+ This repository's persona switcher is a test-only convenience, not authentication.
18
+ Choose Customer, Seller or Admin, then Metered billing. Each operation rechecks
19
+ the server's persona binding and test key. If an authenticated identity is present,
20
+ it must match the persona's stored token identifier. Visitor and affiliate
21
+ personas cannot operate the workflow. Do not expose these demo endpoints as a
22
+ production billing service.
23
+
24
+ In your app, replace the persona lookup with real authentication and server-owned
25
+ customer, product, entitlement and recipient authorization. Never trust a browser
26
+ account ID, product ID, price, rate or settlement policy. See
27
+ [authorization and recovery](usage-security.md).
28
+
29
+ Admin and seller personas can configure the unit, precision, currency, exact price,
30
+ version and model-specific terms before setup. Customers run the server-owned
31
+ defaults. Setup retries retain the original native identities and configuration.
32
+ A saved meter and subscription keep their original terms. Archive a resolved run
33
+ before configuring its replacement.
34
+
35
+ ## Pay as you go
36
+
37
+ 1. Select Pay as you go, then Set up sandbox.
38
+ 2. Run five units three times. The default price is USD 1 per call.
39
+ 3. Replay last work. Its source identity, quantity and occurrence time stay fixed;
40
+ the synthetic application work and usage acceptance happen once.
41
+ 4. Observe native usage. If delivery is queued, use Resume queued deliveries.
42
+ Stripe aggregation is asynchronous. Refresh until the aggregate is 15.
43
+ 5. Close or resume original billing period. This fences new work, checks complete
44
+ local/native equality, drains reservations and checks every correction and
45
+ purchase intent. It advances only this run's test clock.
46
+ 6. Resume after the clock is ready. The server finds the unique original cycle
47
+ invoice, verifies its meter lines, finalizes it and pays with Stripe's sandbox
48
+ card. The default invoice is USD 15.
49
+
50
+ The outcome separately shows invoice payment, original cash verification, actual
51
+ processing fees and any verified recipient transfers. A paid invoice alone does
52
+ not imply that settlement is ready.
53
+
54
+ ## Included monthly usage and overages
55
+
56
+ Select Included monthly usage. The defaults include ten calls per original
57
+ monthly period, then USD 1 per additional call. Run three five-unit jobs. The
58
+ package allowance view shows 15 consumed, ten included, five billable overage
59
+ units and the soft-limit warning at 12. The native invoice is USD 5.
60
+
61
+ Closing the period observes the next native subscription period. When that period
62
+ is active on the Convex server, its separate allowance starts at zero consumed
63
+ and ten remaining included units. The old period and history stay unchanged. A
64
+ test clock can move ahead of real time; future renewal allowance is explicitly
65
+ unavailable. Its view stays read-only until the period is active on the server and
66
+ new event times are inside the provider's real acceptance window. This demo does not forge
67
+ future work timestamps to simulate another month's consumption.
68
+
69
+ ## Paid prepaid credits
70
+
71
+ 1. Select Prepaid credits and set up its dedicated sandbox resources.
72
+ 2. Run five units before funding. Work is held and does not execute.
73
+ 3. Create credit purchase. The default original purchase is ten units for USD 10.
74
+ Pending payment grants no usable credit.
75
+ 4. Confirm sandbox card. The backend uses Stripe's test card and the package
76
+ verifies the original captured PaymentIntent, customer and paid credit grant.
77
+ 5. Run two five-unit jobs. Replay a successful job before creating another one to
78
+ demonstrate idempotency. Another five-unit job is denied after exhaustion.
79
+ 6. Observe native usage, then close and resume the period. The native credit grant
80
+ covers the consumption invoice. The demo refuses to pay any positive prepaid
81
+ invoice remainder with a second cash payment.
82
+
83
+ The USD 10 purchase is the only cash source. Credit consumption collects no new
84
+ cash. The package reconciles native credit transactions against complete invoice
85
+ history. Unavailable observations are shown explicitly, never as a zero balance.
86
+
87
+ For production, send the package purchase result's `clientSecret` only to the
88
+ properly authenticated purchaser's Stripe payment UI. Do not store or log it.
89
+ Confirming a payment in the UI is not proof of usable credits; call
90
+ `observeCreditPurchase` and wait for the verified ready grant. See
91
+ [paid credit accounting](usage-credits.md).
92
+
93
+ Prepaid is limited to the issuer's own services. A seller persona cannot redeem
94
+ credits into reseller proceeds. An authorized affiliate can be paid once from the
95
+ original purchase; usage does not produce another affiliate sale.
96
+
97
+ ## Corrections and retained failures
98
+
99
+ Before closing, Correct last accepted event cancels its original native event
100
+ through the package. Repeated correction requests keep the same correction ID.
101
+ Wait for confirmation and native reaggregation. A new application job can then
102
+ use the released capacity. For example, record 15 units, cancel the last five,
103
+ then record a different five-unit job. Effective usage is 15, and history retains
104
+ 20 originally accepted units plus the five canceled units.
105
+
106
+ Unknown delivery outcomes stay held. Resume queued deliveries schedules only
107
+ records that the package still classifies as queued; it never resends unknown
108
+ attempts. Do not replace the source event ID, change the occurrence time, create
109
+ a new run to relabel the same work or invent a provider event identifier. Resolve
110
+ the original attempt with verified native evidence using the operational runbook.
111
+ A billing or cleanup guard failure preserves all work, purchase and correction
112
+ intents for reconciliation.
113
+
114
+ The fixture timestamps _new synthetic jobs_ at its retained test clock's original
115
+ period start. This keeps native meter events and paid grants on the same logical
116
+ clock. Retrying a job never changes that timestamp. Real applications must use
117
+ the actual occurrence time of their business event. Delivery checks both real
118
+ provider limits and an attached sandbox clock before a native event write.
119
+
120
+ ## Ownership and routing
121
+
122
+ Customer and admin runs use direct issuer billing. Seller runs pin their original
123
+ server-owned seller account and, when available, an existing demo affiliate at
124
+ setup. The demo policy is a 10% inclusive platform fee and a 20% affiliate share
125
+ of the eligible remainder, with recurring commission eligibility. The package
126
+ uses actual processing fees and verifies native payment provenance, recipient
127
+ capabilities and transfer identity. Unsupported Connect configurations remain
128
+ held. Accounts v2 payer configuration is separate from merchant or recipient
129
+ configuration; a customer account is not automatically eligible to receive money.
130
+ Prepaid settlement retains issuer revenue and accepts only eligible affiliate
131
+ policy, never seller or collaborator redemption.
132
+
133
+ ## Scoped cleanup and reset
134
+
135
+ Use Archive or resume scoped cleanup after the original invoice and cash evidence
136
+ are verified. It refuses unresolved delivery, corrections, reservations, purchases,
137
+ credit backing or settlement. Unspent paid credits require verified refund or
138
+ expiry; cleanup cannot wipe them.
139
+
140
+ Cleanup requests period-end cancellation, advances only the owned test clock to
141
+ the cancellation boundary, checks the final native cycle invoice and retires the
142
+ managed enrollment. It deactivates only the owned price, meter and product. It
143
+ retains the native payer, clock, invoice/payment evidence and every component
144
+ history record. It does not clear any Convex table or another developer's data.
145
+ After successful archival, Start new sandbox run creates new isolated resources.
146
+ Admin or seller can save a new version before starting that replacement.
147
+
148
+ Empty or unresolved runs can require operator reconciliation rather than automatic
149
+ archive. In particular, unknown provider outcomes must remain visible and retained.
150
+ Never delete a clock or payer to make financial evidence disappear.
151
+
152
+ ## Model configuration snippets
153
+
154
+ Use the same versioned unit and exact minor-currency rate in each model:
155
+
156
+ ```ts
157
+ import { defineUsagePlan } from "@fantastic.dev/better-stripe/usage";
158
+ const terms = {
159
+ key: "api-calls",
160
+ version: "v1",
161
+ unit: { name: "call", precision: 0 },
162
+ rate: { currency: "usd", unitAmountDecimal: "100" },
163
+ } as const;
164
+ ```
165
+
166
+ Pay as you go bills every effective unit:
167
+
168
+ ```ts
169
+ const payAsYouGo = defineUsagePlan({ ...terms, model: "pay_as_you_go" });
170
+ ```
171
+
172
+ Included monthly usage grants ten units before overages in each original period:
173
+
174
+ ```ts
175
+ const included = defineUsagePlan({
176
+ ...terms,
177
+ model: "included_overage",
178
+ includedQuantity: "10",
179
+ reset: "billing_period",
180
+ });
181
+ ```
182
+
183
+ Prepaid consumption requires verified paid grants and rejects insufficient credit:
184
+
185
+ ```ts
186
+ const prepaid = defineUsagePlan({
187
+ ...terms,
188
+ model: "prepaid",
189
+ insufficientBalance: "reject",
190
+ });
191
+ // After server authorization and native binding setup:
192
+ const purchase = await stripe.usage.purchaseCredits(
193
+ ctx,
194
+ {
195
+ ...originalCreditBinding,
196
+ purchaseId: originalBusinessPurchaseId,
197
+ quantity: "10",
198
+ ownership: "issuer",
199
+ rollover: "retain_original_terms",
200
+ },
201
+ { stripeSecretKey },
202
+ );
203
+ // Return clientSecret only to the authorized purchaser's payment UI.
204
+ // Observe the original purchase after payment; wait for its ready grant.
205
+ ```
206
+
207
+ Use `ensureUsageMeter`, `ensureUsagePrice` and `usage.ensureSubscription` to bind
208
+ the chosen plan to the server-authorized native payer. The exact implementations
209
+ are in the example's `meteredUsage/setup.ts` and `meteredUsage/funding.ts`.
210
+
211
+ ## Package calls behind the example
212
+
213
+ Server code imports neutral types from `@fantastic.dev/better-stripe/usage`; UI
214
+ code uses `@fantastic.dev/better-stripe/react`. The example backend lives under
215
+ `example/convex/meteredUsage`. Its atomic synthetic-work mutation follows this
216
+ pattern, using server-authorized original terms:
217
+
218
+ ```ts
219
+ const reservation =
220
+ model === "prepaid"
221
+ ? await stripe.usage.reserveCredits(ctx, { event, subscription })
222
+ : await stripe.usage.reserveAllowance(ctx, { event, subscription });
223
+ // Handle denied/released reservations before doing any application work.
224
+ const receipt = await stripe.usage.record(ctx, {
225
+ event,
226
+ subscription,
227
+ reservationId: reservation.reservationId,
228
+ });
229
+ // Persist synthetic DB work and receipt in this same mutation transaction.
230
+ ```
231
+
232
+ Schedule delivery from an action after the transaction commits:
233
+
234
+ ```ts
235
+ await stripe.usage.startDelivery(ctx, {
236
+ scope: original.scope,
237
+ eventId: receipt.eventId,
238
+ provider: internal.meteredUsage.delivery.deliver,
239
+ });
240
+ ```
241
+
242
+ For external application work, use a durable idempotent work protocol with the
243
+ original business identity. A database transaction cannot make an external side
244
+ effect atomic. See [ledger](usage-ledger.md), [delivery](usage-delivery.md),
245
+ [limits](usage-limits.md), [corrections](usage-corrections.md) and
246
+ [settlement](usage-settlement.md) for the complete contracts.
@@ -180,3 +180,7 @@ Run `pnpm run check:all` and verify your host's authorization and native setup
180
180
  using the [setup guide](metering-setup.md). Package views do not replace the
181
181
  [ledger](usage-ledger.md), [allowance](usage-limits.md) or
182
182
  [paid-credit](usage-credits.md) work and recovery protocols.
183
+
184
+ Server adapters can import the `UsageViewScope` and `UsageBillingSnapshot` types
185
+ from `@fantastic.dev/better-stripe/usage` without importing React types. The React
186
+ entry point retains its existing exports.
@@ -78,13 +78,18 @@ invoice. Refunds and disputes do not reset eligibility.
78
78
  An unpaid draft/open invoice returns `not_ready/provider_pending`. Missing fees
79
79
  remain `not_ready/fee_pending`. Zero paid invoices and refunded/disputed sources
80
80
  are not payable. Incomplete or ambiguous funding, credit-funded/partial/multiple
81
- payments, multiple priced invoice lines, proration, mismatched original periods,
81
+ payments, unrelated priced invoice lines, proration, mismatched original periods,
82
82
  converted settlement currencies and automatic destination/on-behalf-of charges
83
83
  are held through explicit non-ready outcomes. The method does not guess a
84
84
  multi-product allocation or take over existing destination-charge fee handling.
85
85
  Fixed-plus-metered invoices remain readable with the ordinary invoice APIs, but
86
- this automatic settlement method requires one original priced line. Treat these
87
- limits as unsupported settlement combinations, not as zero proceeds.
86
+ this automatic settlement method requires one paid original meter line. Native
87
+ included-overage invoices can also contain one zero-priced included-tier line.
88
+ Both lines must retain the same original price, product, subscription item,
89
+ period, currency and mode, with no credit adjustments. The complete independent
90
+ line-item read must match both original IDs. Additional paid lines, duplicate IDs
91
+ and foreign zero-priced siblings remain unsupported. Treat unsupported settlement
92
+ combinations as unavailable evidence rather than zero proceeds.
88
93
 
89
94
  ## Prepaid issuer-service revenue
90
95
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fantastic.dev/better-stripe",
3
- "version": "0.61.0",
3
+ "version": "0.63.0",
4
4
  "description": "A Convex component for Stripe V2 Accounts API integration.",
5
5
  "keywords": [
6
6
  "stripe",
@@ -112,7 +112,9 @@
112
112
  "docs/usage-settlement.md",
113
113
  "docs/usage-security.md",
114
114
  "docs/usage-react.md",
115
- "docs/evidence/native-metering"
115
+ "docs/evidence/native-metering",
116
+ "docs/usage-configuration.md",
117
+ "docs/usage-example.md"
116
118
  ],
117
119
  "scripts": {
118
120
  "build": "tsc --project ./tsconfig.build.json && node scripts/check-public-exports.mjs",
@@ -1,3 +1,4 @@
1
+ import { zeroTierLinesMatch } from "./zeroTierLines.js";
1
2
  import type Stripe from "stripe";
2
3
  import type {
3
4
  FinancialOutcome,
@@ -53,6 +54,7 @@ export async function resolveVerifiedPaymentSource(
53
54
  customerId: string;
54
55
  invoiceLine?: {
55
56
  id: string;
57
+ zeroAmountLineIds?: string[];
56
58
  subscriptionItemId: string;
57
59
  period: { start: number; end: number };
58
60
  };
@@ -324,8 +326,18 @@ export async function resolveVerifiedPaymentSource(
324
326
  ),
325
327
  );
326
328
  if (lines.status !== "complete") return lines;
327
- requireSource(lines.data.length === 1, reject("unsupported_source"));
328
- const line = lines.data[0]!;
329
+ const zeroIds = eligibility?.invoiceLine?.zeroAmountLineIds ?? [];
330
+ const line = zeroIds.length
331
+ ? lines.data.find((row) => row.id === eligibility!.invoiceLine!.id)
332
+ : lines.data[0];
333
+ requireSource(
334
+ line &&
335
+ (zeroIds.length
336
+ ? zeroTierLinesMatch(lines.data, line, zeroIds)
337
+ : lines.data.length === 1),
338
+ reject("unsupported_source"),
339
+ );
340
+ if (!line) return reject("unsupported_source");
329
341
  requireSource(
330
342
  line.object === "line_item" &&
331
343
  line.invoice === invoice.id &&
@@ -0,0 +1,42 @@
1
+ import type Stripe from "stripe";
2
+ /** Only explicitly pinned zero-priced siblings of one paid graduated tier are eligible. */
3
+ export function zeroTierLinesMatch(
4
+ lines: Stripe.InvoiceLineItem[],
5
+ paid: Stripe.InvoiceLineItem,
6
+ ids: readonly string[],
7
+ ): boolean {
8
+ if (
9
+ ids.length !== 1 ||
10
+ lines.length !== 2 ||
11
+ new Set(lines.map((row) => row.id)).size !== 2
12
+ )
13
+ return false;
14
+ const free = lines.find((row) => row.id === ids[0]);
15
+ if (!free || free.id === paid.id) return false;
16
+ const parent = free.parent?.subscription_item_details;
17
+ const original = paid.parent?.subscription_item_details;
18
+ const price = free.pricing?.price_details;
19
+ const originalPrice = paid.pricing?.price_details;
20
+ return (
21
+ free.object === "line_item" &&
22
+ free.invoice === paid.invoice &&
23
+ free.livemode === paid.livemode &&
24
+ free.amount === 0 &&
25
+ free.currency === paid.currency &&
26
+ free.period.start === paid.period.start &&
27
+ free.period.end === paid.period.end &&
28
+ !!parent &&
29
+ !parent.proration &&
30
+ parent.subscription === original?.subscription &&
31
+ parent.subscription_item === original?.subscription_item &&
32
+ free.pricing?.type === "price_details" &&
33
+ !!price &&
34
+ price.price === originalPrice?.price &&
35
+ price.product === originalPrice?.product &&
36
+ (free.pretax_credit_amounts ?? []).length === 0 &&
37
+ (free.quantity_decimal != null
38
+ ? /^\d{1,30}(\.\d{1,12})?$/.test(free.quantity_decimal.toString()) &&
39
+ /[1-9]/.test(free.quantity_decimal.toString())
40
+ : Number.isSafeInteger(free.quantity) && free.quantity! > 0)
41
+ );
42
+ }
@@ -0,0 +1,9 @@
1
+ import type { UsagePlan } from "./contracts.js";
2
+ /** Server-safe configuration payload shared with the reusable React form. */
3
+ export type UsageConfigurationValue = {
4
+ plan: UsagePlan;
5
+ eventName: string;
6
+ displayName: string;
7
+ meterId?: string;
8
+ creditPackage?: { quantity: string; topUp: "manual" };
9
+ };