@boelabs/billete-sdk 4.4.0 → 5.0.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/README.md +20 -6
- package/dist/client.d.ts +10 -4
- package/dist/client.js +20 -2
- package/dist/{errors-Ca_4OGi0.d.ts → errors-CGHiFrlh.d.ts} +71 -9
- package/dist/{events-1yiDG8bS.d.ts → events-D09DIgn-.d.ts} +236 -2
- package/dist/{http-CCvluhGO.js → http-D5FMIjK4.js} +48 -21
- package/dist/index.d.ts +8 -4
- package/dist/index.js +4 -3
- package/dist/webhooks.d.ts +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -18,7 +18,8 @@ servidor y tu frontend.
|
|
|
18
18
|
|
|
19
19
|
- **Tipado de punta a punta:** cada recurso, entrada y evento tiene su tipo.
|
|
20
20
|
- **Sin dependencias:** solo `fetch` y Web Crypto; funciona en Node.js 20+, Bun, Deno y
|
|
21
|
-
runtimes edge (Cloudflare Workers, Vercel).
|
|
21
|
+
runtimes edge (Cloudflare Workers, Vercel). El cliente de navegador también funciona en React
|
|
22
|
+
Native y Expo.
|
|
22
23
|
- **Seguro ante reintentos:** cada mutación lleva una clave de idempotencia, así un reintento
|
|
23
24
|
nunca cobra dos veces.
|
|
24
25
|
|
|
@@ -62,7 +63,7 @@ Crea una clave secreta en el dashboard (**Desarrolladores → Claves API**) y gu
|
|
|
62
63
|
```ts
|
|
63
64
|
import { createBillete } from "@boelabs/billete-sdk";
|
|
64
65
|
|
|
65
|
-
const billete = createBillete({ apiVersion: "2026-10-
|
|
66
|
+
const billete = createBillete({ apiVersion: "2026-10-16", environment: "test" });
|
|
66
67
|
|
|
67
68
|
const checkout = await billete.checkouts.create({
|
|
68
69
|
plan: "plan_…",
|
|
@@ -90,7 +91,7 @@ solicite expresamente. En carritos, solo ofrece los demás métodos que todos lo
|
|
|
90
91
|
|
|
91
92
|
```ts
|
|
92
93
|
const billete = createBillete({
|
|
93
|
-
apiVersion: "2026-10-
|
|
94
|
+
apiVersion: "2026-10-16",
|
|
94
95
|
environment: "production",
|
|
95
96
|
apiKey: process.env.BILLETE_API_KEY,
|
|
96
97
|
timeoutMs: 30_000,
|
|
@@ -222,7 +223,7 @@ try {
|
|
|
222
223
|
| Propiedad | Descripción |
|
|
223
224
|
| --- | --- |
|
|
224
225
|
| `type` | Categoría: `invalid_request`, `authentication`, `permission`, `not_found`, `conflict`, `validation`, `rate_limit`, `provider`, `internal` o `network`. |
|
|
225
|
-
| `code` | Código estable, apto para decidir en tu código. |
|
|
226
|
+
| `code` | Código estable, apto para decidir en tu código: uno del [catálogo](https://billete.run/docs/api/errors#catálogo-de-códigos) (`BilleteErrorCode`), o `network_error` / `invalid_response` del SDK. |
|
|
226
227
|
| `message` | Descripción legible del error. |
|
|
227
228
|
| `status` | Código HTTP (`0` si no hubo respuesta). |
|
|
228
229
|
| `param` | Campo que causó el error, cuando aplica. |
|
|
@@ -230,7 +231,7 @@ try {
|
|
|
230
231
|
|
|
231
232
|
## Idempotencia y reintentos
|
|
232
233
|
|
|
233
|
-
Cada mutación envía una `Idempotency-Key` generada automáticamente, que se mantiene entre
|
|
234
|
+
Cada mutación del cliente de servidor envía una `Idempotency-Key` generada automáticamente, que se mantiene entre
|
|
234
235
|
reintentos. Si quieres que un reintento tuyo (por ejemplo, de un job) también sea seguro, pasa
|
|
235
236
|
una clave estable:
|
|
236
237
|
|
|
@@ -256,7 +257,7 @@ return { token: session.token };
|
|
|
256
257
|
// Navegador
|
|
257
258
|
import { createClient } from "@boelabs/billete-sdk/client";
|
|
258
259
|
|
|
259
|
-
const billete = createClient({ apiVersion: "2026-10-
|
|
260
|
+
const billete = createClient({ apiVersion: "2026-10-16", customerSession: token });
|
|
260
261
|
|
|
261
262
|
const { data: subscriptions } = await billete.customer.subscriptions();
|
|
262
263
|
const tokens = await billete.customer.feature("tokens");
|
|
@@ -275,6 +276,19 @@ const portal = await billete.portalSessions.create({
|
|
|
275
276
|
`customerSession` también acepta una función, útil cuando el token se renueva. Sin sesión, el
|
|
276
277
|
cliente puede leer y pagar checkouts, cobros y links de pago, y consultar tasas y monedas.
|
|
277
278
|
|
|
279
|
+
El cliente de navegador solo necesita `fetch`, `AbortController` y `setTimeout`, así que funciona
|
|
280
|
+
igual en React Native y Expo, sin polyfills. No envía `Idempotency-Key`: cada mutación de
|
|
281
|
+
`/v1/client` ya rechaza su repetición por el estado de lo que cambia (un checkout con un pago en
|
|
282
|
+
curso responde `payment_in_progress`), así que reintentar es seguro.
|
|
283
|
+
|
|
284
|
+
Para saber cuándo se confirma un pago, espera el siguiente cambio en vez de consultar en bucle:
|
|
285
|
+
`waitForChange` responde en cuanto el checkout cambia, o el mismo checkout si en 25 segundos no
|
|
286
|
+
pasó nada.
|
|
287
|
+
|
|
288
|
+
```ts
|
|
289
|
+
const next = await billete.checkouts.waitForChange(checkout);
|
|
290
|
+
```
|
|
291
|
+
|
|
278
292
|
## Webhooks
|
|
279
293
|
|
|
280
294
|
Billete firma los webhooks con [Standard Webhooks](https://www.standardwebhooks.com). Verifica la
|
package/dist/client.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { $ as
|
|
2
|
-
import { $ as FulfillmentMethod, $t as PaymentFailureCode, A as Coupon, At as ResetFrequency, B as ExchangeRate, Bt as SubscriptionRenewal, C as CheckoutPurpose, Cn as
|
|
1
|
+
import { $ as ProductCheckoutCreate, A as CustomerUpdate, At as PublicPaymentState, B as InvoiceCreate, Bt as apiVersionLifecycle, C as CouponUpdate, Ct as PublicCheckout, D as CustomerMemberCreate, Dt as PublicFulfillment, E as CustomerInput, Et as PublicClaimSummary, F as FeatureUpdate, Ft as ApiVersion, G as PlanCheckoutCreate, Gt as supportedApiVersions, H as KEY_PATTERN, Ht as currentApiVersion, I as FulfillmentDeliverInput, It as ApiVersionLifecycle, J as PlanFeaturesInput, K as PlanCouponCreate, L as FulfillmentHandoverInput, Lt as ApiVersionStage, M as FeatureCreate, Mt as API_VERSIONS, N as FeatureOperationCommit, Nt as API_VERSION_HEADER, O as CustomerMemberUpdate, Ot as PublicInvoice, P as FeatureOperationCreate, Pt as API_VERSION_PATTERN, Q as PortalSessionCreate, R as FulfillmentInput, Rt as LATEST_API_VERSION, S as CouponCreate, St as PortalFeatures, T as CustomerCreate, Tt as PublicClaim, U as PaymentLinkCreate, Ut as isApiVersion, V as InvoiceLineInput, Vt as apiVersionStage, W as PaymentLinkUpdate, Wt as isApiVersionRetired, X as PlanPriceInput, Y as PlanLinkCreate, Z as PlanUpdate, _ as ClientPaymentCode, _t as PaymentInstructions, a as AfterCompletionInput, at as RetireInput, b as ClientSubscriptionUpdate, bt as PaymentNextAction, c as ClaimResolve, ct as SubscriptionChangePreviewInput, d as ClientCheckoutUpdate, dt as VariantInput, et as ProductCouponCreate, f as ClientClaimCreate, ft as WebhookEndpointCreate, g as ClientLinkCheckout, gt as FulfillmentOption, h as ClientInvoicePay, ht as CustomerSubscriptionChangeResult, i as TransportOptions, it as RefundCreate, j as EventSelector, jt as PublicPortal, k as CustomerSessionCreate, kt as PublicPaymentLink, l as ClaimRespond, lt as SubscriptionCreate, m as ClientFulfillmentProblem, mt as CustomerSubscription, n as BilleteErrorCode, nt as ProductLinkCreate, o as CheckoutCreate, ot as SubscriptionCancel, p as ClientCustomerClaimCreate, pt as WebhookEndpointUpdate, q as PlanCreate, r as RequestOptions, rt as ProductUpdate, s as CheckoutItemInput, st as SubscriptionChangeCreate, t as BilleteError, tt as ProductCreate, u as ClientCheckoutPay, ut as SubscriptionUpdate, v as ClientSubscriptionCancel, vt as PaymentMethodField, w as CustomFieldInput, wt as PublicCheckoutItem, x as CollectInput, xt as PaymentTestScenario, y as ClientSubscriptionSeats, yt as PaymentMethodOption, z as FulfillmentTrackingInput, zt as LatestApiVersion } from "./errors-CGHiFrlh.js";
|
|
2
|
+
import { $ as FulfillmentMethod, $t as PaymentFailureCode, A as Coupon, An as tokenEnvironment, At as ResetFrequency, B as ExchangeRate, Bt as SubscriptionRenewal, C as CheckoutPurpose, Cn as findBank, Ct as PortalSession, D as ClaimReason, Dn as ENVIRONMENTS, Dt as RESET_FREQUENCIES, E as ClaimOutcome, En as nationalPhone, Et as ProductVariant, F as CustomerFeature, Ft as SubmitLabel, G as FeatureOperation, Gt as Weekday, H as FULFILLMENT_METHODS, Ht as SubscriptionTerms, I as CustomerMember, It as Subscription, J as FeatureType, Jt as API_ERROR_TYPES, K as FeatureOperationResult, Kt as ReceiptReference, L as CustomerMemberList, Lt as SubscriptionChange, M as CustomField, Mt as RiskLevel, N as Customer, Nt as SUBMIT_LABELS, O as ClaimStatus, On as Environment, Ot as RISK_LEVELS, P as CustomerDetails, Pt as SUBSCRIPTION_STATUSES, Q as FulfillmentHandover, Qt as PAYMENT_FAILURE_CODES, R as CustomerSession, Rt as SubscriptionChangePreview, S as CheckoutItem, Sn as VENEZUELAN_BANKS, St as PlanSeats, T as ClaimMessage, Tn as isMobilePhone, Tt as ProductCategory, U as FULFILLMENT_STATUSES, Ut as USAGE_FEATURE_TYPES, V as FEATURE_TYPES, Vt as SubscriptionStatus, W as Feature, Wt as WebhookEndpoint, X as Fulfillment, Xt as ApiErrorEnvelope, Y as FeatureUsageResult, Yt as ApiErrorBody, Z as FulfillmentChoice, Zt as ApiErrorType, _ as CLAIM_STATUSES, _n as Metadata, _t as PaymentStatus, a as WEBHOOK_TEST_EVENT, an as BILLING_MONTHS, at as InvoiceReason, b as CarrierOffice, bn as TaxBehavior, bt as PlanFeatureValues, c as AfterCompletion, cn as CURRENCIES, ct as MAX_SEATS, d as CANCELLATION_FEEDBACK, dn as GracePeriodDays, dt as Payment, en as API_ERROR_CODES, et as FulfillmentStatus, f as CARRIERS, fn as List, ft as PaymentAttempt, g as CLAIM_REASONS, gn as MOBILE_PREFIXES, gt as PaymentSettlement, h as CLAIM_OUTCOMES, hn as MAX_QUANTITY, ht as PaymentLink, i as SubscribableEventType, in as AddressInput, it as Invoice, j as CurrencyAvailability, jn as tokenPrefix, jt as Retirement, k as CollectSettings, kn as TokenKind, kt as Refund, l as Balance, ln as Currency, lt as PAYMENT_STATUSES, m as CHECKOUT_PURPOSES, mn as ListSort, mt as PaymentFeeDetails, n as EventDataMap, nn as ACCOUNT_NUMBER_LENGTH, nt as INVOICE_REASONS, o as WebhookEvent, on as BankCode, ot as InvoiceStatus, p as CARRIER_TEST_SCENARIOS, pn as ListQuery, pt as PaymentFailure, q as FeatureReset, qt as ReceiptSend, r as EventType, rn as Address, rt as INVOICE_STATUSES, s as Actor, sn as BillingMonths, st as LineItem, t as EVENT_TYPES, tn as ApiErrorCode, tt as FulfillmentTracking, u as BalanceAmount, un as GRACE_PERIOD_DAYS, ut as PRODUCT_CATEGORIES, v as CancellationFeedback, vn as MobilePrefix, vt as Payout, w as Claim, wn as isLandlinePhone, wt as Product, x as Checkout, xn as Timestamp, xt as PlanPrice, y as Carrier, yn as TAX_BEHAVIORS, yt as Plan, z as Event, zt as SubscriptionChangeResult } from "./events-D09DIgn-.js";
|
|
3
3
|
//#region src/create-client.d.ts
|
|
4
4
|
interface ClientOptions extends TransportOptions {
|
|
5
5
|
/**
|
|
@@ -14,7 +14,7 @@ interface ClientOptions extends TransportOptions {
|
|
|
14
14
|
* and customer data requires a short-lived customer session minted by your server.
|
|
15
15
|
*
|
|
16
16
|
* ```ts
|
|
17
|
-
* const billete = createClient({ apiVersion: "2026-10-
|
|
17
|
+
* const billete = createClient({ apiVersion: "2026-10-16", customerSession: token });
|
|
18
18
|
* const [subscription] = (await billete.customer.subscriptions()).data;
|
|
19
19
|
* if (subscription?.renewal?.status === "overdue") showBanner(subscription.renewal);
|
|
20
20
|
* ```
|
|
@@ -35,6 +35,9 @@ export declare function createClient(options: ClientOptions): {
|
|
|
35
35
|
/** Goes back before authorizing: the payment fails as `canceled` and can be paid again. */
|
|
36
36
|
cancelPayment: (id: string, options?: RequestOptions) => Promise<PublicCheckout>;
|
|
37
37
|
retrieve: (id: string, options?: RequestOptions) => Promise<PublicCheckout>;
|
|
38
|
+
waitForChange: (current: PublicCheckout, options?: RequestOptions & {
|
|
39
|
+
waitSeconds?: number;
|
|
40
|
+
}) => Promise<PublicCheckout>;
|
|
38
41
|
/** Changes quantity, variant, billing cycle or coupon on a payment link checkout. */
|
|
39
42
|
update: (id: string, changes: ClientCheckoutUpdate, options?: RequestOptions) => Promise<PublicCheckout>;
|
|
40
43
|
/** Methods that can pay this checkout, with the converted amount and transfer details. */
|
|
@@ -56,6 +59,9 @@ export declare function createClient(options: ClientOptions): {
|
|
|
56
59
|
/** Goes back before authorizing: the payment fails as `canceled` and can be paid again. */
|
|
57
60
|
cancelPayment: (id: string, options?: RequestOptions) => Promise<PublicInvoice>;
|
|
58
61
|
retrieve: (id: string, options?: RequestOptions) => Promise<PublicInvoice>;
|
|
62
|
+
waitForChange: (current: PublicInvoice, options?: RequestOptions & {
|
|
63
|
+
waitSeconds?: number;
|
|
64
|
+
}) => Promise<PublicInvoice>;
|
|
59
65
|
/** Methods that can pay this Cobro, with the converted amount and transfer details. */
|
|
60
66
|
paymentMethods: (id: string, options?: RequestOptions) => Promise<List<PaymentMethodOption>>;
|
|
61
67
|
/** Submits the payment; the returned Cobro carries the payment status and any failure. */
|
|
@@ -128,4 +134,4 @@ export declare function createClient(options: ClientOptions): {
|
|
|
128
134
|
};
|
|
129
135
|
type BilleteClient = ReturnType<typeof createClient>;
|
|
130
136
|
//#endregion
|
|
131
|
-
export { type ACCOUNT_NUMBER_LENGTH, type API_ERROR_TYPES, type API_VERSIONS, type API_VERSION_HEADER, type API_VERSION_PATTERN, type Actor, type Address, type AddressInput, type AfterCompletion, type AfterCompletionInput, type ApiErrorBody, type ApiErrorEnvelope, type ApiErrorType, type ApiVersion, type ApiVersionLifecycle, type ApiVersionStage, type BILLING_MONTHS, type Balance, type BalanceAmount, type BankCode, type BilleteClient, BilleteError, type BillingMonths, type CANCELLATION_FEEDBACK, type CARRIERS, type CARRIER_TEST_SCENARIOS, type CHECKOUT_PURPOSES, type CLAIM_OUTCOMES, type CLAIM_REASONS, type CLAIM_STATUSES, type CURRENCIES, type CancellationFeedback, type Carrier, type CarrierOffice, type Checkout, type CheckoutCreate, type CheckoutItem, type CheckoutItemInput, type CheckoutPurpose, type Claim, type ClaimMessage, type ClaimOutcome, type ClaimReason, type ClaimResolve, type ClaimRespond, type ClaimStatus, type ClientCheckoutPay, type ClientCheckoutUpdate, type ClientClaimCreate, type ClientCustomerClaimCreate, type ClientFulfillmentProblem, type ClientInvoicePay, type ClientLinkCheckout, type ClientOptions, type ClientPaymentCode, type ClientSubscriptionCancel, type ClientSubscriptionSeats, type ClientSubscriptionUpdate, type CollectInput, type CollectSettings, type Coupon, type CouponCreate, type CouponUpdate, type Currency, type CurrencyAvailability, type CustomField, type CustomFieldInput, type Customer, type CustomerCreate, type CustomerDetails, type CustomerFeature, type CustomerInput, type CustomerMember, type CustomerMemberCreate, type CustomerMemberList, type CustomerMemberUpdate, type CustomerSession, type CustomerSessionCreate, type CustomerSubscription, type CustomerSubscriptionChangeResult, type CustomerUpdate, type ENVIRONMENTS, type EVENT_TYPES, type Environment, type Event, type EventDataMap, type EventSelector, type EventType, type ExchangeRate, type FEATURE_TYPES, type FULFILLMENT_METHODS, type FULFILLMENT_STATUSES, type Feature, type FeatureCreate, type FeatureOperation, type FeatureOperationCommit, type FeatureOperationCreate, type FeatureOperationResult, type FeatureReset, type FeatureType, type FeatureUpdate, type FeatureUsageResult, type Fulfillment, type FulfillmentChoice, type FulfillmentDeliverInput, type FulfillmentHandover, type FulfillmentHandoverInput, type FulfillmentInput, type FulfillmentMethod, type FulfillmentOption, type FulfillmentStatus, type FulfillmentTracking, type FulfillmentTrackingInput, type GRACE_PERIOD_DAYS, type GracePeriodDays, type INVOICE_REASONS, type INVOICE_STATUSES, type Invoice, type InvoiceCreate, type InvoiceLineInput, type InvoiceReason, type InvoiceStatus, type KEY_PATTERN, type LATEST_API_VERSION, type LatestApiVersion, type LineItem, type List, type ListQuery, type ListSort, type MAX_QUANTITY, type MAX_SEATS, type MOBILE_PREFIXES, type Metadata, type MobilePrefix, type PAYMENT_FAILURE_CODES, type PAYMENT_STATUSES, type PRODUCT_CATEGORIES, type Payment, type PaymentAttempt, type PaymentFailure, type PaymentFailureCode, type PaymentFeeDetails, type PaymentInstructions, type PaymentLink, type PaymentLinkCreate, type PaymentLinkUpdate, type PaymentMethodField, type PaymentMethodOption, type PaymentNextAction, type PaymentSettlement, type PaymentStatus, type PaymentTestScenario, type Payout, type Plan, type PlanCheckoutCreate, type PlanCouponCreate, type PlanCreate, type PlanFeatureValues, type PlanFeaturesInput, type PlanLinkCreate, type PlanPrice, type PlanPriceInput, type PlanSeats, type PlanUpdate, type PortalFeatures, type PortalSession, type PortalSessionCreate, type Product, type ProductCategory, type ProductCheckoutCreate, type ProductCouponCreate, type ProductCreate, type ProductLinkCreate, type ProductUpdate, type ProductVariant, type PublicCheckout, type PublicClaim, type PublicClaimSummary, type PublicFulfillment, type PublicInvoice, type PublicPaymentLink, type PublicPaymentState, type PublicPortal, type RESET_FREQUENCIES, type RISK_LEVELS, type ReceiptReference, type ReceiptSend, type Refund, type RefundCreate, type RequestOptions, type ResetFrequency, type RetireInput, type Retirement, type RiskLevel, type SUBMIT_LABELS, type SUBSCRIPTION_STATUSES, type SubmitLabel, type SubscribableEventType, type Subscription, type SubscriptionCancel, type SubscriptionChange, type SubscriptionChangeCreate, type SubscriptionChangePreview, type SubscriptionChangePreviewInput, type SubscriptionChangeResult, type SubscriptionCreate, type SubscriptionRenewal, type SubscriptionStatus, type SubscriptionTerms, type SubscriptionUpdate, type TAX_BEHAVIORS, type TaxBehavior, type Timestamp, type TokenKind, type USAGE_FEATURE_TYPES, type VENEZUELAN_BANKS, type VariantInput, type WEBHOOK_TEST_EVENT, type WebhookEndpoint, type WebhookEndpointCreate, type WebhookEndpointUpdate, type WebhookEvent, type Weekday, type apiVersionLifecycle, type apiVersionStage, type currentApiVersion, type findBank, type isApiVersion, type isApiVersionRetired, type isLandlinePhone, type isMobilePhone, type nationalPhone, type supportedApiVersions, type tokenEnvironment, type tokenPrefix };
|
|
137
|
+
export { type ACCOUNT_NUMBER_LENGTH, type API_ERROR_CODES, type API_ERROR_TYPES, type API_VERSIONS, type API_VERSION_HEADER, type API_VERSION_PATTERN, type Actor, type Address, type AddressInput, type AfterCompletion, type AfterCompletionInput, type ApiErrorBody, type ApiErrorCode, type ApiErrorEnvelope, type ApiErrorType, type ApiVersion, type ApiVersionLifecycle, type ApiVersionStage, type BILLING_MONTHS, type Balance, type BalanceAmount, type BankCode, type BilleteClient, BilleteError, type BilleteErrorCode, type BillingMonths, type CANCELLATION_FEEDBACK, type CARRIERS, type CARRIER_TEST_SCENARIOS, type CHECKOUT_PURPOSES, type CLAIM_OUTCOMES, type CLAIM_REASONS, type CLAIM_STATUSES, type CURRENCIES, type CancellationFeedback, type Carrier, type CarrierOffice, type Checkout, type CheckoutCreate, type CheckoutItem, type CheckoutItemInput, type CheckoutPurpose, type Claim, type ClaimMessage, type ClaimOutcome, type ClaimReason, type ClaimResolve, type ClaimRespond, type ClaimStatus, type ClientCheckoutPay, type ClientCheckoutUpdate, type ClientClaimCreate, type ClientCustomerClaimCreate, type ClientFulfillmentProblem, type ClientInvoicePay, type ClientLinkCheckout, type ClientOptions, type ClientPaymentCode, type ClientSubscriptionCancel, type ClientSubscriptionSeats, type ClientSubscriptionUpdate, type CollectInput, type CollectSettings, type Coupon, type CouponCreate, type CouponUpdate, type Currency, type CurrencyAvailability, type CustomField, type CustomFieldInput, type Customer, type CustomerCreate, type CustomerDetails, type CustomerFeature, type CustomerInput, type CustomerMember, type CustomerMemberCreate, type CustomerMemberList, type CustomerMemberUpdate, type CustomerSession, type CustomerSessionCreate, type CustomerSubscription, type CustomerSubscriptionChangeResult, type CustomerUpdate, type ENVIRONMENTS, type EVENT_TYPES, type Environment, type Event, type EventDataMap, type EventSelector, type EventType, type ExchangeRate, type FEATURE_TYPES, type FULFILLMENT_METHODS, type FULFILLMENT_STATUSES, type Feature, type FeatureCreate, type FeatureOperation, type FeatureOperationCommit, type FeatureOperationCreate, type FeatureOperationResult, type FeatureReset, type FeatureType, type FeatureUpdate, type FeatureUsageResult, type Fulfillment, type FulfillmentChoice, type FulfillmentDeliverInput, type FulfillmentHandover, type FulfillmentHandoverInput, type FulfillmentInput, type FulfillmentMethod, type FulfillmentOption, type FulfillmentStatus, type FulfillmentTracking, type FulfillmentTrackingInput, type GRACE_PERIOD_DAYS, type GracePeriodDays, type INVOICE_REASONS, type INVOICE_STATUSES, type Invoice, type InvoiceCreate, type InvoiceLineInput, type InvoiceReason, type InvoiceStatus, type KEY_PATTERN, type LATEST_API_VERSION, type LatestApiVersion, type LineItem, type List, type ListQuery, type ListSort, type MAX_QUANTITY, type MAX_SEATS, type MOBILE_PREFIXES, type Metadata, type MobilePrefix, type PAYMENT_FAILURE_CODES, type PAYMENT_STATUSES, type PRODUCT_CATEGORIES, type Payment, type PaymentAttempt, type PaymentFailure, type PaymentFailureCode, type PaymentFeeDetails, type PaymentInstructions, type PaymentLink, type PaymentLinkCreate, type PaymentLinkUpdate, type PaymentMethodField, type PaymentMethodOption, type PaymentNextAction, type PaymentSettlement, type PaymentStatus, type PaymentTestScenario, type Payout, type Plan, type PlanCheckoutCreate, type PlanCouponCreate, type PlanCreate, type PlanFeatureValues, type PlanFeaturesInput, type PlanLinkCreate, type PlanPrice, type PlanPriceInput, type PlanSeats, type PlanUpdate, type PortalFeatures, type PortalSession, type PortalSessionCreate, type Product, type ProductCategory, type ProductCheckoutCreate, type ProductCouponCreate, type ProductCreate, type ProductLinkCreate, type ProductUpdate, type ProductVariant, type PublicCheckout, type PublicCheckoutItem, type PublicClaim, type PublicClaimSummary, type PublicFulfillment, type PublicInvoice, type PublicPaymentLink, type PublicPaymentState, type PublicPortal, type RESET_FREQUENCIES, type RISK_LEVELS, type ReceiptReference, type ReceiptSend, type Refund, type RefundCreate, type RequestOptions, type ResetFrequency, type RetireInput, type Retirement, type RiskLevel, type SUBMIT_LABELS, type SUBSCRIPTION_STATUSES, type SubmitLabel, type SubscribableEventType, type Subscription, type SubscriptionCancel, type SubscriptionChange, type SubscriptionChangeCreate, type SubscriptionChangePreview, type SubscriptionChangePreviewInput, type SubscriptionChangeResult, type SubscriptionCreate, type SubscriptionRenewal, type SubscriptionStatus, type SubscriptionTerms, type SubscriptionUpdate, type TAX_BEHAVIORS, type TaxBehavior, type Timestamp, type TokenKind, type USAGE_FEATURE_TYPES, type VENEZUELAN_BANKS, type VariantInput, type WEBHOOK_TEST_EVENT, type WebhookEndpoint, type WebhookEndpointCreate, type WebhookEndpointUpdate, type WebhookEvent, type Weekday, type apiVersionLifecycle, type apiVersionStage, type currentApiVersion, type findBank, type isApiVersion, type isApiVersionRetired, type isLandlinePhone, type isMobilePhone, type nationalPhone, type supportedApiVersions, type tokenEnvironment, type tokenPrefix };
|
package/dist/client.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as segment, r as BilleteError, t as createTransport } from "./http-
|
|
1
|
+
import { n as segment, r as BilleteError, t as createTransport } from "./http-D5FMIjK4.js";
|
|
2
2
|
//#region src/create-client.ts
|
|
3
3
|
/**
|
|
4
4
|
* Browser client. It never holds a secret key: checkouts and Cobros are addressed by their
|
|
@@ -6,7 +6,7 @@ import { n as segment, r as BilleteError, t as createTransport } from "./http-CC
|
|
|
6
6
|
* and customer data requires a short-lived customer session minted by your server.
|
|
7
7
|
*
|
|
8
8
|
* ```ts
|
|
9
|
-
* const billete = createClient({ apiVersion: "2026-10-
|
|
9
|
+
* const billete = createClient({ apiVersion: "2026-10-16", customerSession: token });
|
|
10
10
|
* const [subscription] = (await billete.customer.subscriptions()).data;
|
|
11
11
|
* if (subscription?.renewal?.status === "overdue") showBanner(subscription.renewal);
|
|
12
12
|
* ```
|
|
@@ -18,6 +18,22 @@ function createClient(options) {
|
|
|
18
18
|
token: typeof session === "function" ? session : () => session
|
|
19
19
|
});
|
|
20
20
|
const checkoutPath = (id) => `/v1/client/checkouts/${segment(id)}`;
|
|
21
|
+
/** Under the transport's timeout, so a wait ends before the request gives up. */
|
|
22
|
+
const longestWait = Math.max(0, Math.min(25, Math.floor((options.timeoutMs ?? 3e4) / 1e3) - 5));
|
|
23
|
+
/**
|
|
24
|
+
* Waits until a checkout or Cobro changes (its `revision`), up to `waitSeconds` (25 at most), and
|
|
25
|
+
* answers it changed, or the same one when nothing happened meanwhile: call it in a loop while
|
|
26
|
+
* the payment is pending instead of retrieving it every few seconds.
|
|
27
|
+
*/
|
|
28
|
+
const waitForChange = (path) => async (current, options) => await http.request({
|
|
29
|
+
method: "GET",
|
|
30
|
+
path: path(current.id),
|
|
31
|
+
headers: {
|
|
32
|
+
"If-None-Match": `"${current.revision}"`,
|
|
33
|
+
Prefer: `wait=${Math.min(options?.waitSeconds ?? longestWait, longestWait)}`
|
|
34
|
+
},
|
|
35
|
+
options
|
|
36
|
+
}) ?? current;
|
|
21
37
|
/** A pending payment that waits for a code the payer received (`nextAction.type === "code"`). */
|
|
22
38
|
const paymentCode = (path) => ({
|
|
23
39
|
/** Authorizes the payment with the code; a wrong one fails with `payment_code_invalid`. */
|
|
@@ -73,6 +89,7 @@ function createClient(options) {
|
|
|
73
89
|
path: checkoutPath(id),
|
|
74
90
|
options
|
|
75
91
|
}),
|
|
92
|
+
waitForChange: waitForChange(checkoutPath),
|
|
76
93
|
/** Changes quantity, variant, billing cycle or coupon on a payment link checkout. */
|
|
77
94
|
update: (id, changes, options) => http.request({
|
|
78
95
|
method: "PATCH",
|
|
@@ -102,6 +119,7 @@ function createClient(options) {
|
|
|
102
119
|
path: invoicePath(id),
|
|
103
120
|
options
|
|
104
121
|
}),
|
|
122
|
+
waitForChange: waitForChange(invoicePath),
|
|
105
123
|
/** Methods that can pay this Cobro, with the converted amount and transfer details. */
|
|
106
124
|
paymentMethods: (id, options) => http.request({
|
|
107
125
|
method: "GET",
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { $ as FulfillmentMethod, C as CheckoutPurpose, D as ClaimReason, E as ClaimOutcome,
|
|
1
|
+
import { $ as FulfillmentMethod, $t as PaymentFailureCode, C as CheckoutPurpose, D as ClaimReason, E as ClaimOutcome, Ft as SubmitLabel, It as Subscription, Kt as ReceiptReference, M as CustomField, O as ClaimStatus, On as Environment, P as CustomerDetails, S as CheckoutItem, St as PlanSeats, T as ClaimMessage, Tt as ProductCategory, X as Fulfillment, Yt as ApiErrorBody, Zt as ApiErrorType, _n as Metadata, _t as PaymentStatus, at as InvoiceReason, b as CarrierOffice, bn as TaxBehavior, c as AfterCompletion, dn as GracePeriodDays, et as FulfillmentStatus, i as SubscribableEventType, in as AddressInput, k as CollectSettings, kt as Refund, ln as Currency, ot as InvoiceStatus, pt as PaymentFailure, q as FeatureReset, rn as Address, sn as BillingMonths, st as LineItem, tn as ApiErrorCode, tt as FulfillmentTracking, v as CancellationFeedback, xn as Timestamp, xt as PlanPrice, y as Carrier } from "./events-D09DIgn-.js";
|
|
2
2
|
//#region ../contracts/src/api-versions.d.ts
|
|
3
3
|
/**
|
|
4
4
|
* Billete API versions. Kept free of runtime dependencies: the dashboard, the API, the worker and
|
|
@@ -10,7 +10,7 @@ import { $ as FulfillmentMethod, C as CheckoutPurpose, D as ClaimReason, E as Cl
|
|
|
10
10
|
* that is still supported.
|
|
11
11
|
*/
|
|
12
12
|
/** Every version ever published, oldest first. Append only: retired versions stay listed. */
|
|
13
|
-
declare const API_VERSIONS: readonly ["2026-10-07.beta", "2026-10-08", "2026-10-09", "2026-10-10"];
|
|
13
|
+
declare const API_VERSIONS: readonly ["2026-10-07.beta", "2026-10-08", "2026-10-09", "2026-10-10", "2026-10-16"];
|
|
14
14
|
type ApiVersion = (typeof API_VERSIONS)[number];
|
|
15
15
|
type LatestApiVersion = typeof API_VERSIONS extends readonly [...unknown[], infer Last] ? Last : never;
|
|
16
16
|
/** The version the code speaks: responses are built in its shape. Always the last entry. */
|
|
@@ -154,6 +154,13 @@ interface PublicInvoice {
|
|
|
154
154
|
paidAt: Timestamp | null;
|
|
155
155
|
createdAt: Timestamp;
|
|
156
156
|
payment: PublicPaymentState | null;
|
|
157
|
+
/** Changes whenever the Cobro does: send it to wait for the next change (`waitForChange`). */
|
|
158
|
+
revision: string;
|
|
159
|
+
}
|
|
160
|
+
/** What a checkout sells, with the business's own name for it. */
|
|
161
|
+
interface PublicCheckoutItem extends CheckoutItem {
|
|
162
|
+
/** The `lookupKey` of the plan or product, as it is now; `null` when it has none. */
|
|
163
|
+
lookupKey: string | null;
|
|
157
164
|
}
|
|
158
165
|
/** Browser-safe view of a checkout: everything needed to render and pay it, nothing internal. */
|
|
159
166
|
interface PublicCheckout {
|
|
@@ -171,6 +178,8 @@ interface PublicCheckout {
|
|
|
171
178
|
id: string;
|
|
172
179
|
object: "checkout";
|
|
173
180
|
environment: Environment;
|
|
181
|
+
/** The checkout's hosted page: where to send the customer to pay it there instead. */
|
|
182
|
+
url: string;
|
|
174
183
|
status: "open" | "completed" | "expired";
|
|
175
184
|
purpose: CheckoutPurpose;
|
|
176
185
|
merchant: {
|
|
@@ -179,7 +188,7 @@ interface PublicCheckout {
|
|
|
179
188
|
supportPhone: string | null;
|
|
180
189
|
};
|
|
181
190
|
email: string | null;
|
|
182
|
-
items:
|
|
191
|
+
items: PublicCheckoutItem[];
|
|
183
192
|
currency: Currency;
|
|
184
193
|
subtotal: number;
|
|
185
194
|
discount: number;
|
|
@@ -229,6 +238,8 @@ interface PublicCheckout {
|
|
|
229
238
|
cancelUrl: string | null;
|
|
230
239
|
expiresAt: Timestamp;
|
|
231
240
|
payment: PublicPaymentState | null;
|
|
241
|
+
/** Changes whenever the checkout does: send it to wait for the next change (`waitForChange`). */
|
|
242
|
+
revision: string;
|
|
232
243
|
}
|
|
233
244
|
/** A way to receive a purchase that the business offers, as its checkout shows it. */
|
|
234
245
|
interface FulfillmentOption {
|
|
@@ -365,13 +376,27 @@ interface PaymentInstructions {
|
|
|
365
376
|
qrImage: string | null;
|
|
366
377
|
notes: string | null;
|
|
367
378
|
}
|
|
368
|
-
/**
|
|
379
|
+
/**
|
|
380
|
+
* What to send, step by step, for a known result in the test environment: `fields` go in `pay`
|
|
381
|
+
* and, for a method that asks for a code after paying (`verification`), `code` goes in
|
|
382
|
+
* `submitPaymentCode`.
|
|
383
|
+
*/
|
|
369
384
|
interface PaymentTestScenario {
|
|
370
|
-
outcome: "succeeded" | "failed" | "pending";
|
|
371
385
|
description: string;
|
|
386
|
+
/** Sent in `pay`; empty for the default scenario. */
|
|
372
387
|
fields: Record<string, string>;
|
|
388
|
+
/** Sent in `submitPaymentCode`; `null` when the method asks for no code. */
|
|
389
|
+
code: string | null;
|
|
390
|
+
/**
|
|
391
|
+
* How it ends: paid, failed (`failureCode` says why), still waiting for the provider or for
|
|
392
|
+
* what `nextAction` asks, or the code refused with `payment_code_invalid` while the payment
|
|
393
|
+
* keeps waiting for another.
|
|
394
|
+
*/
|
|
395
|
+
outcome: "succeeded" | "failed" | "pending" | "code_invalid";
|
|
396
|
+
failureCode: PaymentFailureCode | null;
|
|
373
397
|
}
|
|
374
398
|
interface PaymentMethodOption {
|
|
399
|
+
object: "payment_method";
|
|
375
400
|
id: string;
|
|
376
401
|
name: string;
|
|
377
402
|
description: string | null;
|
|
@@ -379,6 +404,12 @@ interface PaymentMethodOption {
|
|
|
379
404
|
amount: number;
|
|
380
405
|
currency: Currency;
|
|
381
406
|
exchangeRate: string | null;
|
|
407
|
+
/**
|
|
408
|
+
* Until when `amount` holds at `exchangeRate`: the rate is frozen for the payer for 30 minutes.
|
|
409
|
+
* Listing the methods after that quotes them again. `null` when the method charges the price's
|
|
410
|
+
* own currency.
|
|
411
|
+
*/
|
|
412
|
+
expiresAt: Timestamp | null;
|
|
382
413
|
fields: PaymentMethodField[];
|
|
383
414
|
/** After paying, the payer verifies it in a step of its own (`nextAction.type === "code"`). */
|
|
384
415
|
verification: boolean;
|
|
@@ -558,6 +589,8 @@ interface VariantInput {
|
|
|
558
589
|
}
|
|
559
590
|
interface ProductCreate {
|
|
560
591
|
name: string;
|
|
592
|
+
/** Public and unique among the business's products: see `Product.lookupKey`. */
|
|
593
|
+
lookupKey?: string;
|
|
561
594
|
description?: string;
|
|
562
595
|
imageUrl?: string;
|
|
563
596
|
category?: ProductCategory;
|
|
@@ -573,6 +606,8 @@ interface ProductCreate {
|
|
|
573
606
|
}
|
|
574
607
|
interface ProductUpdate {
|
|
575
608
|
name?: string;
|
|
609
|
+
/** Public and unique among the business's products: see `Product.lookupKey`. */
|
|
610
|
+
lookupKey?: string | null;
|
|
576
611
|
description?: string | null;
|
|
577
612
|
imageUrl?: string | null;
|
|
578
613
|
category?: ProductCategory;
|
|
@@ -634,6 +669,8 @@ interface PlanCreate {
|
|
|
634
669
|
seats?: PlanSeats;
|
|
635
670
|
fallbackPlanId?: string | null;
|
|
636
671
|
name: string;
|
|
672
|
+
/** Public and unique among the business's plans: see `Plan.lookupKey`. */
|
|
673
|
+
lookupKey?: string;
|
|
637
674
|
description?: string;
|
|
638
675
|
currency: Currency;
|
|
639
676
|
prices: PlanPriceInput[];
|
|
@@ -648,6 +685,8 @@ interface PlanUpdate {
|
|
|
648
685
|
seats?: PlanSeats;
|
|
649
686
|
fallbackPlanId?: string | null;
|
|
650
687
|
name?: string;
|
|
688
|
+
/** Public and unique among the business's plans: see `Plan.lookupKey`. */
|
|
689
|
+
lookupKey?: string | null;
|
|
651
690
|
description?: string | null;
|
|
652
691
|
/** New prices apply to new subscriptions; existing ones keep the price they signed up with. */
|
|
653
692
|
prices?: PlanPriceInput[];
|
|
@@ -880,6 +919,12 @@ interface InvoiceCreate {
|
|
|
880
919
|
interface ClientInvoicePay {
|
|
881
920
|
method: string;
|
|
882
921
|
fields?: Record<string, string>;
|
|
922
|
+
/**
|
|
923
|
+
* The `amount` of the method the payer saw (`paymentMethods`). With a converted price, a
|
|
924
|
+
* different amount, after the rate they saw expired, is refused with `exchange_rate_changed`
|
|
925
|
+
* and nothing is charged.
|
|
926
|
+
*/
|
|
927
|
+
amount?: number;
|
|
883
928
|
}
|
|
884
929
|
/** The code the payer received to authorize a charge (`nextAction.type === "code"`). */
|
|
885
930
|
interface ClientPaymentCode {
|
|
@@ -942,6 +987,12 @@ interface ClientCheckoutPay {
|
|
|
942
987
|
/** Omit only when the checkout total is 0 (free trial, full discount). */
|
|
943
988
|
method?: string;
|
|
944
989
|
fields?: Record<string, string>;
|
|
990
|
+
/**
|
|
991
|
+
* The `amount` of the method the payer saw (`paymentMethods`). With a converted price, a
|
|
992
|
+
* different amount, after the rate they saw expired, is refused with `exchange_rate_changed`
|
|
993
|
+
* and nothing is charged.
|
|
994
|
+
*/
|
|
995
|
+
amount?: number;
|
|
945
996
|
email?: string;
|
|
946
997
|
name?: string;
|
|
947
998
|
phone?: string;
|
|
@@ -1041,22 +1092,33 @@ interface TransportOptions {
|
|
|
1041
1092
|
maxRetries?: number;
|
|
1042
1093
|
}
|
|
1043
1094
|
interface RequestOptions {
|
|
1044
|
-
/**
|
|
1095
|
+
/**
|
|
1096
|
+
* Server client: reuse to make a mutation safe to retry; generated automatically when omitted.
|
|
1097
|
+
* The browser client sends none: what each of its mutations changes (a checkout's payment, a
|
|
1098
|
+
* code) already refuses a repeat.
|
|
1099
|
+
*/
|
|
1045
1100
|
idempotencyKey?: string;
|
|
1046
1101
|
signal?: AbortSignal;
|
|
1047
1102
|
}
|
|
1048
1103
|
//#endregion
|
|
1049
1104
|
//#region src/errors.d.ts
|
|
1105
|
+
/**
|
|
1106
|
+
* What a failed request says: a code of the API (`API_ERROR_CODES` lists what each means), or the
|
|
1107
|
+
* SDK's own when Billete could not be reached (`network_error`) or answered something unexpected
|
|
1108
|
+
* (`invalid_response`).
|
|
1109
|
+
*/
|
|
1110
|
+
type BilleteErrorCode = ApiErrorCode | "network_error" | "invalid_response";
|
|
1050
1111
|
/** Any failed Billete request. `type`/`code` are stable and safe to branch on. */
|
|
1051
1112
|
declare class BilleteError extends Error {
|
|
1052
1113
|
readonly type: ApiErrorType | "network";
|
|
1053
|
-
readonly code:
|
|
1114
|
+
readonly code: BilleteErrorCode;
|
|
1054
1115
|
readonly status: number;
|
|
1055
1116
|
readonly param?: string;
|
|
1056
1117
|
readonly requestId?: string;
|
|
1057
|
-
constructor(body: Omit<ApiErrorBody, "type"> & {
|
|
1118
|
+
constructor(body: Omit<ApiErrorBody, "type" | "code"> & {
|
|
1058
1119
|
type: ApiErrorType | "network";
|
|
1120
|
+
code: BilleteErrorCode;
|
|
1059
1121
|
}, status: number, options?: ErrorOptions);
|
|
1060
1122
|
}
|
|
1061
1123
|
//#endregion
|
|
1062
|
-
export {
|
|
1124
|
+
export { ProductCheckoutCreate as $, CustomerUpdate as A, PublicPaymentState as At, InvoiceCreate as B, apiVersionLifecycle as Bt, CouponUpdate as C, PublicCheckout as Ct, CustomerMemberCreate as D, PublicFulfillment as Dt, CustomerInput as E, PublicClaimSummary as Et, FeatureUpdate as F, ApiVersion as Ft, PlanCheckoutCreate as G, supportedApiVersions as Gt, KEY_PATTERN as H, currentApiVersion as Ht, FulfillmentDeliverInput as I, ApiVersionLifecycle as It, PlanFeaturesInput as J, PlanCouponCreate as K, FulfillmentHandoverInput as L, ApiVersionStage as Lt, FeatureCreate as M, API_VERSIONS as Mt, FeatureOperationCommit as N, API_VERSION_HEADER as Nt, CustomerMemberUpdate as O, PublicInvoice as Ot, FeatureOperationCreate as P, API_VERSION_PATTERN as Pt, PortalSessionCreate as Q, FulfillmentInput as R, LATEST_API_VERSION as Rt, CouponCreate as S, PortalFeatures as St, CustomerCreate as T, PublicClaim as Tt, PaymentLinkCreate as U, isApiVersion as Ut, InvoiceLineInput as V, apiVersionStage as Vt, PaymentLinkUpdate as W, isApiVersionRetired as Wt, PlanPriceInput as X, PlanLinkCreate as Y, PlanUpdate as Z, ClientPaymentCode as _, PaymentInstructions as _t, AfterCompletionInput as a, RetireInput as at, ClientSubscriptionUpdate as b, PaymentNextAction as bt, ClaimResolve as c, SubscriptionChangePreviewInput as ct, ClientCheckoutUpdate as d, VariantInput as dt, ProductCouponCreate as et, ClientClaimCreate as f, WebhookEndpointCreate as ft, ClientLinkCheckout as g, FulfillmentOption as gt, ClientInvoicePay as h, CustomerSubscriptionChangeResult as ht, TransportOptions as i, RefundCreate as it, EventSelector as j, PublicPortal as jt, CustomerSessionCreate as k, PublicPaymentLink as kt, ClaimRespond as l, SubscriptionCreate as lt, ClientFulfillmentProblem as m, CustomerSubscription as mt, BilleteErrorCode as n, ProductLinkCreate as nt, CheckoutCreate as o, SubscriptionCancel as ot, ClientCustomerClaimCreate as p, WebhookEndpointUpdate as pt, PlanCreate as q, RequestOptions as r, ProductUpdate as rt, CheckoutItemInput as s, SubscriptionChangeCreate as st, BilleteError as t, ProductCreate as tt, ClientCheckoutPay as u, SubscriptionUpdate as ut, ClientSubscriptionCancel as v, PaymentMethodField as vt, CustomFieldInput as w, PublicCheckoutItem as wt, CollectInput as x, PaymentTestScenario as xt, ClientSubscriptionSeats as y, PaymentMethodOption as yt, FulfillmentTrackingInput as z, LatestApiVersion as zt };
|
|
@@ -250,12 +250,231 @@ interface List<T> {
|
|
|
250
250
|
/** ISO 8601 timestamp in UTC. */
|
|
251
251
|
type Timestamp = string;
|
|
252
252
|
//#endregion
|
|
253
|
+
//#region ../contracts/src/error-codes.d.ts
|
|
254
|
+
/**
|
|
255
|
+
* Every `code` the API may answer with in `/v1` and `/v1/client`, with what it means. Stable: an
|
|
256
|
+
* integration may decide on them. A new code is an incompatible change and ships in a new API
|
|
257
|
+
* version; the dashboard's own codes are not here (`DASHBOARD_ERROR_CODES`).
|
|
258
|
+
*/
|
|
259
|
+
declare const API_ERROR_CODES: {
|
|
260
|
+
readonly account_not_found: "No existe el negocio.";
|
|
261
|
+
readonly account_suspended: "Este negocio está suspendido.";
|
|
262
|
+
readonly address_required: "Falta la dirección que pide el checkout.";
|
|
263
|
+
readonly amount_required: "El producto sin variantes necesita un precio.";
|
|
264
|
+
readonly amount_too_large: "El importe total supera el máximo permitido.";
|
|
265
|
+
readonly api_key_expired: "Esta clave API venció.";
|
|
266
|
+
readonly api_key_invalid: "La clave API no es válida.";
|
|
267
|
+
readonly api_key_missing: "Falta la cabecera Authorization con tu clave secreta (Bearer).";
|
|
268
|
+
readonly api_version_invalid: "Esa versión de la API no existe; usa una versión vigente.";
|
|
269
|
+
readonly api_version_missing: "Falta la cabecera Billete-Version con la versión de la API de tu integración.";
|
|
270
|
+
readonly api_version_retired: "Esa versión de la API ya se retiró; elige una vigente.";
|
|
271
|
+
readonly approval_not_open: "Esta solicitud ya terminó.";
|
|
272
|
+
readonly approval_not_pending: "Esta solicitud ya no espera una decisión.";
|
|
273
|
+
readonly approval_own_request: "Otra persona debe aprobar o rechazar tu solicitud; tú puedes cancelarla.";
|
|
274
|
+
readonly approval_request_not_found: "No existe la solicitud de aprobación.";
|
|
275
|
+
readonly auto_charge_off: "Esta suscripción no se cobra automáticamente.";
|
|
276
|
+
readonly billing_cycle_unavailable: "Este ciclo de pago no está disponible.";
|
|
277
|
+
readonly business_type_required: "Elige primero el tipo de organización.";
|
|
278
|
+
readonly carrier_office_unavailable: "Esa oficina ya no recibe envíos; elige otra.";
|
|
279
|
+
readonly checkout_completed: "Este checkout ya fue pagado.";
|
|
280
|
+
readonly checkout_expired: "Este checkout venció.";
|
|
281
|
+
readonly checkout_not_editable: "Este checkout no se puede modificar.";
|
|
282
|
+
readonly checkout_not_found: "No existe el checkout.";
|
|
283
|
+
readonly checkout_not_open: "Solo se pueden vencer checkouts abiertos.";
|
|
284
|
+
readonly checkout_selection_locked: "El producto o la variante fue retirado. Puedes completar el pago con la selección actual, pero no modificarla.";
|
|
285
|
+
readonly claim_already_open: "Ya tienes un reclamo abierto por este pago: síguelo desde el enlace que te enviamos por correo.";
|
|
286
|
+
readonly claim_closed: "Este reclamo ya está cerrado.";
|
|
287
|
+
readonly claim_limit_reached: "Ya no puedes abrir más reclamos por este pago: escribe directamente al negocio.";
|
|
288
|
+
readonly claim_messages_limit: "Este reclamo ya tiene demasiados mensajes: es momento de resolverlo.";
|
|
289
|
+
readonly claim_not_found: "No existe el reclamo.";
|
|
290
|
+
readonly coupon_already_used: "Ya usaste este cupón.";
|
|
291
|
+
readonly coupon_applies_to_required: "Indica si el cupón es para productos o para planes (appliesTo).";
|
|
292
|
+
readonly coupon_currency_mismatch: "El cupón solo aplica a precios en otra moneda.";
|
|
293
|
+
readonly coupon_exhausted: "El cupón alcanzó su límite de usos.";
|
|
294
|
+
readonly coupon_exists: "Ya existe un cupón con ese código.";
|
|
295
|
+
readonly coupon_expired: "El cupón venció.";
|
|
296
|
+
readonly coupon_first_purchase_only: "Este cupón es solo para tu primera compra.";
|
|
297
|
+
readonly coupon_inactive: "El cupón está desactivado.";
|
|
298
|
+
readonly coupon_minimum_not_met: "El pedido no llega a la compra mínima del cupón.";
|
|
299
|
+
readonly coupon_not_applicable: "Un cupón no aplica a puestos agregados a mitad del periodo.";
|
|
300
|
+
readonly coupon_not_found: "No existe el cupón.";
|
|
301
|
+
readonly coupons_not_allowed: "Este enlace no acepta cupones.";
|
|
302
|
+
readonly currency_mismatch: "Todos los productos deben usar la misma moneda.";
|
|
303
|
+
readonly custom_field_invalid: "El valor de un campo personalizado no es válido; `param` dice cuál.";
|
|
304
|
+
readonly custom_field_required: "Falta un campo personalizado obligatorio; `param` dice cuál.";
|
|
305
|
+
readonly customer_changed: "El cliente cambió durante la operación; vuelve a intentarlo.";
|
|
306
|
+
readonly customer_exists: "Ya existe un cliente con este externalId.";
|
|
307
|
+
readonly customer_not_found: "No existe el cliente.";
|
|
308
|
+
readonly customer_session_invalid: "La sesión no es válida o venció.";
|
|
309
|
+
readonly customer_session_missing: "Falta la cabecera Authorization con el token de la sesión del cliente (Bearer).";
|
|
310
|
+
readonly delivery_proofs_limit: "La entrega ya tiene el máximo de fotos.";
|
|
311
|
+
readonly email_required: "El correo es obligatorio.";
|
|
312
|
+
readonly entity_not_applicable: "Elige primero un tipo de organización con RIF propio.";
|
|
313
|
+
readonly event_not_found: "No existe el evento.";
|
|
314
|
+
readonly exchange_rate_changed: "La tasa BCV congelada venció y el monto cambió: consulta de nuevo los métodos y muestra el nuevo monto.";
|
|
315
|
+
readonly exchange_rate_unavailable: "No hay una tasa oficial vigente para ese par de monedas; inténtalo en unos minutos.";
|
|
316
|
+
readonly fallback_plan_nested: "Un plan usado como respaldo no puede tener otro respaldo.";
|
|
317
|
+
readonly fallback_plan_not_free: "El respaldo debe ser un plan gratuito activo, en la misma moneda y sin respaldo propio.";
|
|
318
|
+
readonly feature_exists: "Ya existe una cuota con esa clave.";
|
|
319
|
+
readonly feature_not_found: "No existe la cuota.";
|
|
320
|
+
readonly feature_not_metered: "Esa cuota no registra uso: solo las de consumo y de cantidad lo hacen.";
|
|
321
|
+
readonly feature_operation_not_allowed: "Solo las cuotas de consumo permiten operaciones.";
|
|
322
|
+
readonly feature_per_not_applicable: "Solo las cuotas de consumo y de cantidad se cuentan por miembro.";
|
|
323
|
+
readonly feature_release_requires_operation: "Devuelve el consumo mediante su operación original.";
|
|
324
|
+
readonly feature_reset_not_applicable: "Solo las cuotas de consumo se reinician.";
|
|
325
|
+
readonly feature_set_not_allowed: "Solo las cuotas de cantidad permiten fijar su uso.";
|
|
326
|
+
readonly feature_value_invalid: "El valor de una cuota no es válido para su tipo.";
|
|
327
|
+
readonly file_empty: "El archivo está vacío.";
|
|
328
|
+
readonly file_not_found: "No existe el archivo.";
|
|
329
|
+
readonly file_too_large: "Cada archivo puede pesar hasta 10 MB.";
|
|
330
|
+
readonly file_type_not_allowed: "El tipo de archivo no está permitido.";
|
|
331
|
+
readonly fulfillment_closed: "Ya no se puede reportar un problema con esta entrega.";
|
|
332
|
+
readonly fulfillment_method_unavailable: "Este negocio no ofrece esa forma de entrega.";
|
|
333
|
+
readonly fulfillment_methods_conflict: "Los productos no comparten ninguna forma de entrega.";
|
|
334
|
+
readonly fulfillment_not_found: "No existe la entrega.";
|
|
335
|
+
readonly fulfillment_not_offered: "Esta compra no necesita entrega.";
|
|
336
|
+
readonly fulfillment_not_pending: "Solo puedes marcar como entregada una entrega por entregar.";
|
|
337
|
+
readonly fulfillment_not_shipping: "Esta entrega no va por agencia.";
|
|
338
|
+
readonly fulfillment_required: "Elige cómo quieres recibir tu compra.";
|
|
339
|
+
readonly fulfillment_shipped_by_carrier: "Un envío se entrega en la oficina de la agencia: agrega su número de guía.";
|
|
340
|
+
readonly handover_code_invalid: "Este código QR no es el de esta compra.";
|
|
341
|
+
readonly idempotency_conflict: "Repite la solicitud.";
|
|
342
|
+
readonly idempotency_key_invalid: "Idempotency-Key debe tener entre 8 y 255 caracteres ASCII imprimibles.";
|
|
343
|
+
readonly idempotency_key_reused: "Este Idempotency-Key ya se usó con una solicitud distinta.";
|
|
344
|
+
readonly idempotency_request_in_progress: "Todavía estamos procesando una solicitud con este Idempotency-Key.";
|
|
345
|
+
readonly insufficient_stock: "No hay suficientes unidades disponibles de un producto.";
|
|
346
|
+
readonly internal_error: "Ocurrió un error interno; inténtalo de nuevo.";
|
|
347
|
+
readonly invalid_cursor: "El cursor no es válido para este orden.";
|
|
348
|
+
readonly invalid_default_variant: "Elige una sola variante principal activa.";
|
|
349
|
+
readonly invalid_json: "El cuerpo debe ser JSON válido.";
|
|
350
|
+
readonly invalid_payment_details: "Un dato del método de pago no es válido; `param` dice cuál.";
|
|
351
|
+
readonly invalid_reference: "Uno de los recursos indicados no existe.";
|
|
352
|
+
readonly invalid_sort: "Esta lista no se puede ordenar así.";
|
|
353
|
+
readonly invalid_token: "Este enlace no es válido.";
|
|
354
|
+
readonly inventory_in_use: "Hay unidades retenidas por pagos en verificación; espera a que terminen antes de cambiar su control de stock.";
|
|
355
|
+
readonly invoice_closed: "Este cobro ya no se puede pagar.";
|
|
356
|
+
readonly invoice_not_closable: "Solo se pueden marcar como incobrables cobros abiertos sin un pago en verificación.";
|
|
357
|
+
readonly invoice_not_found: "No existe el cobro.";
|
|
358
|
+
readonly invoice_not_open: "Solo se reenvían cobros abiertos.";
|
|
359
|
+
readonly invoice_not_voidable: "Solo se pueden anular cobros abiertos sin un pago en verificación.";
|
|
360
|
+
readonly invoice_paid: "Este cobro ya fue pagado.";
|
|
361
|
+
readonly invoice_resend_limit: "Puedes reenviar un cobro hasta cinco veces por hora. Inténtalo más tarde.";
|
|
362
|
+
readonly lookup_key_in_use: "Ya tienes otro plan o producto con esa clave (lookupKey).";
|
|
363
|
+
readonly max_redemptions_below_redemptions: "El máximo de usos no puede ser menor que los usos que ya tiene el cupón.";
|
|
364
|
+
readonly member_not_found: "No existe el miembro.";
|
|
365
|
+
readonly member_over_limit: "Este miembro supera los puestos del plan.";
|
|
366
|
+
readonly member_recently_changed: "Quien se une al negocio o cambia de rol espera 48 horas para las acciones sensibles.";
|
|
367
|
+
readonly member_removed: "Este miembro fue quitado.";
|
|
368
|
+
readonly member_required: "Indica el miembro para consultar esta cuota.";
|
|
369
|
+
readonly method_required: "Elige un método de pago.";
|
|
370
|
+
readonly name_required: "Nombre: este campo es obligatorio.";
|
|
371
|
+
readonly notification_not_found: "No existe la notificación.";
|
|
372
|
+
readonly notification_preference_forbidden: "No puedes cambiar esta notificación.";
|
|
373
|
+
readonly onboarding_already_submitted: "La verificación ya fue enviada.";
|
|
374
|
+
readonly onboarding_incomplete: "Completa todos los datos requeridos antes de enviar.";
|
|
375
|
+
readonly onboarding_locked: "Los datos del negocio ya fueron enviados a revisión; contacta a soporte para cambiarlos.";
|
|
376
|
+
readonly onboarding_not_submitted: "El negocio todavía no envió su verificación.";
|
|
377
|
+
readonly operation_amount_exceeded: "No puedes confirmar más de lo reservado.";
|
|
378
|
+
readonly operation_expired: "La reserva venció y su capacidad fue devuelta.";
|
|
379
|
+
readonly operation_invalid_state: "La operación ya no está reservada.";
|
|
380
|
+
readonly operation_key_reused: "Esta clave de operación ya se usó con otros datos.";
|
|
381
|
+
readonly operation_not_found: "No existe la operación.";
|
|
382
|
+
readonly parameter_missing: "Falta un parámetro en la ruta.";
|
|
383
|
+
readonly payload_too_large: "El cuerpo de la solicitud supera 1 MB.";
|
|
384
|
+
readonly payment_code_in_progress: "Estamos verificando el código; espera unos segundos.";
|
|
385
|
+
readonly payment_code_invalid: "El código o la referencia no es válido o venció.";
|
|
386
|
+
readonly payment_code_not_expected: "Este pago no está esperando un código.";
|
|
387
|
+
readonly payment_code_not_sent: "No pudimos enviar otro código.";
|
|
388
|
+
readonly payment_in_progress: "Espera a que termine el pago antes de cambiar la selección.";
|
|
389
|
+
readonly payment_link_not_found: "No existe el enlace de pago.";
|
|
390
|
+
readonly payment_link_retired: "Un enlace retirado no puede modificarse ni reactivarse.";
|
|
391
|
+
readonly payment_link_unavailable: "Este enlace de pago ya no está disponible.";
|
|
392
|
+
readonly payment_method_unavailable: "Ese método no permite pagar en la moneda del checkout o del cobro.";
|
|
393
|
+
readonly payment_not_claimable: "Solo puedes abrir un reclamo por un pago confirmado.";
|
|
394
|
+
readonly payment_not_found: "No existe el pago.";
|
|
395
|
+
readonly payment_not_refundable: "Solo se pueden reembolsar pagos confirmados.";
|
|
396
|
+
readonly payments_unavailable: "No pudimos contactar al banco o al proveedor; inténtalo en unos segundos.";
|
|
397
|
+
readonly payout_account_change_pending: "Ya hay un cambio de la cuenta de retiro pendiente: cancélalo antes de pedir otro.";
|
|
398
|
+
readonly payout_not_found: "No existe el retiro.";
|
|
399
|
+
readonly phone_required: "Teléfono: este campo es obligatorio.";
|
|
400
|
+
readonly plan_inactive: "El plan está archivado.";
|
|
401
|
+
readonly plan_not_found: "No existe el plan.";
|
|
402
|
+
readonly plan_seats_locked: "No puedes cambiar la forma de cobro de un plan con suscripciones.";
|
|
403
|
+
readonly portal_action_disabled: "El negocio no permite hacer este cambio desde el portal.";
|
|
404
|
+
readonly portal_session_invalid: "Este enlace ya se abrió o venció.";
|
|
405
|
+
readonly product_inactive: "Este producto está desactivado.";
|
|
406
|
+
readonly product_not_found: "No existe el producto.";
|
|
407
|
+
readonly product_retired: "Este producto fue retirado.";
|
|
408
|
+
readonly product_unavailable: "Uno de los productos ya no existe.";
|
|
409
|
+
readonly production_already_enabled: "El negocio ya opera en producción.";
|
|
410
|
+
readonly production_not_enabled: "Completa la activación del negocio para usar producción.";
|
|
411
|
+
readonly provider_not_found: "No existe el proveedor.";
|
|
412
|
+
readonly quantity_decrease_requires_renewal: "Programa la reducción de puestos para la renovación.";
|
|
413
|
+
readonly quantity_limit_exceeded: "La cantidad supera el máximo por compra.";
|
|
414
|
+
readonly quantity_not_adjustable: "Este plan no se cobra por puesto.";
|
|
415
|
+
readonly quantity_not_allowed: "Este plan no se cobra por puesto.";
|
|
416
|
+
readonly quantity_out_of_range: "La cantidad está fuera del mínimo y el máximo de puestos del plan.";
|
|
417
|
+
readonly rate_limited: "Demasiadas solicitudes seguidas; espera un momento e inténtalo de nuevo.";
|
|
418
|
+
readonly receipt_not_found: "No existe el recibo.";
|
|
419
|
+
readonly receipt_resend_limit: "Puedes enviar el recibo hasta cinco veces por hora. Inténtalo más tarde.";
|
|
420
|
+
readonly refund_amount_mismatch: "Registra el importe completo de la devolución pendiente.";
|
|
421
|
+
readonly refund_approval_pending: "Este pago ya tiene un reembolso esperando aprobación.";
|
|
422
|
+
readonly refund_exceeds_payment: "El reembolso supera lo que queda por reembolsar del pago.";
|
|
423
|
+
readonly refund_threshold_change_pending: "Ya hay un cambio de la aprobación de reembolsos pendiente: cancélalo antes de pedir otro.";
|
|
424
|
+
readonly renewal_invoice: "El cobro es la renovación de una suscripción y no se puede cerrar a mano.";
|
|
425
|
+
readonly representative_not_found: "No existe el representante.";
|
|
426
|
+
readonly representatives_limit: "Se alcanzó el máximo de representantes.";
|
|
427
|
+
readonly request_log_not_found: "No existe el registro.";
|
|
428
|
+
readonly resource_conflict: "Ya existe un recurso con estos datos únicos.";
|
|
429
|
+
readonly role_admin_required: "Solo propietarios y administradores.";
|
|
430
|
+
readonly route_not_found: "Este endpoint no existe.";
|
|
431
|
+
readonly saved_payer_not_found: "No existe el método de pago guardado.";
|
|
432
|
+
readonly seat_limit_reached: "No quedan puestos disponibles en el plan.";
|
|
433
|
+
readonly seats_in_use: "El cambio deja menos puestos que miembros activos: quita miembros o acepta deshabilitarlos (disableExcessMembers).";
|
|
434
|
+
readonly subscription_change_in_progress: "Estamos verificando el pago de un cambio de esta suscripción.";
|
|
435
|
+
readonly subscription_ended: "La suscripción ya terminó o se canceló.";
|
|
436
|
+
readonly subscription_exists: "El cliente ya tiene una suscripción en curso a este plan.";
|
|
437
|
+
readonly subscription_not_canceling: "Esta suscripción no tiene una cancelación programada.";
|
|
438
|
+
readonly subscription_not_found: "No existe la suscripción.";
|
|
439
|
+
readonly subscription_renewal_open: "Paga la renovación o programa el cambio para el próximo periodo.";
|
|
440
|
+
readonly tax_behavior_mismatch: "Todos los productos deben tratar los impuestos igual.";
|
|
441
|
+
readonly tax_id_prefix: "El RIF no corresponde al tipo de organización.";
|
|
442
|
+
readonly too_many_attempts: "Demasiados intentos de pago para este checkout.";
|
|
443
|
+
readonly tracking_deadline_passed: "El plazo para agregar la guía ya terminó.";
|
|
444
|
+
readonly tracking_number_in_use: "Esa guía ya pertenece al envío de otro cliente.";
|
|
445
|
+
readonly tracking_verifying: "Estamos verificando la guía que agregaste.";
|
|
446
|
+
readonly trial_not_applicable: "Un plan gratuito no necesita prueba.";
|
|
447
|
+
readonly trial_required: "Las suscripciones creadas por API empiezan con prueba gratis; vende planes pagos con un checkout.";
|
|
448
|
+
readonly trial_unavailable: "Este cliente ya usó la prueba gratis; el checkout ahora cobra el primer periodo.";
|
|
449
|
+
readonly unsubscribe_invalid: "El enlace no es válido.";
|
|
450
|
+
readonly unused_credit_not_accepted: "Este cambio pierde crédito no utilizado; acéptalo expresamente o prográmalo para la renovación.";
|
|
451
|
+
readonly validation_failed: "El cuerpo o la consulta no cumple el esquema; `param` dice qué campo.";
|
|
452
|
+
readonly variant_not_found: "No existe la variante.";
|
|
453
|
+
readonly variant_pricing_required: "Con variantes, el precio y el stock se configuran por variante.";
|
|
454
|
+
readonly variant_required: "El producto tiene variantes: elige una.";
|
|
455
|
+
readonly variant_retired: "Una variante retirada no puede modificarse ni reactivarse.";
|
|
456
|
+
readonly variant_retirement_required: "Retira la variante explícitamente antes de quitarla del producto.";
|
|
457
|
+
readonly webhook_delivery_in_progress: "Este envío está en curso; podrás reenviarlo cuando termine.";
|
|
458
|
+
readonly webhook_delivery_not_found: "No existe el envío.";
|
|
459
|
+
readonly webhook_endpoint_disabled: "Este webhook está desactivado: actívalo para enviarle eventos.";
|
|
460
|
+
readonly webhook_endpoint_not_found: "No existe el webhook.";
|
|
461
|
+
readonly webhook_signature_invalid: "La firma del evento no es válida.";
|
|
462
|
+
readonly webhook_url_credentials_forbidden: "La URL del webhook no puede incluir credenciales.";
|
|
463
|
+
readonly webhook_url_https_required: "La URL del webhook debe usar HTTPS.";
|
|
464
|
+
readonly webhook_url_invalid: "La URL del webhook no es válida.";
|
|
465
|
+
readonly webhook_url_private: "La URL del webhook no puede apuntar a localhost.";
|
|
466
|
+
readonly webhook_url_protocol: "La URL del webhook debe usar HTTP o HTTPS.";
|
|
467
|
+
readonly webhook_url_unresolvable: "No pudimos resolver el dominio del webhook.";
|
|
468
|
+
};
|
|
469
|
+
type ApiErrorCode = keyof typeof API_ERROR_CODES;
|
|
470
|
+
//#endregion
|
|
253
471
|
//#region ../contracts/src/errors.d.ts
|
|
254
472
|
declare const API_ERROR_TYPES: readonly ["invalid_request", "authentication", "permission", "not_found", "conflict", "validation", "rate_limit", "provider", "internal"];
|
|
255
473
|
type ApiErrorType = (typeof API_ERROR_TYPES)[number];
|
|
256
474
|
interface ApiErrorBody {
|
|
257
475
|
type: ApiErrorType;
|
|
258
|
-
|
|
476
|
+
/** Stable and listed in `API_ERROR_CODES`, with what each means. */
|
|
477
|
+
code: ApiErrorCode;
|
|
259
478
|
message: string;
|
|
260
479
|
/** The request field that caused the error, when there is one. */
|
|
261
480
|
param?: string;
|
|
@@ -354,6 +573,11 @@ interface ProductVariant extends Retirement {
|
|
|
354
573
|
}
|
|
355
574
|
interface Product extends Resource<"product">, Retirement {
|
|
356
575
|
name: string;
|
|
576
|
+
/**
|
|
577
|
+
* The business's own name for it, unique among its products in each environment: unlike
|
|
578
|
+
* `metadata`, it is public, so a custom checkout tells what it sells (`plus`) without keeping IDs.
|
|
579
|
+
*/
|
|
580
|
+
lookupKey: string | null;
|
|
357
581
|
description: string | null;
|
|
358
582
|
imageUrl: string | null;
|
|
359
583
|
category: ProductCategory;
|
|
@@ -386,6 +610,11 @@ interface Plan extends Resource<"plan"> {
|
|
|
386
610
|
seats: PlanSeats;
|
|
387
611
|
fallbackPlanId: string | null;
|
|
388
612
|
name: string;
|
|
613
|
+
/**
|
|
614
|
+
* The business's own name for it, unique among its plans in each environment: unlike
|
|
615
|
+
* `metadata`, it is public, so a custom checkout tells what it sells (`plus`) without keeping IDs.
|
|
616
|
+
*/
|
|
617
|
+
lookupKey: string | null;
|
|
389
618
|
description: string | null;
|
|
390
619
|
currency: Currency;
|
|
391
620
|
prices: PlanPrice[];
|
|
@@ -965,6 +1194,11 @@ interface PaymentSettlement {
|
|
|
965
1194
|
amount: number;
|
|
966
1195
|
currency: Currency;
|
|
967
1196
|
exchangeRate: string | null;
|
|
1197
|
+
/**
|
|
1198
|
+
* The IVA charged, in `currency`. A price in another currency is converted line by line and its
|
|
1199
|
+
* IVA computed in `currency`. Absent on conversions before it was recorded.
|
|
1200
|
+
*/
|
|
1201
|
+
tax?: number;
|
|
968
1202
|
fee: number;
|
|
969
1203
|
/** `fee` split into Billete's and the payment method's. */
|
|
970
1204
|
feeDetails?: PaymentFeeDetails;
|
|
@@ -1216,4 +1450,4 @@ type WebhookEvent = { [TType in EventType]: {
|
|
|
1216
1450
|
data: EventDataMap[TType];
|
|
1217
1451
|
}; }[EventType];
|
|
1218
1452
|
//#endregion
|
|
1219
|
-
export { FulfillmentMethod as $, PaymentFailureCode as $t, Coupon as A, ResetFrequency as At, ExchangeRate as B, SubscriptionRenewal as Bt, CheckoutPurpose as C,
|
|
1453
|
+
export { FulfillmentMethod as $, PaymentFailureCode as $t, Coupon as A, tokenEnvironment as An, ResetFrequency as At, ExchangeRate as B, SubscriptionRenewal as Bt, CheckoutPurpose as C, findBank as Cn, PortalSession as Ct, ClaimReason as D, ENVIRONMENTS as Dn, RESET_FREQUENCIES as Dt, ClaimOutcome as E, nationalPhone as En, ProductVariant as Et, CustomerFeature as F, SubmitLabel as Ft, FeatureOperation as G, Weekday as Gt, FULFILLMENT_METHODS as H, SubscriptionTerms as Ht, CustomerMember as I, Subscription as It, FeatureType as J, API_ERROR_TYPES as Jt, FeatureOperationResult as K, ReceiptReference as Kt, CustomerMemberList as L, SubscriptionChange as Lt, CustomField as M, RiskLevel as Mt, Customer as N, SUBMIT_LABELS as Nt, ClaimStatus as O, Environment as On, RISK_LEVELS as Ot, CustomerDetails as P, SUBSCRIPTION_STATUSES as Pt, FulfillmentHandover as Q, PAYMENT_FAILURE_CODES as Qt, CustomerSession as R, SubscriptionChangePreview as Rt, CheckoutItem as S, VENEZUELAN_BANKS as Sn, PlanSeats as St, ClaimMessage as T, isMobilePhone as Tn, ProductCategory as Tt, FULFILLMENT_STATUSES as U, USAGE_FEATURE_TYPES as Ut, FEATURE_TYPES as V, SubscriptionStatus as Vt, Feature as W, WebhookEndpoint as Wt, Fulfillment as X, ApiErrorEnvelope as Xt, FeatureUsageResult as Y, ApiErrorBody as Yt, FulfillmentChoice as Z, ApiErrorType as Zt, CLAIM_STATUSES as _, Metadata as _n, PaymentStatus as _t, WEBHOOK_TEST_EVENT as a, BILLING_MONTHS as an, InvoiceReason as at, CarrierOffice as b, TaxBehavior as bn, PlanFeatureValues as bt, AfterCompletion as c, CURRENCIES as cn, MAX_SEATS as ct, CANCELLATION_FEEDBACK as d, GracePeriodDays as dn, Payment as dt, API_ERROR_CODES as en, FulfillmentStatus as et, CARRIERS as f, List as fn, PaymentAttempt as ft, CLAIM_REASONS as g, MOBILE_PREFIXES as gn, PaymentSettlement as gt, CLAIM_OUTCOMES as h, MAX_QUANTITY as hn, PaymentLink as ht, SubscribableEventType as i, AddressInput as in, Invoice as it, CurrencyAvailability as j, tokenPrefix as jn, Retirement as jt, CollectSettings as k, TokenKind as kn, Refund as kt, Balance as l, Currency as ln, PAYMENT_STATUSES as lt, CHECKOUT_PURPOSES as m, ListSort as mn, PaymentFeeDetails as mt, EventDataMap as n, ACCOUNT_NUMBER_LENGTH as nn, INVOICE_REASONS as nt, WebhookEvent as o, BankCode as on, InvoiceStatus as ot, CARRIER_TEST_SCENARIOS as p, ListQuery as pn, PaymentFailure as pt, FeatureReset as q, ReceiptSend as qt, EventType as r, Address as rn, INVOICE_STATUSES as rt, Actor as s, BillingMonths as sn, LineItem as st, EVENT_TYPES as t, ApiErrorCode as tn, FulfillmentTracking as tt, BalanceAmount as u, GRACE_PERIOD_DAYS as un, PRODUCT_CATEGORIES as ut, CancellationFeedback as v, MobilePrefix as vn, Payout as vt, Claim as w, isLandlinePhone as wn, Product as wt, Checkout as x, Timestamp as xn, PlanPrice as xt, Carrier as y, TAX_BEHAVIORS as yn, Plan as yt, Event as z, SubscriptionChangeResult as zt };
|
|
@@ -18,7 +18,7 @@ var BilleteError = class extends Error {
|
|
|
18
18
|
};
|
|
19
19
|
//#endregion
|
|
20
20
|
//#region src/http.ts
|
|
21
|
-
const SDK_VERSION = "
|
|
21
|
+
const SDK_VERSION = "5.0.0";
|
|
22
22
|
const DEFAULT_BASE_URL = "https://api.billete.run";
|
|
23
23
|
const RETRYABLE_STATUS = /* @__PURE__ */ new Set([
|
|
24
24
|
429,
|
|
@@ -41,21 +41,41 @@ function pause(ms, signal) {
|
|
|
41
41
|
});
|
|
42
42
|
}
|
|
43
43
|
function buildUrl(baseUrl, path, query) {
|
|
44
|
-
const
|
|
45
|
-
|
|
46
|
-
return url;
|
|
44
|
+
const search = Object.entries(query ?? {}).filter(([, value]) => value !== void 0).map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`).join("&");
|
|
45
|
+
return `${baseUrl.replace(/\/+$/, "")}${path}${search ? `?${search}` : ""}`;
|
|
47
46
|
}
|
|
48
|
-
/**
|
|
49
|
-
|
|
50
|
-
|
|
47
|
+
/**
|
|
48
|
+
* Aborts on the attempt's timeout or the caller's signal, whichever comes first. Built by hand
|
|
49
|
+
* because `AbortSignal.timeout` and `AbortSignal.any` are missing in older React Native.
|
|
50
|
+
*/
|
|
51
|
+
function attemptSignal(timeoutMs, caller) {
|
|
52
|
+
const controller = new AbortController();
|
|
53
|
+
const abort = () => controller.abort(caller?.reason);
|
|
54
|
+
const timer = setTimeout(() => controller.abort(/* @__PURE__ */ new Error(`timed out after ${timeoutMs} ms`)), timeoutMs);
|
|
55
|
+
if (caller?.aborted) abort();
|
|
56
|
+
else caller?.addEventListener("abort", abort, { once: true });
|
|
57
|
+
return {
|
|
58
|
+
signal: controller.signal,
|
|
59
|
+
done: () => {
|
|
60
|
+
clearTimeout(timer);
|
|
61
|
+
caller?.removeEventListener("abort", abort);
|
|
62
|
+
}
|
|
63
|
+
};
|
|
51
64
|
}
|
|
52
|
-
|
|
53
|
-
|
|
65
|
+
function errorBody(reply) {
|
|
66
|
+
try {
|
|
67
|
+
return JSON.parse(reply.text).error;
|
|
68
|
+
} catch {
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
function toError(reply) {
|
|
73
|
+
return new BilleteError(errorBody(reply) ?? {
|
|
54
74
|
type: "internal",
|
|
55
75
|
code: "invalid_response",
|
|
56
|
-
message: `Unexpected HTTP ${
|
|
57
|
-
requestId:
|
|
58
|
-
},
|
|
76
|
+
message: `Unexpected HTTP ${reply.status} from Billete`,
|
|
77
|
+
requestId: reply.headers.get("X-Request-Id") ?? void 0
|
|
78
|
+
}, reply.status);
|
|
59
79
|
}
|
|
60
80
|
function createTransport(options) {
|
|
61
81
|
if (!options.apiVersion) throw new TypeError("Billete needs apiVersion: the API version your integration is written against");
|
|
@@ -71,19 +91,25 @@ function createTransport(options) {
|
|
|
71
91
|
"X-Billete-Client": `billete-js/${SDK_VERSION}`,
|
|
72
92
|
...token ? { Authorization: `Bearer ${token}` } : {},
|
|
73
93
|
...request.body === void 0 ? {} : { "Content-Type": "application/json" },
|
|
74
|
-
...idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {}
|
|
94
|
+
...idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {},
|
|
95
|
+
...request.headers
|
|
75
96
|
};
|
|
76
|
-
const
|
|
97
|
+
const deadline = attemptSignal(timeoutMs, request.options?.signal);
|
|
77
98
|
const response = await fetchImpl(buildUrl(baseUrl, request.path, request.query), {
|
|
78
99
|
method: request.method,
|
|
79
100
|
headers,
|
|
80
101
|
body: request.body === void 0 ? void 0 : JSON.stringify(request.body),
|
|
81
|
-
signal:
|
|
82
|
-
}).
|
|
102
|
+
signal: deadline.signal
|
|
103
|
+
}).then(async (reply) => ({
|
|
104
|
+
ok: reply.ok,
|
|
105
|
+
status: reply.status,
|
|
106
|
+
headers: reply.headers,
|
|
107
|
+
text: await reply.text()
|
|
108
|
+
})).catch((error) => {
|
|
83
109
|
if (request.options?.signal?.aborted) throw error;
|
|
84
110
|
return error instanceof Error ? error : new Error(String(error));
|
|
85
|
-
});
|
|
86
|
-
if ((response instanceof Error || RETRYABLE_STATUS.has(response.status) || response.status === 409 &&
|
|
111
|
+
}).finally(deadline.done);
|
|
112
|
+
if ((response instanceof Error || RETRYABLE_STATUS.has(response.status) || response.status === 409 && errorBody(response)?.code === "idempotency_request_in_progress") && attempt < maxRetries) {
|
|
87
113
|
await pause(backoff(attempt, response instanceof Error ? null : response.headers.get("Retry-After")), request.options?.signal);
|
|
88
114
|
return send(request, idempotencyKey, attempt + 1);
|
|
89
115
|
}
|
|
@@ -92,11 +118,12 @@ function createTransport(options) {
|
|
|
92
118
|
code: "network_error",
|
|
93
119
|
message: `Could not reach Billete: ${response.message}`
|
|
94
120
|
}, 0, { cause: response });
|
|
95
|
-
if (
|
|
96
|
-
|
|
121
|
+
if (response.status === 304) return void 0;
|
|
122
|
+
if (!response.ok) throw toError(response);
|
|
123
|
+
return response.status === 204 ? void 0 : JSON.parse(response.text);
|
|
97
124
|
}
|
|
98
125
|
function request(request) {
|
|
99
|
-
return send(request, request.method === "GET" ? void 0 : request.options?.idempotencyKey ??
|
|
126
|
+
return send(request, request.method === "GET" || !options.idempotencyKey ? void 0 : request.options?.idempotencyKey ?? options.idempotencyKey(), 0);
|
|
100
127
|
}
|
|
101
128
|
/** Walks every page of a list endpoint. */
|
|
102
129
|
async function* paginate(path, query = {}) {
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { $ as
|
|
2
|
-
import { $ as FulfillmentMethod, $t as PaymentFailureCode, A as Coupon, At as ResetFrequency, B as ExchangeRate, Bt as SubscriptionRenewal, C as CheckoutPurpose, Cn as
|
|
1
|
+
import { $ as ProductCheckoutCreate, A as CustomerUpdate, At as PublicPaymentState, B as InvoiceCreate, Bt as apiVersionLifecycle, C as CouponUpdate, Ct as PublicCheckout, D as CustomerMemberCreate, Dt as PublicFulfillment, E as CustomerInput, Et as PublicClaimSummary, F as FeatureUpdate, Ft as ApiVersion, G as PlanCheckoutCreate, Gt as supportedApiVersions, H as KEY_PATTERN, Ht as currentApiVersion, I as FulfillmentDeliverInput, It as ApiVersionLifecycle, J as PlanFeaturesInput, K as PlanCouponCreate, L as FulfillmentHandoverInput, Lt as ApiVersionStage, M as FeatureCreate, Mt as API_VERSIONS, N as FeatureOperationCommit, Nt as API_VERSION_HEADER, O as CustomerMemberUpdate, Ot as PublicInvoice, P as FeatureOperationCreate, Pt as API_VERSION_PATTERN, Q as PortalSessionCreate, R as FulfillmentInput, Rt as LATEST_API_VERSION, S as CouponCreate, St as PortalFeatures, T as CustomerCreate, Tt as PublicClaim, U as PaymentLinkCreate, Ut as isApiVersion, V as InvoiceLineInput, Vt as apiVersionStage, W as PaymentLinkUpdate, Wt as isApiVersionRetired, X as PlanPriceInput, Y as PlanLinkCreate, Z as PlanUpdate, _ as ClientPaymentCode, _t as PaymentInstructions, a as AfterCompletionInput, at as RetireInput, b as ClientSubscriptionUpdate, bt as PaymentNextAction, c as ClaimResolve, ct as SubscriptionChangePreviewInput, d as ClientCheckoutUpdate, dt as VariantInput, et as ProductCouponCreate, f as ClientClaimCreate, ft as WebhookEndpointCreate, g as ClientLinkCheckout, gt as FulfillmentOption, h as ClientInvoicePay, ht as CustomerSubscriptionChangeResult, i as TransportOptions, it as RefundCreate, j as EventSelector, jt as PublicPortal, k as CustomerSessionCreate, kt as PublicPaymentLink, l as ClaimRespond, lt as SubscriptionCreate, m as ClientFulfillmentProblem, mt as CustomerSubscription, n as BilleteErrorCode, nt as ProductLinkCreate, o as CheckoutCreate, ot as SubscriptionCancel, p as ClientCustomerClaimCreate, pt as WebhookEndpointUpdate, q as PlanCreate, r as RequestOptions, rt as ProductUpdate, s as CheckoutItemInput, st as SubscriptionChangeCreate, t as BilleteError, tt as ProductCreate, u as ClientCheckoutPay, ut as SubscriptionUpdate, v as ClientSubscriptionCancel, vt as PaymentMethodField, w as CustomFieldInput, wt as PublicCheckoutItem, x as CollectInput, xt as PaymentTestScenario, y as ClientSubscriptionSeats, yt as PaymentMethodOption, z as FulfillmentTrackingInput, zt as LatestApiVersion } from "./errors-CGHiFrlh.js";
|
|
2
|
+
import { $ as FulfillmentMethod, $t as PaymentFailureCode, A as Coupon, An as tokenEnvironment, At as ResetFrequency, B as ExchangeRate, Bt as SubscriptionRenewal, C as CheckoutPurpose, Cn as findBank, Ct as PortalSession, D as ClaimReason, Dn as ENVIRONMENTS, Dt as RESET_FREQUENCIES, E as ClaimOutcome, En as nationalPhone, Et as ProductVariant, F as CustomerFeature, Ft as SubmitLabel, G as FeatureOperation, Gt as Weekday, H as FULFILLMENT_METHODS, Ht as SubscriptionTerms, I as CustomerMember, It as Subscription, J as FeatureType, Jt as API_ERROR_TYPES, K as FeatureOperationResult, Kt as ReceiptReference, L as CustomerMemberList, Lt as SubscriptionChange, M as CustomField, Mt as RiskLevel, N as Customer, Nt as SUBMIT_LABELS, O as ClaimStatus, On as Environment, Ot as RISK_LEVELS, P as CustomerDetails, Pt as SUBSCRIPTION_STATUSES, Q as FulfillmentHandover, Qt as PAYMENT_FAILURE_CODES, R as CustomerSession, Rt as SubscriptionChangePreview, S as CheckoutItem, Sn as VENEZUELAN_BANKS, St as PlanSeats, T as ClaimMessage, Tn as isMobilePhone, Tt as ProductCategory, U as FULFILLMENT_STATUSES, Ut as USAGE_FEATURE_TYPES, V as FEATURE_TYPES, Vt as SubscriptionStatus, W as Feature, Wt as WebhookEndpoint, X as Fulfillment, Xt as ApiErrorEnvelope, Y as FeatureUsageResult, Yt as ApiErrorBody, Z as FulfillmentChoice, Zt as ApiErrorType, _ as CLAIM_STATUSES, _n as Metadata, _t as PaymentStatus, a as WEBHOOK_TEST_EVENT, an as BILLING_MONTHS, at as InvoiceReason, b as CarrierOffice, bn as TaxBehavior, bt as PlanFeatureValues, c as AfterCompletion, cn as CURRENCIES, ct as MAX_SEATS, d as CANCELLATION_FEEDBACK, dn as GracePeriodDays, dt as Payment, en as API_ERROR_CODES, et as FulfillmentStatus, f as CARRIERS, fn as List, ft as PaymentAttempt, g as CLAIM_REASONS, gn as MOBILE_PREFIXES, gt as PaymentSettlement, h as CLAIM_OUTCOMES, hn as MAX_QUANTITY, ht as PaymentLink, i as SubscribableEventType, in as AddressInput, it as Invoice, j as CurrencyAvailability, jn as tokenPrefix, jt as Retirement, k as CollectSettings, kn as TokenKind, kt as Refund, l as Balance, ln as Currency, lt as PAYMENT_STATUSES, m as CHECKOUT_PURPOSES, mn as ListSort, mt as PaymentFeeDetails, n as EventDataMap, nn as ACCOUNT_NUMBER_LENGTH, nt as INVOICE_REASONS, o as WebhookEvent, on as BankCode, ot as InvoiceStatus, p as CARRIER_TEST_SCENARIOS, pn as ListQuery, pt as PaymentFailure, q as FeatureReset, qt as ReceiptSend, r as EventType, rn as Address, rt as INVOICE_STATUSES, s as Actor, sn as BillingMonths, st as LineItem, t as EVENT_TYPES, tn as ApiErrorCode, tt as FulfillmentTracking, u as BalanceAmount, un as GRACE_PERIOD_DAYS, ut as PRODUCT_CATEGORIES, v as CancellationFeedback, vn as MobilePrefix, vt as Payout, w as Claim, wn as isLandlinePhone, wt as Product, x as Checkout, xn as Timestamp, xt as PlanPrice, y as Carrier, yn as TAX_BEHAVIORS, yt as Plan, z as Event, zt as SubscriptionChangeResult } from "./events-D09DIgn-.js";
|
|
3
3
|
import { WebhookVerificationError, verifyWebhook } from "./webhooks.js";
|
|
4
4
|
//#region src/server.d.ts
|
|
5
5
|
type Filters<T> = ListQuery & T;
|
|
@@ -25,7 +25,7 @@ interface BilleteOptions extends TransportOptions {
|
|
|
25
25
|
*
|
|
26
26
|
* ```ts
|
|
27
27
|
* // Reads BILLETE_API_KEY.
|
|
28
|
-
* const billete = createBillete({ apiVersion: "2026-10-
|
|
28
|
+
* const billete = createBillete({ apiVersion: "2026-10-16", environment: "test" });
|
|
29
29
|
* const { allowed } = await billete.features.consume("user_123", "tokens", 850);
|
|
30
30
|
* ```
|
|
31
31
|
*/
|
|
@@ -70,6 +70,7 @@ export declare function createBillete(options: BilleteOptions): {
|
|
|
70
70
|
active?: boolean;
|
|
71
71
|
retired?: boolean;
|
|
72
72
|
search?: string;
|
|
73
|
+
lookupKey?: string;
|
|
73
74
|
sort?: ListSort<"created" | "name">;
|
|
74
75
|
}>, options?: RequestOptions) => Promise<List<Product>>;
|
|
75
76
|
/** Iterates every item across pages: `for await (const item of iterate())`. */
|
|
@@ -77,6 +78,7 @@ export declare function createBillete(options: BilleteOptions): {
|
|
|
77
78
|
active?: boolean;
|
|
78
79
|
retired?: boolean;
|
|
79
80
|
search?: string;
|
|
81
|
+
lookupKey?: string;
|
|
80
82
|
sort?: ListSort<"created" | "name">;
|
|
81
83
|
}>) => AsyncGenerator<Product, any, any>;
|
|
82
84
|
retire: (id: string, input?: RetireInput, options?: RequestOptions) => Promise<Product>;
|
|
@@ -89,12 +91,14 @@ export declare function createBillete(options: BilleteOptions): {
|
|
|
89
91
|
list: (query?: Filters<{
|
|
90
92
|
active?: boolean;
|
|
91
93
|
search?: string;
|
|
94
|
+
lookupKey?: string;
|
|
92
95
|
sort?: ListSort<"created" | "name">;
|
|
93
96
|
}>, options?: RequestOptions) => Promise<List<Plan>>;
|
|
94
97
|
/** Iterates every item across pages: `for await (const item of iterate())`. */
|
|
95
98
|
iterate: (query?: Filters<{
|
|
96
99
|
active?: boolean;
|
|
97
100
|
search?: string;
|
|
101
|
+
lookupKey?: string;
|
|
98
102
|
sort?: ListSort<"created" | "name">;
|
|
99
103
|
}>) => AsyncGenerator<Plan, any, any>;
|
|
100
104
|
};
|
|
@@ -364,4 +368,4 @@ export declare function createBillete(options: BilleteOptions): {
|
|
|
364
368
|
/** The server client: what `createBillete` returns. */
|
|
365
369
|
type Billete = ReturnType<typeof createBillete>;
|
|
366
370
|
//#endregion
|
|
367
|
-
export { type ACCOUNT_NUMBER_LENGTH, type API_ERROR_TYPES, type API_VERSIONS, type API_VERSION_HEADER, type API_VERSION_PATTERN, type Actor, type Address, type AddressInput, type AfterCompletion, type AfterCompletionInput, type ApiErrorBody, type ApiErrorEnvelope, type ApiErrorType, type ApiVersion, type ApiVersionLifecycle, type ApiVersionStage, type BILLING_MONTHS, type Balance, type BalanceAmount, type BankCode, type Billete, BilleteError, type BilleteOptions, type BillingMonths, type CANCELLATION_FEEDBACK, type CARRIERS, type CARRIER_TEST_SCENARIOS, type CHECKOUT_PURPOSES, type CLAIM_OUTCOMES, type CLAIM_REASONS, type CLAIM_STATUSES, type CURRENCIES, type CancellationFeedback, type Carrier, type CarrierOffice, type Checkout, type CheckoutCreate, type CheckoutItem, type CheckoutItemInput, type CheckoutPurpose, type Claim, type ClaimMessage, type ClaimOutcome, type ClaimReason, type ClaimResolve, type ClaimRespond, type ClaimStatus, type ClientCheckoutPay, type ClientCheckoutUpdate, type ClientClaimCreate, type ClientCustomerClaimCreate, type ClientFulfillmentProblem, type ClientInvoicePay, type ClientLinkCheckout, type ClientPaymentCode, type ClientSubscriptionCancel, type ClientSubscriptionSeats, type ClientSubscriptionUpdate, type CollectInput, type CollectSettings, type Coupon, type CouponCreate, type CouponUpdate, type Currency, type CurrencyAvailability, type CustomField, type CustomFieldInput, type Customer, type CustomerCreate, type CustomerDetails, type CustomerFeature, type CustomerInput, type CustomerMember, type CustomerMemberCreate, type CustomerMemberList, type CustomerMemberUpdate, type CustomerSession, type CustomerSessionCreate, type CustomerSubscription, type CustomerSubscriptionChangeResult, type CustomerUpdate, type ENVIRONMENTS, type EVENT_TYPES, type Environment, type Event, type EventDataMap, type EventSelector, type EventType, type ExchangeRate, type FEATURE_TYPES, type FULFILLMENT_METHODS, type FULFILLMENT_STATUSES, type Feature, type FeatureCreate, type FeatureOperation, type FeatureOperationCommit, type FeatureOperationCreate, type FeatureOperationResult, type FeatureReset, type FeatureType, type FeatureUpdate, type FeatureUsageResult, type Fulfillment, type FulfillmentChoice, type FulfillmentDeliverInput, type FulfillmentHandover, type FulfillmentHandoverInput, type FulfillmentInput, type FulfillmentMethod, type FulfillmentOption, type FulfillmentStatus, type FulfillmentTracking, type FulfillmentTrackingInput, type GRACE_PERIOD_DAYS, type GracePeriodDays, type INVOICE_REASONS, type INVOICE_STATUSES, type Invoice, type InvoiceCreate, type InvoiceLineInput, type InvoiceReason, type InvoiceStatus, type KEY_PATTERN, type LATEST_API_VERSION, type LatestApiVersion, type LineItem, type List, type ListQuery, type ListSort, type MAX_QUANTITY, type MAX_SEATS, type MOBILE_PREFIXES, type Metadata, type MobilePrefix, type PAYMENT_FAILURE_CODES, type PAYMENT_STATUSES, type PRODUCT_CATEGORIES, type Payment, type PaymentAttempt, type PaymentFailure, type PaymentFailureCode, type PaymentFeeDetails, type PaymentInstructions, type PaymentLink, type PaymentLinkCreate, type PaymentLinkUpdate, type PaymentMethodField, type PaymentMethodOption, type PaymentNextAction, type PaymentSettlement, type PaymentStatus, type PaymentTestScenario, type Payout, type Plan, type PlanCheckoutCreate, type PlanCouponCreate, type PlanCreate, type PlanFeatureValues, type PlanFeaturesInput, type PlanLinkCreate, type PlanPrice, type PlanPriceInput, type PlanSeats, type PlanUpdate, type PortalFeatures, type PortalSession, type PortalSessionCreate, type Product, type ProductCategory, type ProductCheckoutCreate, type ProductCouponCreate, type ProductCreate, type ProductLinkCreate, type ProductUpdate, type ProductVariant, type PublicCheckout, type PublicClaim, type PublicClaimSummary, type PublicFulfillment, type PublicInvoice, type PublicPaymentLink, type PublicPaymentState, type PublicPortal, type RESET_FREQUENCIES, type RISK_LEVELS, type ReceiptReference, type ReceiptSend, type Refund, type RefundCreate, type RequestOptions, type ResetFrequency, type RetireInput, type Retirement, type RiskLevel, type SUBMIT_LABELS, type SUBSCRIPTION_STATUSES, type SubmitLabel, type SubscribableEventType, type Subscription, type SubscriptionCancel, type SubscriptionChange, type SubscriptionChangeCreate, type SubscriptionChangePreview, type SubscriptionChangePreviewInput, type SubscriptionChangeResult, type SubscriptionCreate, type SubscriptionRenewal, type SubscriptionStatus, type SubscriptionTerms, type SubscriptionUpdate, type TAX_BEHAVIORS, type TaxBehavior, type Timestamp, type TokenKind, type TransportOptions, type USAGE_FEATURE_TYPES, type VENEZUELAN_BANKS, type VariantInput, type WEBHOOK_TEST_EVENT, type WebhookEndpoint, type WebhookEndpointCreate, type WebhookEndpointUpdate, type WebhookEvent, WebhookVerificationError, type Weekday, type apiVersionLifecycle, type apiVersionStage, type currentApiVersion, type findBank, type isApiVersion, type isApiVersionRetired, type isLandlinePhone, type isMobilePhone, type nationalPhone, type supportedApiVersions, type tokenEnvironment, type tokenPrefix, verifyWebhook };
|
|
371
|
+
export { type ACCOUNT_NUMBER_LENGTH, type API_ERROR_CODES, type API_ERROR_TYPES, type API_VERSIONS, type API_VERSION_HEADER, type API_VERSION_PATTERN, type Actor, type Address, type AddressInput, type AfterCompletion, type AfterCompletionInput, type ApiErrorBody, type ApiErrorCode, type ApiErrorEnvelope, type ApiErrorType, type ApiVersion, type ApiVersionLifecycle, type ApiVersionStage, type BILLING_MONTHS, type Balance, type BalanceAmount, type BankCode, type Billete, BilleteError, type BilleteErrorCode, type BilleteOptions, type BillingMonths, type CANCELLATION_FEEDBACK, type CARRIERS, type CARRIER_TEST_SCENARIOS, type CHECKOUT_PURPOSES, type CLAIM_OUTCOMES, type CLAIM_REASONS, type CLAIM_STATUSES, type CURRENCIES, type CancellationFeedback, type Carrier, type CarrierOffice, type Checkout, type CheckoutCreate, type CheckoutItem, type CheckoutItemInput, type CheckoutPurpose, type Claim, type ClaimMessage, type ClaimOutcome, type ClaimReason, type ClaimResolve, type ClaimRespond, type ClaimStatus, type ClientCheckoutPay, type ClientCheckoutUpdate, type ClientClaimCreate, type ClientCustomerClaimCreate, type ClientFulfillmentProblem, type ClientInvoicePay, type ClientLinkCheckout, type ClientPaymentCode, type ClientSubscriptionCancel, type ClientSubscriptionSeats, type ClientSubscriptionUpdate, type CollectInput, type CollectSettings, type Coupon, type CouponCreate, type CouponUpdate, type Currency, type CurrencyAvailability, type CustomField, type CustomFieldInput, type Customer, type CustomerCreate, type CustomerDetails, type CustomerFeature, type CustomerInput, type CustomerMember, type CustomerMemberCreate, type CustomerMemberList, type CustomerMemberUpdate, type CustomerSession, type CustomerSessionCreate, type CustomerSubscription, type CustomerSubscriptionChangeResult, type CustomerUpdate, type ENVIRONMENTS, type EVENT_TYPES, type Environment, type Event, type EventDataMap, type EventSelector, type EventType, type ExchangeRate, type FEATURE_TYPES, type FULFILLMENT_METHODS, type FULFILLMENT_STATUSES, type Feature, type FeatureCreate, type FeatureOperation, type FeatureOperationCommit, type FeatureOperationCreate, type FeatureOperationResult, type FeatureReset, type FeatureType, type FeatureUpdate, type FeatureUsageResult, type Fulfillment, type FulfillmentChoice, type FulfillmentDeliverInput, type FulfillmentHandover, type FulfillmentHandoverInput, type FulfillmentInput, type FulfillmentMethod, type FulfillmentOption, type FulfillmentStatus, type FulfillmentTracking, type FulfillmentTrackingInput, type GRACE_PERIOD_DAYS, type GracePeriodDays, type INVOICE_REASONS, type INVOICE_STATUSES, type Invoice, type InvoiceCreate, type InvoiceLineInput, type InvoiceReason, type InvoiceStatus, type KEY_PATTERN, type LATEST_API_VERSION, type LatestApiVersion, type LineItem, type List, type ListQuery, type ListSort, type MAX_QUANTITY, type MAX_SEATS, type MOBILE_PREFIXES, type Metadata, type MobilePrefix, type PAYMENT_FAILURE_CODES, type PAYMENT_STATUSES, type PRODUCT_CATEGORIES, type Payment, type PaymentAttempt, type PaymentFailure, type PaymentFailureCode, type PaymentFeeDetails, type PaymentInstructions, type PaymentLink, type PaymentLinkCreate, type PaymentLinkUpdate, type PaymentMethodField, type PaymentMethodOption, type PaymentNextAction, type PaymentSettlement, type PaymentStatus, type PaymentTestScenario, type Payout, type Plan, type PlanCheckoutCreate, type PlanCouponCreate, type PlanCreate, type PlanFeatureValues, type PlanFeaturesInput, type PlanLinkCreate, type PlanPrice, type PlanPriceInput, type PlanSeats, type PlanUpdate, type PortalFeatures, type PortalSession, type PortalSessionCreate, type Product, type ProductCategory, type ProductCheckoutCreate, type ProductCouponCreate, type ProductCreate, type ProductLinkCreate, type ProductUpdate, type ProductVariant, type PublicCheckout, type PublicCheckoutItem, type PublicClaim, type PublicClaimSummary, type PublicFulfillment, type PublicInvoice, type PublicPaymentLink, type PublicPaymentState, type PublicPortal, type RESET_FREQUENCIES, type RISK_LEVELS, type ReceiptReference, type ReceiptSend, type Refund, type RefundCreate, type RequestOptions, type ResetFrequency, type RetireInput, type Retirement, type RiskLevel, type SUBMIT_LABELS, type SUBSCRIPTION_STATUSES, type SubmitLabel, type SubscribableEventType, type Subscription, type SubscriptionCancel, type SubscriptionChange, type SubscriptionChangeCreate, type SubscriptionChangePreview, type SubscriptionChangePreviewInput, type SubscriptionChangeResult, type SubscriptionCreate, type SubscriptionRenewal, type SubscriptionStatus, type SubscriptionTerms, type SubscriptionUpdate, type TAX_BEHAVIORS, type TaxBehavior, type Timestamp, type TokenKind, type TransportOptions, type USAGE_FEATURE_TYPES, type VENEZUELAN_BANKS, type VariantInput, type WEBHOOK_TEST_EVENT, type WebhookEndpoint, type WebhookEndpointCreate, type WebhookEndpointUpdate, type WebhookEvent, WebhookVerificationError, type Weekday, type apiVersionLifecycle, type apiVersionStage, type currentApiVersion, type findBank, type isApiVersion, type isApiVersionRetired, type isLandlinePhone, type isMobilePhone, type nationalPhone, type supportedApiVersions, type tokenEnvironment, type tokenPrefix, verifyWebhook };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as segment, r as BilleteError, t as createTransport } from "./http-
|
|
1
|
+
import { n as segment, r as BilleteError, t as createTransport } from "./http-D5FMIjK4.js";
|
|
2
2
|
import { WebhookVerificationError, verifyWebhook } from "./webhooks.js";
|
|
3
3
|
//#region ../contracts/src/environment.ts
|
|
4
4
|
/**
|
|
@@ -64,7 +64,7 @@ function fromEnv(name) {
|
|
|
64
64
|
*
|
|
65
65
|
* ```ts
|
|
66
66
|
* // Reads BILLETE_API_KEY.
|
|
67
|
-
* const billete = createBillete({ apiVersion: "2026-10-
|
|
67
|
+
* const billete = createBillete({ apiVersion: "2026-10-16", environment: "test" });
|
|
68
68
|
* const { allowed } = await billete.features.consume("user_123", "tokens", 850);
|
|
69
69
|
* ```
|
|
70
70
|
*/
|
|
@@ -78,7 +78,8 @@ function createBillete(options) {
|
|
|
78
78
|
const http = createTransport({
|
|
79
79
|
...options,
|
|
80
80
|
baseUrl: options.baseUrl ?? fromEnv("BILLETE_BASE_URL"),
|
|
81
|
-
token: () => apiKey
|
|
81
|
+
token: () => apiKey,
|
|
82
|
+
idempotencyKey: () => globalThis.crypto.randomUUID()
|
|
82
83
|
});
|
|
83
84
|
const customers = collection(http, "/v1/customers");
|
|
84
85
|
const memberPath = (customer) => `/v1/customers/${segment(customer)}/members`;
|
package/dist/webhooks.d.ts
CHANGED