@usebillow/sdk 0.5.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 (56) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/LICENSE +21 -0
  3. package/README.md +274 -0
  4. package/dist/billing-C4RIMgH_.d.ts +1053 -0
  5. package/dist/billing-DZ4rIyg7.d.cts +1053 -0
  6. package/dist/billing-status-BZQN_gm7.d.cts +29 -0
  7. package/dist/billing-status-BZQN_gm7.d.ts +29 -0
  8. package/dist/chunk-CCG4F5FK.js +48 -0
  9. package/dist/chunk-CCG4F5FK.js.map +1 -0
  10. package/dist/chunk-Z6VXPONT.js +1493 -0
  11. package/dist/chunk-Z6VXPONT.js.map +1 -0
  12. package/dist/config.cjs +233 -0
  13. package/dist/config.cjs.map +1 -0
  14. package/dist/config.d.cts +104 -0
  15. package/dist/config.d.ts +104 -0
  16. package/dist/config.js +228 -0
  17. package/dist/config.js.map +1 -0
  18. package/dist/credits-C3Fe3TO0.d.cts +315 -0
  19. package/dist/credits-C3Fe3TO0.d.ts +315 -0
  20. package/dist/index.cjs +1560 -0
  21. package/dist/index.cjs.map +1 -0
  22. package/dist/index.d.cts +2379 -0
  23. package/dist/index.d.ts +2379 -0
  24. package/dist/index.js +4 -0
  25. package/dist/index.js.map +1 -0
  26. package/dist/ingestion.cjs +259 -0
  27. package/dist/ingestion.cjs.map +1 -0
  28. package/dist/ingestion.d.cts +182 -0
  29. package/dist/ingestion.d.ts +182 -0
  30. package/dist/ingestion.js +252 -0
  31. package/dist/ingestion.js.map +1 -0
  32. package/dist/react.cjs +360 -0
  33. package/dist/react.cjs.map +1 -0
  34. package/dist/react.d.cts +71 -0
  35. package/dist/react.d.ts +71 -0
  36. package/dist/react.js +153 -0
  37. package/dist/react.js.map +1 -0
  38. package/dist/server.cjs +98 -0
  39. package/dist/server.cjs.map +1 -0
  40. package/dist/server.d.cts +54 -0
  41. package/dist/server.d.ts +54 -0
  42. package/dist/server.js +96 -0
  43. package/dist/server.js.map +1 -0
  44. package/dist/status.cjs +60 -0
  45. package/dist/status.cjs.map +1 -0
  46. package/dist/status.d.cts +31 -0
  47. package/dist/status.d.ts +31 -0
  48. package/dist/status.js +3 -0
  49. package/dist/status.js.map +1 -0
  50. package/dist/webhooks.cjs +157 -0
  51. package/dist/webhooks.cjs.map +1 -0
  52. package/dist/webhooks.d.cts +391 -0
  53. package/dist/webhooks.d.ts +391 -0
  54. package/dist/webhooks.js +143 -0
  55. package/dist/webhooks.js.map +1 -0
  56. package/package.json +169 -0
