@theengineerscanvas/payment 0.0.0-stage → 0.1.0-rc.16

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.
@@ -0,0 +1,1257 @@
1
+ /**
2
+ * ISO 4217 currency code. Branded union of the supported codes with a
3
+ * `(string & {})` catch-all so any valid 3-letter code still type-checks.
4
+ *
5
+ * `Currency` is both a type and a runtime validator — it is NOT an enum.
6
+ * Prefer the constants (`Currency.NGN`) when the code is known at compile
7
+ * time, or the validator (`Currency("NGN")`) for runtime input.
8
+ */
9
+ type Currency = "NGN" | "GHS" | "ZAR" | "KES" | "USD" | "EUR" | "GBP" | (string & {});
10
+ /**
11
+ * Validates and brands a 3-letter ISO 4217 currency code.
12
+ *
13
+ * @throws {ValidationError} if the value is not a 3-letter ISO 4217 code
14
+ */
15
+ declare function Currency(value: string): Currency;
16
+ /** Pre-validated currency constants. Equivalent to `Currency("NGN")` etc. */
17
+ declare namespace Currency {
18
+ const NGN: Currency;
19
+ const GHS: Currency;
20
+ const ZAR: Currency;
21
+ const KES: Currency;
22
+ const USD: Currency;
23
+ const EUR: Currency;
24
+ const GBP: Currency;
25
+ }
26
+
27
+ declare const MinorUnitsSymbol: unique symbol;
28
+ type MinorUnits = number & {
29
+ readonly [MinorUnitsSymbol]: true;
30
+ };
31
+ declare function MinorUnits(value: number): MinorUnits;
32
+ interface Money {
33
+ readonly amount: MinorUnits;
34
+ readonly currency: Currency;
35
+ }
36
+ declare function Money(input: {
37
+ amount: number;
38
+ currency: string;
39
+ }): Money;
40
+
41
+ declare const PaymentReferenceSymbol: unique symbol;
42
+ type PaymentReference = string & {
43
+ readonly [PaymentReferenceSymbol]: true;
44
+ };
45
+ declare function PaymentReference(raw: string): PaymentReference;
46
+
47
+ type Provider = "paystack" | "bachs" | (string & {});
48
+ declare function Provider(value: string): Provider;
49
+
50
+ type Metadata = Readonly<Record<string, string | number | boolean | null>>;
51
+
52
+ type Result<T, E = never> = {
53
+ readonly ok: true;
54
+ readonly value: T;
55
+ } | {
56
+ readonly ok: false;
57
+ readonly error: E;
58
+ };
59
+ declare function ok<T>(value: T): Result<T, never>;
60
+ declare function err<E>(error: E): Result<never, E>;
61
+ declare function attempt<T>(fn: () => Promise<T>): Promise<Result<T, Error>>;
62
+
63
+ declare const ErrorCode: {
64
+ readonly CONFIGURATION: "CONFIGURATION";
65
+ readonly VALIDATION: "VALIDATION";
66
+ readonly PROVIDER_UNAVAILABLE: "PROVIDER_UNAVAILABLE";
67
+ readonly NETWORK: "NETWORK";
68
+ readonly TIMEOUT: "TIMEOUT";
69
+ readonly WEBHOOK_VALIDATION: "WEBHOOK_VALIDATION";
70
+ readonly VERIFICATION: "VERIFICATION";
71
+ readonly REFUND: "REFUND";
72
+ readonly PROVIDER: "PROVIDER";
73
+ readonly PROVIDER_BAD_REQUEST: "PROVIDER_BAD_REQUEST";
74
+ readonly PROVIDER_UNAUTHORIZED: "PROVIDER_UNAUTHORIZED";
75
+ readonly PROVIDER_NOT_FOUND: "PROVIDER_NOT_FOUND";
76
+ readonly PROVIDER_CONFLICT: "PROVIDER_CONFLICT";
77
+ readonly PROVIDER_RATE_LIMIT: "PROVIDER_RATE_LIMIT";
78
+ readonly UNSUPPORTED: "UNSUPPORTED";
79
+ readonly INTERNAL: "INTERNAL";
80
+ };
81
+ type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode];
82
+ declare const ErrorCategory: {
83
+ readonly CONFIGURATION: "configuration";
84
+ readonly VALIDATION: "validation";
85
+ readonly PROVIDER: "provider";
86
+ readonly NETWORK: "network";
87
+ readonly TIMEOUT: "timeout";
88
+ readonly WEBHOOK: "webhook";
89
+ readonly REFUND: "refund";
90
+ readonly VERIFICATION: "verification";
91
+ readonly UNSUPPORTED: "unsupported";
92
+ readonly INTERNAL: "internal";
93
+ };
94
+ type ErrorCategory = (typeof ErrorCategory)[keyof typeof ErrorCategory];
95
+
96
+ interface PaymentErrorOptions {
97
+ readonly provider?: Provider;
98
+ readonly providerCode?: string;
99
+ readonly correlationId?: string;
100
+ readonly isRetryable?: boolean;
101
+ readonly httpStatus?: number;
102
+ readonly meta?: Readonly<Record<string, unknown>>;
103
+ readonly cause?: unknown;
104
+ }
105
+ declare abstract class PaymentError extends Error {
106
+ abstract readonly code: ErrorCode;
107
+ abstract readonly category: ErrorCategory;
108
+ readonly provider?: Provider;
109
+ readonly providerCode?: string;
110
+ readonly correlationId: string;
111
+ readonly isRetryable: boolean;
112
+ readonly httpStatus: number;
113
+ readonly meta?: Readonly<Record<string, unknown>>;
114
+ constructor(message: string, options?: PaymentErrorOptions);
115
+ }
116
+
117
+ declare class WebhookValidationError extends PaymentError {
118
+ readonly code: "WEBHOOK_VALIDATION";
119
+ readonly category: "webhook";
120
+ readonly httpStatus = 401;
121
+ readonly isRetryable = false;
122
+ constructor(message: string, options?: Omit<PaymentErrorOptions, "httpStatus" | "isRetryable">);
123
+ }
124
+
125
+ type PaymentStatus = {
126
+ readonly kind: "initialized";
127
+ } | {
128
+ readonly kind: "pending";
129
+ } | {
130
+ readonly kind: "success";
131
+ readonly paidAt: Date;
132
+ } | {
133
+ readonly kind: "failed";
134
+ readonly reason: string;
135
+ readonly failedAt: Date;
136
+ } | {
137
+ readonly kind: "abandoned";
138
+ } | {
139
+ readonly kind: "refunded";
140
+ readonly refundedAt: Date;
141
+ readonly refundId: string;
142
+ };
143
+ type PaymentStatusKind = PaymentStatus["kind"];
144
+ declare function isFinalStatus(status: PaymentStatus): boolean;
145
+ declare function isTransitionAllowed(from: PaymentStatusKind, to: PaymentStatusKind): boolean;
146
+
147
+ type PaymentChannel = "card" | "bank" | "ussd" | "qr" | "mobile_money" | "bank_transfer" | (string & {});
148
+
149
+ interface PaymentAttempt {
150
+ readonly id: string;
151
+ readonly status: PaymentStatus;
152
+ readonly channel: PaymentChannel;
153
+ readonly ipAddress?: string;
154
+ readonly fees?: Money;
155
+ readonly authorizationCode?: string;
156
+ readonly bin?: string;
157
+ readonly last4?: string;
158
+ readonly bank?: string;
159
+ readonly attemptedAt: Date;
160
+ }
161
+
162
+ interface Customer {
163
+ readonly id: string;
164
+ readonly email: string;
165
+ readonly phone?: string;
166
+ readonly name?: string;
167
+ readonly metadata?: Metadata;
168
+ }
169
+
170
+ interface Payment {
171
+ readonly id?: string;
172
+ readonly providerId: Provider;
173
+ readonly reference: PaymentReference;
174
+ /**
175
+ * The amount charged in the charge currency.
176
+ *
177
+ * Absent while a catalog checkout is still open: the provider prices the
178
+ * cart, so the total is only known once the payment exists (from
179
+ * `verify`/`fetch`, a list item, or the webhook payload).
180
+ */
181
+ readonly amount?: Money;
182
+ readonly fees?: Money;
183
+ readonly netAmount?: Money;
184
+ /**
185
+ * The settlement side of the payment, when the provider publishes it (Bachs
186
+ * pays out a converted amount under adaptive pricing). Partial refunds are
187
+ * sized in this currency, not the charge currency.
188
+ */
189
+ readonly settlementAmount?: Money;
190
+ readonly status: PaymentStatus;
191
+ readonly customer: Customer;
192
+ readonly authorizationUrl?: string;
193
+ readonly accessCode?: string;
194
+ readonly channel?: PaymentChannel;
195
+ readonly attempts: ReadonlyArray<PaymentAttempt>;
196
+ readonly metadata: Metadata;
197
+ readonly createdAt: Date;
198
+ readonly updatedAt: Date;
199
+ readonly paidAt?: Date;
200
+ readonly failureReason?: string;
201
+ }
202
+
203
+ type CustomerReference = {
204
+ readonly kind: "new";
205
+ readonly email: string;
206
+ readonly phone?: string;
207
+ readonly name?: string;
208
+ } | {
209
+ readonly kind: "existing";
210
+ readonly providerCustomerId: string;
211
+ } | {
212
+ readonly kind: "inline";
213
+ readonly customer: Customer;
214
+ };
215
+ interface PaymentRequestItem {
216
+ readonly productId: string;
217
+ readonly quantity?: number;
218
+ /** Buyer-chosen amount for a pay-what-you-want (custom) price. */
219
+ readonly amount?: Money;
220
+ }
221
+ /**
222
+ * What to charge. Exactly one of `amount` and `products` — a provider either
223
+ * charges an explicit amount (one-off) or prices a catalog cart, which is how
224
+ * a subscription starts. Passing both is a type error rather than a silently
225
+ * ignored field.
226
+ */
227
+ interface PaymentRequestBase {
228
+ readonly customer: CustomerReference;
229
+ readonly reference: PaymentReference;
230
+ readonly callbackUrl?: string;
231
+ readonly channels?: ReadonlyArray<PaymentChannel>;
232
+ readonly metadata?: Metadata;
233
+ readonly expiresAt?: Date;
234
+ readonly idempotencyKey?: string;
235
+ readonly correlationId?: string;
236
+ }
237
+ type PaymentRequest = (PaymentRequestBase & {
238
+ readonly amount: Money;
239
+ readonly products?: undefined;
240
+ }) | (PaymentRequestBase & {
241
+ /**
242
+ * Catalog items to charge. Providers with catalog support build the
243
+ * checkout from the cart; the total is provider-priced and reported once
244
+ * the payment exists.
245
+ */
246
+ readonly products: ReadonlyArray<PaymentRequestItem>;
247
+ readonly amount?: undefined;
248
+ });
249
+
250
+ interface WebhookEvent {
251
+ readonly id: string;
252
+ readonly provider: Provider;
253
+ readonly type: string;
254
+ readonly originalType: string;
255
+ readonly createdAt: Date;
256
+ readonly receivedAt: Date;
257
+ readonly payload: Readonly<Record<string, unknown>>;
258
+ readonly raw: Readonly<Record<string, unknown>>;
259
+ }
260
+
261
+ type TransferStatus = {
262
+ readonly kind: "pending";
263
+ /**
264
+ * Set when the provider reports that merchant action is required before
265
+ * the transfer can complete (Paystack's `otp` state). Without it,
266
+ * "queued" and "waiting on you" are indistinguishable.
267
+ */
268
+ readonly requiresAction?: boolean;
269
+ } | {
270
+ readonly kind: "processing";
271
+ } | {
272
+ readonly kind: "succeeded";
273
+ readonly settledAt: Date;
274
+ } | {
275
+ readonly kind: "failed";
276
+ readonly reason: string;
277
+ readonly failedAt: Date;
278
+ } | {
279
+ readonly kind: "reversed";
280
+ readonly reversedAt: Date;
281
+ };
282
+ type TransferStatusKind = TransferStatus["kind"];
283
+ declare function isFinalTransferStatus(status: TransferStatus): boolean;
284
+
285
+ /**
286
+ * A payout destination.
287
+ *
288
+ * Two providers' semantics are reconciled here:
289
+ *
290
+ * - Paystack exposes bank recipients only (`name`, account, bank, currency).
291
+ * - Bachs exposes bank accounts, mobile-money wallets, and crypto wallets, and
292
+ * gates a new destination behind a review: it is not payable until approved.
293
+ * For those providers `status` carries the review state — a freshly created
294
+ * destination is normally `pending_review` and cannot be paid yet.
295
+ *
296
+ * When a provider response only carries the destination id (Paystack's create
297
+ * response, a Bachs payout that does not echo the destination), the details
298
+ * fields are `"unknown"` and only `code` is trustworthy. Fetch the recipient
299
+ * by code, or keep the object returned by the create call.
300
+ */
301
+ interface TransferRecipient {
302
+ readonly code: string;
303
+ readonly name: string;
304
+ readonly accountNumber: string;
305
+ readonly bankCode: string;
306
+ readonly currency: Currency;
307
+ /** Provider-reported review state, when the provider has one. */
308
+ readonly status?: "pending_review" | "approved" | "rejected";
309
+ readonly createdAt: Date;
310
+ readonly metadata: Metadata;
311
+ }
312
+
313
+ interface Transfer {
314
+ readonly id: string;
315
+ readonly providerId: Provider;
316
+ /**
317
+ * The amount delivered to the destination. On a cross-currency payout this
318
+ * is in the destination currency; `fee` and `totalDebited` are in
319
+ * `sourceCurrency` (see the Bachs payout guide).
320
+ */
321
+ readonly amount: Money;
322
+ readonly recipient: TransferRecipient;
323
+ readonly status: TransferStatus;
324
+ readonly reference: string;
325
+ readonly reason?: string;
326
+ readonly transferCode?: string;
327
+ /** Provider-charged fee, when the provider reports one. */
328
+ readonly fee?: Money;
329
+ /**
330
+ * Gross amount debited from the balance, when the provider reports it.
331
+ * Equals `amount` + `fee` for same-currency payouts only.
332
+ */
333
+ readonly totalDebited?: Money;
334
+ /** Currency the balance was debited in, when the provider reports it. */
335
+ readonly sourceCurrency?: Currency;
336
+ readonly createdAt: Date;
337
+ readonly completedAt?: Date;
338
+ readonly failureReason?: string;
339
+ readonly metadata: Metadata;
340
+ }
341
+
342
+ interface BankCode {
343
+ readonly code: string;
344
+ readonly name: string;
345
+ readonly currency: Currency;
346
+ }
347
+
348
+ interface ProviderCapabilities {
349
+ readonly supportsAuthorizationUrl: boolean;
350
+ readonly supportsRecurring: boolean;
351
+ readonly supportsPartialRefund: boolean;
352
+ readonly supportsWebhooks: boolean;
353
+ readonly supportsTransfers: boolean;
354
+ /**
355
+ * `true` when the provider documents an `Idempotency-Key` header on write
356
+ * endpoints, so a retried request is deduplicated by the provider itself
357
+ * (Bachs). `false`/absent when dedupe relies on app-owned unique references
358
+ * (Paystack), where a retry can duplicate the effect.
359
+ */
360
+ readonly supportsIdempotencyKey?: boolean;
361
+ readonly maxAmount?: Money;
362
+ readonly supportedCurrencies: ReadonlyArray<Currency>;
363
+ readonly supportedChannels: ReadonlyArray<PaymentChannel>;
364
+ readonly supportedTransferCurrencies: ReadonlyArray<Currency>;
365
+ }
366
+ interface ListQuery {
367
+ readonly page?: number;
368
+ readonly perPage?: number;
369
+ /**
370
+ * Opaque cursor from a previous `Page.nextCursor`. Providers that paginate
371
+ * by cursor use it in preference to `page`/`perPage`.
372
+ */
373
+ readonly cursor?: string;
374
+ readonly from?: Date;
375
+ readonly to?: Date;
376
+ readonly status?: string;
377
+ readonly customer?: string;
378
+ }
379
+ interface Page<T> {
380
+ readonly items: ReadonlyArray<T>;
381
+ readonly total: number;
382
+ readonly page: number;
383
+ readonly perPage: number;
384
+ /**
385
+ * Opaque cursor for the next page, `null` when there are no more results,
386
+ * `undefined` for providers that do not paginate by cursor.
387
+ */
388
+ readonly nextCursor?: string | null;
389
+ }
390
+ interface HealthStatus {
391
+ readonly healthy: boolean;
392
+ readonly latencyMs: number;
393
+ readonly timestamp: Date;
394
+ }
395
+ interface RefundRequest {
396
+ readonly paymentId: string;
397
+ /**
398
+ * Partial refund amount. Money carries its currency deliberately: a refund
399
+ * sized in the wrong currency is silently wrong, so adapters validate it
400
+ * against the charge (Bachs sizes partial refunds in the **settlement**
401
+ * currency, which can differ from the charge currency under adaptive
402
+ * pricing).
403
+ */
404
+ readonly amount?: Money;
405
+ readonly reason: string;
406
+ readonly reference: string;
407
+ readonly idempotencyKey?: string;
408
+ readonly correlationId?: string;
409
+ }
410
+ /**
411
+ * A payout destination.
412
+ *
413
+ * The routing fields beyond `accountNumber`/`bankCode` exist for providers
414
+ * whose destinations are not bank accounts (Bachs mobile-money wallets and
415
+ * international bank accounts). A provider validates what it needs and fails
416
+ * locally when required fields for a destination type are missing.
417
+ */
418
+ interface CreateRecipientInput {
419
+ readonly name: string;
420
+ readonly accountNumber: string;
421
+ readonly bankCode: string;
422
+ readonly currency: Currency;
423
+ /**
424
+ * Destination kind. Only the two kinds the SDK can actually construct are
425
+ * declared: crypto destinations are asset+network pairs
426
+ * (`USDT_TRC20`) which `Currency` deliberately cannot represent (see the
427
+ * Bachs guide), so they are rejected rather than approximated.
428
+ *
429
+ * @default "bank_account"
430
+ */
431
+ readonly type?: "bank_account" | "mobile_money";
432
+ readonly phoneNumber?: string;
433
+ readonly mobileProvider?: string;
434
+ readonly accountName?: string;
435
+ readonly bankName?: string;
436
+ readonly scheme?: string;
437
+ readonly routingNumber?: string;
438
+ readonly sortCode?: string;
439
+ readonly metadata?: Metadata;
440
+ }
441
+ interface InitiateTransferInput {
442
+ /**
443
+ * Amount to deliver, in `currency`. Exactly one of `amount` and `quoteId`
444
+ * must be present: a quote fixes both sides of a cross-currency payout, so
445
+ * sending both is rejected locally.
446
+ */
447
+ readonly amount?: Money;
448
+ readonly recipientCode: string;
449
+ readonly reference: string;
450
+ readonly reason?: string;
451
+ readonly currency: Currency;
452
+ /**
453
+ * Quote id for a payout delivered in a currency other than the balance
454
+ * currency (from `transfers.createQuote`). Providers without cross-currency
455
+ * payouts answer `UnsupportedProviderError`.
456
+ */
457
+ readonly quoteId?: string;
458
+ /** Provider-specific reference for account-number-based rails (Paystack: Kenya MPESA). */
459
+ readonly accountReference?: string;
460
+ readonly correlationId?: string;
461
+ readonly idempotencyKey?: string;
462
+ readonly metadata?: Metadata;
463
+ }
464
+ /** A locked exchange rate for a payout delivered in another currency. */
465
+ interface TransferQuoteInput {
466
+ readonly fromCurrency: Currency;
467
+ readonly toCurrency: Currency;
468
+ /** Amount to convert, in `fromCurrency`. */
469
+ readonly amount: Money;
470
+ }
471
+ interface TransferQuote {
472
+ readonly id: string;
473
+ readonly providerId: Provider;
474
+ readonly fromCurrency: Currency;
475
+ readonly toCurrency: Currency;
476
+ readonly fromAmount: Money;
477
+ readonly toAmount: Money;
478
+ readonly exchangeRate: string;
479
+ readonly expiresAt?: Date;
480
+ }
481
+ interface RefundResult {
482
+ readonly id: string;
483
+ readonly paymentId: string;
484
+ readonly amount: Money;
485
+ readonly status: "pending" | "processing" | "succeeded" | "failed";
486
+ /**
487
+ * The provider's own status string, when it has one that the four-state
488
+ * union cannot express (for example Paystack's `needs-attention`, which
489
+ * requires merchant action rather than retrying).
490
+ */
491
+ readonly providerStatus?: string;
492
+ readonly reason: string;
493
+ readonly reference: string;
494
+ readonly createdAt: Date;
495
+ readonly completedAt?: Date;
496
+ }
497
+ interface PaymentProvider {
498
+ readonly id: Provider;
499
+ readonly capabilities: ProviderCapabilities;
500
+ initialize(req: PaymentRequest): Promise<Result<Payment, PaymentError>>;
501
+ verify(reference: PaymentReference): Promise<Result<Payment, PaymentError>>;
502
+ fetch(id: string): Promise<Result<Payment, PaymentError>>;
503
+ list(query: ListQuery): Promise<Result<Page<Payment>, PaymentError>>;
504
+ refund(input: RefundRequest): Promise<Result<RefundResult, PaymentError>>;
505
+ /**
506
+ * Verifies and maps a webhook delivery. `signature` is an optional fallback
507
+ * for providers whose signature is a single value the caller may have
508
+ * extracted already (Paystack); providers that need several headers
509
+ * (Bachs' timestamp + signature pair) read them from `headers`.
510
+ */
511
+ parseWebhook(headers: Readonly<Record<string, string>>, rawBody: string, signature?: string): Promise<Result<WebhookEvent, WebhookValidationError>>;
512
+ fetchRefund?(refundId: string): Promise<Result<RefundResult, PaymentError>>;
513
+ /** Providers with cross-currency payouts implement this. */
514
+ createTransferQuote?(input: TransferQuoteInput): Promise<Result<TransferQuote, PaymentError>>;
515
+ health(): Promise<HealthStatus>;
516
+ listBankCodes(input: {
517
+ readonly currency: Currency;
518
+ /**
519
+ * Two-letter ISO country for the bank list. Providers that resolve banks
520
+ * by country need it when the currency alone is ambiguous.
521
+ */
522
+ readonly country?: string;
523
+ }): Promise<Result<ReadonlyArray<BankCode>, PaymentError>>;
524
+ resolveAccount(input: {
525
+ readonly accountNumber: string;
526
+ readonly bankCode: string;
527
+ readonly currency: Currency;
528
+ readonly country?: string;
529
+ }): Promise<Result<ResolveAccountResult, PaymentError>>;
530
+ createRecipient(input: CreateRecipientInput): Promise<Result<TransferRecipient, PaymentError>>;
531
+ initiateTransfer(input: InitiateTransferInput): Promise<Result<Transfer, PaymentError>>;
532
+ fetchTransfer(id: string): Promise<Result<Transfer, PaymentError>>;
533
+ listTransfers(query: ListQuery): Promise<Result<Page<Transfer>, PaymentError>>;
534
+ }
535
+ interface ResolveAccountResult {
536
+ readonly accountName: string;
537
+ readonly accountNumber: string;
538
+ /**
539
+ * Provider-internal bank identifier. Optional because not every
540
+ * provider exposes a numeric bank ID.
541
+ */
542
+ readonly bankId?: number;
543
+ }
544
+
545
+ /**
546
+ * A short-lived, pre-authenticated session that opens the provider's hosted
547
+ * customer portal as one specific customer.
548
+ *
549
+ * The URL is a credential: it works on any device and must never be logged,
550
+ * cached, or shared. Mint a fresh session per request.
551
+ */
552
+ interface PortalSession {
553
+ /** Session id (for example `psn_...`). Correlation only, not a credential. */
554
+ readonly id?: string;
555
+ /** Redirect URL for the customer. */
556
+ readonly url: string;
557
+ }
558
+
559
+ type PriceType = "fixed" | "free" | "custom";
560
+ /**
561
+ * A per-currency price. Bachs only charges a currency option when adaptive
562
+ * pricing is enabled on the account, so these are intent, not a guarantee.
563
+ */
564
+ interface CurrencyPriceOption {
565
+ readonly currency: Currency;
566
+ readonly amount?: Money;
567
+ readonly minimumAmount?: Money;
568
+ readonly maximumAmount?: Money;
569
+ }
570
+ interface ProductPrice {
571
+ readonly priceType: PriceType;
572
+ /** The catalog currency. */
573
+ readonly currency: Currency;
574
+ /** Fixed price. Absent for `free` and `custom` prices. */
575
+ readonly amount?: Money;
576
+ /** Suggested amount for a `custom` (pay-what-you-want) price. */
577
+ readonly presetAmount?: Money;
578
+ readonly minimumAmount?: Money;
579
+ readonly maximumAmount?: Money;
580
+ /** Local-currency prices. The primary currency never appears here. */
581
+ readonly currencyOptions: ReadonlyArray<CurrencyPriceOption>;
582
+ }
583
+
584
+ type RecurringInterval = "day" | "week" | "month" | "year";
585
+ /**
586
+ * How often a recurring product bills. Bachs expresses cadences the same way
587
+ * on products (`billing_cycle`) and in checkout sessions (`recurring`).
588
+ */
589
+ interface RecurringCadence {
590
+ readonly interval: RecurringInterval;
591
+ readonly frequency: number;
592
+ }
593
+ /**
594
+ * Validates and brands a billing cadence.
595
+ *
596
+ * @throws {ValidationError} when the interval is unknown or the frequency is
597
+ * not a positive integer
598
+ */
599
+ declare function RecurringCadence(input: {
600
+ interval: string;
601
+ frequency: number;
602
+ }): RecurringCadence;
603
+
604
+ type ProductStatus = "active" | "archived";
605
+ interface Product {
606
+ readonly id: string;
607
+ readonly providerId: Provider;
608
+ readonly name: string;
609
+ readonly description?: string;
610
+ readonly price: ProductPrice;
611
+ readonly status: ProductStatus;
612
+ /** Present on recurring products. Immutable once the product exists. */
613
+ readonly billingCycle?: RecurringCadence;
614
+ /** Free period before the first charge, on recurring products only. */
615
+ readonly trialPeriod?: RecurringCadence;
616
+ readonly metadata: Metadata;
617
+ readonly createdAt: Date;
618
+ readonly updatedAt: Date;
619
+ readonly archivedAt?: Date;
620
+ }
621
+ /** A recurring product becomes a subscription when a checkout completes. */
622
+ declare function isRecurring(product: Product): boolean;
623
+
624
+ type SubscriptionStatus = {
625
+ readonly kind: "trialing";
626
+ readonly trialEnd: Date;
627
+ } | {
628
+ readonly kind: "active";
629
+ } | {
630
+ readonly kind: "pastDue";
631
+ } | {
632
+ readonly kind: "unpaid";
633
+ } | {
634
+ readonly kind: "canceled";
635
+ readonly canceledAt: Date;
636
+ } | {
637
+ readonly kind: "paused";
638
+ };
639
+ type SubscriptionStatusKind = SubscriptionStatus["kind"];
640
+ /** Cancellation is terminal; everything else can still transition. */
641
+ declare function isFinalSubscriptionStatus(status: SubscriptionStatus): boolean;
642
+ /** Whether the subscription currently grants access (trialing included). */
643
+ declare function isSubscriptionActive(status: SubscriptionStatus): boolean;
644
+ /** Whether the subscription is in payment recovery and needs attention. */
645
+ declare function isSubscriptionDelinquent(status: SubscriptionStatus): boolean;
646
+
647
+ interface Subscription {
648
+ readonly id: string;
649
+ readonly providerId: Provider;
650
+ readonly customer: Customer;
651
+ /** Catalog product this subscription bills. */
652
+ readonly productId?: string;
653
+ readonly productName?: string;
654
+ readonly status: SubscriptionStatus;
655
+ /** Recurring amount, in the subscription currency. */
656
+ readonly amount: Money;
657
+ readonly billingCycle: RecurringCadence;
658
+ readonly quantity: number;
659
+ readonly currentPeriodStart: Date;
660
+ readonly currentPeriodEnd: Date;
661
+ /** When the next invoice is due, if one is scheduled. */
662
+ readonly nextBilledAt?: Date;
663
+ /** True when a cancellation is scheduled for the period end. */
664
+ readonly cancelAtPeriodEnd: boolean;
665
+ readonly canceledAt?: Date;
666
+ readonly createdAt: Date;
667
+ readonly metadata: Metadata;
668
+ }
669
+
670
+ /**
671
+ * Catalog, subscription, and customer capabilities.
672
+ *
673
+ * Separate from `PaymentProvider` on purpose: a provider that only collects
674
+ * one-time payments stays a valid `PaymentProvider`. Use
675
+ * `isSubscriptionProvider` to detect support at runtime; the SDK's
676
+ * `products`, `subscriptions`, and `customers` facades return
677
+ * `UnsupportedProviderError` when the configured provider does not implement
678
+ * this port.
679
+ */
680
+ interface SubscriptionProvider {
681
+ listProducts(query: ProductListQuery): Promise<Result<Page<Product>, PaymentError>>;
682
+ fetchProduct(id: string): Promise<Result<Product, PaymentError>>;
683
+ createProduct(input: CreateProductInput): Promise<Result<Product, PaymentError>>;
684
+ updateProduct(id: string, input: UpdateProductInput): Promise<Result<Product, PaymentError>>;
685
+ archiveProduct(id: string): Promise<Result<Product, PaymentError>>;
686
+ unarchiveProduct(id: string): Promise<Result<Product, PaymentError>>;
687
+ listSubscriptions(query: SubscriptionListQuery): Promise<Result<Page<Subscription>, PaymentError>>;
688
+ fetchSubscription(id: string): Promise<Result<Subscription, PaymentError>>;
689
+ updateSubscription(id: string, input: UpdateSubscriptionInput): Promise<Result<Subscription, PaymentError>>;
690
+ cancelSubscription(id: string, input: CancelSubscriptionInput): Promise<Result<Subscription, PaymentError>>;
691
+ listCustomers(query: CustomerListQuery): Promise<Result<Page<Customer>, PaymentError>>;
692
+ fetchCustomer(id: string): Promise<Result<Customer, PaymentError>>;
693
+ createCustomer(input: CreateCustomerInput): Promise<Result<Customer, PaymentError>>;
694
+ updateCustomer(id: string, input: UpdateCustomerInput): Promise<Result<Customer, PaymentError>>;
695
+ createPortalSession(customerId: string): Promise<Result<PortalSession, PaymentError>>;
696
+ }
697
+ declare function isSubscriptionProvider(value: unknown): value is SubscriptionProvider;
698
+ interface CurrencyPriceInput {
699
+ readonly currency: Currency;
700
+ readonly amount?: Money;
701
+ readonly minimumAmount?: Money;
702
+ readonly maximumAmount?: Money;
703
+ }
704
+ interface ProductPriceInput {
705
+ readonly priceType: PriceType;
706
+ readonly currency: Currency;
707
+ readonly amount?: Money;
708
+ readonly presetAmount?: Money;
709
+ readonly minimumAmount?: Money;
710
+ readonly maximumAmount?: Money;
711
+ /** Replaces the whole set on update; omitted currencies are removed. */
712
+ readonly currencyOptions?: ReadonlyArray<CurrencyPriceInput>;
713
+ }
714
+ interface CreateProductInput {
715
+ readonly name: string;
716
+ readonly description?: string;
717
+ readonly price: ProductPriceInput;
718
+ /** Presence makes the product recurring. Immutable once created. */
719
+ readonly billingCycle?: RecurringCadence;
720
+ /** Free period before the first charge; requires a billing cycle. */
721
+ readonly trialPeriod?: RecurringCadence;
722
+ readonly metadata?: Metadata;
723
+ }
724
+ /**
725
+ * Catalog updates. `billingCycle` is intentionally absent: Bachs treats a
726
+ * product's cadence as immutable, so a different cadence is a new product
727
+ * rather than an update.
728
+ */
729
+ interface UpdateProductInput {
730
+ readonly name?: string;
731
+ readonly description?: string;
732
+ readonly amount?: Money;
733
+ readonly currencyOptions?: ReadonlyArray<CurrencyPriceInput>;
734
+ readonly trialPeriod?: RecurringCadence;
735
+ readonly metadata?: Metadata;
736
+ }
737
+ interface ProductListQuery {
738
+ /** Products page by cursor (`Page.nextCursor`); `page` is not supported. */
739
+ readonly cursor?: string;
740
+ readonly limit?: number;
741
+ readonly includeArchived?: boolean;
742
+ }
743
+ interface SubscriptionListQuery {
744
+ readonly page?: number;
745
+ readonly limit?: number;
746
+ readonly customerId?: string;
747
+ readonly status?: SubscriptionStatusKind;
748
+ }
749
+ /**
750
+ * Subscription changes. Every transition Bachs supports is exactly one
751
+ * intent per call — combining them is rejected by the provider, so the
752
+ * service validates that too.
753
+ */
754
+ interface UpdateSubscriptionInput {
755
+ /** Plan change; the replacement must bill on the same interval. */
756
+ readonly productId?: string;
757
+ /** Future date adds or extends a trial; past or now ends it and bills immediately. */
758
+ readonly trialEnd?: Date;
759
+ readonly paymentMethodId?: string;
760
+ readonly metadata?: Metadata;
761
+ /** Only meaningful with `productId`. Defaults to `invoice_now` at Bachs. */
762
+ readonly prorationBehavior?: "invoice_now" | "next_cycle" | "none";
763
+ }
764
+ interface CancelSubscriptionInput {
765
+ /** `true` keeps access until the period ends; `false` cancels immediately. */
766
+ readonly atPeriodEnd?: boolean;
767
+ readonly reason?: string;
768
+ }
769
+ interface CreateCustomerInput {
770
+ readonly email: string;
771
+ readonly name?: string;
772
+ readonly phone?: string;
773
+ readonly metadata?: Metadata;
774
+ }
775
+ interface UpdateCustomerInput {
776
+ readonly email?: string;
777
+ readonly name?: string;
778
+ readonly phone?: string;
779
+ readonly metadata?: Metadata;
780
+ }
781
+ interface CustomerListQuery {
782
+ readonly page?: number;
783
+ readonly limit?: number;
784
+ /** Free-text search on customer email or name. */
785
+ readonly search?: string;
786
+ }
787
+
788
+ interface HttpRequest {
789
+ readonly method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD";
790
+ readonly url: string;
791
+ readonly headers?: Readonly<Record<string, string>>;
792
+ readonly body?: string;
793
+ readonly timeoutMs?: number;
794
+ readonly isRetryable?: boolean;
795
+ readonly correlationId?: string;
796
+ readonly idempotencyKey?: string;
797
+ }
798
+ interface HttpResponse {
799
+ readonly status: number;
800
+ readonly headers: Readonly<Record<string, string>>;
801
+ readonly body: string;
802
+ }
803
+ interface HttpClient {
804
+ send(request: HttpRequest): Promise<Result<HttpResponse, PaymentError>>;
805
+ }
806
+
807
+ interface LogContext {
808
+ readonly [key: string]: string | number | boolean | undefined;
809
+ }
810
+ interface Logger {
811
+ debug(message: string, context?: LogContext): void;
812
+ info(message: string, context?: LogContext): void;
813
+ warn(message: string, context?: LogContext): void;
814
+ error(message: string, error?: unknown, context?: LogContext): void;
815
+ child(bindings: LogContext): Logger;
816
+ }
817
+
818
+ interface Clock {
819
+ now(): Date;
820
+ }
821
+
822
+ interface IdGenerator {
823
+ generate(): string;
824
+ }
825
+
826
+ interface EventBase {
827
+ readonly type: string;
828
+ readonly occurredAt: Date;
829
+ readonly correlationId: string;
830
+ }
831
+
832
+ interface PaymentInitialized extends EventBase {
833
+ readonly type: "payment.initialized";
834
+ readonly payment: Payment;
835
+ }
836
+
837
+ interface PaymentPending extends EventBase {
838
+ readonly type: "payment.pending";
839
+ readonly payment: Payment;
840
+ }
841
+
842
+ interface PaymentSucceeded extends EventBase {
843
+ readonly type: "payment.succeeded";
844
+ readonly payment: Payment;
845
+ }
846
+
847
+ interface PaymentFailed extends EventBase {
848
+ readonly type: "payment.failed";
849
+ readonly payment: Payment;
850
+ readonly reason: string;
851
+ }
852
+
853
+ interface VerificationCompleted extends EventBase {
854
+ readonly type: "verification.completed";
855
+ readonly payment: Payment;
856
+ }
857
+
858
+ interface WebhookReceived extends EventBase {
859
+ readonly type: "webhook.received";
860
+ readonly provider: string;
861
+ readonly eventId: string;
862
+ readonly eventType: string;
863
+ readonly originalType: string;
864
+ readonly payload: Readonly<Record<string, unknown>>;
865
+ }
866
+
867
+ type RefundStatus = {
868
+ readonly kind: "pending";
869
+ } | {
870
+ readonly kind: "processing";
871
+ } | {
872
+ readonly kind: "succeeded";
873
+ readonly settledAt: Date;
874
+ } | {
875
+ readonly kind: "failed";
876
+ readonly reason: string;
877
+ readonly failedAt: Date;
878
+ };
879
+ type RefundStatusKind = RefundStatus["kind"];
880
+ declare function isFinalRefundStatus(status: RefundStatus): boolean;
881
+
882
+ interface Refund {
883
+ readonly id: string;
884
+ readonly paymentId: string;
885
+ readonly providerId: Provider;
886
+ readonly amount: Money;
887
+ readonly reason: string;
888
+ readonly status: RefundStatus;
889
+ /** The provider's own status string when it cannot be expressed as a `RefundStatus`. */
890
+ readonly providerStatus?: string;
891
+ readonly initiatedAt: Date;
892
+ readonly completedAt?: Date;
893
+ readonly failureReason?: string;
894
+ readonly metadata: Metadata;
895
+ }
896
+
897
+ interface RefundInitiated extends EventBase {
898
+ readonly type: "refund.initiated";
899
+ readonly refund: Refund;
900
+ }
901
+
902
+ interface RefundSucceeded extends EventBase {
903
+ readonly type: "refund.succeeded";
904
+ readonly refund: Refund;
905
+ }
906
+
907
+ interface RefundFailed extends EventBase {
908
+ readonly type: "refund.failed";
909
+ readonly refund: Refund;
910
+ readonly reason: string;
911
+ }
912
+
913
+ interface TransferInitiated extends EventBase {
914
+ readonly type: "transfer.initiated";
915
+ readonly transfer: Transfer;
916
+ }
917
+
918
+ interface TransferSucceeded extends EventBase {
919
+ readonly type: "transfer.succeeded";
920
+ readonly transfer: Transfer;
921
+ }
922
+
923
+ interface TransferFailed extends EventBase {
924
+ readonly type: "transfer.failed";
925
+ readonly transfer: Transfer;
926
+ readonly reason: string;
927
+ }
928
+
929
+ interface TransferReversed extends EventBase {
930
+ readonly type: "transfer.reversed";
931
+ readonly transfer: Transfer;
932
+ }
933
+
934
+ interface SubscriptionUpdated extends EventBase {
935
+ readonly type: "subscription.updated";
936
+ readonly subscription: Subscription;
937
+ }
938
+
939
+ interface SubscriptionCanceled extends EventBase {
940
+ readonly type: "subscription.canceled";
941
+ readonly subscription: Subscription;
942
+ }
943
+
944
+ type PaymentEvent = PaymentInitialized | PaymentPending | PaymentSucceeded | PaymentFailed | VerificationCompleted | WebhookReceived | RefundInitiated | RefundSucceeded | RefundFailed | TransferInitiated | TransferSucceeded | TransferFailed | TransferReversed | SubscriptionUpdated | SubscriptionCanceled | {
945
+ readonly type: string;
946
+ readonly occurredAt: Date;
947
+ readonly correlationId: string;
948
+ };
949
+ type PaymentEventType = PaymentEvent["type"];
950
+
951
+ type EventHandler<T extends PaymentEventType = PaymentEventType> = (event: Extract<PaymentEvent, {
952
+ type: T;
953
+ }>) => void | Promise<void>;
954
+ type Unsubscribe = () => void;
955
+ interface EventBus {
956
+ emit(event: PaymentEvent): void;
957
+ on<T extends PaymentEventType>(type: T, handler: EventHandler<T>): Unsubscribe;
958
+ onAny(handler: EventHandler): Unsubscribe;
959
+ }
960
+ interface EventSubscription {
961
+ on<T extends PaymentEventType>(type: T, handler: EventHandler<T>): Unsubscribe;
962
+ onAny(handler: EventHandler): Unsubscribe;
963
+ }
964
+
965
+ interface WebhookVerifier {
966
+ verify(rawBody: string | Uint8Array, signature: string): boolean;
967
+ }
968
+
969
+ interface ProviderConfig {
970
+ readonly secretKey: string;
971
+ readonly publicKey?: string;
972
+ readonly webhookSecret?: string;
973
+ readonly baseUrl?: string;
974
+ /**
975
+ * Opts this provider into a plain-`http://` base URL. Only for local stubs
976
+ * and test harnesses: every real provider requires HTTPS, and an insecure
977
+ * URL is rejected at construction otherwise.
978
+ */
979
+ readonly allowInsecureBaseUrl?: boolean;
980
+ readonly timeoutMs?: number;
981
+ readonly enabled?: boolean;
982
+ readonly options?: Readonly<Record<string, unknown>>;
983
+ }
984
+ interface ProviderDeps {
985
+ readonly httpClient: HttpClient;
986
+ readonly logger: Logger;
987
+ readonly clock: Clock;
988
+ readonly idGenerator: IdGenerator;
989
+ readonly eventBus: EventBus;
990
+ readonly webhookVerifier: WebhookVerifier;
991
+ }
992
+ /**
993
+ * What a provider factory returns. Every provider implements the payment
994
+ * port; providers that also support recurring billing implement the
995
+ * subscription port. Narrow with `isSubscriptionProvider`.
996
+ */
997
+ type ProviderInstance = PaymentProvider & Partial<SubscriptionProvider>;
998
+ interface ProviderFactory {
999
+ create(id: Provider, config: ProviderConfig, deps: ProviderDeps): ProviderInstance;
1000
+ supported(): ReadonlyArray<Provider>;
1001
+ }
1002
+
1003
+ interface LoggingConfig {
1004
+ readonly level?: "debug" | "info" | "warn" | "error";
1005
+ }
1006
+ interface HttpClientConfig {
1007
+ readonly timeoutMs?: number;
1008
+ readonly baseUrl?: string;
1009
+ }
1010
+ interface RetryConfig {
1011
+ readonly maxRetries?: number;
1012
+ readonly delayMs?: number;
1013
+ }
1014
+ interface PaymentClientConfig {
1015
+ readonly providers: Record<string, ProviderConfig>;
1016
+ readonly defaultProvider?: string;
1017
+ readonly logging?: LoggingConfig;
1018
+ readonly http?: HttpClientConfig;
1019
+ readonly retry?: RetryConfig;
1020
+ readonly eventBus?: EventBus;
1021
+ readonly clock?: Clock;
1022
+ readonly idGenerator?: IdGenerator;
1023
+ readonly logger?: Logger;
1024
+ readonly httpClient?: HttpClient;
1025
+ }
1026
+
1027
+ declare class PaymentService {
1028
+ private readonly provider;
1029
+ private readonly eventBus;
1030
+ private readonly logger;
1031
+ private readonly clock;
1032
+ private readonly idGenerator;
1033
+ constructor(provider: PaymentProvider, eventBus: EventBus, logger: Logger, clock: Clock, idGenerator: IdGenerator);
1034
+ initialize(req: PaymentRequest): Promise<Result<Payment, PaymentError>>;
1035
+ verify(reference: PaymentReference): Promise<Result<Payment, PaymentError>>;
1036
+ fetch(id: string): Promise<Result<Payment, PaymentError>>;
1037
+ list(query: ListQuery): Promise<Result<Page<Payment>, PaymentError>>;
1038
+ }
1039
+
1040
+ interface RefundCreateInput {
1041
+ readonly paymentId: string;
1042
+ readonly amount?: Money;
1043
+ readonly reason: string;
1044
+ readonly reference?: string;
1045
+ readonly idempotencyKey?: string;
1046
+ readonly metadata?: Metadata;
1047
+ readonly correlationId?: string;
1048
+ }
1049
+ declare class RefundService {
1050
+ private readonly provider;
1051
+ private readonly eventBus;
1052
+ private readonly logger;
1053
+ private readonly clock;
1054
+ private readonly idGenerator;
1055
+ constructor(provider: PaymentProvider, deps: {
1056
+ readonly eventBus: EventBus;
1057
+ readonly logger: Logger;
1058
+ readonly clock: Clock;
1059
+ readonly idGenerator: IdGenerator;
1060
+ });
1061
+ create(input: RefundCreateInput): Promise<Result<Refund, PaymentError>>;
1062
+ fetch(id: string): Promise<Result<Refund, PaymentError>>;
1063
+ }
1064
+
1065
+ interface WebhookInput {
1066
+ readonly provider?: string;
1067
+ /**
1068
+ * Exact received bytes. `Buffer` is accepted too — it is a `Uint8Array` —
1069
+ * but the public type avoids requiring `@types/node` of consumers.
1070
+ */
1071
+ readonly rawBody: string | Uint8Array;
1072
+ /**
1073
+ * Optional single-value signature. Providers read their own headers; this is
1074
+ * a fallback for callers that already extracted the value (Paystack's
1075
+ * `x-paystack-signature`). Bachs needs the header pair, so it ignores it.
1076
+ */
1077
+ readonly signature?: string;
1078
+ readonly headers?: Readonly<Record<string, string | readonly string[] | undefined>>;
1079
+ }
1080
+ declare class WebhookService {
1081
+ private readonly providers;
1082
+ private readonly eventBus;
1083
+ private readonly logger;
1084
+ private readonly clock;
1085
+ private readonly idGenerator;
1086
+ constructor(providers: ReadonlyMap<Provider, PaymentProvider>, deps: {
1087
+ readonly eventBus: EventBus;
1088
+ readonly logger: Logger;
1089
+ readonly clock: Clock;
1090
+ readonly idGenerator: IdGenerator;
1091
+ });
1092
+ receive(input: WebhookInput): Promise<Result<WebhookEvent, WebhookValidationError>>;
1093
+ }
1094
+
1095
+ interface ListBankCodesOptions {
1096
+ /**
1097
+ * Two-letter ISO country for providers that resolve banks by country
1098
+ * (Bachs). Required there when the currency alone does not identify one.
1099
+ */
1100
+ readonly country?: string;
1101
+ }
1102
+
1103
+ interface ResolveAccountInput {
1104
+ readonly accountNumber: string;
1105
+ readonly bankCode: string;
1106
+ readonly currency: Currency;
1107
+ /** Two-letter ISO country, for providers that resolve by country (Bachs). */
1108
+ readonly country?: string;
1109
+ }
1110
+
1111
+ declare class TransferService {
1112
+ private readonly provider;
1113
+ private readonly eventBus;
1114
+ private readonly logger;
1115
+ private readonly clock;
1116
+ private readonly idGenerator;
1117
+ constructor(provider: PaymentProvider, eventBus: EventBus, logger: Logger, clock: Clock, idGenerator: IdGenerator);
1118
+ listBankCodes(currency: Currency, options?: ListBankCodesOptions): Promise<Result<ReadonlyArray<BankCode>, PaymentError>>;
1119
+ resolveAccount(input: ResolveAccountInput): Promise<Result<ResolveAccountResult, PaymentError>>;
1120
+ createRecipient(input: CreateRecipientInput): Promise<Result<TransferRecipient, PaymentError>>;
1121
+ /**
1122
+ * Locks an exchange rate for a cross-currency payout. Pass the returned id
1123
+ * as `quoteId` to {@link initiate} (and omit `amount`).
1124
+ */
1125
+ createQuote(input: TransferQuoteInput): Promise<Result<TransferQuote, PaymentError>>;
1126
+ initiate(input: InitiateTransferInput): Promise<Result<Transfer, PaymentError>>;
1127
+ fetch(id: string): Promise<Result<Transfer, PaymentError>>;
1128
+ list(query: ListQuery): Promise<Result<Page<Transfer>, PaymentError>>;
1129
+ }
1130
+
1131
+ /**
1132
+ * Shared dependencies for the catalog/billing facades.
1133
+ *
1134
+ * `subscriptionProvider` is undefined when the configured provider does not
1135
+ * implement the subscription capability; every facade method then returns an
1136
+ * `UnsupportedProviderError` instead of throwing, so an application can call
1137
+ * the API unconditionally and handle one error shape.
1138
+ */
1139
+ interface SubscriptionFacadeDeps {
1140
+ readonly providerId: Provider;
1141
+ readonly subscriptionProvider?: SubscriptionProvider;
1142
+ readonly logger: Logger;
1143
+ readonly eventBus?: EventBus;
1144
+ readonly clock?: Clock;
1145
+ readonly idGenerator?: IdGenerator;
1146
+ }
1147
+
1148
+ /**
1149
+ * Catalog facade. Products are the billing catalog: fixed, free, or
1150
+ * pay-what-you-want prices, optionally recurring.
1151
+ */
1152
+ declare class ProductService {
1153
+ private readonly providerId;
1154
+ private readonly products;
1155
+ private readonly logger;
1156
+ constructor(deps: SubscriptionFacadeDeps);
1157
+ list(query?: ProductListQuery): Promise<Result<Page<Product>, PaymentError>>;
1158
+ fetch(id: string): Promise<Result<Product, PaymentError>>;
1159
+ create(input: CreateProductInput): Promise<Result<Product, PaymentError>>;
1160
+ update(id: string, input: UpdateProductInput): Promise<Result<Product, PaymentError>>;
1161
+ /** Archived products stop selling but keep billing existing subscriptions. */
1162
+ archive(id: string): Promise<Result<Product, PaymentError>>;
1163
+ unarchive(id: string): Promise<Result<Product, PaymentError>>;
1164
+ }
1165
+
1166
+ /**
1167
+ * Recurring billing facade.
1168
+ *
1169
+ * Subscriptions are created by completing a checkout for a recurring product —
1170
+ * there is no create-subscription call — so this facade lists, inspects,
1171
+ * changes plan, moves trials, and cancels.
1172
+ */
1173
+ declare class SubscriptionService {
1174
+ private readonly providerId;
1175
+ private readonly subscriptions;
1176
+ private readonly logger;
1177
+ private readonly eventBus;
1178
+ private readonly clock;
1179
+ private readonly idGenerator;
1180
+ constructor(deps: SubscriptionFacadeDeps);
1181
+ list(query?: SubscriptionListQuery): Promise<Result<Page<Subscription>, PaymentError>>;
1182
+ fetch(id: string): Promise<Result<Subscription, PaymentError>>;
1183
+ /**
1184
+ * Applies exactly one change. Bachs rejects combined intents, so combining
1185
+ * `productId`, `trialEnd`, `paymentMethodId`, or `metadata` in one call
1186
+ * throws rather than sending a request the provider will refuse.
1187
+ *
1188
+ * Emits `subscription.updated` on success.
1189
+ */
1190
+ update(id: string, input: UpdateSubscriptionInput): Promise<Result<Subscription, PaymentError>>;
1191
+ /**
1192
+ * Cancels immediately, or at the period end when `atPeriodEnd` is true.
1193
+ * Emits `subscription.canceled` on success.
1194
+ */
1195
+ cancel(id: string, input?: CancelSubscriptionInput): Promise<Result<Subscription, PaymentError>>;
1196
+ private emit;
1197
+ }
1198
+
1199
+ /**
1200
+ * Billing-customer facade. A customer groups a buyer's payments,
1201
+ * subscriptions, and saved payment methods.
1202
+ */
1203
+ declare class CustomerService {
1204
+ private readonly providerId;
1205
+ private readonly customers;
1206
+ private readonly logger;
1207
+ constructor(deps: SubscriptionFacadeDeps);
1208
+ list(query?: CustomerListQuery): Promise<Result<Page<Customer>, PaymentError>>;
1209
+ fetch(id: string): Promise<Result<Customer, PaymentError>>;
1210
+ create(input: CreateCustomerInput): Promise<Result<Customer, PaymentError>>;
1211
+ update(id: string, input: UpdateCustomerInput): Promise<Result<Customer, PaymentError>>;
1212
+ /**
1213
+ * Mints a short-lived, pre-authenticated portal URL for one customer.
1214
+ *
1215
+ * The URL is a credential. It is deliberately not logged, and callers must
1216
+ * not cache or persist it — mint a fresh session per request.
1217
+ */
1218
+ createPortalSession(customerId: string): Promise<Result<PortalSession, PaymentError>>;
1219
+ }
1220
+
1221
+ declare class ProviderRegistry {
1222
+ private readonly factory;
1223
+ private readonly providers;
1224
+ private readonly logger;
1225
+ constructor(factory: ProviderFactory, providers: ReadonlyMap<Provider, PaymentProvider>, logger: Logger);
1226
+ get(id: string): PaymentProvider;
1227
+ list(): ReadonlyArray<Provider>;
1228
+ capabilities(id: string): ProviderCapabilities;
1229
+ health(id: string): Promise<HealthStatus>;
1230
+ }
1231
+
1232
+ declare class EventSubscriptionView implements EventSubscription {
1233
+ private readonly bus;
1234
+ constructor(bus: EventBus);
1235
+ on<T extends PaymentEventType>(type: T, handler: EventHandler<T>): Unsubscribe;
1236
+ onAny(handler: EventHandler): Unsubscribe;
1237
+ }
1238
+
1239
+ interface PaymentClient {
1240
+ readonly payments: PaymentService;
1241
+ readonly refunds: RefundService;
1242
+ readonly webhooks: WebhookService;
1243
+ readonly transfers: TransferService;
1244
+ /**
1245
+ * Catalog, recurring billing, and billing customers. Available on providers
1246
+ * that implement the subscription capability (Bachs); every method returns
1247
+ * an `UnsupportedProviderError` otherwise.
1248
+ */
1249
+ readonly products: ProductService;
1250
+ readonly subscriptions: SubscriptionService;
1251
+ readonly customers: CustomerService;
1252
+ readonly events: EventSubscriptionView;
1253
+ readonly providers: ProviderRegistry;
1254
+ health(): Promise<ReadonlyArray<HealthStatus>>;
1255
+ }
1256
+
1257
+ export { type ProductPrice as $, type Payment as A, type BankCode as B, type CancelSubscriptionInput as C, type PaymentAttempt as D, ErrorCode as E, type PaymentChannel as F, type PaymentEvent as G, type HealthStatus as H, type IdGenerator as I, type PaymentEventType as J, type PaymentFailed as K, type Logger as L, type Metadata as M, type PaymentInitialized as N, type PaymentPending as O, type PaymentClientConfig as P, PaymentReference as Q, type Result as R, type PaymentRequest as S, type PaymentRequestItem as T, type PaymentStatus as U, type PaymentStatusKind as V, type PaymentSucceeded as W, type PortalSession as X, type PriceType as Y, type Product as Z, type ProductListQuery as _, type PaymentClient as a, type ProductPriceInput as a0, ProductService as a1, type ProductStatus as a2, Provider as a3, type ProviderCapabilities as a4, type ProviderInstance as a5, RecurringCadence as a6, type RecurringInterval as a7, type Refund as a8, type RefundCreateInput as a9, type UpdateProductInput as aA, type UpdateSubscriptionInput as aB, type VerificationCompleted as aC, type WebhookEvent as aD, type WebhookInput as aE, type WebhookReceived as aF, WebhookValidationError as aG, attempt as aH, err as aI, isFinalRefundStatus as aJ, isFinalStatus as aK, isFinalSubscriptionStatus as aL, isFinalTransferStatus as aM, isRecurring as aN, isSubscriptionActive as aO, isSubscriptionDelinquent as aP, isSubscriptionProvider as aQ, isTransitionAllowed as aR, ok as aS, type RefundFailed as aa, type RefundInitiated as ab, type RefundRequest as ac, type RefundResult as ad, type RefundStatus as ae, type RefundStatusKind as af, type RefundSucceeded as ag, type ResolveAccountResult as ah, type Subscription as ai, type SubscriptionCanceled as aj, type SubscriptionListQuery as ak, type SubscriptionProvider as al, SubscriptionService as am, type SubscriptionStatus as an, type SubscriptionStatusKind as ao, type SubscriptionUpdated as ap, type Transfer as aq, type TransferFailed as ar, type TransferInitiated as as, type TransferRecipient as at, type TransferReversed as au, type TransferStatus as av, type TransferStatusKind as aw, type TransferSucceeded as ax, type Unsubscribe as ay, type UpdateCustomerInput as az, PaymentError as b, type PaymentErrorOptions as c, type HttpClient as d, type HttpRequest as e, type HttpResponse as f, type Clock as g, type CreateCustomerInput as h, type CreateProductInput as i, type CreateRecipientInput as j, Currency as k, type CurrencyPriceInput as l, type CurrencyPriceOption as m, type Customer as n, type CustomerListQuery as o, type CustomerReference as p, CustomerService as q, ErrorCategory as r, type EventBus as s, type EventHandler as t, type EventSubscription as u, type InitiateTransferInput as v, type ListQuery as w, MinorUnits as x, Money as y, type Page as z };