@fantastic.dev/better-stripe 0.60.1 → 0.61.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 (66) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +3 -1
  3. package/dist/client/usage/index.d.ts +2 -0
  4. package/dist/client/usage/index.d.ts.map +1 -1
  5. package/dist/react/index.d.ts +12 -0
  6. package/dist/react/index.d.ts.map +1 -1
  7. package/dist/react/index.js +7 -0
  8. package/dist/react/index.js.map +1 -1
  9. package/dist/react/workflows/Pagination.d.ts +1 -0
  10. package/dist/react/workflows/Pagination.d.ts.map +1 -1
  11. package/dist/react/workflows/Pagination.js +1 -0
  12. package/dist/react/workflows/Pagination.js.map +1 -1
  13. package/dist/react/workflows/Usage.fixtures.d.ts +17 -0
  14. package/dist/react/workflows/Usage.fixtures.d.ts.map +1 -0
  15. package/dist/react/workflows/Usage.fixtures.js +79 -0
  16. package/dist/react/workflows/Usage.fixtures.js.map +1 -0
  17. package/dist/react/workflows/Usage.types.d.ts +25 -0
  18. package/dist/react/workflows/Usage.types.d.ts.map +1 -0
  19. package/dist/react/workflows/Usage.types.js +11 -0
  20. package/dist/react/workflows/Usage.types.js.map +1 -0
  21. package/dist/react/workflows/UsageAllowance.d.ts +14 -0
  22. package/dist/react/workflows/UsageAllowance.d.ts.map +1 -0
  23. package/dist/react/workflows/UsageAllowance.js +21 -0
  24. package/dist/react/workflows/UsageAllowance.js.map +1 -0
  25. package/dist/react/workflows/UsageBilling.d.ts +20 -0
  26. package/dist/react/workflows/UsageBilling.d.ts.map +1 -0
  27. package/dist/react/workflows/UsageBilling.js +40 -0
  28. package/dist/react/workflows/UsageBilling.js.map +1 -0
  29. package/dist/react/workflows/UsageCredits.d.ts +14 -0
  30. package/dist/react/workflows/UsageCredits.d.ts.map +1 -0
  31. package/dist/react/workflows/UsageCredits.js +25 -0
  32. package/dist/react/workflows/UsageCredits.js.map +1 -0
  33. package/dist/react/workflows/UsageHistory.d.ts +40 -0
  34. package/dist/react/workflows/UsageHistory.d.ts.map +1 -0
  35. package/dist/react/workflows/UsageHistory.js +74 -0
  36. package/dist/react/workflows/UsageHistory.js.map +1 -0
  37. package/dist/react/workflows/UsageSummary.d.ts +19 -0
  38. package/dist/react/workflows/UsageSummary.d.ts.map +1 -0
  39. package/dist/react/workflows/UsageSummary.js +54 -0
  40. package/dist/react/workflows/UsageSummary.js.map +1 -0
  41. package/dist/react/workflows/usage-format.d.ts +11 -0
  42. package/dist/react/workflows/usage-format.d.ts.map +1 -0
  43. package/dist/react/workflows/usage-format.js +43 -0
  44. package/dist/react/workflows/usage-format.js.map +1 -0
  45. package/dist/react/workflows/usage-scope.d.ts +5 -0
  46. package/dist/react/workflows/usage-scope.d.ts.map +1 -0
  47. package/dist/react/workflows/usage-scope.js +26 -0
  48. package/dist/react/workflows/usage-scope.js.map +1 -0
  49. package/docs/README.md +2 -0
  50. package/docs/react-api.md +4 -0
  51. package/docs/usage-react.md +182 -0
  52. package/package.json +2 -1
  53. package/src/client/usage/index.ts +3 -0
  54. package/src/react/index.ts +20 -0
  55. package/src/react/workflows/Pagination.tsx +2 -0
  56. package/src/react/workflows/Usage.fixtures.ts +88 -0
  57. package/src/react/workflows/Usage.test.tsx +373 -0
  58. package/src/react/workflows/Usage.types.ts +39 -0
  59. package/src/react/workflows/UsageAllowance.tsx +114 -0
  60. package/src/react/workflows/UsageBilling.tsx +90 -0
  61. package/src/react/workflows/UsageCredits.tsx +112 -0
  62. package/src/react/workflows/UsageHistory.test.tsx +206 -0
  63. package/src/react/workflows/UsageHistory.tsx +154 -0
  64. package/src/react/workflows/UsageSummary.tsx +204 -0
  65. package/src/react/workflows/usage-format.ts +48 -0
  66. package/src/react/workflows/usage-scope.ts +42 -0
