@usebillow/sdk 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -0
- package/dist/{billing-B-VyZCXV.d.cts → billing-B16zL5xU.d.cts} +5 -1
- package/dist/{billing-CgjcWmvb.d.ts → billing-BF4OGaLI.d.ts} +5 -1
- package/dist/{chunk-J6JIZGWB.js → chunk-GT5VBLN5.js} +38 -2
- package/dist/chunk-GT5VBLN5.js.map +1 -0
- package/dist/config.d.cts +3 -3
- package/dist/config.d.ts +3 -3
- package/dist/{hosted-domains-BP91tg9P.d.ts → hosted-domains-DSTQ1GZz.d.ts} +109 -16
- package/dist/{hosted-domains-BbuyxnuH.d.cts → hosted-domains-DwakPG4J.d.cts} +109 -16
- package/dist/index.cjs +36 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +41 -12
- package/dist/index.d.ts +41 -12
- package/dist/index.js +1 -1
- package/dist/ingestion.d.cts +3 -3
- package/dist/ingestion.d.ts +3 -3
- package/dist/react.d.cts +2 -2
- package/dist/react.d.ts +2 -2
- package/dist/react.js +1 -1
- package/dist/server.d.cts +3 -3
- package/dist/server.d.ts +3 -3
- package/dist/webhooks.cjs.map +1 -1
- package/dist/webhooks.d.cts +10 -2
- package/dist/webhooks.d.ts +10 -2
- package/dist/webhooks.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-J6JIZGWB.js.map +0 -1
- package/dist/{index.d-CKQAhQfJ.d.ts → index.d-DSEYhV2c.d.cts} +2 -2
- package/dist/{index.d-CKQAhQfJ.d.cts → index.d-DSEYhV2c.d.ts} +2 -2
package/dist/index.d.cts
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import { f as SavedPaymentMethod, g as CreateHostedDomainInput, h as PayInvoiceInput } from './index.d-
|
|
2
|
-
export { i as ContractAddSubscriptionItemInput, j as ContractApplySubscriptionCouponInput, k as ContractCancelSubscriptionInput, l as ContractChangeSubscriptionPlanInput, m as ContractCreateChargeInput, n as ContractCreateCustomerInput, o as ContractCreateMerchantInitiatedChargeInput, p as ContractCreatePortalSessionInput, q as ContractCreateProductInput, r as ContractCreateSubscriptionInput, s as ContractCreateWebhookEndpointInput, M as ContractMigrateSubscribersInput, R as ContractRefundChargeInput, t as ContractResolveRefundInput, U as ContractUpdateProductInput, u as ContractUpdateSubscriptionItemInput, v as ContractUpdateWebhookEndpointInput, H as HostedDomain, w as HostedDomainList, I as InvoicePaymentResult } from './index.d-
|
|
1
|
+
import { f as SavedPaymentMethod, g as CreateHostedDomainInput, h as PayInvoiceInput } from './index.d-DSEYhV2c.cjs';
|
|
2
|
+
export { i as ContractAddSubscriptionItemInput, j as ContractApplySubscriptionCouponInput, k as ContractCancelSubscriptionInput, l as ContractChangeSubscriptionPlanInput, m as ContractCreateChargeInput, n as ContractCreateCustomerInput, o as ContractCreateMerchantInitiatedChargeInput, p as ContractCreatePortalSessionInput, q as ContractCreateProductInput, r as ContractCreateSubscriptionInput, s as ContractCreateWebhookEndpointInput, M as ContractMigrateSubscribersInput, R as ContractRefundChargeInput, t as ContractResolveRefundInput, U as ContractUpdateProductInput, u as ContractUpdateSubscriptionItemInput, v as ContractUpdateWebhookEndpointInput, H as HostedDomain, w as HostedDomainList, I as InvoicePaymentResult } from './index.d-DSEYhV2c.cjs';
|
|
3
3
|
import { C as ChargeStatus, P as PaymentMethodStatus, I as InvoiceStatus, R as RefundStatus, W as WebhookDeliveryStatus } from './billing-status-BZQN_gm7.cjs';
|
|
4
4
|
export { a as CHARGE_STATUSES, b as INVOICE_STATUSES, c as PAYMENT_METHOD_STATUSES, d as REFUND_STATUSES, e as WEBHOOK_DELIVERY_STATUSES } from './billing-status-BZQN_gm7.cjs';
|
|
5
5
|
import { SubscriptionStatus } from './status.cjs';
|
|
6
6
|
export { ACTIVE_SUBSCRIPTION_STATUSES, NEVER_ACTIVATED_SUBSCRIPTION_STATUSES, SUBSCRIPTION_STATUSES, TERMINAL_SUBSCRIPTION_STATUSES, grantsAccess, isTerminal } from './status.cjs';
|
|
7
|
-
import { c as TaxBehavior, d as Customer, U as UnappliedPaymentReason, e as CreateChargeInput, R as RequestOptions, f as Charge, g as CreateMerchantInitiatedChargeInput, I as IdempotentRequestOptions, h as CallOptions, C as CreateProductInput, i as UpdateProductInput, j as MigrationResult, k as CreateSubscriptionInput, B as BillowOptions, a as CreateCouponInput, l as Coupon, F as FeatureKind, M as MeterConfig, m as Feature, n as UpdateFeatureInput, o as UsageAlert, p as CreateUsageAlertInput, b as CheckResult, T as TrackResult, E as EntitlementView, A as AttachResult } from './billing-
|
|
8
|
-
export { q as ActivatedSubscriptionResult, r as BillingInterval, s as CouponDuration, t as CouponKind, u as CreateSubscriptionResult, v as EntitlementInput, w as MeterAggregation, x as MeterFilter, y as MeterRoundingMode, z as PendingSubscriptionCheckoutResult, D as PriceInput, P as Product, G as ProductEntitlement, H as ProductPrice, S as Subscription, J as SubscriptionDetail, K as SubscriptionItem, L as UpdatePriceInput, N as UsageAlertKind, O as UsageAlertMetric, Q as UsageModel, V as UsageTier } from './billing-
|
|
9
|
-
import { a as CreditThresholdLevel, e as CreditGrant, f as CreditTopUp, g as
|
|
10
|
-
export {
|
|
7
|
+
import { c as TaxBehavior, d as Customer, U as UnappliedPaymentReason, e as CreateChargeInput, R as RequestOptions, f as Charge, g as CreateMerchantInitiatedChargeInput, I as IdempotentRequestOptions, h as CallOptions, C as CreateProductInput, i as UpdateProductInput, j as MigrationResult, k as CreateSubscriptionInput, B as BillowOptions, a as CreateCouponInput, l as Coupon, F as FeatureKind, M as MeterConfig, m as Feature, n as UpdateFeatureInput, o as UsageAlert, p as CreateUsageAlertInput, b as CheckResult, T as TrackResult, E as EntitlementView, A as AttachResult } from './billing-B16zL5xU.cjs';
|
|
8
|
+
export { q as ActivatedSubscriptionResult, r as BillingInterval, s as CouponDuration, t as CouponKind, u as CreateSubscriptionResult, v as EntitlementInput, w as MeterAggregation, x as MeterFilter, y as MeterRoundingMode, z as PendingSubscriptionCheckoutResult, D as PriceInput, P as Product, G as ProductEntitlement, H as ProductPrice, S as Subscription, J as SubscriptionDetail, K as SubscriptionItem, L as UpdatePriceInput, N as UsageAlertKind, O as UsageAlertMetric, Q as UsageModel, V as UsageTier } from './billing-B16zL5xU.cjs';
|
|
9
|
+
import { a as CreditThresholdLevel, e as CreditGrant, f as CreditTopUp, g as CreditIncludedWindow, h as CreateCreditGrantInput, i as CreditGrantRequestResult, j as CreditPacks, k as CreateCreditPackInput, l as CreditPack, U as UpdateCreditPackInput, m as CreateCreditIncludedRuleInput, n as CreditIncludedRule, o as UpdateCreditIncludedRuleInput, p as CreditIncludedWindowListParams, q as CreateCreditTopUpInput, r as CreditTopUpRequestResult, s as CreditTopUpListParams, t as CreditBalance, u as CreditLedgerEntry, v as CreditUsageParams, w as CreditUsage } from './hosted-domains-DwakPG4J.cjs';
|
|
10
|
+
export { x as CreditAccountStatus, y as CreditAllocationInterval, C as CreditGrantKind, z as CreditMoney, A as CreditPackBreakdown, B as CreditPackListItem, D as CreditTopUpStatus, E as CreditTransactionType, F as CreditUsageGroupBy, G as CreditWindowState, H as HostedDomainActivatedData, d as HostedDomainDisabledData, b as HostedDomainDnsFailingData, I as HostedDomainEventBase, c as HostedDomainReassignmentPendingData, J as HostedDomainStatus, K as HostedDomainStatusReason, L as IncludedCredits, M as IncludedPeriod } from './hosted-domains-DwakPG4J.cjs';
|
|
11
11
|
import 'zod';
|
|
12
12
|
|
|
13
13
|
/**
|
|
@@ -599,6 +599,7 @@ interface InvoiceListParams extends ListParams {
|
|
|
599
599
|
}
|
|
600
600
|
interface InvoiceDetail {
|
|
601
601
|
invoice: Invoice;
|
|
602
|
+
/** In the order the invoice lists them (as its PDF and receipt email do). */
|
|
602
603
|
lineItems: InvoiceLineItem[];
|
|
603
604
|
}
|
|
604
605
|
/** How an offline payment was collected (ADR-0026). `other` is the escape hatch. */
|
|
@@ -1110,6 +1111,7 @@ interface CustomerDataExport {
|
|
|
1110
1111
|
createdAt: string;
|
|
1111
1112
|
updatedAt: string;
|
|
1112
1113
|
}>;
|
|
1114
|
+
/** By invoice, each invoice's lines in the order it lists them. */
|
|
1113
1115
|
invoiceLineItems: Array<{
|
|
1114
1116
|
id: string;
|
|
1115
1117
|
invoiceId: string;
|
|
@@ -1118,6 +1120,8 @@ interface CustomerDataExport {
|
|
|
1118
1120
|
amount: number;
|
|
1119
1121
|
quantity: number;
|
|
1120
1122
|
currency: string;
|
|
1123
|
+
/** Where the line sits on its invoice, from 0. */
|
|
1124
|
+
position: number;
|
|
1121
1125
|
createdAt: string;
|
|
1122
1126
|
updatedAt: string;
|
|
1123
1127
|
}>;
|
|
@@ -1186,6 +1190,8 @@ interface CustomerCreditsExport {
|
|
|
1186
1190
|
reversals: CreditReversal[];
|
|
1187
1191
|
/** Every quote made for the customer (even with no credit account), with its priced lines. */
|
|
1188
1192
|
quotes: CreditQuote[];
|
|
1193
|
+
/** Every Included Credit Window of the customer's subscriptions, oldest first. */
|
|
1194
|
+
includedWindows: CreditIncludedWindow[];
|
|
1189
1195
|
/** Every ledger transaction, in the order it was written, with its postings. */
|
|
1190
1196
|
ledger: Array<{
|
|
1191
1197
|
id: string;
|
|
@@ -1496,6 +1502,18 @@ declare function createCreditsResource(ctx: RequestContext): {
|
|
|
1496
1502
|
*/
|
|
1497
1503
|
update: (ruleId: string, input: UpdateCreditIncludedRuleInput, options?: CallOptions) => Promise<CreditIncludedRule>;
|
|
1498
1504
|
};
|
|
1505
|
+
includedWindows: {
|
|
1506
|
+
/**
|
|
1507
|
+
* The Included Credit Windows of one or more subscriptions (`subscription`, an id or a list
|
|
1508
|
+
* of up to 100), or of a customer (`customer`, by external id) - newest first: what each
|
|
1509
|
+
* period Billow granted includes (the whole period, each month of it under a monthly rule,
|
|
1510
|
+
* or a trial), how far it was issued, and its `state`. With `current: true`, only each
|
|
1511
|
+
* subscription's latest window that has started - what it stands at now. Auto-paginating by
|
|
1512
|
+
* cursor: `await` the first page, `for await (…)` every window, or `.listAll()` to collect
|
|
1513
|
+
* them.
|
|
1514
|
+
*/
|
|
1515
|
+
list: (params: CreditIncludedWindowListParams, options?: CallOptions) => CursorListPromise<CreditIncludedWindow>;
|
|
1516
|
+
};
|
|
1499
1517
|
topUps: {
|
|
1500
1518
|
/**
|
|
1501
1519
|
* Buy a Credit Pack for a customer: answers the top-up with `checkoutUrl`, the hosted
|
|
@@ -1709,7 +1727,7 @@ declare function createHostedDomainsResource(ctx: RequestContext): {
|
|
|
1709
1727
|
hostnameUnicode: string;
|
|
1710
1728
|
environment: "live";
|
|
1711
1729
|
status: "failed" | "active" | "pending_verification" | "verified" | "disabled";
|
|
1712
|
-
statusReason: "verification_expired" | "tls_unavailable" | "edge_blocked" | "dns_lost" | "reassigned" | "entitlement_lapsed" |
|
|
1730
|
+
statusReason: "suspended" | "verification_expired" | "tls_unavailable" | "edge_blocked" | "dns_lost" | "reassigned" | "entitlement_lapsed" | null;
|
|
1713
1731
|
isPrimary: boolean;
|
|
1714
1732
|
records: {
|
|
1715
1733
|
type: "TXT" | "CNAME";
|
|
@@ -1766,7 +1784,7 @@ declare function createHostedDomainsResource(ctx: RequestContext): {
|
|
|
1766
1784
|
hostnameUnicode: string;
|
|
1767
1785
|
environment: "live";
|
|
1768
1786
|
status: "failed" | "active" | "pending_verification" | "verified" | "disabled";
|
|
1769
|
-
statusReason: "verification_expired" | "tls_unavailable" | "edge_blocked" | "dns_lost" | "reassigned" | "entitlement_lapsed" |
|
|
1787
|
+
statusReason: "suspended" | "verification_expired" | "tls_unavailable" | "edge_blocked" | "dns_lost" | "reassigned" | "entitlement_lapsed" | null;
|
|
1770
1788
|
isPrimary: boolean;
|
|
1771
1789
|
records: {
|
|
1772
1790
|
type: "TXT" | "CNAME";
|
|
@@ -1814,7 +1832,7 @@ declare function createHostedDomainsResource(ctx: RequestContext): {
|
|
|
1814
1832
|
hostnameUnicode: string;
|
|
1815
1833
|
environment: "live";
|
|
1816
1834
|
status: "failed" | "active" | "pending_verification" | "verified" | "disabled";
|
|
1817
|
-
statusReason: "verification_expired" | "tls_unavailable" | "edge_blocked" | "dns_lost" | "reassigned" | "entitlement_lapsed" |
|
|
1835
|
+
statusReason: "suspended" | "verification_expired" | "tls_unavailable" | "edge_blocked" | "dns_lost" | "reassigned" | "entitlement_lapsed" | null;
|
|
1818
1836
|
isPrimary: boolean;
|
|
1819
1837
|
records: {
|
|
1820
1838
|
type: "TXT" | "CNAME";
|
|
@@ -1863,7 +1881,7 @@ declare function createHostedDomainsResource(ctx: RequestContext): {
|
|
|
1863
1881
|
hostnameUnicode: string;
|
|
1864
1882
|
environment: "live";
|
|
1865
1883
|
status: "failed" | "active" | "pending_verification" | "verified" | "disabled";
|
|
1866
|
-
statusReason: "verification_expired" | "tls_unavailable" | "edge_blocked" | "dns_lost" | "reassigned" | "entitlement_lapsed" |
|
|
1884
|
+
statusReason: "suspended" | "verification_expired" | "tls_unavailable" | "edge_blocked" | "dns_lost" | "reassigned" | "entitlement_lapsed" | null;
|
|
1867
1885
|
isPrimary: boolean;
|
|
1868
1886
|
records: {
|
|
1869
1887
|
type: "TXT" | "CNAME";
|
|
@@ -1912,7 +1930,7 @@ declare function createHostedDomainsResource(ctx: RequestContext): {
|
|
|
1912
1930
|
hostnameUnicode: string;
|
|
1913
1931
|
environment: "live";
|
|
1914
1932
|
status: "failed" | "active" | "pending_verification" | "verified" | "disabled";
|
|
1915
|
-
statusReason: "verification_expired" | "tls_unavailable" | "edge_blocked" | "dns_lost" | "reassigned" | "entitlement_lapsed" |
|
|
1933
|
+
statusReason: "suspended" | "verification_expired" | "tls_unavailable" | "edge_blocked" | "dns_lost" | "reassigned" | "entitlement_lapsed" | null;
|
|
1916
1934
|
isPrimary: boolean;
|
|
1917
1935
|
records: {
|
|
1918
1936
|
type: "TXT" | "CNAME";
|
|
@@ -2451,6 +2469,10 @@ declare function createSubscriptionsResource(ctx: RequestContext): {
|
|
|
2451
2469
|
defaultPaymentMethodId: string | null;
|
|
2452
2470
|
createdAt: string;
|
|
2453
2471
|
}>;
|
|
2472
|
+
/**
|
|
2473
|
+
* Pause an active or trialing subscription: no renewals and no access until it is resumed.
|
|
2474
|
+
* Refused while one of its invoices is still being collected.
|
|
2475
|
+
*/
|
|
2454
2476
|
pause: (id: string) => Promise<{
|
|
2455
2477
|
id: string;
|
|
2456
2478
|
status: "active" | "incomplete" | "incomplete_expired" | "trialing" | "past_due" | "paused" | "canceled" | "unpaid";
|
|
@@ -2473,6 +2495,13 @@ declare function createSubscriptionsResource(ctx: RequestContext): {
|
|
|
2473
2495
|
defaultPaymentMethodId: string | null;
|
|
2474
2496
|
createdAt: string;
|
|
2475
2497
|
}>;
|
|
2498
|
+
/**
|
|
2499
|
+
* Resume a paused subscription. Paused time is never billed: resumed before its paid period
|
|
2500
|
+
* ends, it carries on and renews at `currentPeriodEnd`; resumed after, a fresh full period
|
|
2501
|
+
* starts now and is charged at once like a renewal, with the ended period's usage (a decline
|
|
2502
|
+
* returns it `past_due`). Usage recorded while paused is never billed. A paused trial resumes
|
|
2503
|
+
* `trialing`. Duplicate calls are safe.
|
|
2504
|
+
*/
|
|
2476
2505
|
resume: (id: string) => Promise<{
|
|
2477
2506
|
id: string;
|
|
2478
2507
|
status: "active" | "incomplete" | "incomplete_expired" | "trialing" | "past_due" | "paused" | "canceled" | "unpaid";
|
|
@@ -2973,4 +3002,4 @@ declare class BillowPortal {
|
|
|
2973
3002
|
};
|
|
2974
3003
|
}
|
|
2975
3004
|
|
|
2976
|
-
export { AttachResult, BILLOW_ERROR_CODES, Billow, BillowApiError, type BillowErrorCode, BillowOptions, BillowPortal, BillowPublishable, type BusinessProfile, CallOptions, type CatalogItem, Charge, type ChargeListItem, type ChargeListParams, type ChargeSearchHit, ChargeStatus, CheckResult, type CheckoutMethodInfo, type ConfigField, type ConfigFieldOption, type ConfigFieldType, Coupon, CreateChargeInput, CreateCouponInput, CreateCreditGrantInput, CreateCreditIncludedRuleInput, CreateCreditPackInput, type CreateCreditQuoteInput, type CreateCreditReservationInput, CreateCreditTopUpInput, CreateHostedDomainInput, CreateMerchantInitiatedChargeInput, type CreatePortalSessionInput, CreateProductInput, CreateSubscriptionInput, CreateUsageAlertInput, type CreateWebhookEndpointInput, type CredentialSet, CreditBalance, type CreditDimensions, CreditGrant, CreditGrantRequestResult, CreditIncludedRule, CreditLedgerEntry, type CreditLineItem, CreditPack, CreditPacks, type CreditPricedLine, type CreditQuote, type CreditRateCard, type CreditRateCardItem, type CreditReservation, type CreditReservationListParams, type CreditReservationPage, type CreditReservationRequestResult, type CreditReservationStatus, type CreditReversal, type CreditReversalRequestResult, CreditThresholdLevel, CreditTopUp, CreditTopUpListParams, CreditTopUpRequestResult, CreditUsage, CreditUsageParams, type CursorListParams, type CursorListPromise, type CursorPaginated, Customer, type CustomerAnonymizationResult, type CustomerCreditsExport, type CustomerDataExport, type CustomerListItem, type CustomerListParams, type CustomerOverview, type CustomerSearchHit, type CustomerUsage, type CustomerUsageDetail, type EmailDeliveryListItem, type EmailDeliveryListParams, type EmailDeliveryStatus, type EmailTemplateSetting, EntitlementView, type ExchangeRate, type ExportJsonValue, type ExternalPaymentMethod, type ExternalPaymentResult, Feature, FeatureKind, IdempotentRequestOptions, type InboundWebhookListItem, type InboundWebhookListParams, type InboundWebhookOutcome, type IntegrationDefinition, type IntegrationKind, type IntegrationTier, type Invoice, type InvoiceDetail, type InvoiceLineItem, type InvoiceListItem, type InvoiceListParams, type InvoiceSearchHit, InvoiceStatus, type ListParams, type ListPromise, MeterConfig, type MetricsOverview, type MetricsParams, type MetricsRollup, MigrationResult, type OutboxEventListItem, type OutboxEventListParams, type OutboxEventStatus, type Paginated, PayInvoiceInput, type PaymentMethod, PaymentMethodStatus, type PaymentProviderDefinition, type PortalCardSetupResult, type PortalCheckout, type PortalPlanChange, type PortalSession, type PortalSessionExchange, type PortalSessionExchangeInput, type PortalSessionFlow, type PortalSessionInfo, type PortalSubscriptionStatus, type PortalView, type ProviderCredentialSummary, type ProviderVerifyResult, type ProviderVerifyTarget, type ProviderVerifyTargetResult, type PublishCreditRateCardInput, type RecordExternalPaymentInput, type Refund, type RefundChargeInput, type RefundRequestResult, type RefundReviewReason, RefundStatus, RequestOptions, type ResolveRefundInput, type ReverseCreditConsumptionInput, SavedPaymentMethod, type ScheduledSubscriptionChange, type SearchResults, type SubscriptionListItem, type SubscriptionListParams, type SubscriptionSearchHit, SubscriptionStatus, TaxBehavior, type TimeseriesInterval, type TimeseriesMetric, type TimeseriesParams, type TimeseriesPoint, type TimeseriesResult, TrackResult, UnappliedPaymentReason, type UpdateBusinessProfileInput, UpdateCreditIncludedRuleInput, UpdateCreditPackInput, type UpdateEmailTemplateInput, UpdateFeatureInput, UpdateProductInput, type UpdateWebhookEndpointInput, type UpsertCredentialsInput, UsageAlert, type WebhookDelivery, WebhookDeliveryStatus, type WebhookEndpoint, type WebhookEndpointWithSecret, type Whoami, currencyExponent, formatMoney, isSecretField, toMajorUnits, toMinorUnits };
|
|
3005
|
+
export { AttachResult, BILLOW_ERROR_CODES, Billow, BillowApiError, type BillowErrorCode, BillowOptions, BillowPortal, BillowPublishable, type BusinessProfile, CallOptions, type CatalogItem, Charge, type ChargeListItem, type ChargeListParams, type ChargeSearchHit, ChargeStatus, CheckResult, type CheckoutMethodInfo, type ConfigField, type ConfigFieldOption, type ConfigFieldType, Coupon, CreateChargeInput, CreateCouponInput, CreateCreditGrantInput, CreateCreditIncludedRuleInput, CreateCreditPackInput, type CreateCreditQuoteInput, type CreateCreditReservationInput, CreateCreditTopUpInput, CreateHostedDomainInput, CreateMerchantInitiatedChargeInput, type CreatePortalSessionInput, CreateProductInput, CreateSubscriptionInput, CreateUsageAlertInput, type CreateWebhookEndpointInput, type CredentialSet, CreditBalance, type CreditDimensions, CreditGrant, CreditGrantRequestResult, CreditIncludedRule, CreditIncludedWindow, CreditIncludedWindowListParams, CreditLedgerEntry, type CreditLineItem, CreditPack, CreditPacks, type CreditPricedLine, type CreditQuote, type CreditRateCard, type CreditRateCardItem, type CreditReservation, type CreditReservationListParams, type CreditReservationPage, type CreditReservationRequestResult, type CreditReservationStatus, type CreditReversal, type CreditReversalRequestResult, CreditThresholdLevel, CreditTopUp, CreditTopUpListParams, CreditTopUpRequestResult, CreditUsage, CreditUsageParams, type CursorListParams, type CursorListPromise, type CursorPaginated, Customer, type CustomerAnonymizationResult, type CustomerCreditsExport, type CustomerDataExport, type CustomerListItem, type CustomerListParams, type CustomerOverview, type CustomerSearchHit, type CustomerUsage, type CustomerUsageDetail, type EmailDeliveryListItem, type EmailDeliveryListParams, type EmailDeliveryStatus, type EmailTemplateSetting, EntitlementView, type ExchangeRate, type ExportJsonValue, type ExternalPaymentMethod, type ExternalPaymentResult, Feature, FeatureKind, IdempotentRequestOptions, type InboundWebhookListItem, type InboundWebhookListParams, type InboundWebhookOutcome, type IntegrationDefinition, type IntegrationKind, type IntegrationTier, type Invoice, type InvoiceDetail, type InvoiceLineItem, type InvoiceListItem, type InvoiceListParams, type InvoiceSearchHit, InvoiceStatus, type ListParams, type ListPromise, MeterConfig, type MetricsOverview, type MetricsParams, type MetricsRollup, MigrationResult, type OutboxEventListItem, type OutboxEventListParams, type OutboxEventStatus, type Paginated, PayInvoiceInput, type PaymentMethod, PaymentMethodStatus, type PaymentProviderDefinition, type PortalCardSetupResult, type PortalCheckout, type PortalPlanChange, type PortalSession, type PortalSessionExchange, type PortalSessionExchangeInput, type PortalSessionFlow, type PortalSessionInfo, type PortalSubscriptionStatus, type PortalView, type ProviderCredentialSummary, type ProviderVerifyResult, type ProviderVerifyTarget, type ProviderVerifyTargetResult, type PublishCreditRateCardInput, type RecordExternalPaymentInput, type Refund, type RefundChargeInput, type RefundRequestResult, type RefundReviewReason, RefundStatus, RequestOptions, type ResolveRefundInput, type ReverseCreditConsumptionInput, SavedPaymentMethod, type ScheduledSubscriptionChange, type SearchResults, type SubscriptionListItem, type SubscriptionListParams, type SubscriptionSearchHit, SubscriptionStatus, TaxBehavior, type TimeseriesInterval, type TimeseriesMetric, type TimeseriesParams, type TimeseriesPoint, type TimeseriesResult, TrackResult, UnappliedPaymentReason, type UpdateBusinessProfileInput, UpdateCreditIncludedRuleInput, UpdateCreditPackInput, type UpdateEmailTemplateInput, UpdateFeatureInput, UpdateProductInput, type UpdateWebhookEndpointInput, type UpsertCredentialsInput, UsageAlert, type WebhookDelivery, WebhookDeliveryStatus, type WebhookEndpoint, type WebhookEndpointWithSecret, type Whoami, currencyExponent, formatMoney, isSecretField, toMajorUnits, toMinorUnits };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import { f as SavedPaymentMethod, g as CreateHostedDomainInput, h as PayInvoiceInput } from './index.d-
|
|
2
|
-
export { i as ContractAddSubscriptionItemInput, j as ContractApplySubscriptionCouponInput, k as ContractCancelSubscriptionInput, l as ContractChangeSubscriptionPlanInput, m as ContractCreateChargeInput, n as ContractCreateCustomerInput, o as ContractCreateMerchantInitiatedChargeInput, p as ContractCreatePortalSessionInput, q as ContractCreateProductInput, r as ContractCreateSubscriptionInput, s as ContractCreateWebhookEndpointInput, M as ContractMigrateSubscribersInput, R as ContractRefundChargeInput, t as ContractResolveRefundInput, U as ContractUpdateProductInput, u as ContractUpdateSubscriptionItemInput, v as ContractUpdateWebhookEndpointInput, H as HostedDomain, w as HostedDomainList, I as InvoicePaymentResult } from './index.d-
|
|
1
|
+
import { f as SavedPaymentMethod, g as CreateHostedDomainInput, h as PayInvoiceInput } from './index.d-DSEYhV2c.js';
|
|
2
|
+
export { i as ContractAddSubscriptionItemInput, j as ContractApplySubscriptionCouponInput, k as ContractCancelSubscriptionInput, l as ContractChangeSubscriptionPlanInput, m as ContractCreateChargeInput, n as ContractCreateCustomerInput, o as ContractCreateMerchantInitiatedChargeInput, p as ContractCreatePortalSessionInput, q as ContractCreateProductInput, r as ContractCreateSubscriptionInput, s as ContractCreateWebhookEndpointInput, M as ContractMigrateSubscribersInput, R as ContractRefundChargeInput, t as ContractResolveRefundInput, U as ContractUpdateProductInput, u as ContractUpdateSubscriptionItemInput, v as ContractUpdateWebhookEndpointInput, H as HostedDomain, w as HostedDomainList, I as InvoicePaymentResult } from './index.d-DSEYhV2c.js';
|
|
3
3
|
import { C as ChargeStatus, P as PaymentMethodStatus, I as InvoiceStatus, R as RefundStatus, W as WebhookDeliveryStatus } from './billing-status-BZQN_gm7.js';
|
|
4
4
|
export { a as CHARGE_STATUSES, b as INVOICE_STATUSES, c as PAYMENT_METHOD_STATUSES, d as REFUND_STATUSES, e as WEBHOOK_DELIVERY_STATUSES } from './billing-status-BZQN_gm7.js';
|
|
5
5
|
import { SubscriptionStatus } from './status.js';
|
|
6
6
|
export { ACTIVE_SUBSCRIPTION_STATUSES, NEVER_ACTIVATED_SUBSCRIPTION_STATUSES, SUBSCRIPTION_STATUSES, TERMINAL_SUBSCRIPTION_STATUSES, grantsAccess, isTerminal } from './status.js';
|
|
7
|
-
import { c as TaxBehavior, d as Customer, U as UnappliedPaymentReason, e as CreateChargeInput, R as RequestOptions, f as Charge, g as CreateMerchantInitiatedChargeInput, I as IdempotentRequestOptions, h as CallOptions, C as CreateProductInput, i as UpdateProductInput, j as MigrationResult, k as CreateSubscriptionInput, B as BillowOptions, a as CreateCouponInput, l as Coupon, F as FeatureKind, M as MeterConfig, m as Feature, n as UpdateFeatureInput, o as UsageAlert, p as CreateUsageAlertInput, b as CheckResult, T as TrackResult, E as EntitlementView, A as AttachResult } from './billing-
|
|
8
|
-
export { q as ActivatedSubscriptionResult, r as BillingInterval, s as CouponDuration, t as CouponKind, u as CreateSubscriptionResult, v as EntitlementInput, w as MeterAggregation, x as MeterFilter, y as MeterRoundingMode, z as PendingSubscriptionCheckoutResult, D as PriceInput, P as Product, G as ProductEntitlement, H as ProductPrice, S as Subscription, J as SubscriptionDetail, K as SubscriptionItem, L as UpdatePriceInput, N as UsageAlertKind, O as UsageAlertMetric, Q as UsageModel, V as UsageTier } from './billing-
|
|
9
|
-
import { a as CreditThresholdLevel, e as CreditGrant, f as CreditTopUp, g as
|
|
10
|
-
export {
|
|
7
|
+
import { c as TaxBehavior, d as Customer, U as UnappliedPaymentReason, e as CreateChargeInput, R as RequestOptions, f as Charge, g as CreateMerchantInitiatedChargeInput, I as IdempotentRequestOptions, h as CallOptions, C as CreateProductInput, i as UpdateProductInput, j as MigrationResult, k as CreateSubscriptionInput, B as BillowOptions, a as CreateCouponInput, l as Coupon, F as FeatureKind, M as MeterConfig, m as Feature, n as UpdateFeatureInput, o as UsageAlert, p as CreateUsageAlertInput, b as CheckResult, T as TrackResult, E as EntitlementView, A as AttachResult } from './billing-BF4OGaLI.js';
|
|
8
|
+
export { q as ActivatedSubscriptionResult, r as BillingInterval, s as CouponDuration, t as CouponKind, u as CreateSubscriptionResult, v as EntitlementInput, w as MeterAggregation, x as MeterFilter, y as MeterRoundingMode, z as PendingSubscriptionCheckoutResult, D as PriceInput, P as Product, G as ProductEntitlement, H as ProductPrice, S as Subscription, J as SubscriptionDetail, K as SubscriptionItem, L as UpdatePriceInput, N as UsageAlertKind, O as UsageAlertMetric, Q as UsageModel, V as UsageTier } from './billing-BF4OGaLI.js';
|
|
9
|
+
import { a as CreditThresholdLevel, e as CreditGrant, f as CreditTopUp, g as CreditIncludedWindow, h as CreateCreditGrantInput, i as CreditGrantRequestResult, j as CreditPacks, k as CreateCreditPackInput, l as CreditPack, U as UpdateCreditPackInput, m as CreateCreditIncludedRuleInput, n as CreditIncludedRule, o as UpdateCreditIncludedRuleInput, p as CreditIncludedWindowListParams, q as CreateCreditTopUpInput, r as CreditTopUpRequestResult, s as CreditTopUpListParams, t as CreditBalance, u as CreditLedgerEntry, v as CreditUsageParams, w as CreditUsage } from './hosted-domains-DSTQ1GZz.js';
|
|
10
|
+
export { x as CreditAccountStatus, y as CreditAllocationInterval, C as CreditGrantKind, z as CreditMoney, A as CreditPackBreakdown, B as CreditPackListItem, D as CreditTopUpStatus, E as CreditTransactionType, F as CreditUsageGroupBy, G as CreditWindowState, H as HostedDomainActivatedData, d as HostedDomainDisabledData, b as HostedDomainDnsFailingData, I as HostedDomainEventBase, c as HostedDomainReassignmentPendingData, J as HostedDomainStatus, K as HostedDomainStatusReason, L as IncludedCredits, M as IncludedPeriod } from './hosted-domains-DSTQ1GZz.js';
|
|
11
11
|
import 'zod';
|
|
12
12
|
|
|
13
13
|
/**
|
|
@@ -599,6 +599,7 @@ interface InvoiceListParams extends ListParams {
|
|
|
599
599
|
}
|
|
600
600
|
interface InvoiceDetail {
|
|
601
601
|
invoice: Invoice;
|
|
602
|
+
/** In the order the invoice lists them (as its PDF and receipt email do). */
|
|
602
603
|
lineItems: InvoiceLineItem[];
|
|
603
604
|
}
|
|
604
605
|
/** How an offline payment was collected (ADR-0026). `other` is the escape hatch. */
|
|
@@ -1110,6 +1111,7 @@ interface CustomerDataExport {
|
|
|
1110
1111
|
createdAt: string;
|
|
1111
1112
|
updatedAt: string;
|
|
1112
1113
|
}>;
|
|
1114
|
+
/** By invoice, each invoice's lines in the order it lists them. */
|
|
1113
1115
|
invoiceLineItems: Array<{
|
|
1114
1116
|
id: string;
|
|
1115
1117
|
invoiceId: string;
|
|
@@ -1118,6 +1120,8 @@ interface CustomerDataExport {
|
|
|
1118
1120
|
amount: number;
|
|
1119
1121
|
quantity: number;
|
|
1120
1122
|
currency: string;
|
|
1123
|
+
/** Where the line sits on its invoice, from 0. */
|
|
1124
|
+
position: number;
|
|
1121
1125
|
createdAt: string;
|
|
1122
1126
|
updatedAt: string;
|
|
1123
1127
|
}>;
|
|
@@ -1186,6 +1190,8 @@ interface CustomerCreditsExport {
|
|
|
1186
1190
|
reversals: CreditReversal[];
|
|
1187
1191
|
/** Every quote made for the customer (even with no credit account), with its priced lines. */
|
|
1188
1192
|
quotes: CreditQuote[];
|
|
1193
|
+
/** Every Included Credit Window of the customer's subscriptions, oldest first. */
|
|
1194
|
+
includedWindows: CreditIncludedWindow[];
|
|
1189
1195
|
/** Every ledger transaction, in the order it was written, with its postings. */
|
|
1190
1196
|
ledger: Array<{
|
|
1191
1197
|
id: string;
|
|
@@ -1496,6 +1502,18 @@ declare function createCreditsResource(ctx: RequestContext): {
|
|
|
1496
1502
|
*/
|
|
1497
1503
|
update: (ruleId: string, input: UpdateCreditIncludedRuleInput, options?: CallOptions) => Promise<CreditIncludedRule>;
|
|
1498
1504
|
};
|
|
1505
|
+
includedWindows: {
|
|
1506
|
+
/**
|
|
1507
|
+
* The Included Credit Windows of one or more subscriptions (`subscription`, an id or a list
|
|
1508
|
+
* of up to 100), or of a customer (`customer`, by external id) - newest first: what each
|
|
1509
|
+
* period Billow granted includes (the whole period, each month of it under a monthly rule,
|
|
1510
|
+
* or a trial), how far it was issued, and its `state`. With `current: true`, only each
|
|
1511
|
+
* subscription's latest window that has started - what it stands at now. Auto-paginating by
|
|
1512
|
+
* cursor: `await` the first page, `for await (…)` every window, or `.listAll()` to collect
|
|
1513
|
+
* them.
|
|
1514
|
+
*/
|
|
1515
|
+
list: (params: CreditIncludedWindowListParams, options?: CallOptions) => CursorListPromise<CreditIncludedWindow>;
|
|
1516
|
+
};
|
|
1499
1517
|
topUps: {
|
|
1500
1518
|
/**
|
|
1501
1519
|
* Buy a Credit Pack for a customer: answers the top-up with `checkoutUrl`, the hosted
|
|
@@ -1709,7 +1727,7 @@ declare function createHostedDomainsResource(ctx: RequestContext): {
|
|
|
1709
1727
|
hostnameUnicode: string;
|
|
1710
1728
|
environment: "live";
|
|
1711
1729
|
status: "failed" | "active" | "pending_verification" | "verified" | "disabled";
|
|
1712
|
-
statusReason: "verification_expired" | "tls_unavailable" | "edge_blocked" | "dns_lost" | "reassigned" | "entitlement_lapsed" |
|
|
1730
|
+
statusReason: "suspended" | "verification_expired" | "tls_unavailable" | "edge_blocked" | "dns_lost" | "reassigned" | "entitlement_lapsed" | null;
|
|
1713
1731
|
isPrimary: boolean;
|
|
1714
1732
|
records: {
|
|
1715
1733
|
type: "TXT" | "CNAME";
|
|
@@ -1766,7 +1784,7 @@ declare function createHostedDomainsResource(ctx: RequestContext): {
|
|
|
1766
1784
|
hostnameUnicode: string;
|
|
1767
1785
|
environment: "live";
|
|
1768
1786
|
status: "failed" | "active" | "pending_verification" | "verified" | "disabled";
|
|
1769
|
-
statusReason: "verification_expired" | "tls_unavailable" | "edge_blocked" | "dns_lost" | "reassigned" | "entitlement_lapsed" |
|
|
1787
|
+
statusReason: "suspended" | "verification_expired" | "tls_unavailable" | "edge_blocked" | "dns_lost" | "reassigned" | "entitlement_lapsed" | null;
|
|
1770
1788
|
isPrimary: boolean;
|
|
1771
1789
|
records: {
|
|
1772
1790
|
type: "TXT" | "CNAME";
|
|
@@ -1814,7 +1832,7 @@ declare function createHostedDomainsResource(ctx: RequestContext): {
|
|
|
1814
1832
|
hostnameUnicode: string;
|
|
1815
1833
|
environment: "live";
|
|
1816
1834
|
status: "failed" | "active" | "pending_verification" | "verified" | "disabled";
|
|
1817
|
-
statusReason: "verification_expired" | "tls_unavailable" | "edge_blocked" | "dns_lost" | "reassigned" | "entitlement_lapsed" |
|
|
1835
|
+
statusReason: "suspended" | "verification_expired" | "tls_unavailable" | "edge_blocked" | "dns_lost" | "reassigned" | "entitlement_lapsed" | null;
|
|
1818
1836
|
isPrimary: boolean;
|
|
1819
1837
|
records: {
|
|
1820
1838
|
type: "TXT" | "CNAME";
|
|
@@ -1863,7 +1881,7 @@ declare function createHostedDomainsResource(ctx: RequestContext): {
|
|
|
1863
1881
|
hostnameUnicode: string;
|
|
1864
1882
|
environment: "live";
|
|
1865
1883
|
status: "failed" | "active" | "pending_verification" | "verified" | "disabled";
|
|
1866
|
-
statusReason: "verification_expired" | "tls_unavailable" | "edge_blocked" | "dns_lost" | "reassigned" | "entitlement_lapsed" |
|
|
1884
|
+
statusReason: "suspended" | "verification_expired" | "tls_unavailable" | "edge_blocked" | "dns_lost" | "reassigned" | "entitlement_lapsed" | null;
|
|
1867
1885
|
isPrimary: boolean;
|
|
1868
1886
|
records: {
|
|
1869
1887
|
type: "TXT" | "CNAME";
|
|
@@ -1912,7 +1930,7 @@ declare function createHostedDomainsResource(ctx: RequestContext): {
|
|
|
1912
1930
|
hostnameUnicode: string;
|
|
1913
1931
|
environment: "live";
|
|
1914
1932
|
status: "failed" | "active" | "pending_verification" | "verified" | "disabled";
|
|
1915
|
-
statusReason: "verification_expired" | "tls_unavailable" | "edge_blocked" | "dns_lost" | "reassigned" | "entitlement_lapsed" |
|
|
1933
|
+
statusReason: "suspended" | "verification_expired" | "tls_unavailable" | "edge_blocked" | "dns_lost" | "reassigned" | "entitlement_lapsed" | null;
|
|
1916
1934
|
isPrimary: boolean;
|
|
1917
1935
|
records: {
|
|
1918
1936
|
type: "TXT" | "CNAME";
|
|
@@ -2451,6 +2469,10 @@ declare function createSubscriptionsResource(ctx: RequestContext): {
|
|
|
2451
2469
|
defaultPaymentMethodId: string | null;
|
|
2452
2470
|
createdAt: string;
|
|
2453
2471
|
}>;
|
|
2472
|
+
/**
|
|
2473
|
+
* Pause an active or trialing subscription: no renewals and no access until it is resumed.
|
|
2474
|
+
* Refused while one of its invoices is still being collected.
|
|
2475
|
+
*/
|
|
2454
2476
|
pause: (id: string) => Promise<{
|
|
2455
2477
|
id: string;
|
|
2456
2478
|
status: "active" | "incomplete" | "incomplete_expired" | "trialing" | "past_due" | "paused" | "canceled" | "unpaid";
|
|
@@ -2473,6 +2495,13 @@ declare function createSubscriptionsResource(ctx: RequestContext): {
|
|
|
2473
2495
|
defaultPaymentMethodId: string | null;
|
|
2474
2496
|
createdAt: string;
|
|
2475
2497
|
}>;
|
|
2498
|
+
/**
|
|
2499
|
+
* Resume a paused subscription. Paused time is never billed: resumed before its paid period
|
|
2500
|
+
* ends, it carries on and renews at `currentPeriodEnd`; resumed after, a fresh full period
|
|
2501
|
+
* starts now and is charged at once like a renewal, with the ended period's usage (a decline
|
|
2502
|
+
* returns it `past_due`). Usage recorded while paused is never billed. A paused trial resumes
|
|
2503
|
+
* `trialing`. Duplicate calls are safe.
|
|
2504
|
+
*/
|
|
2476
2505
|
resume: (id: string) => Promise<{
|
|
2477
2506
|
id: string;
|
|
2478
2507
|
status: "active" | "incomplete" | "incomplete_expired" | "trialing" | "past_due" | "paused" | "canceled" | "unpaid";
|
|
@@ -2973,4 +3002,4 @@ declare class BillowPortal {
|
|
|
2973
3002
|
};
|
|
2974
3003
|
}
|
|
2975
3004
|
|
|
2976
|
-
export { AttachResult, BILLOW_ERROR_CODES, Billow, BillowApiError, type BillowErrorCode, BillowOptions, BillowPortal, BillowPublishable, type BusinessProfile, CallOptions, type CatalogItem, Charge, type ChargeListItem, type ChargeListParams, type ChargeSearchHit, ChargeStatus, CheckResult, type CheckoutMethodInfo, type ConfigField, type ConfigFieldOption, type ConfigFieldType, Coupon, CreateChargeInput, CreateCouponInput, CreateCreditGrantInput, CreateCreditIncludedRuleInput, CreateCreditPackInput, type CreateCreditQuoteInput, type CreateCreditReservationInput, CreateCreditTopUpInput, CreateHostedDomainInput, CreateMerchantInitiatedChargeInput, type CreatePortalSessionInput, CreateProductInput, CreateSubscriptionInput, CreateUsageAlertInput, type CreateWebhookEndpointInput, type CredentialSet, CreditBalance, type CreditDimensions, CreditGrant, CreditGrantRequestResult, CreditIncludedRule, CreditLedgerEntry, type CreditLineItem, CreditPack, CreditPacks, type CreditPricedLine, type CreditQuote, type CreditRateCard, type CreditRateCardItem, type CreditReservation, type CreditReservationListParams, type CreditReservationPage, type CreditReservationRequestResult, type CreditReservationStatus, type CreditReversal, type CreditReversalRequestResult, CreditThresholdLevel, CreditTopUp, CreditTopUpListParams, CreditTopUpRequestResult, CreditUsage, CreditUsageParams, type CursorListParams, type CursorListPromise, type CursorPaginated, Customer, type CustomerAnonymizationResult, type CustomerCreditsExport, type CustomerDataExport, type CustomerListItem, type CustomerListParams, type CustomerOverview, type CustomerSearchHit, type CustomerUsage, type CustomerUsageDetail, type EmailDeliveryListItem, type EmailDeliveryListParams, type EmailDeliveryStatus, type EmailTemplateSetting, EntitlementView, type ExchangeRate, type ExportJsonValue, type ExternalPaymentMethod, type ExternalPaymentResult, Feature, FeatureKind, IdempotentRequestOptions, type InboundWebhookListItem, type InboundWebhookListParams, type InboundWebhookOutcome, type IntegrationDefinition, type IntegrationKind, type IntegrationTier, type Invoice, type InvoiceDetail, type InvoiceLineItem, type InvoiceListItem, type InvoiceListParams, type InvoiceSearchHit, InvoiceStatus, type ListParams, type ListPromise, MeterConfig, type MetricsOverview, type MetricsParams, type MetricsRollup, MigrationResult, type OutboxEventListItem, type OutboxEventListParams, type OutboxEventStatus, type Paginated, PayInvoiceInput, type PaymentMethod, PaymentMethodStatus, type PaymentProviderDefinition, type PortalCardSetupResult, type PortalCheckout, type PortalPlanChange, type PortalSession, type PortalSessionExchange, type PortalSessionExchangeInput, type PortalSessionFlow, type PortalSessionInfo, type PortalSubscriptionStatus, type PortalView, type ProviderCredentialSummary, type ProviderVerifyResult, type ProviderVerifyTarget, type ProviderVerifyTargetResult, type PublishCreditRateCardInput, type RecordExternalPaymentInput, type Refund, type RefundChargeInput, type RefundRequestResult, type RefundReviewReason, RefundStatus, RequestOptions, type ResolveRefundInput, type ReverseCreditConsumptionInput, SavedPaymentMethod, type ScheduledSubscriptionChange, type SearchResults, type SubscriptionListItem, type SubscriptionListParams, type SubscriptionSearchHit, SubscriptionStatus, TaxBehavior, type TimeseriesInterval, type TimeseriesMetric, type TimeseriesParams, type TimeseriesPoint, type TimeseriesResult, TrackResult, UnappliedPaymentReason, type UpdateBusinessProfileInput, UpdateCreditIncludedRuleInput, UpdateCreditPackInput, type UpdateEmailTemplateInput, UpdateFeatureInput, UpdateProductInput, type UpdateWebhookEndpointInput, type UpsertCredentialsInput, UsageAlert, type WebhookDelivery, WebhookDeliveryStatus, type WebhookEndpoint, type WebhookEndpointWithSecret, type Whoami, currencyExponent, formatMoney, isSecretField, toMajorUnits, toMinorUnits };
|
|
3005
|
+
export { AttachResult, BILLOW_ERROR_CODES, Billow, BillowApiError, type BillowErrorCode, BillowOptions, BillowPortal, BillowPublishable, type BusinessProfile, CallOptions, type CatalogItem, Charge, type ChargeListItem, type ChargeListParams, type ChargeSearchHit, ChargeStatus, CheckResult, type CheckoutMethodInfo, type ConfigField, type ConfigFieldOption, type ConfigFieldType, Coupon, CreateChargeInput, CreateCouponInput, CreateCreditGrantInput, CreateCreditIncludedRuleInput, CreateCreditPackInput, type CreateCreditQuoteInput, type CreateCreditReservationInput, CreateCreditTopUpInput, CreateHostedDomainInput, CreateMerchantInitiatedChargeInput, type CreatePortalSessionInput, CreateProductInput, CreateSubscriptionInput, CreateUsageAlertInput, type CreateWebhookEndpointInput, type CredentialSet, CreditBalance, type CreditDimensions, CreditGrant, CreditGrantRequestResult, CreditIncludedRule, CreditIncludedWindow, CreditIncludedWindowListParams, CreditLedgerEntry, type CreditLineItem, CreditPack, CreditPacks, type CreditPricedLine, type CreditQuote, type CreditRateCard, type CreditRateCardItem, type CreditReservation, type CreditReservationListParams, type CreditReservationPage, type CreditReservationRequestResult, type CreditReservationStatus, type CreditReversal, type CreditReversalRequestResult, CreditThresholdLevel, CreditTopUp, CreditTopUpListParams, CreditTopUpRequestResult, CreditUsage, CreditUsageParams, type CursorListParams, type CursorListPromise, type CursorPaginated, Customer, type CustomerAnonymizationResult, type CustomerCreditsExport, type CustomerDataExport, type CustomerListItem, type CustomerListParams, type CustomerOverview, type CustomerSearchHit, type CustomerUsage, type CustomerUsageDetail, type EmailDeliveryListItem, type EmailDeliveryListParams, type EmailDeliveryStatus, type EmailTemplateSetting, EntitlementView, type ExchangeRate, type ExportJsonValue, type ExternalPaymentMethod, type ExternalPaymentResult, Feature, FeatureKind, IdempotentRequestOptions, type InboundWebhookListItem, type InboundWebhookListParams, type InboundWebhookOutcome, type IntegrationDefinition, type IntegrationKind, type IntegrationTier, type Invoice, type InvoiceDetail, type InvoiceLineItem, type InvoiceListItem, type InvoiceListParams, type InvoiceSearchHit, InvoiceStatus, type ListParams, type ListPromise, MeterConfig, type MetricsOverview, type MetricsParams, type MetricsRollup, MigrationResult, type OutboxEventListItem, type OutboxEventListParams, type OutboxEventStatus, type Paginated, PayInvoiceInput, type PaymentMethod, PaymentMethodStatus, type PaymentProviderDefinition, type PortalCardSetupResult, type PortalCheckout, type PortalPlanChange, type PortalSession, type PortalSessionExchange, type PortalSessionExchangeInput, type PortalSessionFlow, type PortalSessionInfo, type PortalSubscriptionStatus, type PortalView, type ProviderCredentialSummary, type ProviderVerifyResult, type ProviderVerifyTarget, type ProviderVerifyTargetResult, type PublishCreditRateCardInput, type RecordExternalPaymentInput, type Refund, type RefundChargeInput, type RefundRequestResult, type RefundReviewReason, RefundStatus, RequestOptions, type ResolveRefundInput, type ReverseCreditConsumptionInput, SavedPaymentMethod, type ScheduledSubscriptionChange, type SearchResults, type SubscriptionListItem, type SubscriptionListParams, type SubscriptionSearchHit, SubscriptionStatus, TaxBehavior, type TimeseriesInterval, type TimeseriesMetric, type TimeseriesParams, type TimeseriesPoint, type TimeseriesResult, TrackResult, UnappliedPaymentReason, type UpdateBusinessProfileInput, UpdateCreditIncludedRuleInput, UpdateCreditPackInput, type UpdateEmailTemplateInput, UpdateFeatureInput, UpdateProductInput, type UpdateWebhookEndpointInput, type UpsertCredentialsInput, UsageAlert, type WebhookDelivery, WebhookDeliveryStatus, type WebhookEndpoint, type WebhookEndpointWithSecret, type Whoami, currencyExponent, formatMoney, isSecretField, toMajorUnits, toMinorUnits };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { BILLOW_ERROR_CODES, Billow, BillowApiError, BillowPortal, BillowPublishable, currencyExponent, formatMoney, isSecretField, toMajorUnits, toMinorUnits } from './chunk-
|
|
1
|
+
export { BILLOW_ERROR_CODES, Billow, BillowApiError, BillowPortal, BillowPublishable, currencyExponent, formatMoney, isSecretField, toMajorUnits, toMinorUnits } from './chunk-GT5VBLN5.js';
|
|
2
2
|
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';
|
|
3
3
|
//# sourceMappingURL=index.js.map
|
|
4
4
|
//# sourceMappingURL=index.js.map
|
package/dist/ingestion.d.cts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { Billow } from './index.cjs';
|
|
2
|
-
import './index.d-
|
|
2
|
+
import './index.d-DSEYhV2c.cjs';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import './billing-status-BZQN_gm7.cjs';
|
|
5
5
|
import './status.cjs';
|
|
6
|
-
import './billing-
|
|
7
|
-
import './hosted-domains-
|
|
6
|
+
import './billing-B16zL5xU.cjs';
|
|
7
|
+
import './hosted-domains-DwakPG4J.cjs';
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* Auto-metering (PRD-16): ingestion strategies that call billow's `track()` for you,
|
package/dist/ingestion.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { Billow } from './index.js';
|
|
2
|
-
import './index.d-
|
|
2
|
+
import './index.d-DSEYhV2c.js';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import './billing-status-BZQN_gm7.js';
|
|
5
5
|
import './status.js';
|
|
6
|
-
import './billing-
|
|
7
|
-
import './hosted-domains-
|
|
6
|
+
import './billing-BF4OGaLI.js';
|
|
7
|
+
import './hosted-domains-DSTQ1GZz.js';
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* Auto-metering (PRD-16): ingestion strategies that call billow's `track()` for you,
|
package/dist/react.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as react from 'react';
|
|
2
2
|
import { ReactNode } from 'react';
|
|
3
|
-
import { A as AttachResult, b as CheckResult, E as EntitlementView, P as Product, T as TrackResult } from './billing-
|
|
4
|
-
import './index.d-
|
|
3
|
+
import { A as AttachResult, b as CheckResult, E as EntitlementView, P as Product, T as TrackResult } from './billing-B16zL5xU.cjs';
|
|
4
|
+
import './index.d-DSEYhV2c.cjs';
|
|
5
5
|
import 'zod';
|
|
6
6
|
import './billing-status-BZQN_gm7.cjs';
|
|
7
7
|
|
package/dist/react.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as react from 'react';
|
|
2
2
|
import { ReactNode } from 'react';
|
|
3
|
-
import { A as AttachResult, b as CheckResult, E as EntitlementView, P as Product, T as TrackResult } from './billing-
|
|
4
|
-
import './index.d-
|
|
3
|
+
import { A as AttachResult, b as CheckResult, E as EntitlementView, P as Product, T as TrackResult } from './billing-BF4OGaLI.js';
|
|
4
|
+
import './index.d-DSEYhV2c.js';
|
|
5
5
|
import 'zod';
|
|
6
6
|
import './billing-status-BZQN_gm7.js';
|
|
7
7
|
|
package/dist/react.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import { BillowPublishable } from './chunk-
|
|
2
|
+
import { BillowPublishable } from './chunk-GT5VBLN5.js';
|
|
3
3
|
import './chunk-CCG4F5FK.js';
|
|
4
4
|
import { createContext, useCallback, useState, useEffect, useMemo, useContext } from 'react';
|
|
5
5
|
import { jsx } from 'react/jsx-runtime';
|
package/dist/server.d.cts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { Billow } from './index.cjs';
|
|
2
|
-
import './index.d-
|
|
2
|
+
import './index.d-DSEYhV2c.cjs';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import './billing-status-BZQN_gm7.cjs';
|
|
5
5
|
import './status.cjs';
|
|
6
|
-
import './billing-
|
|
7
|
-
import './hosted-domains-
|
|
6
|
+
import './billing-B16zL5xU.cjs';
|
|
7
|
+
import './hosted-domains-DwakPG4J.cjs';
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* Backend handler for the browser-facing surface (the React hooks talk to this,
|
package/dist/server.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { Billow } from './index.js';
|
|
2
|
-
import './index.d-
|
|
2
|
+
import './index.d-DSEYhV2c.js';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import './billing-status-BZQN_gm7.js';
|
|
5
5
|
import './status.js';
|
|
6
|
-
import './billing-
|
|
7
|
-
import './hosted-domains-
|
|
6
|
+
import './billing-BF4OGaLI.js';
|
|
7
|
+
import './hosted-domains-DSTQ1GZz.js';
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* Backend handler for the browser-facing surface (the React hooks talk to this,
|
package/dist/webhooks.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/webhook-event-types.ts","../src/webhooks.ts"],"names":[],"mappings":";;;AASO,IAAM,mBAAA,GAAsB;AAAA,EACjC,kBAAA;AAAA,EACA,eAAA;AAAA,EACA,iBAAA;AAAA,EACA,iBAAA;AAAA,EACA,yBAAA;AAAA,EACA,cAAA;AAAA,EACA,wBAAA;AAAA,EACA,4BAAA;AAAA,EACA,wBAAA;AAAA,EACA,gCAAA;AAAA,EACA,sBAAA;AAAA,EACA,uBAAA;AAAA,EACA,6BAAA;AAAA,EACA,sCAAA;AAAA,EACA,qBAAA;AAAA,EACA,qBAAA;AAAA,EACA,sBAAA;AAAA,EACA,sBAAA;AAAA,EACA,+BAAA;AAAA,EACA,6BAAA;AAAA,EACA,kCAAA;AAAA,EACA,iCAAA;AAAA,EACA,uBAAA;AAAA,EACA,oBAAA;AAAA,EACA,qBAAA;AAAA,EACA,mBAAA;AAAA,EACA,yBAAA;AAAA,EACA,aAAA;AAAA,EACA,mBAAA;AAAA,EACA,kCAAA;AAAA,EACA,sBAAA;AAAA,EACA,sBAAA;AAAA,EACA,4BAAA;AAAA,EACA,yBAAA;AAAA,EACA,sBAAA;AAAA,EACA,wBAAA;AAAA,EACA,2BAAA;AAAA,EACA,yBAAA;AAAA,EACA,2BAAA;AAAA,EACA,oCAAA;AAAA,EACA;AACF;AAqBA,SAAS,qBAC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AAA,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 * The webhook event catalog: every event type billow emits, and its families as types and runtime\n * arrays (for subscription pickers and exhaustive routing). Re-exported by ./webhooks.ts.\n */\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 \"hosted_domain.activated\",\n \"hosted_domain.dns_failing\",\n \"hosted_domain.reassignment_pending\",\n \"hosted_domain.disabled\",\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/** The `hosted_domain.*` subset of {@link BillowEventType}: custom portal domains. */\nexport type HostedDomainEventType = Extract<BillowEventType, `hosted_domain.${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/** The `hosted_domain.*` event types, as a runtime array. */\nexport const HOSTED_DOMAIN_EVENT_TYPES: readonly HostedDomainEventType[] =\n eventTypesWithPrefix(\"hosted_domain.\");\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 * 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\";\nimport type {\n HostedDomainActivatedData,\n HostedDomainDisabledData,\n HostedDomainDnsFailingData,\n HostedDomainReassignmentPendingData,\n} from \"./types/hosted-domains\";\nimport type {\n BillowEventType,\n EntitlementEventType,\n InvoiceEventType,\n SubscriptionEventType,\n} from \"./webhook-event-types\";\n\nexport * from \"./webhook-event-types\";\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 \"hosted_domain.activated\": HostedDomainActivatedData;\n \"hosted_domain.dns_failing\": HostedDomainDnsFailingData;\n \"hosted_domain.reassignment_pending\": HostedDomainReassignmentPendingData;\n \"hosted_domain.disabled\": HostedDomainDisabledData;\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"]}
|
|
1
|
+
{"version":3,"sources":["../src/webhook-event-types.ts","../src/webhooks.ts"],"names":[],"mappings":";;;AASO,IAAM,mBAAA,GAAsB;AAAA,EACjC,kBAAA;AAAA,EACA,eAAA;AAAA,EACA,iBAAA;AAAA,EACA,iBAAA;AAAA,EACA,yBAAA;AAAA,EACA,cAAA;AAAA,EACA,wBAAA;AAAA,EACA,4BAAA;AAAA,EACA,wBAAA;AAAA,EACA,gCAAA;AAAA,EACA,sBAAA;AAAA,EACA,uBAAA;AAAA,EACA,6BAAA;AAAA,EACA,sCAAA;AAAA,EACA,qBAAA;AAAA,EACA,qBAAA;AAAA,EACA,sBAAA;AAAA,EACA,sBAAA;AAAA,EACA,+BAAA;AAAA,EACA,6BAAA;AAAA,EACA,kCAAA;AAAA,EACA,iCAAA;AAAA,EACA,uBAAA;AAAA,EACA,oBAAA;AAAA,EACA,qBAAA;AAAA,EACA,mBAAA;AAAA,EACA,yBAAA;AAAA,EACA,aA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AA,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 * The webhook event catalog: every event type billow emits, and its families as types and runtime\n * arrays (for subscription pickers and exhaustive routing). Re-exported by ./webhooks.ts.\n */\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 \"hosted_domain.activated\",\n \"hosted_domain.dns_failing\",\n \"hosted_domain.reassignment_pending\",\n \"hosted_domain.disabled\",\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/** The `hosted_domain.*` subset of {@link BillowEventType}: custom portal domains. */\nexport type HostedDomainEventType = Extract<BillowEventType, `hosted_domain.${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/** The `hosted_domain.*` event types, as a runtime array. */\nexport const HOSTED_DOMAIN_EVENT_TYPES: readonly HostedDomainEventType[] =\n eventTypesWithPrefix(\"hosted_domain.\");\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 * 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\";\nimport type {\n HostedDomainActivatedData,\n HostedDomainDisabledData,\n HostedDomainDnsFailingData,\n HostedDomainReassignmentPendingData,\n} from \"./types/hosted-domains\";\nimport type {\n BillowEventType,\n EntitlementEventType,\n InvoiceEventType,\n SubscriptionEventType,\n} from \"./webhook-event-types\";\n\nexport * from \"./webhook-event-types\";\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 /** For an `included` grant, its window's end. */\n expiresAt: string | null;\n eligibility: string[] | null;\n topUpId: string | null;\n /** An `included` grant's subscription; null for every other kind. */\n subscriptionId: string | null;\n /** The billing period an `included` grant's window belongs to; null for every other kind. */\n periodStart: string | null;\n periodEnd: 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 /** Why it expired: `grant_expired` - the grant reached its expiry. */\n reason: \"grant_expired\";\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 \"hosted_domain.activated\": HostedDomainActivatedData;\n \"hosted_domain.dns_failing\": HostedDomainDnsFailingData;\n \"hosted_domain.reassignment_pending\": HostedDomainReassignmentPendingData;\n \"hosted_domain.disabled\": HostedDomainDisabledData;\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"]}
|