@@ -0,0 +1,31 @@
1
+ export { a as CHARGE_STATUSES, C as ChargeStatus, b as INVOICE_STATUSES, I as InvoiceStatus, c as PAYMENT_METHOD_STATUSES, P as PaymentMethodStatus, d as REFUND_STATUSES, R as RefundStatus, e as WEBHOOK_DELIVERY_STATUSES, W as WebhookDeliveryStatus } from './billing-status-BZQN_gm7.js';
2
+
3
+ /**
4
+ * The subscription status vocabulary + access predicate, mirrored from @billow/core
5
+ * (`enums.ts` + `billing/subscription-state.ts`) so SDK consumers can type and branch on
6
+ * billow's own model instead of hand-maintaining a union that drifts (a real bug: an app
7
+ * copy once carried a non-existent `ended` status - that string is a webhook event type,
8
+ * not a subscription status).
9
+ *
10
+ * Mirrored, not imported: @billow/core is a server package the published SDK cannot depend
11
+ * on (the same reason @billow/contracts mirrors core's pure logic). The parity test
12
+ * `subscription-status.test.ts` imports @billow/core and fails CI on any drift.
13
+ */
14
+ /** The 8 canonical subscription statuses, in lifecycle order. */
15
+ declare const SUBSCRIPTION_STATUSES: readonly ["incomplete", "incomplete_expired", "trialing", "active", "past_due", "paused", "canceled", "unpaid"];
16
+ type SubscriptionStatus = (typeof SUBSCRIPTION_STATUSES)[number];
17
+ /**
18
+ * Statuses that currently grant access (a live commitment): `trialing`, `active`, and
19
+ * `past_due` (access is retained through dunning). Note `paused` does NOT grant access.
20
+ */
21
+ declare const ACTIVE_SUBSCRIPTION_STATUSES: readonly SubscriptionStatus[];
22
+ /** Statuses a subscription can never leave: `incomplete_expired` and `canceled`. */
23
+ declare const TERMINAL_SUBSCRIPTION_STATUSES: readonly SubscriptionStatus[];
24
+ /** Statuses in which a subscription never activated (no access was ever granted). */
25
+ declare const NEVER_ACTIVATED_SUBSCRIPTION_STATUSES: readonly SubscriptionStatus[];
26
+ /** Whether access should currently be granted for a subscription in this state. */
27
+ declare function grantsAccess(status: SubscriptionStatus): boolean;
28
+ /** Whether this is a terminal status the subscription can never leave. */
29
+ declare function isTerminal(status: SubscriptionStatus): boolean;
30
+
31
+ export { ACTIVE_SUBSCRIPTION_STATUSES, NEVER_ACTIVATED_SUBSCRIPTION_STATUSES, SUBSCRIPTION_STATUSES, type SubscriptionStatus, TERMINAL_SUBSCRIPTION_STATUSES, grantsAccess, isTerminal };
package/dist/status.js ADDED
@@ -0,0 +1,3 @@
1
+ export { ACTIVE_SUBSCRIPTION_STATUSES, CHARGE_STATUSES, INVOICE_STATUSES, NEVER_ACTIVATED_SUBSCRIPTION_STATUSES, PAYMENT_METHOD_STATUSES, REFUND_STATUSES, SUBSCRIPTION_STATUSES, TERMINAL_SUBSCRIPTION_STATUSES, WEBHOOK_DELIVERY_STATUSES, grantsAccess, isTerminal } from './chunk-CCG4F5FK.js';
2
+ //# sourceMappingURL=status.js.map
3
+ //# sourceMappingURL=status.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"status.js"}
@@ -0,0 +1,157 @@
1
+ 'use strict';
2
+
3
+ // src/webhooks.ts
4
+ var WEBHOOK_EVENT_TYPES = [
5
+ "charge.succeeded",
6
+ "charge.failed",
7
+ "charge.refunded",
8
+ "charge.disputed",
9
+ "charge.dispute_resolved",
10
+ "invoice.paid",
11
+ "invoice.payment_failed",
12
+ "subscription.trial_started",
13
+ "subscription.activated",
14
+ "subscription.activation_failed",
15
+ "subscription.renewed",
16
+ "subscription.past_due",
17
+ "subscription.payment_failed",
18
+ "subscription.requires_payment_method",
19
+ "subscription.unpaid",
20
+ "subscription.paused",
21
+ "subscription.resumed",
22
+ "subscription.updated",
23
+ "subscription.cancel_scheduled",
24
+ "subscription.cancel_resumed",
25
+ "subscription.downgrade_scheduled",
26
+ "subscription.downgrade_canceled",
27
+ "subscription.canceled",
28
+ "subscription.ended",
29
+ "entitlement.granted",
30
+ "entitlement.reset",
31
+ "usage.threshold_reached",
32
+ "usage.alert",
33
+ "usage.cap_reached",
34
+ "credit_balance.threshold_crossed",
35
+ "credit_grant.created",
36
+ "credit_grant.expired",
37
+ "credit_reservation.expired",
38
+ "credit_top_up.succeeded",
39
+ "credit_top_up.failed",
40
+ "credit_top_up.refunded",
41
+ "credit_top_up.unfulfilled"
42
+ ];
43
+ function eventTypesWithPrefix(prefix) {
44
+ return WEBHOOK_EVENT_TYPES.filter(
45
+ (type) => type.startsWith(prefix)
46
+ );
47
+ }
48
+ var CHARGE_EVENT_TYPES = eventTypesWithPrefix("charge.");
49
+ var INVOICE_EVENT_TYPES = eventTypesWithPrefix("invoice.");
50
+ var SUBSCRIPTION_EVENT_TYPES = eventTypesWithPrefix("subscription.");
51
+ var ENTITLEMENT_EVENT_TYPES = eventTypesWithPrefix("entitlement.");
52
+ var USAGE_EVENT_TYPES = eventTypesWithPrefix("usage.");
53
+ var CREDIT_EVENT_TYPES = eventTypesWithPrefix("credit_");
54
+ function isSubscriptionEvent(type) {
55
+ return type.startsWith("subscription.");
56
+ }
57
+ var WebhookVerificationError = class extends Error {
58
+ constructor(message) {
59
+ super(message);
60
+ this.name = "WebhookVerificationError";
61
+ }
62
+ };
63
+ var DEFAULT_TOLERANCE_SECONDS = 300;
64
+ var encoder = new TextEncoder();
65
+ function parseHeader(header) {
66
+ let timestamp = Number.NaN;
67
+ const signatures = [];
68
+ for (const part of header.split(",")) {
69
+ const eq = part.indexOf("=");
70
+ if (eq === -1) continue;
71
+ const key = part.slice(0, eq).trim();
72
+ const value = part.slice(eq + 1).trim();
73
+ if (key === "t") timestamp = Number(value);
74
+ else if (key === "v1") signatures.push(value);
75
+ }
76
+ if (!Number.isFinite(timestamp) || signatures.length === 0) return null;
77
+ return { timestamp, signatures };
78
+ }
79
+ async function hmacHex(secret, payload) {
80
+ const key = await crypto.subtle.importKey(
81
+ "raw",
82
+ encoder.encode(secret),
83
+ { name: "HMAC", hash: "SHA-256" },
84
+ false,
85
+ ["sign"]
86
+ );
87
+ const sig = await crypto.subtle.sign("HMAC", key, encoder.encode(payload));
88
+ return Array.from(new Uint8Array(sig), (b) => b.toString(16).padStart(2, "0")).join("");
89
+ }
90
+ function timingSafeEqual(a, b) {
91
+ if (a.length !== b.length) return false;
92
+ let mismatch = 0;
93
+ for (let i = 0; i < a.length; i++) mismatch |= a.charCodeAt(i) ^ b.charCodeAt(i);
94
+ return mismatch === 0;
95
+ }
96
+ async function verifySignature(payload, header, secret, opts = {}) {
97
+ if (!header) return false;
98
+ const parsed = parseHeader(header);
99
+ if (!parsed) return false;
100
+ const tolerance = opts.toleranceSeconds ?? DEFAULT_TOLERANCE_SECONDS;
101
+ const now = Math.floor(Date.now() / 1e3);
102
+ if (Math.abs(now - parsed.timestamp) > tolerance) return false;
103
+ const expected = await hmacHex(secret, `${parsed.timestamp}.${payload}`);
104
+ return parsed.signatures.some((sig) => timingSafeEqual(sig, expected));
105
+ }
106
+ async function signWebhook(payload, secret, opts = {}) {
107
+ const timestamp = opts.timestamp ?? Math.floor(Date.now() / 1e3);
108
+ const signature = await hmacHex(secret, `${timestamp}.${payload}`);
109
+ return `t=${timestamp},v1=${signature}`;
110
+ }
111
+ async function constructEvent(payload, header, secret, opts = {}) {
112
+ if (!await verifySignature(payload, header, secret, opts)) {
113
+ throw new WebhookVerificationError("billow webhook signature verification failed");
114
+ }
115
+ let parsed;
116
+ try {
117
+ parsed = JSON.parse(payload);
118
+ } catch {
119
+ throw new WebhookVerificationError("billow webhook payload is not valid JSON");
120
+ }
121
+ if (!isWebhookEvent(parsed)) {
122
+ throw new WebhookVerificationError("billow webhook payload is not a valid event envelope");
123
+ }
124
+ return parsed;
125
+ }
126
+ function createWebhookDispatcher(config) {
127
+ const { secret, handlers, toleranceSeconds } = config;
128
+ const opts = toleranceSeconds === void 0 ? void 0 : { toleranceSeconds };
129
+ return async (payload, signatureHeader) => {
130
+ const event = await constructEvent(payload, signatureHeader, secret, opts);
131
+ const own = Object.hasOwn(handlers, event.type) ? handlers[event.type] : void 0;
132
+ const handler = own ?? handlers.onEvent;
133
+ if (handler) await handler(event);
134
+ return event;
135
+ };
136
+ }
137
+ function isWebhookEvent(value) {
138
+ if (typeof value !== "object" || value === null) return false;
139
+ const e = value;
140
+ return typeof e.id === "string" && typeof e.version === "number" && typeof e.type === "string" && typeof e.createdAt === "string" && typeof e.data === "object" && e.data !== null;
141
+ }
142
+
143
+ exports.CHARGE_EVENT_TYPES = CHARGE_EVENT_TYPES;
144
+ exports.CREDIT_EVENT_TYPES = CREDIT_EVENT_TYPES;
145
+ exports.ENTITLEMENT_EVENT_TYPES = ENTITLEMENT_EVENT_TYPES;
146
+ exports.INVOICE_EVENT_TYPES = INVOICE_EVENT_TYPES;
147
+ exports.SUBSCRIPTION_EVENT_TYPES = SUBSCRIPTION_EVENT_TYPES;
148
+ exports.USAGE_EVENT_TYPES = USAGE_EVENT_TYPES;
149
+ exports.WEBHOOK_EVENT_TYPES = WEBHOOK_EVENT_TYPES;
150
+ exports.WebhookVerificationError = WebhookVerificationError;
151
+ exports.constructEvent = constructEvent;
152
+ exports.createWebhookDispatcher = createWebhookDispatcher;
153
+ exports.isSubscriptionEvent = isSubscriptionEvent;
154
+ exports.signWebhook = signWebhook;
155
+ exports.verifySignature = verifySignature;
156
+ //# sourceMappingURL=webhooks.cjs.map
157
+ //# sourceMappingURL=webhooks.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/webhooks.ts"],"names":[],"mappings":";;;AAyBO,IAAM,mBAAA,GAAsB;AAAA,EACjC,kBAAA;AAAA,EACA,eAAA;AAAA,EACA,iBAAA;AAAA,EACA,iBAAA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7E,EAAA,OAAO,OAAO,SAAS,eAAA,KAAoB;AACzC,IAAA,MAAM,QAAQ,MAAM,cAAA,CAAe,OAAA,EAAS,eAAA,EAAiB,QAAQ,IAAI,CAAA;AAUzE,IAAA,MAAM,GAAA,GAAM,MAAA,CAAO,MAAA,CAAO,QAAA,EAAU,KAAA,CAAM,IAAI,CAAA,GACzC,QAAA,CAAS,KAAA,CAAM,IAAI,CAAA,GACpB,MAAA;AACJ,IAAA,MAAM,OAAA,GAAU,OAAO,QAAA,CAAS,OAAA;AAChC,IAAA,IAAI,OAAA,EAAS,MAAM,OAAA,CAAQ,KAAK,CAAA;AAChC,IAAA,OAAO,KAAA;AAAA,EACT,CAAA;AACF;AAEA,SAAS,eAAe,KAAA,EAAuC;AAC7D,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,MAAM,OAAO,KAAA;AACxD,EAAA,MAAM,CAAA,GAAI,KAAA;AAOV,EAAA,OACE,OAAO,EAAE,EAAA,KAAO,QAAA,IAChB,OAAO,CAAA,CAAE,OAAA,KAAY,YACrB,OAAO,CAAA,CAAE,SAAS,QAAA,IAClB,OAAO,EAAE,SAAA,KAAc,QAAA,IACvB,OAAO,CAAA,CAAE,IAAA,KAAS,QAAA,IAClB,CAAA,CAAE,IAAA,KAAS,IAAA;AAEf","file":"webhooks.cjs","sourcesContent":["/**\n * Verify and parse billow webhook deliveries.\n *\n * billow signs each delivery with HMAC-SHA256 over `\"<timestamp>.<rawBody>\"` and\n * sends it in the `billow-signature` header as `t=<unix-seconds>,v1=<hex>`. The\n * timestamp lets you reject replays outside a freshness window.\n *\n * Verification is async and uses the Web Crypto API (`globalThis.crypto.subtle`),\n * so the same code runs in Node 20+, edge runtimes, Cloudflare Workers, Deno, and\n * Bun — it never imports `node:crypto`.\n *\n * import { constructEvent } from \"@usebillow/sdk/webhooks\";\n *\n * const event = await constructEvent(rawBody, req.headers[\"billow-signature\"], secret);\n * switch (event.type) {\n * case \"invoice.paid\": // …\n * }\n */\n\nimport type { CreditGrantKind, CreditThresholdLevel } from \"./types/credits\";\n\n/**\n * Every event type billow emits, in contract order. Mirrors `@billow/core`'s\n * EVENT_TYPES — exported as a runtime array so UIs can render a subscription picker.\n */\nexport const WEBHOOK_EVENT_TYPES = [\n \"charge.succeeded\",\n \"charge.failed\",\n \"charge.refunded\",\n \"charge.disputed\",\n \"charge.dispute_resolved\",\n \"invoice.paid\",\n \"invoice.payment_failed\",\n \"subscription.trial_started\",\n \"subscription.activated\",\n \"subscription.activation_failed\",\n \"subscription.renewed\",\n \"subscription.past_due\",\n \"subscription.payment_failed\",\n \"subscription.requires_payment_method\",\n \"subscription.unpaid\",\n \"subscription.paused\",\n \"subscription.resumed\",\n \"subscription.updated\",\n \"subscription.cancel_scheduled\",\n \"subscription.cancel_resumed\",\n \"subscription.downgrade_scheduled\",\n \"subscription.downgrade_canceled\",\n \"subscription.canceled\",\n \"subscription.ended\",\n \"entitlement.granted\",\n \"entitlement.reset\",\n \"usage.threshold_reached\",\n \"usage.alert\",\n \"usage.cap_reached\",\n \"credit_balance.threshold_crossed\",\n \"credit_grant.created\",\n \"credit_grant.expired\",\n \"credit_reservation.expired\",\n \"credit_top_up.succeeded\",\n \"credit_top_up.failed\",\n \"credit_top_up.refunded\",\n \"credit_top_up.unfulfilled\",\n] as const;\n\n/** A valid billow event type (the compile-time freeze derived from the array above). */\nexport type BillowEventType = (typeof WEBHOOK_EVENT_TYPES)[number];\n\n/** The `charge.*` subset of {@link BillowEventType}. */\nexport type ChargeEventType = Extract<BillowEventType, `charge.${string}`>;\n/** The `invoice.*` subset of {@link BillowEventType}. */\nexport type InvoiceEventType = Extract<BillowEventType, `invoice.${string}`>;\n/** The `subscription.*` subset of {@link BillowEventType} - the events that change a subscription. */\nexport type SubscriptionEventType = Extract<BillowEventType, `subscription.${string}`>;\n/** The `entitlement.*` subset of {@link BillowEventType}. */\nexport type EntitlementEventType = Extract<BillowEventType, `entitlement.${string}`>;\n/** The `usage.*` subset of {@link BillowEventType}. */\nexport type UsageEventType = Extract<BillowEventType, `usage.${string}`>;\n/** The prepaid credits subset of {@link BillowEventType} (`credit_balance.*`, `credit_grant.*`, ...). */\nexport type CreditEventType = Extract<BillowEventType, `credit_${string}`>;\n\n/** The subset of {@link WEBHOOK_EVENT_TYPES} sharing `prefix`, as a runtime array (order preserved). */\nfunction eventTypesWithPrefix<P extends string>(\n prefix: P,\n): readonly Extract<BillowEventType, `${P}${string}`>[] {\n return WEBHOOK_EVENT_TYPES.filter((type): type is Extract<BillowEventType, `${P}${string}`> =>\n type.startsWith(prefix),\n );\n}\n\n/** The `charge.*` event types, as a runtime array (for pickers / exhaustive routing). */\nexport const CHARGE_EVENT_TYPES: readonly ChargeEventType[] = eventTypesWithPrefix(\"charge.\");\n/** The `invoice.*` event types, as a runtime array. */\nexport const INVOICE_EVENT_TYPES: readonly InvoiceEventType[] = eventTypesWithPrefix(\"invoice.\");\n/**\n * The subscription lifecycle event types - the `subscription.*` subset of\n * {@link WEBHOOK_EVENT_TYPES}, as a runtime array. Use it (or {@link isSubscriptionEvent})\n * to select the events that affect a subscription mirror without a brittle string match.\n */\nexport const SUBSCRIPTION_EVENT_TYPES: readonly SubscriptionEventType[] =\n eventTypesWithPrefix(\"subscription.\");\n/** The `entitlement.*` event types, as a runtime array. */\nexport const ENTITLEMENT_EVENT_TYPES: readonly EntitlementEventType[] =\n eventTypesWithPrefix(\"entitlement.\");\n/** The `usage.*` event types, as a runtime array. */\nexport const USAGE_EVENT_TYPES: readonly UsageEventType[] = eventTypesWithPrefix(\"usage.\");\n/** The prepaid credits event types, as a runtime array. */\nexport const CREDIT_EVENT_TYPES: readonly CreditEventType[] = eventTypesWithPrefix(\"credit_\");\n\n/** Whether `type` is a subscription lifecycle event (`subscription.*`); narrows the type. */\nexport function isSubscriptionEvent(type: string): type is SubscriptionEventType {\n return type.startsWith(\"subscription.\");\n}\n\n/**\n * The fields every webhook envelope carries. Each {@link WebhookEvent} variant intersects\n * this with its own `type` + payload-typed `data`.\n */\nexport interface WebhookEventEnvelope {\n /** Stable event id — your idempotency key (delivery is at-least-once). */\n id: string;\n /** Envelope schema version. */\n version: number;\n /** ISO-8601 timestamp of when the event was recorded. */\n createdAt: string;\n}\n\n// --- Per-event-group payloads -------------------------------------------------------------\n// Shapes mirror what the server emits (packages/server/src/services: charges.ts, billing.ts,\n// renewal/*, subscriptions/*, entitlements/*). Grouped where a group's emitters are uniform;\n// `usage.*` is split per event because its emitters diverge. `customerExternalId` is added to\n// every customer-scoped payload by the server's outbox emitter (events.ts).\n\n/** `charge.succeeded` / `charge.failed`. */\nexport interface ChargeEventData {\n chargeId: string;\n /**\n * `false` on a `charge.failed` that closed a checkout its customer abandoned long before: no\n * \"payment failed\" email was sent to the customer. Absent otherwise.\n */\n notifyCustomer?: false;\n}\n/** `charge.refunded`, emitted once for each succeeded refund transition. */\nexport interface ChargeRefundedEventData {\n chargeId: string;\n refundId: string;\n amount: number;\n cumulativeAmount: number;\n currency: string;\n}\n/** Stable dispute facts shared by the opened and resolved events. */\nexport interface ChargeDisputeEventData {\n chargeId: string;\n disputeId: string;\n amount: number;\n currency: string;\n reason: string | null;\n state: \"open\" | \"won\" | \"lost\";\n}\n/** `invoice.paid` / `invoice.payment_failed`. */\nexport interface InvoiceEventData {\n invoiceId: string;\n chargeId: string;\n /**\n * `false` on an `invoice.payment_failed` that closed a checkout its customer abandoned long\n * before: no \"payment failed\" email was sent to the customer. Absent otherwise.\n */\n notifyCustomer?: false;\n}\n/** Any `subscription.*` lifecycle event. */\nexport interface SubscriptionEventData {\n subscriptionId: string;\n customerId: string;\n customerExternalId: string;\n /** The subscription's plan — so a consumer knows which product the event is about. */\n productId: string;\n productSlug: string;\n /** The product's metadata map (Stripe-style); `{}` when the plan carries none. */\n productMetadata: Record<string, string>;\n /** Set on dunning events that reference the unpaid invoice (`unpaid`, `requires_payment_method`). */\n invoiceId?: string;\n /** Set on lifecycle-ending events (`ended`, downgrade-driven `updated`). */\n reason?: string;\n /** Present when a downgrade is scheduled; null when that schedule is cleared. */\n scheduledChange?: {\n productVersionId: string;\n productId: string;\n productSlug: string;\n productName: string;\n effectiveAt: string | null;\n } | null;\n}\n/** `entitlement.granted` / `entitlement.reset`. */\nexport interface EntitlementEventData {\n subscriptionId: string;\n customerId: string;\n customerExternalId: string;\n featureId: string;\n /** Remaining allowance; `null` when the feature is unlimited. */\n balance: number | null;\n /** Whether the feature grants unlimited usage. */\n unlimited: boolean;\n}\n/** Fields shared by every `usage.*` event. */\nexport interface UsageEventBase {\n subscriptionId: string;\n customerId: string;\n customerExternalId: string;\n /** Feature slug. */\n feature: string;\n featureName: string;\n /** Aggregate usage after this step. */\n used: number;\n /** Included allowance; `null` when unlimited. */\n allowance: number | null;\n /** Remaining allowance; `null` when unlimited. */\n balance: number | null;\n}\n/** `usage.threshold_reached` — a built-in usage threshold was crossed. */\nexport interface UsageThresholdReachedData extends UsageEventBase {\n featureId: string;\n /** The threshold crossed (currently only the included allowance being exhausted). */\n level: \"exhausted\";\n}\n/** `usage.alert` — a configured usage alert fired. */\nexport interface UsageAlertData extends UsageEventBase {\n metric: string;\n threshold: number;\n recurring: boolean;\n notifyCustomer: boolean;\n}\n/** `usage.cap_reached` — a configured spend/usage cap was reached. */\nexport interface UsageCapReachedData extends UsageEventBase {\n metric: string;\n cap: number;\n capAt: number;\n}\n\n// Prepaid credits: every credit quantity is a decimal string of microcredits, never a number.\n// Payloads carry ids, codes and quantities, never a grant's, reservation's or top-up's reason or\n// metadata.\n\n/** Fields shared by every prepaid credits event. */\nexport interface CreditEventBase {\n customerId: string;\n customerExternalId: string;\n}\n/**\n * `credit_balance.threshold_crossed` - the balance moved to another level, in either direction\n * (raise a low-balance banner, or clear it). `exhausted` when nothing is spendable; otherwise\n * `critical` / `low` at or below the percentages of `thresholds.reference`, else `normal`.\n */\nexport interface CreditThresholdCrossedData extends CreditEventBase {\n level: CreditThresholdLevel;\n previousLevel: CreditThresholdLevel;\n /** The balance the level was judged on, as of `asOf`; re-read the balance for truth. */\n balance: { spendable: string; held: string; asOf: string };\n thresholds: { lowPercent: number; criticalPercent: number; reference: string | null };\n}\n/** `credit_grant.created` - credits were granted. */\nexport interface CreditGrantCreatedData extends CreditEventBase {\n grantId: string;\n kind: CreditGrantKind;\n amount: string;\n expiresAt: string | null;\n eligibility: string[] | null;\n topUpId: string | null;\n}\n/**\n * `credit_grant.expired` - one expiry took `expired` credits off a grant: its unheld credits when\n * it expired, or a held part that came back to it afterwards (one more event each).\n */\nexport interface CreditGrantExpiredData extends CreditEventBase {\n grantId: string;\n kind: CreditGrantKind;\n expiresAt: string | null;\n expired: string;\n /** The `expire` ledger transaction. */\n transactionId: string;\n}\n/** `credit_reservation.expired` - a hold passed its expiry unsettled and was released. */\nexport interface CreditReservationExpiredData extends CreditEventBase {\n reservationId: string;\n operationKey: string;\n category: string;\n amount: string;\n expiresAt: string;\n}\n/** What every `credit_top_up.*` event says about the purchase and its payment. */\nexport interface CreditTopUpEventBase extends CreditEventBase {\n topUpId: string;\n packId: string;\n chargeId: string;\n /** What the payment collects, in minor units of `currency`. */\n amount: number;\n currency: string;\n /** The terms bought. */\n credits: string;\n bonusCredits: string;\n}\n/** `credit_top_up.succeeded` - the payment succeeded and its credits (and any bonus) were granted. */\nexport interface CreditTopUpSucceededData extends CreditTopUpEventBase {\n purchasedGrantId: string | null;\n bonusGrantId: string | null;\n}\n/**\n * `credit_top_up.failed` - the payment failed. A later payment on the same checkout can still\n * succeed it: `credit_top_up.succeeded` may follow for the same top-up.\n */\nexport type CreditTopUpFailedData = CreditTopUpEventBase;\n/** `credit_top_up.unfulfilled` - paid after the customer was erased: nothing granted, refund it. */\nexport type CreditTopUpUnfulfilledData = CreditTopUpEventBase;\n/**\n * `credit_top_up.refunded` - a refund or lost chargeback revoked the top-up's credits in\n * proportion to the money returned.\n */\nexport interface CreditTopUpRefundedData extends CreditTopUpEventBase {\n cause: \"refund\" | \"chargeback\";\n /** Money returned so far (refunds plus lost disputes, at most what was charged), minor units. */\n amountReturned: number;\n /** Microcredits this refund or chargeback revoked. */\n revokedNow: string;\n /** Microcredits revoked so far in all. */\n revoked: string;\n /** Of them, what the customer had already spent and nothing has paid back. */\n shortfall: string;\n}\n\n/**\n * The verified webhook envelope billow POSTs to your endpoint — a discriminated union on\n * {@link WebhookEvent.type}. `switch` (or a {@link WebhookHandlers} map) on `type` and `data`\n * narrows to the exact payload for that event.\n *\n * switch (event.type) {\n * case \"invoice.paid\": settle(event.data.invoiceId); break; // InvoiceEventData\n * case \"subscription.canceled\": revoke(event.data.customerExternalId); break;\n * }\n */\nexport type WebhookEventDataMap = {\n [K in \"charge.succeeded\" | \"charge.failed\"]: ChargeEventData;\n} & {\n \"charge.refunded\": ChargeRefundedEventData;\n} & {\n [K in \"charge.disputed\" | \"charge.dispute_resolved\"]: ChargeDisputeEventData;\n} & {\n [K in InvoiceEventType]: InvoiceEventData;\n} & {\n [K in SubscriptionEventType]: SubscriptionEventData;\n} & {\n [K in EntitlementEventType]: EntitlementEventData;\n} & {\n \"usage.threshold_reached\": UsageThresholdReachedData;\n \"usage.alert\": UsageAlertData;\n \"usage.cap_reached\": UsageCapReachedData;\n} & {\n \"credit_balance.threshold_crossed\": CreditThresholdCrossedData;\n \"credit_grant.created\": CreditGrantCreatedData;\n \"credit_grant.expired\": CreditGrantExpiredData;\n \"credit_reservation.expired\": CreditReservationExpiredData;\n \"credit_top_up.succeeded\": CreditTopUpSucceededData;\n \"credit_top_up.failed\": CreditTopUpFailedData;\n \"credit_top_up.refunded\": CreditTopUpRefundedData;\n \"credit_top_up.unfulfilled\": CreditTopUpUnfulfilledData;\n};\n\n/** One distributive union member per event literal, derived from the payload map. */\nexport type WebhookEvent = {\n [K in BillowEventType]: WebhookEventEnvelope & { type: K; data: WebhookEventDataMap[K] };\n}[BillowEventType];\n\nexport interface VerifyOptions {\n /**\n * Max age (seconds) of a delivery's signature timestamp before it's rejected as\n * a possible replay. Default 300 (5 minutes).\n */\n toleranceSeconds?: number;\n}\n\n/** Thrown by {@link constructEvent} when a delivery can't be trusted. */\nexport class WebhookVerificationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"WebhookVerificationError\";\n }\n}\n\nconst DEFAULT_TOLERANCE_SECONDS = 300;\nconst encoder = new TextEncoder();\n\ninterface ParsedHeader {\n timestamp: number;\n signatures: string[];\n}\n\n/** Parse `t=<unix>,v1=<hex>[,v1=<hex>…]` — multiple v1 supports key rotation. */\nfunction parseHeader(header: string): ParsedHeader | null {\n let timestamp = Number.NaN;\n const signatures: string[] = [];\n for (const part of header.split(\",\")) {\n const eq = part.indexOf(\"=\");\n if (eq === -1) continue;\n const key = part.slice(0, eq).trim();\n const value = part.slice(eq + 1).trim();\n if (key === \"t\") timestamp = Number(value);\n else if (key === \"v1\") signatures.push(value);\n }\n if (!Number.isFinite(timestamp) || signatures.length === 0) return null;\n return { timestamp, signatures };\n}\n\nasync function hmacHex(secret: string, payload: string): Promise<string> {\n const key = await crypto.subtle.importKey(\n \"raw\",\n encoder.encode(secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n const sig = await crypto.subtle.sign(\"HMAC\", key, encoder.encode(payload));\n return Array.from(new Uint8Array(sig), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/** Constant-time compare of two equal-length hex strings (no early exit). */\nfunction timingSafeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) return false;\n let mismatch = 0;\n for (let i = 0; i < a.length; i++) mismatch |= a.charCodeAt(i) ^ b.charCodeAt(i);\n return mismatch === 0;\n}\n\n/**\n * Return `true` if `header` is a valid signature for `payload` under `secret` and\n * within the freshness window. Never throws — use {@link constructEvent} when you\n * want the parsed event and a thrown error on failure. Pass the RAW request body.\n */\nexport async function verifySignature(\n payload: string,\n header: string | null | undefined,\n secret: string,\n opts: VerifyOptions = {},\n): Promise<boolean> {\n if (!header) return false;\n const parsed = parseHeader(header);\n if (!parsed) return false;\n\n const tolerance = opts.toleranceSeconds ?? DEFAULT_TOLERANCE_SECONDS;\n const now = Math.floor(Date.now() / 1000);\n if (Math.abs(now - parsed.timestamp) > tolerance) return false;\n\n const expected = await hmacHex(secret, `${parsed.timestamp}.${payload}`);\n return parsed.signatures.some((sig) => timingSafeEqual(sig, expected));\n}\n\n/**\n * Produce a valid `billow-signature` header for `payload` under `secret` - the inverse of\n * {@link verifySignature}. Use it to exercise your webhook endpoint in tests without\n * reverse-engineering the signing scheme. Pass the RAW body you will POST. `timestamp` (unix\n * seconds) defaults to now; pass a fixed value for a deterministic - or intentionally stale\n * (replay) - signature.\n *\n * const header = await signWebhook(rawBody, endpointSecret);\n * await fetch(url, { method: \"POST\", headers: { \"billow-signature\": header }, body: rawBody });\n */\nexport async function signWebhook(\n payload: string,\n secret: string,\n opts: { timestamp?: number } = {},\n): Promise<string> {\n const timestamp = opts.timestamp ?? Math.floor(Date.now() / 1000);\n const signature = await hmacHex(secret, `${timestamp}.${payload}`);\n return `t=${timestamp},v1=${signature}`;\n}\n\n/**\n * Verify `payload` against the `billow-signature` header and return the parsed,\n * typed {@link WebhookEvent}. Throws {@link WebhookVerificationError} if the\n * signature is invalid, the timestamp is outside the freshness window, or the body\n * isn't a billow envelope. Always pass the RAW request body — a re-serialized\n * parsed body will not match.\n */\nexport async function constructEvent(\n payload: string,\n header: string | null | undefined,\n secret: string,\n opts: VerifyOptions = {},\n): Promise<WebhookEvent> {\n if (!(await verifySignature(payload, header, secret, opts))) {\n throw new WebhookVerificationError(\"billow webhook signature verification failed\");\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(payload);\n } catch {\n throw new WebhookVerificationError(\"billow webhook payload is not valid JSON\");\n }\n if (!isWebhookEvent(parsed)) {\n throw new WebhookVerificationError(\"billow webhook payload is not a valid event envelope\");\n }\n return parsed;\n}\n\n/** A handler for one verified webhook event. May be async; a throw propagates to the caller. */\nexport type WebhookHandler = (event: WebhookEvent) => void | Promise<void>;\n\n/**\n * A map of per-event-type handlers plus an optional `onEvent` fallback. Each handler receives\n * the event NARROWED to its type, so `data` is the exact payload for that event\n * (e.g. `\"invoice.paid\": (e) => settle(e.data.invoiceId)`). Keyed by the literal event type so\n * it stays in lock-step with the contract — a new event type is dispatchable with no parallel\n * `onFooBar` name registry to keep in sync.\n */\nexport type WebhookHandlers = {\n [K in BillowEventType]?: (event: Extract<WebhookEvent, { type: K }>) => void | Promise<void>;\n} & {\n /** Called for any event that has no specific handler (receives the full union). */\n onEvent?: WebhookHandler;\n};\n\n/**\n * Build a reusable dispatcher bound to your endpoint secret + handlers: it verifies a\n * delivery (via {@link constructEvent}) then routes the typed event to the matching\n * handler, falling back to `onEvent`. Returns the verified event so the caller can log\n * or ack it. Throws {@link WebhookVerificationError} on an untrusted delivery (return a\n * 4xx) and propagates any error a handler throws (return a 5xx so billow retries).\n * Pass the RAW request body — a re-serialized parsed body won't match the signature.\n *\n * const dispatch = createWebhookDispatcher({\n * secret: process.env.BILLOW_WEBHOOK_SECRET,\n * handlers: {\n * \"invoice.paid\": (e) => fulfil(e.data.invoiceId),\n * \"subscription.canceled\": (e) => revoke(e.data),\n * onEvent: (e) => log(e.type),\n * },\n * });\n * // per request:\n * const event = await dispatch(rawBody, req.headers[\"billow-signature\"]);\n */\nexport function createWebhookDispatcher(config: {\n secret: string;\n handlers: WebhookHandlers;\n toleranceSeconds?: number;\n}): (payload: string, signatureHeader: string | null | undefined) => Promise<WebhookEvent> {\n const { secret, handlers, toleranceSeconds } = config;\n const opts = toleranceSeconds === undefined ? undefined : { toleranceSeconds };\n return async (payload, signatureHeader) => {\n const event = await constructEvent(payload, signatureHeader, secret, opts);\n // Own-property lookup, NOT `handlers[event.type]` directly: `event.type` is only\n // runtime-typed as a string, so a value colliding with an inherited key\n // (\"toString\"/\"constructor\"/\"__proto__\") would otherwise resolve to a prototype\n // method and be invoked instead of routing to `onEvent`. (Not reachable via a\n // trusted delivery — the type is HMAC-verified above and billow only emits fixed\n // event types — but the fallback contract must hold for any signature-valid type.)\n // The looked-up handler expects only its own narrowed variant; cast it to accept the full\n // union so we can invoke it with `event` — safe because the handler registered under key\n // `event.type` only ever receives the matching variant at runtime.\n const own = Object.hasOwn(handlers, event.type)\n ? (handlers[event.type] as WebhookHandler | undefined)\n : undefined;\n const handler = own ?? handlers.onEvent;\n if (handler) await handler(event);\n return event;\n };\n}\n\nfunction isWebhookEvent(value: unknown): value is WebhookEvent {\n if (typeof value !== \"object\" || value === null) return false;\n const e = value as {\n id?: unknown;\n version?: unknown;\n type?: unknown;\n createdAt?: unknown;\n data?: unknown;\n };\n return (\n typeof e.id === \"string\" &&\n typeof e.version === \"number\" &&\n typeof e.type === \"string\" &&\n typeof e.createdAt === \"string\" &&\n typeof e.data === \"object\" &&\n e.data !== null\n );\n}\n"]}
@@ -0,0 +1,391 @@
1
+ import { C as CreditGrantKind, a as CreditThresholdLevel } from './credits-C3Fe3TO0.cjs';
2
+
3
+ /**
4
+ * Verify and parse billow webhook deliveries.
5
+ *
6
+ * billow signs each delivery with HMAC-SHA256 over `"<timestamp>.<rawBody>"` and
7
+ * sends it in the `billow-signature` header as `t=<unix-seconds>,v1=<hex>`. The
8
+ * timestamp lets you reject replays outside a freshness window.
9
+ *
10
+ * Verification is async and uses the Web Crypto API (`globalThis.crypto.subtle`),
11
+ * so the same code runs in Node 20+, edge runtimes, Cloudflare Workers, Deno, and
12
+ * Bun — it never imports `node:crypto`.
13
+ *
14
+ * import { constructEvent } from "@usebillow/sdk/webhooks";
15
+ *
16
+ * const event = await constructEvent(rawBody, req.headers["billow-signature"], secret);
17
+ * switch (event.type) {
18
+ * case "invoice.paid": // …
19
+ * }
20
+ */
21
+
22
+ /**
23
+ * Every event type billow emits, in contract order. Mirrors `@billow/core`'s
24
+ * EVENT_TYPES — exported as a runtime array so UIs can render a subscription picker.
25
+ */
26
+ declare const WEBHOOK_EVENT_TYPES: readonly ["charge.succeeded", "charge.failed", "charge.refunded", "charge.disputed", "charge.dispute_resolved", "invoice.paid", "invoice.payment_failed", "subscription.trial_started", "subscription.activated", "subscription.activation_failed", "subscription.renewed", "subscription.past_due", "subscription.payment_failed", "subscription.requires_payment_method", "subscription.unpaid", "subscription.paused", "subscription.resumed", "subscription.updated", "subscription.cancel_scheduled", "subscription.cancel_resumed", "subscription.downgrade_scheduled", "subscription.downgrade_canceled", "subscription.canceled", "subscription.ended", "entitlement.granted", "entitlement.reset", "usage.threshold_reached", "usage.alert", "usage.cap_reached", "credit_balance.threshold_crossed", "credit_grant.created", "credit_grant.expired", "credit_reservation.expired", "credit_top_up.succeeded", "credit_top_up.failed", "credit_top_up.refunded", "credit_top_up.unfulfilled"];
27
+ /** A valid billow event type (the compile-time freeze derived from the array above). */
28
+ type BillowEventType = (typeof WEBHOOK_EVENT_TYPES)[number];
29
+ /** The `charge.*` subset of {@link BillowEventType}. */
30
+ type ChargeEventType = Extract<BillowEventType, `charge.${string}`>;
31
+ /** The `invoice.*` subset of {@link BillowEventType}. */
32
+ type InvoiceEventType = Extract<BillowEventType, `invoice.${string}`>;
33
+ /** The `subscription.*` subset of {@link BillowEventType} - the events that change a subscription. */
34
+ type SubscriptionEventType = Extract<BillowEventType, `subscription.${string}`>;
35
+ /** The `entitlement.*` subset of {@link BillowEventType}. */
36
+ type EntitlementEventType = Extract<BillowEventType, `entitlement.${string}`>;
37
+ /** The `usage.*` subset of {@link BillowEventType}. */
38
+ type UsageEventType = Extract<BillowEventType, `usage.${string}`>;
39
+ /** The prepaid credits subset of {@link BillowEventType} (`credit_balance.*`, `credit_grant.*`, ...). */
40
+ type CreditEventType = Extract<BillowEventType, `credit_${string}`>;
41
+ /** The `charge.*` event types, as a runtime array (for pickers / exhaustive routing). */
42
+ declare const CHARGE_EVENT_TYPES: readonly ChargeEventType[];
43
+ /** The `invoice.*` event types, as a runtime array. */
44
+ declare const INVOICE_EVENT_TYPES: readonly InvoiceEventType[];
45
+ /**
46
+ * The subscription lifecycle event types - the `subscription.*` subset of
47
+ * {@link WEBHOOK_EVENT_TYPES}, as a runtime array. Use it (or {@link isSubscriptionEvent})
48
+ * to select the events that affect a subscription mirror without a brittle string match.
49
+ */
50
+ declare const SUBSCRIPTION_EVENT_TYPES: readonly SubscriptionEventType[];
51
+ /** The `entitlement.*` event types, as a runtime array. */
52
+ declare const ENTITLEMENT_EVENT_TYPES: readonly EntitlementEventType[];
53
+ /** The `usage.*` event types, as a runtime array. */
54
+ declare const USAGE_EVENT_TYPES: readonly UsageEventType[];
55
+ /** The prepaid credits event types, as a runtime array. */
56
+ declare const CREDIT_EVENT_TYPES: readonly CreditEventType[];
57
+ /** Whether `type` is a subscription lifecycle event (`subscription.*`); narrows the type. */
58
+ declare function isSubscriptionEvent(type: string): type is SubscriptionEventType;
59
+ /**
60
+ * The fields every webhook envelope carries. Each {@link WebhookEvent} variant intersects
61
+ * this with its own `type` + payload-typed `data`.
62
+ */
63
+ interface WebhookEventEnvelope {
64
+ /** Stable event id — your idempotency key (delivery is at-least-once). */
65
+ id: string;
66
+ /** Envelope schema version. */
67
+ version: number;
68
+ /** ISO-8601 timestamp of when the event was recorded. */
69
+ createdAt: string;
70
+ }
71
+ /** `charge.succeeded` / `charge.failed`. */
72
+ interface ChargeEventData {
73
+ chargeId: string;
74
+ /**
75
+ * `false` on a `charge.failed` that closed a checkout its customer abandoned long before: no
76
+ * "payment failed" email was sent to the customer. Absent otherwise.
77
+ */
78
+ notifyCustomer?: false;
79
+ }
80
+ /** `charge.refunded`, emitted once for each succeeded refund transition. */
81
+ interface ChargeRefundedEventData {
82
+ chargeId: string;
83
+ refundId: string;
84
+ amount: number;
85
+ cumulativeAmount: number;
86
+ currency: string;
87
+ }
88
+ /** Stable dispute facts shared by the opened and resolved events. */
89
+ interface ChargeDisputeEventData {
90
+ chargeId: string;
91
+ disputeId: string;
92
+ amount: number;
93
+ currency: string;
94
+ reason: string | null;
95
+ state: "open" | "won" | "lost";
96
+ }
97
+ /** `invoice.paid` / `invoice.payment_failed`. */
98
+ interface InvoiceEventData {
99
+ invoiceId: string;
100
+ chargeId: string;
101
+ /**
102
+ * `false` on an `invoice.payment_failed` that closed a checkout its customer abandoned long
103
+ * before: no "payment failed" email was sent to the customer. Absent otherwise.
104
+ */
105
+ notifyCustomer?: false;
106
+ }
107
+ /** Any `subscription.*` lifecycle event. */
108
+ interface SubscriptionEventData {
109
+ subscriptionId: string;
110
+ customerId: string;
111
+ customerExternalId: string;
112
+ /** The subscription's plan — so a consumer knows which product the event is about. */
113
+ productId: string;
114
+ productSlug: string;
115
+ /** The product's metadata map (Stripe-style); `{}` when the plan carries none. */
116
+ productMetadata: Record<string, string>;
117
+ /** Set on dunning events that reference the unpaid invoice (`unpaid`, `requires_payment_method`). */
118
+ invoiceId?: string;
119
+ /** Set on lifecycle-ending events (`ended`, downgrade-driven `updated`). */
120
+ reason?: string;
121
+ /** Present when a downgrade is scheduled; null when that schedule is cleared. */
122
+ scheduledChange?: {
123
+ productVersionId: string;
124
+ productId: string;
125
+ productSlug: string;
126
+ productName: string;
127
+ effectiveAt: string | null;
128
+ } | null;
129
+ }
130
+ /** `entitlement.granted` / `entitlement.reset`. */
131
+ interface EntitlementEventData {
132
+ subscriptionId: string;
133
+ customerId: string;
134
+ customerExternalId: string;
135
+ featureId: string;
136
+ /** Remaining allowance; `null` when the feature is unlimited. */
137
+ balance: number | null;
138
+ /** Whether the feature grants unlimited usage. */
139
+ unlimited: boolean;
140
+ }
141
+ /** Fields shared by every `usage.*` event. */
142
+ interface UsageEventBase {
143
+ subscriptionId: string;
144
+ customerId: string;
145
+ customerExternalId: string;
146
+ /** Feature slug. */
147
+ feature: string;
148
+ featureName: string;
149
+ /** Aggregate usage after this step. */
150
+ used: number;
151
+ /** Included allowance; `null` when unlimited. */
152
+ allowance: number | null;
153
+ /** Remaining allowance; `null` when unlimited. */
154
+ balance: number | null;
155
+ }
156
+ /** `usage.threshold_reached` — a built-in usage threshold was crossed. */
157
+ interface UsageThresholdReachedData extends UsageEventBase {
158
+ featureId: string;
159
+ /** The threshold crossed (currently only the included allowance being exhausted). */
160
+ level: "exhausted";
161
+ }
162
+ /** `usage.alert` — a configured usage alert fired. */
163
+ interface UsageAlertData extends UsageEventBase {
164
+ metric: string;
165
+ threshold: number;
166
+ recurring: boolean;
167
+ notifyCustomer: boolean;
168
+ }
169
+ /** `usage.cap_reached` — a configured spend/usage cap was reached. */
170
+ interface UsageCapReachedData extends UsageEventBase {
171
+ metric: string;
172
+ cap: number;
173
+ capAt: number;
174
+ }
175
+ /** Fields shared by every prepaid credits event. */
176
+ interface CreditEventBase {
177
+ customerId: string;
178
+ customerExternalId: string;
179
+ }
180
+ /**
181
+ * `credit_balance.threshold_crossed` - the balance moved to another level, in either direction
182
+ * (raise a low-balance banner, or clear it). `exhausted` when nothing is spendable; otherwise
183
+ * `critical` / `low` at or below the percentages of `thresholds.reference`, else `normal`.
184
+ */
185
+ interface CreditThresholdCrossedData extends CreditEventBase {
186
+ level: CreditThresholdLevel;
187
+ previousLevel: CreditThresholdLevel;
188
+ /** The balance the level was judged on, as of `asOf`; re-read the balance for truth. */
189
+ balance: {
190
+ spendable: string;
191
+ held: string;
192
+ asOf: string;
193
+ };
194
+ thresholds: {
195
+ lowPercent: number;
196
+ criticalPercent: number;
197
+ reference: string | null;
198
+ };
199
+ }
200
+ /** `credit_grant.created` - credits were granted. */
201
+ interface CreditGrantCreatedData extends CreditEventBase {
202
+ grantId: string;
203
+ kind: CreditGrantKind;
204
+ amount: string;
205
+ expiresAt: string | null;
206
+ eligibility: string[] | null;
207
+ topUpId: string | null;
208
+ }
209
+ /**
210
+ * `credit_grant.expired` - one expiry took `expired` credits off a grant: its unheld credits when
211
+ * it expired, or a held part that came back to it afterwards (one more event each).
212
+ */
213
+ interface CreditGrantExpiredData extends CreditEventBase {
214
+ grantId: string;
215
+ kind: CreditGrantKind;
216
+ expiresAt: string | null;
217
+ expired: string;
218
+ /** The `expire` ledger transaction. */
219
+ transactionId: string;
220
+ }
221
+ /** `credit_reservation.expired` - a hold passed its expiry unsettled and was released. */
222
+ interface CreditReservationExpiredData extends CreditEventBase {
223
+ reservationId: string;
224
+ operationKey: string;
225
+ category: string;
226
+ amount: string;
227
+ expiresAt: string;
228
+ }
229
+ /** What every `credit_top_up.*` event says about the purchase and its payment. */
230
+ interface CreditTopUpEventBase extends CreditEventBase {
231
+ topUpId: string;
232
+ packId: string;
233
+ chargeId: string;
234
+ /** What the payment collects, in minor units of `currency`. */
235
+ amount: number;
236
+ currency: string;
237
+ /** The terms bought. */
238
+ credits: string;
239
+ bonusCredits: string;
240
+ }
241
+ /** `credit_top_up.succeeded` - the payment succeeded and its credits (and any bonus) were granted. */
242
+ interface CreditTopUpSucceededData extends CreditTopUpEventBase {
243
+ purchasedGrantId: string | null;
244
+ bonusGrantId: string | null;
245
+ }
246
+ /**
247
+ * `credit_top_up.failed` - the payment failed. A later payment on the same checkout can still
248
+ * succeed it: `credit_top_up.succeeded` may follow for the same top-up.
249
+ */
250
+ type CreditTopUpFailedData = CreditTopUpEventBase;
251
+ /** `credit_top_up.unfulfilled` - paid after the customer was erased: nothing granted, refund it. */
252
+ type CreditTopUpUnfulfilledData = CreditTopUpEventBase;
253
+ /**
254
+ * `credit_top_up.refunded` - a refund or lost chargeback revoked the top-up's credits in
255
+ * proportion to the money returned.
256
+ */
257
+ interface CreditTopUpRefundedData extends CreditTopUpEventBase {
258
+ cause: "refund" | "chargeback";
259
+ /** Money returned so far (refunds plus lost disputes, at most what was charged), minor units. */
260
+ amountReturned: number;
261
+ /** Microcredits this refund or chargeback revoked. */
262
+ revokedNow: string;
263
+ /** Microcredits revoked so far in all. */
264
+ revoked: string;
265
+ /** Of them, what the customer had already spent and nothing has paid back. */
266
+ shortfall: string;
267
+ }
268
+ /**
269
+ * The verified webhook envelope billow POSTs to your endpoint — a discriminated union on
270
+ * {@link WebhookEvent.type}. `switch` (or a {@link WebhookHandlers} map) on `type` and `data`
271
+ * narrows to the exact payload for that event.
272
+ *
273
+ * switch (event.type) {
274
+ * case "invoice.paid": settle(event.data.invoiceId); break; // InvoiceEventData
275
+ * case "subscription.canceled": revoke(event.data.customerExternalId); break;
276
+ * }
277
+ */
278
+ type WebhookEventDataMap = {
279
+ [K in "charge.succeeded" | "charge.failed"]: ChargeEventData;
280
+ } & {
281
+ "charge.refunded": ChargeRefundedEventData;
282
+ } & {
283
+ [K in "charge.disputed" | "charge.dispute_resolved"]: ChargeDisputeEventData;
284
+ } & {
285
+ [K in InvoiceEventType]: InvoiceEventData;
286
+ } & {
287
+ [K in SubscriptionEventType]: SubscriptionEventData;
288
+ } & {
289
+ [K in EntitlementEventType]: EntitlementEventData;
290
+ } & {
291
+ "usage.threshold_reached": UsageThresholdReachedData;
292
+ "usage.alert": UsageAlertData;
293
+ "usage.cap_reached": UsageCapReachedData;
294
+ } & {
295
+ "credit_balance.threshold_crossed": CreditThresholdCrossedData;
296
+ "credit_grant.created": CreditGrantCreatedData;
297
+ "credit_grant.expired": CreditGrantExpiredData;
298
+ "credit_reservation.expired": CreditReservationExpiredData;
299
+ "credit_top_up.succeeded": CreditTopUpSucceededData;
300
+ "credit_top_up.failed": CreditTopUpFailedData;
301
+ "credit_top_up.refunded": CreditTopUpRefundedData;
302
+ "credit_top_up.unfulfilled": CreditTopUpUnfulfilledData;
303
+ };
304
+ /** One distributive union member per event literal, derived from the payload map. */
305
+ type WebhookEvent = {
306
+ [K in BillowEventType]: WebhookEventEnvelope & {
307
+ type: K;
308
+ data: WebhookEventDataMap[K];
309
+ };
310
+ }[BillowEventType];
311
+ interface VerifyOptions {
312
+ /**
313
+ * Max age (seconds) of a delivery's signature timestamp before it's rejected as
314
+ * a possible replay. Default 300 (5 minutes).
315
+ */
316
+ toleranceSeconds?: number;
317
+ }
318
+ /** Thrown by {@link constructEvent} when a delivery can't be trusted. */
319
+ declare class WebhookVerificationError extends Error {
320
+ constructor(message: string);
321
+ }
322
+ /**
323
+ * Return `true` if `header` is a valid signature for `payload` under `secret` and
324
+ * within the freshness window. Never throws — use {@link constructEvent} when you
325
+ * want the parsed event and a thrown error on failure. Pass the RAW request body.
326
+ */
327
+ declare function verifySignature(payload: string, header: string | null | undefined, secret: string, opts?: VerifyOptions): Promise<boolean>;
328
+ /**
329
+ * Produce a valid `billow-signature` header for `payload` under `secret` - the inverse of
330
+ * {@link verifySignature}. Use it to exercise your webhook endpoint in tests without
331
+ * reverse-engineering the signing scheme. Pass the RAW body you will POST. `timestamp` (unix
332
+ * seconds) defaults to now; pass a fixed value for a deterministic - or intentionally stale
333
+ * (replay) - signature.
334
+ *
335
+ * const header = await signWebhook(rawBody, endpointSecret);
336
+ * await fetch(url, { method: "POST", headers: { "billow-signature": header }, body: rawBody });
337
+ */
338
+ declare function signWebhook(payload: string, secret: string, opts?: {
339
+ timestamp?: number;
340
+ }): Promise<string>;
341
+ /**
342
+ * Verify `payload` against the `billow-signature` header and return the parsed,
343
+ * typed {@link WebhookEvent}. Throws {@link WebhookVerificationError} if the
344
+ * signature is invalid, the timestamp is outside the freshness window, or the body
345
+ * isn't a billow envelope. Always pass the RAW request body — a re-serialized
346
+ * parsed body will not match.
347
+ */
348
+ declare function constructEvent(payload: string, header: string | null | undefined, secret: string, opts?: VerifyOptions): Promise<WebhookEvent>;
349
+ /** A handler for one verified webhook event. May be async; a throw propagates to the caller. */
350
+ type WebhookHandler = (event: WebhookEvent) => void | Promise<void>;
351
+ /**
352
+ * A map of per-event-type handlers plus an optional `onEvent` fallback. Each handler receives
353
+ * the event NARROWED to its type, so `data` is the exact payload for that event
354
+ * (e.g. `"invoice.paid": (e) => settle(e.data.invoiceId)`). Keyed by the literal event type so
355
+ * it stays in lock-step with the contract — a new event type is dispatchable with no parallel
356
+ * `onFooBar` name registry to keep in sync.
357
+ */
358
+ type WebhookHandlers = {
359
+ [K in BillowEventType]?: (event: Extract<WebhookEvent, {
360
+ type: K;
361
+ }>) => void | Promise<void>;
362
+ } & {
363
+ /** Called for any event that has no specific handler (receives the full union). */
364
+ onEvent?: WebhookHandler;
365
+ };
366
+ /**
367
+ * Build a reusable dispatcher bound to your endpoint secret + handlers: it verifies a
368
+ * delivery (via {@link constructEvent}) then routes the typed event to the matching
369
+ * handler, falling back to `onEvent`. Returns the verified event so the caller can log
370
+ * or ack it. Throws {@link WebhookVerificationError} on an untrusted delivery (return a
371
+ * 4xx) and propagates any error a handler throws (return a 5xx so billow retries).
372
+ * Pass the RAW request body — a re-serialized parsed body won't match the signature.
373
+ *
374
+ * const dispatch = createWebhookDispatcher({
375
+ * secret: process.env.BILLOW_WEBHOOK_SECRET,
376
+ * handlers: {
377
+ * "invoice.paid": (e) => fulfil(e.data.invoiceId),
378
+ * "subscription.canceled": (e) => revoke(e.data),
379
+ * onEvent: (e) => log(e.type),
380
+ * },
381
+ * });
382
+ * // per request:
383
+ * const event = await dispatch(rawBody, req.headers["billow-signature"]);
384
+ */
385
+ declare function createWebhookDispatcher(config: {
386
+ secret: string;
387
+ handlers: WebhookHandlers;
388
+ toleranceSeconds?: number;
389
+ }): (payload: string, signatureHeader: string | null | undefined) => Promise<WebhookEvent>;
390
+
391
+ export { type BillowEventType, CHARGE_EVENT_TYPES, CREDIT_EVENT_TYPES, type ChargeDisputeEventData, type ChargeEventData, type ChargeEventType, type ChargeRefundedEventData, type CreditEventBase, type CreditEventType, type CreditGrantCreatedData, type CreditGrantExpiredData, type CreditReservationExpiredData, type CreditThresholdCrossedData, type CreditTopUpEventBase, type CreditTopUpFailedData, type CreditTopUpRefundedData, type CreditTopUpSucceededData, type CreditTopUpUnfulfilledData, ENTITLEMENT_EVENT_TYPES, type EntitlementEventData, type EntitlementEventType, INVOICE_EVENT_TYPES, type InvoiceEventData, type InvoiceEventType, SUBSCRIPTION_EVENT_TYPES, type SubscriptionEventData, type SubscriptionEventType, USAGE_EVENT_TYPES, type UsageAlertData, type UsageCapReachedData, type UsageEventBase, type UsageEventType, type UsageThresholdReachedData, type VerifyOptions, WEBHOOK_EVENT_TYPES, type WebhookEvent, type WebhookEventDataMap, type WebhookEventEnvelope, type WebhookHandler, type WebhookHandlers, WebhookVerificationError, constructEvent, createWebhookDispatcher, isSubscriptionEvent, signWebhook, verifySignature };