@@ -0,0 +1,74 @@
1
+ "use client";
2
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { useWorkflowResource } from "./useWorkflowResource.js";
4
+ import { Pagination, useCursorPagination } from "./Pagination.js";
5
+ import { usageViewKey } from "./Usage.types.js";
6
+ export function useUsageHistory(props) {
7
+ const limit = props.limit ?? 25;
8
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100)
9
+ throw new RangeError("Usage history page size must be 1–100");
10
+ const key = JSON.stringify([
11
+ usageViewKey(props.scope),
12
+ props.historyKey,
13
+ limit,
14
+ ]);
15
+ const navigation = useCursorPagination(key);
16
+ const resource = useWorkflowResource(async () => {
17
+ try {
18
+ const result = await props.load(props.scope, {
19
+ cursor: navigation.cursor,
20
+ limit,
21
+ });
22
+ if (result.status === "available" &&
23
+ (result.value.records.length > limit ||
24
+ (result.value.cursor !== null && result.value.cursor.length > 2048)))
25
+ throw new Error("Invalid history page");
26
+ return result;
27
+ }
28
+ catch {
29
+ throw new Error("History unavailable. Try again.");
30
+ }
31
+ }, JSON.stringify([key, navigation.cursor]));
32
+ const available = resource.data?.status === "available" ? resource.data.value : null;
33
+ const advancing = !!available &&
34
+ typeof available.cursor === "string" &&
35
+ available.cursor.length > 0 &&
36
+ !navigation.hasCursor(available.cursor);
37
+ const incomplete = available?.complete === false ||
38
+ (!!available && !available.isDone && !advancing);
39
+ const canNext = !!available && !available.isDone && advancing;
40
+ return {
41
+ ...resource,
42
+ page: navigation.page,
43
+ canPrevious: navigation.canPrevious,
44
+ canNext,
45
+ isIncomplete: incomplete,
46
+ isEmpty: !!available &&
47
+ available.records.length === 0 &&
48
+ available.isDone &&
49
+ !incomplete,
50
+ previous: () => {
51
+ if (!resource.isLoading)
52
+ navigation.previous();
53
+ },
54
+ next: () => {
55
+ if (!resource.isLoading && canNext)
56
+ navigation.next(available.cursor);
57
+ },
58
+ };
59
+ }
60
+ export function UsageHistory(props) {
61
+ return (_jsx(UsageHistoryBody, { ...props }, JSON.stringify([
62
+ usageViewKey(props.scope),
63
+ props.historyKey,
64
+ props.limit ?? 25,
65
+ ])));
66
+ }
67
+ function UsageHistoryBody(props) {
68
+ const state = useUsageHistory(props);
69
+ if (props.children)
70
+ return _jsx(_Fragment, { children: props.children(state) });
71
+ const available = state.data?.status === "available" ? state.data.value : null;
72
+ return (_jsxs("section", { "data-better-stripe": "usage-history", className: props.className, "aria-label": props.label ?? "Usage history", "aria-busy": state.isLoading, children: [_jsx("h2", { children: props.label ?? "Usage history" }), _jsx("button", { type: "button", disabled: state.isLoading, onClick: state.refresh, children: "Refresh history" }), state.isLoading && _jsx("p", { role: "status", children: "Loading history\u2026" }), (state.isLoading || state.error) && available && (_jsx("p", { role: "status", children: "Displayed history may be stale." })), state.error && _jsx("p", { role: "alert", children: state.error }), state.data && state.data.status !== "available" && (_jsxs("p", { role: "status", children: ["History ", state.data.status, ". Original scoped history is required."] })), state.isIncomplete && (_jsx("p", { role: "status", children: "History incomplete. This page does not establish complete totals." })), state.isEmpty && _jsx("p", { children: "No history for this view." }), available && (_jsx("ol", { children: available.records.map((record) => (_jsx("li", { children: props.renderRecord(record) }, props.getKey(record)))) })), _jsx(Pagination, { page: state.page, canPrevious: state.canPrevious, canNext: state.canNext, isLoading: state.isLoading, onPrevious: state.previous, onNext: state.next })] }));
73
+ }
74
+ //# sourceMappingURL=UsageHistory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"UsageHistory.js","sourceRoot":"","sources":["../../../src/react/workflows/UsageHistory.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAGb,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAC/D,OAAO,EAAE,UAAU,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAClE,OAAO,EAAE,YAAY,EAAuB,MAAM,kBAAkB,CAAC;AAsBrE,MAAM,UAAU,eAAe,CAC7B,KAGC;IAED,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,IAAI,EAAE,CAAC;IAChC,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC,IAAI,KAAK,GAAG,GAAG;QACt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AAC,MAAM,CAAC,CAAmC,CACjE,CAAC,GACC,CACN,EACD,KAAC,UAAU,IACT,IAAI,EAAE,KAAK,CAAC,IAAI,EAChB,WAAW,EAAE,KAAK,CAAC,WAAW,EAC9B,OAAO,EAAE,KAAK,CAAC,OAAO,EACtB,SAAS,EAAE,KAAK,CAAC,SAAS,EAC1B,UAAU,EAAE,KAAK,CAAC,QAAQ,EAC1B,MAAM,EAAE,KAAK,CAAC,IAAI,GAClB,IACM,CACX,CAAC;AACJ,CAAC"}
@@ -0,0 +1,19 @@
1
+ import type { ReactNode } from "react";
2
+ import type { UsageAvailability } from "../../client/usage/boundaries.js";
3
+ import type { UsageLocalSummary } from "../../client/usage/summary.js";
4
+ import type { UsageAggregateObservation } from "../../client/usage/observationTypes.js";
5
+ import type { UsageViewScope } from "./Usage.types.js";
6
+ export type UsageSummaryProps = {
7
+ scope: UsageViewScope;
8
+ summary: UsageAvailability<UsageLocalSummary> | undefined;
9
+ provider?: UsageAggregateObservation;
10
+ className?: string;
11
+ children?: (state: {
12
+ summary: UsageSummaryProps["summary"];
13
+ provider: UsageSummaryProps["provider"];
14
+ isLoading: boolean;
15
+ isEmpty: boolean;
16
+ }) => ReactNode;
17
+ };
18
+ export declare function UsageSummary(props: UsageSummaryProps): import("react").JSX.Element;
19
+ //# sourceMappingURL=UsageSummary.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"UsageSummary.d.ts","sourceRoot":"","sources":["../../../src/react/workflows/UsageSummary.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AACvC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kCAAkC,CAAC;AAC1E,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AACvE,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,wCAAwC,CAAC;AACxF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAEvD,MAAM,MAAM,iBAAiB,GAAG;IAC9B,KAAK,EAAE,cAAc,CAAC;IACtB,OAAO,EAAE,iBAAiB,CAAC,iBAAiB,CAAC,GAAG,SAAS,CAAC;IAC1D,QAAQ,CAAC,EAAE,yBAAyB,CAAC;IACrC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE;QACjB,OAAO,EAAE,iBAAiB,CAAC,SAAS,CAAC,CAAC;QACtC,QAAQ,EAAE,iBAAiB,CAAC,UAAU,CAAC,CAAC;QACxC,SAAS,EAAE,OAAO,CAAC;QACnB,OAAO,EAAE,OAAO,CAAC;KAClB,KAAK,SAAS,CAAC;CACjB,CAAC;AAeF,wBAAgB,YAAY,CAAC,KAAK,EAAE,iBAAiB,+BAyKpD"}
@@ -0,0 +1,54 @@
1
+ "use client";
2
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { usageSummaryMatches } from "./usage-scope.js";
4
+ import { formatUsageEstimate, formatUsageTime } from "./usage-format.js";
5
+ const models = {
6
+ pay_as_you_go: "Pay as you go",
7
+ included_overage: "Included monthly usage with overages",
8
+ prepaid: "Prepaid credits",
9
+ };
10
+ const deliveryLabels = {
11
+ queued: "Queued delivery",
12
+ sending: "Sending delivery",
13
+ provider_accepted: "Provider accepted",
14
+ rejected: "Rejected delivery",
15
+ unknown: "Unknown delivery",
16
+ held: "Held delivery",
17
+ canceled: "Canceled usage",
18
+ };
19
+ export function UsageSummary(props) {
20
+ const provider = props.provider?.status === "available" &&
21
+ (props.provider.value.period.start !== props.scope.period.start ||
22
+ props.provider.value.period.end !== props.scope.period.end)
23
+ ? {
24
+ status: "unavailable",
25
+ reason: "observation_scope_mismatch",
26
+ retryable: true,
27
+ }
28
+ : props.provider;
29
+ const summary = props.summary?.status === "available" &&
30
+ !usageSummaryMatches(props.scope, props.summary.value)
31
+ ? {
32
+ status: "unavailable",
33
+ reason: "observation_scope_mismatch",
34
+ retryable: true,
35
+ }
36
+ : props.summary;
37
+ const available = summary?.status === "available" ? summary.value : null;
38
+ if (props.children)
39
+ return (_jsx(_Fragment, { children: props.children({
40
+ summary,
41
+ provider,
42
+ isLoading: summary === undefined,
43
+ isEmpty: !!available?.complete && available.eventCount === 0,
44
+ }) }));
45
+ return (_jsxs("section", { "data-better-stripe": "usage-summary", className: props.className, "aria-label": "Usage summary", "aria-busy": summary === undefined, children: [_jsx("h2", { children: "Usage by meter" }), !summary ? (_jsx("p", { role: "status", children: "Loading usage\u2026" })) : summary.status !== "available" ? (_jsxs("p", { role: "status", children: ["Usage ", summary.status, ". Refresh when original usage evidence is available."] })) : (_jsxs(_Fragment, { children: [_jsxs("p", { children: ["Period ", formatUsageTime(summary.value.period.start), " to", " ", formatUsageTime(summary.value.period.end)] }), !summary.value.complete && (_jsx("p", { role: "status", children: "Local history incomplete. Totals are partial." })), summary.value.complete && summary.value.eventCount === 0 && (_jsx("p", { children: "No usage in this period." })), summary.value.groups.map((group) => (_jsxs("article", { "data-billing-model": group.binding.plan.model, children: [_jsxs("h3", { children: [group.binding.plan.unit.name, " \u00B7", " ", models[group.binding.plan.model]] }), _jsxs("p", { children: ["Plan ", group.binding.plan.key, ", version", " ", group.binding.plan.version] }), _jsxs("dl", { children: [_jsx("dt", { children: "Accepted usage" }), _jsxs("dd", { children: [group.acceptedQuantity, " ", group.binding.plan.unit.name] }), _jsx("dt", { children: "Billable after corrections" }), _jsxs("dd", { children: [group.effectiveQuantity, " ", group.binding.plan.unit.name] }), _jsx("dt", { children: "Provider accepted" }), _jsxs("dd", { children: [group.providerAcceptedQuantity, " ", group.binding.plan.unit.name] }), Object.entries(group.deliveryQuantities)
46
+ .filter(([kind, quantity]) => kind !== "provider_accepted" &&
47
+ !/^0(?:\.0+)?$/.test(quantity))
48
+ .map(([kind, quantity]) => (_jsxs("div", { children: [_jsx("dt", { children: deliveryLabels[kind] }), _jsxs("dd", { children: [quantity, " ", group.binding.plan.unit.name] })] }, kind)))] }), group.validationErrorEventCount > 0 && (_jsxs("p", { role: "status", children: ["Native validation rejected ", group.validationErrorEventCount, " ", "event(s)."] })), group.estimate.status === "available" ? (_jsxs("p", { children: ["Estimated usage charge:", " ", formatUsageEstimate(group.estimate.value.amountDecimal, group.estimate.value.currency) ?? "Unavailable"] })) : (_jsxs("p", { children: ["Estimate ", group.estimate.status, ". Complete original usage and pricing evidence is required."] })), group.included.status === "available" && (_jsxs("dl", { children: [_jsx("dt", { children: "Included units" }), _jsx("dd", { children: group.included.value.included }), _jsx("dt", { children: "Remaining included units" }), _jsx("dd", { children: group.included.value.remaining }), _jsx("dt", { children: "Overage units" }), _jsx("dd", { children: group.included.value.overage })] }))] }, JSON.stringify([
49
+ group.binding.stripePriceId,
50
+ group.subscription.subscriptionItemId,
51
+ group.subscription.period,
52
+ ])))), _jsx("p", { children: "Estimate only. Finalized invoices and verified payments determine billing." })] })), !provider || provider.status !== "available" ? (_jsxs("p", { role: "status", children: ["Native aggregation ", provider?.status ?? "unavailable", ". Refresh after provider ingestion."] })) : (_jsxs(_Fragment, { children: [_jsxs("p", { children: ["Native aggregate: ", provider.value.quantity] }), provider.value.stale && (_jsx("p", { role: "status", children: "Native aggregation stale." })), !provider.value.complete && (_jsx("p", { role: "status", children: "Native aggregation partial. More provider pages remain." })), _jsx("p", { children: "Aggregation may be delayed. Provider acceptance does not prove ingestion or payment." })] }))] }));
53
+ }
54
+ //# sourceMappingURL=UsageSummary.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"UsageSummary.js","sourceRoot":"","sources":["../../../src/react/workflows/UsageSummary.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AACb,OAAO,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAMvD,OAAO,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAazE,MAAM,MAAM,GAAG;IACb,aAAa,EAAE,eAAe;IAC9B,gBAAgB,EAAE,sCAAsC;IACx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Aa,IAChB,CACL,CAAC,CAAC,CAAC,CACF,qCACY,KAAK,CAAC,QAAQ,CAAC,MAAM,mEAE7B,CACL,EACA,KAAK,CAAC,QAAQ,CAAC,MAAM,KAAK,WAAW,IAAI,CACxC,yBACE,0CAAuB,EACvB,uBAAK,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,QAAQ,GAAM,EACxC,oDAAiC,EACjC,uBAAK,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,SAAS,GAAM,EACzC,yCAAsB,EACtB,uBAAK,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,OAAO,GAAM,IACpC,CACN,KA3EI,IAAI,CAAC,SAAS,CAAC;wBAClB,KAAK,CAAC,OAAO,CAAC,aAAa;wBAC3B,KAAK,CAAC,YAAY,CAAC,kBAAkB;wBACrC,KAAK,CAAC,YAAY,CAAC,MAAM;qBAC1B,CAAC,CAwEM,CACX,CAAC,EACF,qGAGI,IACH,CACJ,EACA,CAAC,QAAQ,IAAI,QAAQ,CAAC,MAAM,KAAK,WAAW,CAAC,CAAC,CAAC,CAC9C,aAAG,IAAI,EAAC,QAAQ,oCACM,QAAQ,EAAE,MAAM,IAAI,aAAa,2CAEnD,CACL,CAAC,CAAC,CAAC,CACF,8BACE,8CAAsB,QAAQ,CAAC,KAAK,CAAC,QAAQ,IAAK,EACjD,QAAQ,CAAC,KAAK,CAAC,KAAK,IAAI,CACvB,YAAG,IAAI,EAAC,QAAQ,0CAA8B,CAC/C,EACA,CAAC,QAAQ,CAAC,KAAK,CAAC,QAAQ,IAAI,CAC3B,YAAG,IAAI,EAAC,QAAQ,wEAEZ,CACL,EACD,+GAGI,IACH,CACJ,IACO,CACX,CAAC;AACJ,CAAC"}
@@ -0,0 +1,11 @@
1
+ /** Native metered rates/estimates use minor currency decimals. Preserve fractional cents and large quantities. */
2
+ export declare function formatUsageEstimate(amountDecimal: string, currency: string): string | null;
3
+ /** Normalize only the visual progress position; keep all visible quantities exact. */
4
+ export declare function allowanceProgress(value: {
5
+ consumedQuantity: string;
6
+ reservedQuantity: string;
7
+ includedQuantity: string;
8
+ }): number | null;
9
+ /** Numeric usage periods can exceed Date's supported display range. */
10
+ export declare function formatUsageTime(seconds: number): string;
11
+ //# sourceMappingURL=usage-format.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usage-format.d.ts","sourceRoot":"","sources":["../../../src/react/workflows/usage-format.ts"],"names":[],"mappings":"AACA,kHAAkH;AAClH,wBAAgB,mBAAmB,CACjC,aAAa,EAAE,MAAM,EACrB,QAAQ,EAAE,MAAM,GACf,MAAM,GAAG,IAAI,CAYf;AAED,sFAAsF;AACtF,wBAAgB,iBAAiB,CAAC,KAAK,EAAE;IACvC,gBAAgB,EAAE,MAAM,CAAC;IACzB,gBAAgB,EAAE,MAAM,CAAC;IACzB,gBAAgB,EAAE,MAAM,CAAC;CAC1B,GAAG,MAAM,GAAG,IAAI,CAehB;AAED,uEAAuE;AACvE,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAKvD"}
@@ -0,0 +1,43 @@
1
+ import { getChargeCurrencyMetadata } from "../../client/charge-currency.js";
2
+ /** Native metered rates/estimates use minor currency decimals. Preserve fractional cents and large quantities. */
3
+ export function formatUsageEstimate(amountDecimal, currency) {
4
+ const metadata = getChargeCurrencyMetadata(currency);
5
+ if (!metadata || !/^\d+(?:\.\d+)?$/.test(amountDecimal))
6
+ return null;
7
+ const [whole, fraction = ""] = amountDecimal.split(".");
8
+ const digits = (whole + fraction).replace(/^0+(?=\d)/, "");
9
+ const scale = metadata.apiDecimals + fraction.length;
10
+ const padded = digits.padStart(scale + 1, "0");
11
+ const major = scale ? padded.slice(0, -scale) : padded;
12
+ let minor = scale ? padded.slice(-scale).replace(/0+$/, "") : "";
13
+ if (metadata.displayDecimals === 0 && minor)
14
+ return null;
15
+ minor = minor.padEnd(metadata.displayDecimals, "0");
16
+ return `${major}${minor ? "." + minor : ""} ${metadata.currency.toUpperCase()}`;
17
+ }
18
+ /** Normalize only the visual progress position; keep all visible quantities exact. */
19
+ export function allowanceProgress(value) {
20
+ const quantities = [
21
+ value.consumedQuantity,
22
+ value.reservedQuantity,
23
+ value.includedQuantity,
24
+ ];
25
+ if (quantities.some((quantity) => !/^\d{1,18}(?:\.\d{1,6})?$/.test(quantity)))
26
+ return null;
27
+ const [consumed, reserved, included] = quantities.map((quantity) => {
28
+ const [whole, fraction = ""] = quantity.split(".");
29
+ return BigInt(whole + fraction.padEnd(6, "0"));
30
+ });
31
+ if (included === 0n)
32
+ return null;
33
+ const ratio = ((consumed + reserved) * 10000n) / included;
34
+ return Number(ratio > 10000n ? 10000n : ratio);
35
+ }
36
+ /** Numeric usage periods can exceed Date's supported display range. */
37
+ export function formatUsageTime(seconds) {
38
+ const value = new Date(seconds * 1000);
39
+ return Number.isFinite(value.getTime())
40
+ ? value.toISOString()
41
+ : "Time unavailable";
42
+ }
43
+ //# sourceMappingURL=usage-format.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usage-format.js","sourceRoot":"","sources":["../../../src/react/workflows/usage-format.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,yBAAyB,EAAE,MAAM,iCAAiC,CAAC;AAC5E,kHAAkH;AAClH,MAAM,UAAU,mBAAmB,CACjC,aAAqB,EACrB,QAAgB;IAEhB,MAAM,QAAQ,GAAG,yBAAyB,CAAC,QAAQ,CAAC,CAAC;IACrD,IAAI,CAAC,QAAQ,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,aAAa,CAAC;QAAE,OAAO,IAAI,CAAC;IACrE,MAAM,CAAC,KAAK,EAAE,QAAQ,GAAG,EAAE,CAAC,GAAG,aAAa,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACxD,MAAM,MAAM,GAAG,CAAC,KAAK,GAAG,QAAQ,CAAC,CAAC,OAAO,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC;IAC3D,MAAM,KAAK,GAAG,QAAQ,CAAC,WAAW,GAAG,QA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AAC,KAAK,CAAC,GAAG,CAAC,CAAC;QACnD,OAAO,MAAM,CAAC,KAAK,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC;IACjD,CAAC,CAAC,CAAC;IACH,IAAI,QAAQ,KAAK,EAAE;QAAE,OAAO,IAAI,CAAC;IACjC,MAAM,KAAK,GAAG,CAAC,CAAC,QAAQ,GAAG,QAAQ,CAAC,GAAG,MAAM,CAAC,GAAG,QAAQ,CAAC;IAC1D,OAAO,MAAM,CAAC,KAAK,GAAG,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;AACjD,CAAC;AAED,uEAAuE;AACvE,MAAM,UAAU,eAAe,CAAC,OAAe;IAC7C,MAAM,KAAK,GAAG,IAAI,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,CAAC;IACvC,OAAO,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;QACrC,CAAC,CAAC,KAAK,CAAC,WAAW,EAAE;QACrB,CAAC,CAAC,kBAAkB,CAAC;AACzB,CAAC"}
@@ -0,0 +1,5 @@
1
+ import type { UsageBillingSnapshot, UsageViewScope } from "./Usage.types.js";
2
+ import type { UsageLocalSummary } from "../../client/usage/summary.js";
3
+ export declare function usageSummaryMatches(scope: UsageViewScope, value: UsageLocalSummary): boolean;
4
+ export declare function usageSnapshotMatches(scope: UsageViewScope, value: UsageBillingSnapshot): boolean;
5
+ //# sourceMappingURL=usage-scope.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usage-scope.d.ts","sourceRoot":"","sources":["../../../src/react/workflows/usage-scope.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAC7E,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AACvE,wBAAgB,mBAAmB,CACjC,KAAK,EAAE,cAAc,EACrB,KAAK,EAAE,iBAAiB,WAczB;AACD,wBAAgB,oBAAoB,CAClC,KAAK,EAAE,cAAc,EACrB,KAAK,EAAE,oBAAoB,WAoB5B"}
@@ -0,0 +1,26 @@
1
+ export function usageSummaryMatches(scope, value) {
2
+ return (value.period.start === scope.period.start &&
3
+ value.period.end === scope.period.end &&
4
+ value.groups.every((group) => group.binding.plan.rate.currency.toLowerCase() ===
5
+ scope.currency.toLowerCase() &&
6
+ (group.estimate.status !== "available" ||
7
+ group.estimate.value.currency.toLowerCase() ===
8
+ scope.currency.toLowerCase())));
9
+ }
10
+ export function usageSnapshotMatches(scope, value) {
11
+ const periodMatches = (period) => period.start === scope.period.start && period.end === scope.period.end;
12
+ const currencyMatches = (currency) => currency.toLowerCase() === scope.currency.toLowerCase();
13
+ return ((value.summary.status !== "available" ||
14
+ usageSummaryMatches(scope, value.summary.value)) &&
15
+ (value.provider?.status !== "available" ||
16
+ periodMatches(value.provider.value.period)) &&
17
+ (value.allowance?.status !== "available" ||
18
+ !value.allowance.value ||
19
+ (periodMatches(value.allowance.value.period) &&
20
+ currencyMatches(value.allowance.value.committedEstimate.currency) &&
21
+ currencyMatches(value.allowance.value.projectedEstimate.currency))) &&
22
+ (value.credits?.status !== "available" ||
23
+ currencyMatches(value.credits.value.currency)) &&
24
+ (!value.purchase || currencyMatches(value.purchase.currency)));
25
+ }
26
+ //# sourceMappingURL=usage-scope.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usage-scope.js","sourceRoot":"","sources":["../../../src/react/workflows/usage-scope.ts"],"names":[],"mappings":"AAEA,MAAM,UAAU,mBAAmB,CACjC,KAAqB,EACrB,KAAwB;IAExB,OAAO,CACL,KAAK,CAAC,MAAM,CAAC,KAAK,KAAK,KAAK,CAAC,MAAM,CAAC,KAAK;QACzC,KAAK,CAAC,MAAM,CAAC,GAAG,KAAK,KAAK,CAAC,MAAM,CAAC,GAAG;QACrC,KAAK,CAAC,MAAM,CAAC,KAAK,CAChB,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AAC;gBACjE,eAAe,CAAC,KAAK,CAAC,SAAS,CAAC,KAAK,CAAC,iBAAiB,CAAC,QAAQ,CAAC,CAAC,CAAC;QACvE,CAAC,KAAK,CAAC,OAAO,EAAE,MAAM,KAAK,WAAW;YACpC,eAAe,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;QAChD,CAAC,CAAC,KAAK,CAAC,QAAQ,IAAI,eAAe,CAAC,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAC9D,CAAC;AACJ,CAAC"}
package/docs/README.md CHANGED
@@ -76,3 +76,5 @@ Start with the [native Stripe setup guide](metering-setup.md), then read the
76
76
  - [Native usage settlement](./usage-settlement.md) covers original paid invoices, issuer-service credit purchases and affiliate recovery.
77
77
 
78
78
  - [Metered billing authorization](./usage-security.md) covers server ownership, work deduplication, native proof limits and retained recovery liabilities.
79
+
80
+ - [Reusable metered billing UI](usage-react.md) covers all three models, render props, authenticated adapters and bounded history.
package/docs/react-api.md CHANGED
@@ -282,3 +282,7 @@ function SellerDisputes({ stripeAccountId }: { stripeAccountId: string }) {
282
282
  );
283
283
  }
284
284
  ```
285
+
286
+ ## Metered billing
287
+
288
+ See [reusable metered billing UI](usage-react.md) for `UsageBilling`, `UsageSummary`, `UsageAllowance`, `UsageCredits`, `UsageHistory` and their hooks.
@@ -0,0 +1,182 @@
1
+ # Reusable metered billing UI
2
+
3
+ Import the metered views from `@fantastic.dev/better-stripe/react`. They use the
4
+ package's native usage observations and component accounting for all three models:
5
+ pay as you go, included monthly usage with overages, and prepaid credits.
6
+
7
+ The defaults are unstyled semantic HTML. Each view supports render props and a
8
+ `className`; stable `data-better-stripe` attributes identify its root. No Stripe
9
+ embedded metering component or browser provider credential is required.
10
+
11
+ ## One workflow, either host transport
12
+
13
+ `UsageBilling` and `useUsageBilling` accept an authenticated asynchronous loader.
14
+ The same loader contract works with a Convex query/action client or an HTTP API.
15
+ `UsageSummary`, `UsageAllowance` and `UsageCredits` also accept observations
16
+ directly, including reactive host-query results. Both routes use the same display
17
+ components and exact decimal formatting.
18
+
19
+ ```tsx
20
+ import {
21
+ UsageBilling,
22
+ type UsageBillingSnapshot,
23
+ type UsageViewScope,
24
+ } from "@fantastic.dev/better-stripe/react";
25
+
26
+ const view: UsageViewScope = {
27
+ identityKey: authenticatedSessionKey,
28
+ accountKey: authorizedTenantKey,
29
+ meterKey: originalMeterAndPriceVersionKey,
30
+ period: verifiedBillingPeriod,
31
+ currency: originalCurrency,
32
+ };
33
+
34
+ async function loadUsage(scope: UsageViewScope): Promise<UsageBillingSnapshot> {
35
+ const response = await fetch("/api/billing/usage", {
36
+ method: "POST",
37
+ credentials: "same-origin",
38
+ headers: { "content-type": "application/json" },
39
+ body: JSON.stringify({
40
+ meterKey: scope.meterKey,
41
+ period: scope.period,
42
+ currency: scope.currency,
43
+ }),
44
+ });
45
+ if (!response.ok) throw new Error("Usage read unavailable");
46
+ return response.json();
47
+ }
48
+
49
+ <UsageBilling scope={view} unit="API calls" load={loadUsage} />;
50
+ ```
51
+
52
+ The scope is a cache identity, not authorization. Update `identityKey` on logout,
53
+ login or membership changes. Include original plan/price version in `meterKey`.
54
+ Changing identity, tenant, meter/version, period or currency resets the workflow
55
+ and its history navigation. Responses from the previous scope cannot replace the
56
+ current view. Period/currency mismatches in returned snapshots fail closed.
57
+
58
+ Authenticate every host read, refresh and page. Resolve the current tenant and
59
+ original native binding on the server. Do not trust a browser-selected payer,
60
+ price, subscription, secret or scope claim. See [authorization](usage-security.md).
61
+
62
+ The host loader should assemble `UsageBillingSnapshot` from existing package APIs:
63
+
64
+ | Snapshot field | Authenticated server source |
65
+ | ------------------- | ----------------------------------------------------------------------------------------- |
66
+ | `summary` | `stripe.usage.getSummary`, wrapped as `available` with its `observedAt` |
67
+ | `provider` | `stripe.usage.getProviderUsage`, or a fresh authorized `observeProviderUsage` action |
68
+ | `allowance` | `stripe.usage.getAllowanceStatus` for an included model or a configured pay-as-you-go cap |
69
+ | `credits` | `stripe.usage.getCreditBalance` for the original prepaid binding |
70
+ | `purchase` | `stripe.usage.getCreditPurchase` for the authorized original purchase ID |
71
+ | `creditApplication` | Authorized `stripe.usage.reconcileCreditPurchase` for that same original purchase |
72
+
73
+ Wrap successful allowance/credit reads in `{ status: "available", observedAt,
74
+ value }`. Preserve `null` allowance as no configured policy. Return explicit
75
+ `unavailable` or `unsupported` observations when evidence cannot be read. Include
76
+ only fields relevant to the verified model. The UI does not initiate purchases,
77
+ configure limits, run work, reconcile funds automatically or poll Stripe.
78
+
79
+ For a reactive adapter, pass the same observations to `UsageSummary`,
80
+ `UsageAllowance` and `UsageCredits`. Treat `undefined` as loading. Clear results
81
+ when the authenticated scope changes; never pass a previous query's data as the
82
+ new scope's observation. The asynchronous workflow performs this reset itself.
83
+
84
+ ## All three models and observation states
85
+
86
+ `UsageSummary` displays the original plan/version, per-meter and subscription-item
87
+ breakdown, accepted/effective/provider-accepted quantities, nonzero delivery
88
+ states and estimated charge. It preserves exact quantity strings, including
89
+ values beyond JavaScript's safe floating-point range. `formatUsageEstimate`
90
+ converts native minor-unit decimal estimates into exact major currency decimals,
91
+ including fractional cents; unsupported amounts stay unavailable.
92
+
93
+ Loading, empty, partial, unavailable and unsupported are separate states. A
94
+ complete zero-event local summary is empty. An unavailable summary is never zero.
95
+ Native stale/partial aggregates and possible ingestion delay remain visible.
96
+ Unknown/rejected/held delivery is distinct from acceptance and aggregation.
97
+ Estimates never become finalized or paid invoice amounts in these views.
98
+
99
+ `UsageAllowance` shows consumed plus reserved progress, included and remaining
100
+ units, overage, soft warnings and hard-cap observations. Its progress bar is
101
+ normalized for presentation; its accessible value text retains exact quantities.
102
+ A display is never permission to start work. Use the server's atomic reservation
103
+ API. The period is the verified managed billing period with no rollover, not a
104
+ calendar reset performed by React.
105
+
106
+ `UsageCredits` shows available, reserved, consumed, expired and frozen quantities,
107
+ purchase pending/ready/frozen/canceled status, exhaustion and native application
108
+ proof status. A frozen grant may hold units even while the overall account is
109
+ open. Pending purchase payment does not grant units. Consumption is not another
110
+ cash collection or a withdrawable balance. Pass the original currency when
111
+ presenting an application proof without a balance or purchase observation.
112
+
113
+ Refresh is explicit. Existing observations shown during refresh or a failed
114
+ refresh are marked potentially stale. Loader errors use a sanitized message.
115
+ Host adapters must also sanitize returned observation reasons and custom history
116
+ content before sending them to a browser.
117
+
118
+ ## Bounded history
119
+
120
+ `UsageHistory<Row>` and `useUsageHistory<Row>` own cursor navigation, loading,
121
+ retry, scope reset and stale-request protection. They work with event, delivery,
122
+ allowance and credit history. The host provides a row key and presentation rather
123
+ than another pagination engine.
124
+
125
+ ```tsx
126
+ import { UsageHistory } from "@fantastic.dev/better-stripe/react";
127
+ import type { UsageEventView } from "@fantastic.dev/better-stripe/usage";
128
+
129
+ <UsageHistory<UsageEventView>
130
+ scope={view}
131
+ historyKey="accepted-events"
132
+ limit={25}
133
+ load={async (scope, page) => {
134
+ // This host endpoint authenticates this request and resolves its binding.
135
+ const result = await loadAuthorizedEventPage(scope, page);
136
+ return {
137
+ status: "available",
138
+ observedAt: result.observedAt,
139
+ value: {
140
+ records: result.events,
141
+ cursor: result.cursor,
142
+ isDone: result.isDone,
143
+ },
144
+ };
145
+ }}
146
+ getKey={(row) => row.receipt.eventId}
147
+ renderRecord={(row) => (
148
+ <p>
149
+ {row.record.sourceEventId}: {row.record.quantity}{" "}
150
+ {row.record.binding.plan.unit.name}, {row.delivery}
151
+ </p>
152
+ )}
153
+ />;
154
+ ```
155
+
156
+ Use `readCreditHistory`, `readCreditGrants`, `readAllowanceHistory` or
157
+ `readDeliveryHistory` in analogous authorized loaders. The component accepts
158
+ 1–100 rows per page and opaque cursors up to 2,048 characters. Change `historyKey`
159
+ when changing reader kind, filters or transport cache semantics. Reauthorize
160
+ every page; a cursor never grants access. Partial or empty nonterminal pages do
161
+ not mean no history. Incomplete pages never establish complete totals. Missing, empty or repeated
162
+ nonterminal cursors stop forward navigation while preserving Previous and retry.
163
+
164
+ Render props receive the same hook state: data, loading/error, refresh, page,
165
+ previous/next and completeness. Native buttons support keyboard navigation;
166
+ status/alert regions announce loading and errors. Maintain these behaviors when
167
+ replacing defaults with a design system.
168
+
169
+ ## Verification
170
+
171
+ The co-located React tests exercise large exact quantities, every billing model,
172
+ loading/empty/partial/stale/unsupported states, native lag, pending and held
173
+ credits, error sanitization, retries, cursor navigation and delayed responses
174
+ after each scope field changes. The packed consumer typechecks these public
175
+ exports. The deterministic browser fixture is
176
+ `scripts/fixtures/usage-ui.html`; it uses the package components and does not call
177
+ Stripe. Its UI captures are separate from native financial acceptance.
178
+
179
+ Run `pnpm run check:all` and verify your host's authorization and native setup
180
+ using the [setup guide](metering-setup.md). Package views do not replace the
181
+ [ledger](usage-ledger.md), [allowance](usage-limits.md) or
182
+ [paid-credit](usage-credits.md) work and recovery protocols.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fantastic.dev/better-stripe",
3
- "version": "0.60.1",
3
+ "version": "0.61.0",
4
4
  "description": "A Convex component for Stripe V2 Accounts API integration.",
5
5
  "keywords": [
6
6
  "stripe",
@@ -111,6 +111,7 @@
111
111
  "docs/usage-corrections.md",
112
112
  "docs/usage-settlement.md",
113
113
  "docs/usage-security.md",
114
+ "docs/usage-react.md",
114
115
  "docs/evidence/native-metering"
115
116
  ],
116
117
  "scripts": {
@@ -108,3 +108,6 @@ export type { UsageInvoiceSettlementOptions } from "./settlement.js";
108
108
  export type { UsageCreditRevenue } from "./creditRevenue.js";
109
109
 
110
110
  export type { UsageCreditSettlementOptions } from "./creditSettlement.js";
111
+
112
+ export type { UsageEventView } from "./client.js";
113
+ export type { UsageCreditReconciliation } from "./creditObservation.js";
@@ -306,3 +306,23 @@ export type {
306
306
 
307
307
  // Pins end cursors for the component paginator, including reactive page splits.
308
308
  export { usePaginatedQuery as useComponentPaginatedQuery } from "convex-helpers/react";
309
+
310
+ // Native metered billing views, shared by authenticated component and HTTP adapters.
311
+ export { UsageBilling, useUsageBilling } from "./workflows/UsageBilling.js";
312
+ export type { UsageBillingProps } from "./workflows/UsageBilling.js";
313
+ export { UsageSummary } from "./workflows/UsageSummary.js";
314
+ export type { UsageSummaryProps } from "./workflows/UsageSummary.js";
315
+ export { UsageAllowance } from "./workflows/UsageAllowance.js";
316
+ export type { UsageAllowanceProps } from "./workflows/UsageAllowance.js";
317
+ export { UsageCredits } from "./workflows/UsageCredits.js";
318
+ export type { UsageCreditsProps } from "./workflows/UsageCredits.js";
319
+ export type {
320
+ UsageViewScope,
321
+ UsageBillingSnapshot,
322
+ } from "./workflows/Usage.types.js";
323
+ export { formatUsageEstimate } from "./workflows/usage-format.js";
324
+ export { UsageHistory, useUsageHistory } from "./workflows/UsageHistory.js";
325
+ export type {
326
+ UsageHistoryProps,
327
+ UsageHistoryPage,
328
+ } from "./workflows/UsageHistory.js";
@@ -11,6 +11,8 @@ export function useCursorPagination(scopeKey: string) {
11
11
  cursor: current.cursors[current.index],
12
12
  page: current.index + 1,
13
13
  canPrevious: current.index > 0,
14
+ hasCursor: (cursor: string) =>
15
+ current.cursors.slice(0, current.index + 1).includes(cursor),
14
16
  previous: () =>
15
17
  setState((previous) => ({
16
18
  ...previous,
@@ -0,0 +1,88 @@
1
+ import {
2
+ defineUsagePlan,
3
+ type UsageBillingModel,
4
+ } from "../../client/usage/contracts.js";
5
+ import { prepareUsageRecord } from "../../client/usage/records.js";
6
+ import { summarizeUsageRecords } from "../../client/usage/summary.js";
7
+ import type { UsageViewScope, UsageBillingSnapshot } from "./Usage.types.js";
8
+ export const usageScope: UsageViewScope = {
9
+ identityKey: "actor1",
10
+ accountKey: "tenant1",
11
+ meterKey: "calls-v1",
12
+ period: { start: 600, end: 1200 },
13
+ currency: "usd",
14
+ };
15
+ export function usageSnapshot(
16
+ quantity = "14",
17
+ model: UsageBillingModel = "pay_as_you_go",
18
+ ): UsageBillingSnapshot {
19
+ const record = prepareUsageRecord({
20
+ scope: {
21
+ stripeAccountId: "acct_platform",
22
+ customerAccount: "acct_buyer",
23
+ meterId: "mtr_calls",
24
+ livemode: false,
25
+ },
26
+ binding: {
27
+ stripeCustomerId: "cus_buyer",
28
+ stripePriceId: "price_calls",
29
+ eventName: "calls",
30
+ plan: defineUsagePlan({
31
+ key: "calls",
32
+ version: "v1",
33
+ model,
34
+ ...(model === "included_overage"
35
+ ? { includedQuantity: "10", reset: "billing_period" }
36
+ : model === "prepaid"
37
+ ? { insufficientBalance: "reject" }
38
+ : {}),
39
+ unit: { name: "call", precision: 6 },
40
+ rate: { currency: "usd", unitAmountDecimal: "2" },
41
+ }),
42
+ },
43
+ sourceEventId: "work1",
44
+ quantity,
45
+ occurredAt: 700,
46
+ });
47
+ const subscription = {
48
+ subscriptionId: "sub_calls",
49
+ subscriptionItemId: "si_calls",
50
+ stripePriceId: "price_calls",
51
+ period: usageScope.period,
52
+ interval: "month" as const,
53
+ };
54
+ return {
55
+ summary: {
56
+ status: "available",
57
+ observedAt: 700,
58
+ value: summarizeUsageRecords(
59
+ [
60
+ {
61
+ record,
62
+ subscription,
63
+ delivery: "unknown",
64
+ hasValidationError: false,
65
+ },
66
+ ],
67
+ { period: usageScope.period, complete: true, observedAt: 700 },
68
+ ),
69
+ },
70
+ provider: {
71
+ status: "unavailable",
72
+ reason: "provider_not_observed",
73
+ retryable: true,
74
+ },
75
+ };
76
+ }
77
+ export const creditBalance = {
78
+ availableQuantity: "0",
79
+ reservedQuantity: "2",
80
+ consumedQuantity: "8",
81
+ expiredQuantity: "0",
82
+ frozenQuantity: "0",
83
+ precision: 0,
84
+ currency: "usd",
85
+ unit: "call",
86
+ status: "available" as const,
87
+ cashCollection: "none" as const,
88
+ };