@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,4979 @@
1
+ 'use strict';
2
+
3
+ var common = require('@nestjs/common');
4
+ var crypto = require('crypto');
5
+
6
+ var __defProp = Object.defineProperty;
7
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
8
+ var __decorateClass = (decorators, target, key, kind) => {
9
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
10
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
11
+ if (decorator = decorators[i])
12
+ result = (kind ? decorator(target, key, result) : decorator(result)) || result;
13
+ if (kind && result) __defProp(target, key, result);
14
+ return result;
15
+ };
16
+ var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
17
+
18
+ // src/errors/payment-error.ts
19
+ var PaymentError = class extends Error {
20
+ provider;
21
+ providerCode;
22
+ correlationId;
23
+ isRetryable;
24
+ httpStatus;
25
+ meta;
26
+ constructor(message, options = {}) {
27
+ super(message, { cause: options.cause });
28
+ this.name = this.constructor.name;
29
+ this.provider = options.provider;
30
+ this.providerCode = options.providerCode;
31
+ this.correlationId = options.correlationId ?? "unknown";
32
+ this.isRetryable = options.isRetryable ?? false;
33
+ this.httpStatus = options.httpStatus ?? 500;
34
+ this.meta = options.meta;
35
+ }
36
+ };
37
+
38
+ // src/errors/error-codes.ts
39
+ var ErrorCode = {
40
+ CONFIGURATION: "CONFIGURATION",
41
+ VALIDATION: "VALIDATION",
42
+ PROVIDER_UNAVAILABLE: "PROVIDER_UNAVAILABLE",
43
+ NETWORK: "NETWORK",
44
+ TIMEOUT: "TIMEOUT",
45
+ WEBHOOK_VALIDATION: "WEBHOOK_VALIDATION",
46
+ VERIFICATION: "VERIFICATION",
47
+ PROVIDER: "PROVIDER",
48
+ PROVIDER_BAD_REQUEST: "PROVIDER_BAD_REQUEST",
49
+ PROVIDER_UNAUTHORIZED: "PROVIDER_UNAUTHORIZED",
50
+ PROVIDER_NOT_FOUND: "PROVIDER_NOT_FOUND",
51
+ PROVIDER_CONFLICT: "PROVIDER_CONFLICT",
52
+ PROVIDER_RATE_LIMIT: "PROVIDER_RATE_LIMIT",
53
+ UNSUPPORTED: "UNSUPPORTED",
54
+ INTERNAL: "INTERNAL"
55
+ };
56
+ var ErrorCategory = {
57
+ CONFIGURATION: "configuration",
58
+ VALIDATION: "validation",
59
+ PROVIDER: "provider",
60
+ NETWORK: "network",
61
+ TIMEOUT: "timeout",
62
+ WEBHOOK: "webhook",
63
+ VERIFICATION: "verification",
64
+ UNSUPPORTED: "unsupported",
65
+ INTERNAL: "internal"
66
+ };
67
+
68
+ // src/errors/validation-error.ts
69
+ var ValidationError = class extends PaymentError {
70
+ code = ErrorCode.VALIDATION;
71
+ category = ErrorCategory.VALIDATION;
72
+ httpStatus = 400;
73
+ isRetryable = false;
74
+ constructor(message, options = {}) {
75
+ super(message, { ...options, httpStatus: 400, isRetryable: false });
76
+ }
77
+ };
78
+
79
+ // src/domain/money/currency.ts
80
+ var ISO_4217_RE = /^[A-Z]{3}$/;
81
+ function Currency(value) {
82
+ if (typeof value !== "string" || !ISO_4217_RE.test(value)) {
83
+ throw new ValidationError(`Invalid currency code "${value}": must be a 3-letter ISO 4217 code`);
84
+ }
85
+ return value;
86
+ }
87
+ ((Currency2) => {
88
+ Currency2.NGN = "NGN";
89
+ Currency2.GHS = "GHS";
90
+ Currency2.ZAR = "ZAR";
91
+ Currency2.KES = "KES";
92
+ Currency2.USD = "USD";
93
+ Currency2.EUR = "EUR";
94
+ Currency2.GBP = "GBP";
95
+ })(Currency || (Currency = {}));
96
+
97
+ // src/domain/money/money.ts
98
+ function MinorUnits(value) {
99
+ if (!Number.isFinite(value)) {
100
+ throw new ValidationError("Amount must be a finite number");
101
+ }
102
+ if (!Number.isInteger(value)) {
103
+ throw new ValidationError("Amount must be an integer (minor units)");
104
+ }
105
+ if (value < 0) {
106
+ throw new ValidationError("Amount must not be negative");
107
+ }
108
+ if (value > Number.MAX_SAFE_INTEGER) {
109
+ throw new ValidationError("Amount exceeds maximum safe integer");
110
+ }
111
+ return value;
112
+ }
113
+ function Money(input) {
114
+ return {
115
+ amount: MinorUnits(input.amount),
116
+ currency: Currency(input.currency)
117
+ };
118
+ }
119
+
120
+ // src/domain/reference/payment-reference.ts
121
+ function PaymentReference(raw) {
122
+ if (typeof raw !== "string" || raw.length === 0) {
123
+ throw new ValidationError("Payment reference must be a non-empty string");
124
+ }
125
+ if (!/^[A-Za-z0-9._=,+\-]{6,100}$/.test(raw)) {
126
+ throw new ValidationError(
127
+ `Payment reference must be 6-100 characters, containing only alphanumeric characters, hyphens, underscores, dots, equals, commas, and plus signs (got length ${raw.length})`
128
+ );
129
+ }
130
+ return raw;
131
+ }
132
+
133
+ // src/domain/provider/provider.ts
134
+ var PROVIDER_RE = /^[a-z][a-z0-9_]*$/;
135
+ function Provider(value) {
136
+ if (typeof value !== "string" || value.length === 0) {
137
+ throw new ValidationError("Provider must be a non-empty string");
138
+ }
139
+ if (!PROVIDER_RE.test(value)) {
140
+ throw new ValidationError(
141
+ `Invalid provider name "${value}": must start with a lowercase letter and contain only lowercase letters, digits, and underscores`
142
+ );
143
+ }
144
+ return value;
145
+ }
146
+
147
+ // src/shared/result/result.ts
148
+ function ok(value) {
149
+ return { ok: true, value };
150
+ }
151
+ function err(error) {
152
+ return { ok: false, error };
153
+ }
154
+
155
+ // src/errors/configuration-error.ts
156
+ var ConfigurationError = class extends PaymentError {
157
+ code = ErrorCode.CONFIGURATION;
158
+ category = ErrorCategory.CONFIGURATION;
159
+ httpStatus = 500;
160
+ isRetryable = false;
161
+ constructor(message, options = {}) {
162
+ super(message, { ...options, httpStatus: 500, isRetryable: false });
163
+ }
164
+ };
165
+
166
+ // src/errors/provider-error.ts
167
+ var ProviderError = class extends PaymentError {
168
+ code = ErrorCode.PROVIDER;
169
+ category = ErrorCategory.PROVIDER;
170
+ httpStatus;
171
+ isRetryable;
172
+ constructor(message, options = {}) {
173
+ const status = options.httpStatus ?? 502;
174
+ const retryable = options.isRetryable ?? false;
175
+ super(message, { ...options, httpStatus: status, isRetryable: retryable });
176
+ this.httpStatus = status;
177
+ this.isRetryable = retryable;
178
+ }
179
+ };
180
+ var ProviderBadRequestError = class extends ProviderError {
181
+ code = ErrorCode.PROVIDER_BAD_REQUEST;
182
+ httpStatus = 400;
183
+ isRetryable = false;
184
+ constructor(message, options = {}) {
185
+ super(message, { ...options, httpStatus: 400, isRetryable: false });
186
+ }
187
+ };
188
+ var ProviderUnauthorizedError = class extends ProviderError {
189
+ code = ErrorCode.PROVIDER_UNAUTHORIZED;
190
+ httpStatus;
191
+ isRetryable = false;
192
+ constructor(message, options = {}) {
193
+ const status = options.httpStatus ?? 401;
194
+ super(message, { ...options, httpStatus: status, isRetryable: false });
195
+ this.httpStatus = status;
196
+ }
197
+ };
198
+ var ProviderNotFoundError = class extends ProviderError {
199
+ code = ErrorCode.PROVIDER_NOT_FOUND;
200
+ httpStatus = 404;
201
+ isRetryable = false;
202
+ constructor(message, options = {}) {
203
+ super(message, { ...options, httpStatus: 404, isRetryable: false });
204
+ }
205
+ };
206
+ var ProviderConflictError = class extends ProviderError {
207
+ code = ErrorCode.PROVIDER_CONFLICT;
208
+ httpStatus = 409;
209
+ isRetryable = false;
210
+ constructor(message, options = {}) {
211
+ super(message, { ...options, httpStatus: 409, isRetryable: false });
212
+ }
213
+ };
214
+ var ProviderRateLimitError = class extends ProviderError {
215
+ code = ErrorCode.PROVIDER_RATE_LIMIT;
216
+ httpStatus = 429;
217
+ isRetryable = true;
218
+ constructor(message, options = {}) {
219
+ super(message, { ...options, httpStatus: 429, isRetryable: true });
220
+ }
221
+ };
222
+
223
+ // src/errors/provider-unavailable-error.ts
224
+ var ProviderUnavailableError = class extends PaymentError {
225
+ code = ErrorCode.PROVIDER_UNAVAILABLE;
226
+ category = ErrorCategory.PROVIDER;
227
+ httpStatus = 502;
228
+ isRetryable = true;
229
+ constructor(message, options = {}) {
230
+ super(message, { ...options, httpStatus: 502, isRetryable: true });
231
+ }
232
+ };
233
+
234
+ // src/errors/unsupported-provider-error.ts
235
+ var UnsupportedProviderError = class extends PaymentError {
236
+ code = ErrorCode.UNSUPPORTED;
237
+ category = ErrorCategory.UNSUPPORTED;
238
+ constructor(message, options = {}) {
239
+ super(message, { ...options, httpStatus: options.httpStatus ?? 501, isRetryable: false });
240
+ }
241
+ };
242
+
243
+ // src/errors/network-error.ts
244
+ var NetworkError = class extends PaymentError {
245
+ code = ErrorCode.NETWORK;
246
+ category = ErrorCategory.NETWORK;
247
+ httpStatus = 502;
248
+ isRetryable = true;
249
+ constructor(message, options = {}) {
250
+ super(message, { ...options, httpStatus: 502, isRetryable: true });
251
+ }
252
+ };
253
+
254
+ // src/errors/timeout-error.ts
255
+ var TimeoutError = class extends PaymentError {
256
+ code = ErrorCode.TIMEOUT;
257
+ category = ErrorCategory.TIMEOUT;
258
+ httpStatus = 504;
259
+ isRetryable = true;
260
+ constructor(message, options = {}) {
261
+ super(message, { ...options, httpStatus: 504, isRetryable: true });
262
+ }
263
+ };
264
+
265
+ // src/errors/webhook-validation-error.ts
266
+ var WebhookValidationError = class extends PaymentError {
267
+ code = ErrorCode.WEBHOOK_VALIDATION;
268
+ category = ErrorCategory.WEBHOOK;
269
+ httpStatus = 401;
270
+ isRetryable = false;
271
+ constructor(message, options = {}) {
272
+ super(message, { ...options, httpStatus: 401, isRetryable: false });
273
+ }
274
+ };
275
+
276
+ // src/errors/verification-error.ts
277
+ var VerificationError = class extends PaymentError {
278
+ code = ErrorCode.VERIFICATION;
279
+ category = ErrorCategory.VERIFICATION;
280
+ httpStatus = 422;
281
+ isRetryable = false;
282
+ constructor(message, options = {}) {
283
+ super(message, { ...options, httpStatus: 422, isRetryable: false });
284
+ }
285
+ };
286
+
287
+ // src/errors/internal-error.ts
288
+ var InternalError = class extends PaymentError {
289
+ code = ErrorCode.INTERNAL;
290
+ category = ErrorCategory.INTERNAL;
291
+ httpStatus = 500;
292
+ isRetryable = false;
293
+ constructor(message, options = {}) {
294
+ super(message, { ...options, httpStatus: 500, isRetryable: false });
295
+ }
296
+ };
297
+
298
+ // src/infrastructure/providers/provider-factory.ts
299
+ var registry = /* @__PURE__ */ new Map();
300
+ function registerProvider(id, factory) {
301
+ if (registry.has(id)) {
302
+ throw new ConfigurationError(`Provider "${id}" is already registered`);
303
+ }
304
+ registry.set(id, factory);
305
+ }
306
+ function createProviderFactory() {
307
+ return {
308
+ create(id, config, deps) {
309
+ const factory = registry.get(id);
310
+ if (!factory) {
311
+ throw new ConfigurationError(
312
+ `Unknown provider "${id}". Available providers: ${[...registry.keys()].join(", ") || "none"}`
313
+ );
314
+ }
315
+ if (config.enabled === false) {
316
+ throw new ConfigurationError(`Provider "${id}" is disabled in configuration`);
317
+ }
318
+ return factory(config, deps);
319
+ },
320
+ supported() {
321
+ return [...registry.keys()];
322
+ }
323
+ };
324
+ }
325
+
326
+ // src/shared/errors/mapper-error.ts
327
+ function mapMapperError(e, options) {
328
+ if (e instanceof ProviderError || e instanceof VerificationError) {
329
+ return e;
330
+ }
331
+ return new ProviderError(
332
+ `Failed to parse ${options.context}: ${e instanceof Error ? e.message : String(e)}`,
333
+ {
334
+ provider: options.provider,
335
+ httpStatus: 502,
336
+ isRetryable: false
337
+ }
338
+ );
339
+ }
340
+
341
+ // src/infrastructure/providers/paystack/paystack-primitives.ts
342
+ function toPaystackDate(...candidates) {
343
+ for (const candidate of candidates) {
344
+ if (candidate === null || candidate === void 0 || candidate === "") continue;
345
+ const date = new Date(candidate);
346
+ if (!Number.isNaN(date.getTime())) return date;
347
+ }
348
+ return void 0;
349
+ }
350
+
351
+ // src/infrastructure/providers/paystack/paystack-mapper.ts
352
+ var PAYSTACK = Provider("paystack");
353
+ function transactionIdOf(transaction) {
354
+ if (transaction === null || transaction === void 0) return void 0;
355
+ if (typeof transaction === "number") return Number.isFinite(transaction) ? String(transaction) : void 0;
356
+ const id = transaction.id;
357
+ return typeof id === "number" && Number.isFinite(id) ? String(id) : void 0;
358
+ }
359
+ function requireTimestamp(candidates, context) {
360
+ const date = toPaystackDate(...candidates);
361
+ if (!date) {
362
+ throw new ProviderError(`Paystack returned ${context} without a usable timestamp`, {
363
+ provider: PAYSTACK,
364
+ httpStatus: 422,
365
+ isRetryable: false
366
+ });
367
+ }
368
+ return date;
369
+ }
370
+ function mapPaystackStatus(status, tx) {
371
+ switch (status) {
372
+ case "abandoned":
373
+ return { kind: "abandoned" };
374
+ case "success":
375
+ return {
376
+ kind: "success",
377
+ paidAt: requireTimestamp([tx.paid_at, tx.updated_at, tx.created_at], "a successful transaction")
378
+ };
379
+ case "failed":
380
+ return {
381
+ kind: "failed",
382
+ reason: tx.gateway_response ?? "payment_failed",
383
+ failedAt: requireTimestamp([tx.updated_at, tx.created_at], "a failed transaction")
384
+ };
385
+ case "pending":
386
+ case "processing":
387
+ case "ongoing":
388
+ case "queued":
389
+ return { kind: "pending" };
390
+ case "reversed":
391
+ return {
392
+ kind: "refunded",
393
+ refundedAt: requireTimestamp([tx.updated_at, tx.created_at], "a reversed transaction"),
394
+ // Paystack exposes no refund id on a reversed transaction.
395
+ refundId: "unknown"
396
+ };
397
+ default:
398
+ return { kind: "pending" };
399
+ }
400
+ }
401
+ function emptyMetadata() {
402
+ return Object.freeze({});
403
+ }
404
+ function mapPaystackCustomer(pc) {
405
+ const name = [pc.first_name, pc.last_name].filter(Boolean).join(" ") || void 0;
406
+ return {
407
+ id: String(pc.id),
408
+ email: pc.email,
409
+ phone: pc.phone,
410
+ name,
411
+ metadata: pc.metadata ? Object.freeze({ ...pc.metadata }) : emptyMetadata()
412
+ };
413
+ }
414
+ function mapAuthorization(auth, tx) {
415
+ return {
416
+ id: auth.authorization_code,
417
+ status: {
418
+ kind: "success",
419
+ paidAt: requireTimestamp(
420
+ [tx.paid_at, tx.updated_at, tx.created_at],
421
+ "an authorization attempt"
422
+ )
423
+ },
424
+ channel: auth.channel,
425
+ bin: auth.bin,
426
+ last4: auth.last4,
427
+ bank: auth.bank,
428
+ authorizationCode: auth.authorization_code,
429
+ attemptedAt: requireTimestamp(
430
+ [tx.paid_at, tx.updated_at, tx.created_at],
431
+ "an authorization attempt"
432
+ )
433
+ };
434
+ }
435
+ function mapPaystackTransactionToPayment(tx) {
436
+ const amount = Money({ amount: tx.amount, currency: tx.currency });
437
+ const status = mapPaystackStatus(tx.status, tx);
438
+ const customer = mapPaystackCustomer(tx.customer);
439
+ const reference = PaymentReference(tx.reference);
440
+ const attempts = [];
441
+ if (tx.authorization) {
442
+ attempts.push(mapAuthorization(tx.authorization, tx));
443
+ }
444
+ const fees = tx.fees != null ? Money({ amount: tx.fees, currency: tx.currency }) : void 0;
445
+ const net = fees && tx.amount - fees.amount >= 0 ? Money({ amount: tx.amount - fees.amount, currency: tx.currency }) : void 0;
446
+ return {
447
+ id: String(tx.id),
448
+ providerId: PAYSTACK,
449
+ reference,
450
+ amount,
451
+ fees,
452
+ netAmount: net,
453
+ status,
454
+ customer,
455
+ authorizationUrl: void 0,
456
+ accessCode: void 0,
457
+ channel: tx.channel,
458
+ attempts: Object.freeze(attempts),
459
+ metadata: tx.metadata ? Object.freeze({ ...tx.metadata }) : emptyMetadata(),
460
+ createdAt: requireTimestamp([tx.created_at], "a transaction"),
461
+ updatedAt: requireTimestamp([tx.updated_at, tx.created_at], "a transaction"),
462
+ paidAt: tx.paid_at ? toPaystackDate(tx.paid_at) : void 0,
463
+ failureReason: tx.status === "failed" ? tx.gateway_response : void 0
464
+ };
465
+ }
466
+ function mapInitializeResponse(response, request) {
467
+ if (!response.status) {
468
+ throw new ProviderError(response.message, {
469
+ provider: PAYSTACK,
470
+ httpStatus: 422,
471
+ isRetryable: false
472
+ });
473
+ }
474
+ const data = response.data;
475
+ const reference = request.reference;
476
+ const amount = request.amount;
477
+ return {
478
+ providerId: PAYSTACK,
479
+ reference,
480
+ amount,
481
+ status: { kind: "initialized" },
482
+ customer: request.customer.kind === "inline" ? request.customer.customer : {
483
+ id: "pending",
484
+ email: request.customer.kind === "new" ? request.customer.email : "unknown",
485
+ phone: request.customer.kind === "new" ? request.customer.phone : void 0,
486
+ name: request.customer.kind === "new" ? request.customer.name : void 0
487
+ },
488
+ authorizationUrl: data.authorization_url,
489
+ accessCode: data.access_code,
490
+ channel: void 0,
491
+ attempts: Object.freeze([]),
492
+ metadata: request.metadata ? Object.freeze({ ...request.metadata }) : emptyMetadata(),
493
+ createdAt: /* @__PURE__ */ new Date(),
494
+ updatedAt: /* @__PURE__ */ new Date()
495
+ };
496
+ }
497
+ function mapPaystackResponseToPayment(response) {
498
+ if (!response.status) {
499
+ throw new VerificationError(`Paystack verification failed: ${response.message}`, {
500
+ provider: PAYSTACK
501
+ });
502
+ }
503
+ return mapPaystackTransactionToPayment(response.data);
504
+ }
505
+ function mapPaystackListResponse(response) {
506
+ if (!response.status) {
507
+ throw new ProviderError(response.message, {
508
+ provider: PAYSTACK,
509
+ httpStatus: 422,
510
+ isRetryable: false
511
+ });
512
+ }
513
+ return {
514
+ items: response.data.map(mapPaystackTransactionToPayment),
515
+ total: response.meta.total,
516
+ page: response.meta.page,
517
+ perPage: response.meta.perPage
518
+ };
519
+ }
520
+ function mapPaystackWebhookEvent(webhook, rawBody, receivedAt) {
521
+ const data = webhook.data ?? {};
522
+ const resourceId = typeof data.id === "number" && Number.isFinite(data.id) ? String(data.id) : void 0;
523
+ return {
524
+ id: resourceId ?? contentHash(rawBody),
525
+ provider: PAYSTACK,
526
+ type: normalizeWebhookType(webhook.event),
527
+ originalType: webhook.event,
528
+ createdAt: toPaystackDate(data.created_at, data.createdAt) ?? receivedAt,
529
+ receivedAt,
530
+ payload: data,
531
+ raw: webhook
532
+ };
533
+ }
534
+ function contentHash(rawBody) {
535
+ return `sha256:${crypto.createHash("sha256").update(rawBody, "utf8").digest("hex").slice(0, 32)}`;
536
+ }
537
+ function normalizeWebhookType(event) {
538
+ switch (event) {
539
+ case "charge.success":
540
+ return "payment.succeeded";
541
+ case "charge.failed":
542
+ case "charge.timeout":
543
+ return "payment.failed";
544
+ case "charge.pending":
545
+ case "charge.ongoing":
546
+ return "payment.pending";
547
+ case "charge.created":
548
+ return "payment.initialized";
549
+ case "refund.processed":
550
+ return "refund.succeeded";
551
+ case "refund.failed":
552
+ return "refund.failed";
553
+ case "refund.pending":
554
+ case "refund.processing":
555
+ return "refund.initiated";
556
+ case "transfer.success":
557
+ return "transfer.succeeded";
558
+ case "transfer.failed":
559
+ return "transfer.failed";
560
+ case "transfer.reversed":
561
+ return "transfer.reversed";
562
+ default:
563
+ return "payment.unknown";
564
+ }
565
+ }
566
+ function mapPaystackRefundResponse(response, now) {
567
+ if (!response.status) {
568
+ throw new ProviderError(response.message, {
569
+ provider: PAYSTACK,
570
+ httpStatus: 422,
571
+ isRetryable: false
572
+ });
573
+ }
574
+ const data = response.data;
575
+ const paymentId = transactionIdOf(data.transaction);
576
+ const settled = data.status === "processed" || data.status === "success";
577
+ const providerStatus = isNeedsAttention(data.status) ? data.status : void 0;
578
+ return {
579
+ id: String(data.id),
580
+ // Only reachable on a response that omits `transaction` entirely, which
581
+ // neither documented refund shape does.
582
+ paymentId: paymentId ?? "unknown",
583
+ amount: Money({ amount: data.amount, currency: data.currency }),
584
+ status: mapRefundStatus(data.status),
585
+ ...providerStatus ? { providerStatus } : {},
586
+ reason: data.merchant_note ?? "",
587
+ reference: String(data.id),
588
+ createdAt: toPaystackDate(data.createdAt, data.created_at) ?? now,
589
+ completedAt: settled ? toPaystackDate(data.updatedAt, data.updated_at) : void 0
590
+ };
591
+ }
592
+ function isNeedsAttention(status) {
593
+ const normalized = status.toLowerCase();
594
+ return normalized === "needs-attention" || normalized === "needs_attention";
595
+ }
596
+ function mapRefundStatus(status) {
597
+ switch (status.toLowerCase()) {
598
+ case "processed":
599
+ case "success":
600
+ case "succeeded":
601
+ return "succeeded";
602
+ case "failed":
603
+ case "cancelled":
604
+ return "failed";
605
+ case "pending":
606
+ case "processing":
607
+ case "needs-attention":
608
+ return "pending";
609
+ default:
610
+ return "pending";
611
+ }
612
+ }
613
+ var HmacWebhookVerifier = class {
614
+ secret;
615
+ algorithm;
616
+ constructor(secret, algorithm = "sha512") {
617
+ this.secret = secret;
618
+ this.algorithm = algorithm;
619
+ }
620
+ verify(rawBody, signature) {
621
+ try {
622
+ const bodyBuffer = typeof rawBody === "string" ? Buffer.from(rawBody, "utf8") : rawBody;
623
+ const expected = crypto.createHmac(this.algorithm, this.secret).update(bodyBuffer).digest("hex");
624
+ const a = Buffer.from(expected);
625
+ const b = Buffer.from(signature);
626
+ if (a.length !== b.length) {
627
+ return false;
628
+ }
629
+ return crypto.timingSafeEqual(a, b);
630
+ } catch {
631
+ return false;
632
+ }
633
+ }
634
+ };
635
+
636
+ // src/infrastructure/providers/paystack/paystack-webhook.ts
637
+ var SIGNATURE_HEADER = "x-paystack-signature";
638
+ function parsePaystackWebhook(headers, rawBody, webhookSecret, now, signatureFallback) {
639
+ const signature = findHeader(headers, SIGNATURE_HEADER) ?? signatureFallback;
640
+ if (!signature) {
641
+ return err(new WebhookValidationError("Missing x-paystack-signature header"));
642
+ }
643
+ const verifier = new HmacWebhookVerifier(webhookSecret, "sha512");
644
+ if (!verifier.verify(rawBody, signature)) {
645
+ return err(new WebhookValidationError("Invalid webhook signature"));
646
+ }
647
+ let payload;
648
+ try {
649
+ payload = JSON.parse(rawBody);
650
+ } catch {
651
+ return err(new WebhookValidationError("Invalid webhook body: not valid JSON"));
652
+ }
653
+ if (!payload.event || !payload.data) {
654
+ return err(new WebhookValidationError("Invalid webhook body: missing event or data"));
655
+ }
656
+ try {
657
+ const event = mapPaystackWebhookEvent(payload, rawBody, now);
658
+ return ok(event);
659
+ } catch (e) {
660
+ return err(new WebhookValidationError(
661
+ `Failed to parse webhook payload: ${e instanceof Error ? e.message : String(e)}`
662
+ ));
663
+ }
664
+ }
665
+ function findHeader(headers, name) {
666
+ const lower = name.toLowerCase();
667
+ for (const key of Object.keys(headers)) {
668
+ if (key.toLowerCase() === lower) {
669
+ return headers[key];
670
+ }
671
+ }
672
+ return void 0;
673
+ }
674
+
675
+ // src/infrastructure/providers/paystack/paystack-transfer-mapper.ts
676
+ var PAYSTACK2 = Provider("paystack");
677
+ function emptyMetadata2() {
678
+ return Object.freeze({});
679
+ }
680
+ function assertOk(response) {
681
+ if (response.status) return;
682
+ throw new ProviderError(response.message, {
683
+ provider: PAYSTACK2,
684
+ httpStatus: 422,
685
+ isRetryable: false
686
+ });
687
+ }
688
+ function mapPaystackBank(bank) {
689
+ return {
690
+ code: bank.code,
691
+ name: bank.name,
692
+ currency: Currency(bank.currency)
693
+ };
694
+ }
695
+ function mapPaystackBankListResponse(response) {
696
+ assertOk(response);
697
+ return response.data.filter((bank) => bank.active !== false).map(mapPaystackBank);
698
+ }
699
+ function mapPaystackRecipient(data, now) {
700
+ return {
701
+ code: data.recipient_code,
702
+ name: data.name,
703
+ accountNumber: data.details.account_number,
704
+ bankCode: data.details.bank_code,
705
+ currency: Currency(data.currency),
706
+ createdAt: toPaystackDate(data.createdAt, data.created_at) ?? now,
707
+ metadata: data.metadata ? Object.freeze({ ...data.metadata }) : emptyMetadata2()
708
+ };
709
+ }
710
+ function mapPaystackCreateRecipientResponse(response, now) {
711
+ assertOk(response);
712
+ return mapPaystackRecipient(response.data, now);
713
+ }
714
+ function stubRecipient(recipientId, currency, now) {
715
+ return {
716
+ code: recipientId === null ? "unknown" : String(recipientId),
717
+ name: "unknown",
718
+ accountNumber: "unknown",
719
+ bankCode: "unknown",
720
+ currency: Currency(currency),
721
+ createdAt: now,
722
+ metadata: emptyMetadata2()
723
+ };
724
+ }
725
+ function resolveTransferRecipient(value, currency, now, hint) {
726
+ if (value !== null && value !== void 0 && typeof value === "object") {
727
+ return mapPaystackRecipient(value, now);
728
+ }
729
+ if (hint) return hint;
730
+ return stubRecipient(typeof value === "number" ? value : null, currency, now);
731
+ }
732
+ function mapPaystackTransferStatus(status, data, now) {
733
+ const updatedAt = toPaystackDate(data.updatedAt, data.updated_at, data.createdAt, data.created_at);
734
+ switch (status) {
735
+ case "pending":
736
+ return { kind: "pending" };
737
+ // Paystack requires an OTP to be finalized when it reports `otp`; without
738
+ // the flag a caller cannot tell "queued" from "waiting on you".
739
+ case "otp":
740
+ return { kind: "pending", requiresAction: true };
741
+ case "processing":
742
+ return { kind: "processing" };
743
+ case "success":
744
+ return {
745
+ kind: "succeeded",
746
+ settledAt: toPaystackDate(
747
+ data.transferred_at,
748
+ data.updatedAt,
749
+ data.updated_at,
750
+ data.createdAt,
751
+ data.created_at
752
+ ) ?? now
753
+ };
754
+ case "failed":
755
+ return {
756
+ kind: "failed",
757
+ reason: data.reason || "transfer_failed",
758
+ failedAt: updatedAt ?? now
759
+ };
760
+ case "reversed":
761
+ return { kind: "reversed", reversedAt: updatedAt ?? now };
762
+ default:
763
+ return { kind: "pending" };
764
+ }
765
+ }
766
+ function mapFee(data, currency) {
767
+ const charged = data.fee_charged;
768
+ if (typeof charged !== "number" || !Number.isInteger(charged) || charged < 0) {
769
+ return void 0;
770
+ }
771
+ return Money({ amount: charged, currency });
772
+ }
773
+ function mapPaystackTransferToDomain(data, now, recipientHint) {
774
+ const currency = Currency(data.currency);
775
+ const fee = mapFee(data, currency);
776
+ return {
777
+ id: String(data.id),
778
+ providerId: PAYSTACK2,
779
+ amount: Money({ amount: data.amount, currency }),
780
+ ...fee ? { fee } : {},
781
+ recipient: resolveTransferRecipient(data.recipient, data.currency, now, recipientHint),
782
+ status: mapPaystackTransferStatus(data.status, data, now),
783
+ reference: data.reference,
784
+ reason: data.reason || void 0,
785
+ transferCode: data.transfer_code,
786
+ createdAt: toPaystackDate(data.createdAt, data.created_at) ?? now,
787
+ completedAt: toPaystackDate(data.transferred_at),
788
+ failureReason: data.status === "failed" ? data.reason || void 0 : void 0,
789
+ metadata: emptyMetadata2()
790
+ };
791
+ }
792
+ function mapPaystackTransferResponse(response, now, recipientHint) {
793
+ assertOk(response);
794
+ return mapPaystackTransferToDomain(response.data, now, recipientHint);
795
+ }
796
+ function mapPaystackTransferListResponse(response, now) {
797
+ assertOk(response);
798
+ return {
799
+ items: response.data.map((data) => mapPaystackTransferToDomain(data, now)),
800
+ total: response.meta.total,
801
+ page: response.meta.page,
802
+ perPage: response.meta.perPage
803
+ };
804
+ }
805
+
806
+ // src/infrastructure/providers/paystack/paystack-adapter.ts
807
+ var PAYSTACK_BASE_URL = "https://api.paystack.co";
808
+ var PAYSTACK_BANK_TYPES_BY_CURRENCY = {
809
+ NGN: "nuban",
810
+ USD: "nuban",
811
+ GHS: "ghipss",
812
+ ZAR: "basa"
813
+ };
814
+ var PAYSTACK_TRANSFER_REFERENCE_RE = /^[a-z0-9_-]{16,50}$/;
815
+ var BANK_PAGE_SIZE = 100;
816
+ var MAX_BANK_PAGES = 10;
817
+ var PAYSTACK_CAPABILITIES = {
818
+ supportsAuthorizationUrl: true,
819
+ supportsRecurring: true,
820
+ supportsPartialRefund: true,
821
+ supportsWebhooks: true,
822
+ supportsTransfers: true,
823
+ // Paystack documents no Idempotency-Key header: dedupe relies on unique
824
+ // references, and a retried refund can duplicate the effect.
825
+ supportsIdempotencyKey: false,
826
+ supportedCurrencies: [
827
+ "NGN",
828
+ "GHS",
829
+ "ZAR",
830
+ "KES",
831
+ "USD"
832
+ ],
833
+ supportedChannels: ["card", "bank", "ussd", "qr", "mobile_money", "bank_transfer"],
834
+ supportedTransferCurrencies: [
835
+ "NGN",
836
+ "GHS",
837
+ "ZAR",
838
+ "KES"
839
+ ]
840
+ };
841
+ var PaystackAdapter = class {
842
+ id;
843
+ capabilities;
844
+ httpClient;
845
+ logger;
846
+ clock;
847
+ eventBus;
848
+ idGenerator;
849
+ webhookVerifier;
850
+ secretKey;
851
+ webhookSecret;
852
+ baseUrl;
853
+ timeoutMs;
854
+ constructor(config, deps) {
855
+ this.id = "paystack";
856
+ this.capabilities = PAYSTACK_CAPABILITIES;
857
+ this.httpClient = deps.httpClient;
858
+ this.logger = deps.logger;
859
+ this.clock = deps.clock;
860
+ this.eventBus = deps.eventBus;
861
+ this.idGenerator = deps.idGenerator;
862
+ this.webhookVerifier = deps.webhookVerifier;
863
+ this.secretKey = config.secretKey;
864
+ this.webhookSecret = config.webhookSecret ?? config.secretKey;
865
+ this.baseUrl = config.baseUrl ?? PAYSTACK_BASE_URL;
866
+ this.timeoutMs = config.timeoutMs ?? 3e4;
867
+ }
868
+ async initialize(req) {
869
+ if (req.products && req.products.length > 0) {
870
+ return err(
871
+ new UnsupportedProviderError(
872
+ "Paystack does not support catalog checkouts; product-based checkouts need a provider with the subscription capability (Bachs)",
873
+ { provider: this.id }
874
+ )
875
+ );
876
+ }
877
+ if (req.customer.kind === "existing") {
878
+ return err(
879
+ new ValidationError(
880
+ 'Paystack cannot initialize from an existing customer id because the API requires an email; pass { kind: "new", email } or { kind: "inline", customer }'
881
+ )
882
+ );
883
+ }
884
+ const amount = req.amount;
885
+ if (!amount) {
886
+ throw new ValidationError("Paystack initialize requires an amount");
887
+ }
888
+ const payload = {
889
+ amount: amount.amount,
890
+ email: getEmail(req.customer),
891
+ reference: req.reference,
892
+ currency: amount.currency,
893
+ callback_url: req.callbackUrl,
894
+ channels: req.channels ? req.channels.slice() : void 0,
895
+ metadata: req.metadata ? req.metadata : void 0
896
+ };
897
+ const correlationId = req.correlationId ?? this.idGenerator.generate();
898
+ this.logger.info("initializing payment", {
899
+ provider: "paystack",
900
+ reference: req.reference,
901
+ correlationId,
902
+ amount: String(amount.amount),
903
+ currency: amount.currency
904
+ });
905
+ const result = await this.httpClient.send({
906
+ method: "POST",
907
+ url: `${this.baseUrl}/transaction/initialize`,
908
+ headers: this.authHeaders(),
909
+ body: JSON.stringify(payload),
910
+ timeoutMs: this.timeoutMs,
911
+ correlationId,
912
+ idempotencyKey: req.idempotencyKey
913
+ });
914
+ if (!result.ok) {
915
+ this.logger.error("initialize failed", result.error, {
916
+ provider: "paystack",
917
+ reference: req.reference,
918
+ correlationId
919
+ });
920
+ return result;
921
+ }
922
+ try {
923
+ const response = JSON.parse(result.value.body);
924
+ const payment = mapInitializeResponse(response, req);
925
+ return ok(payment);
926
+ } catch (e) {
927
+ return err(mapMapperError(e, { provider: this.id, context: "initialize response" }));
928
+ }
929
+ }
930
+ async verify(reference) {
931
+ const correlationId = this.idGenerator.generate();
932
+ this.logger.info("verifying payment", {
933
+ provider: "paystack",
934
+ reference,
935
+ correlationId
936
+ });
937
+ const result = await this.httpClient.send({
938
+ method: "GET",
939
+ url: `${this.baseUrl}/transaction/verify/${encodeURIComponent(reference)}`,
940
+ headers: this.authHeaders(),
941
+ timeoutMs: this.timeoutMs,
942
+ correlationId
943
+ });
944
+ if (!result.ok) return result;
945
+ try {
946
+ const response = JSON.parse(result.value.body);
947
+ const payment = mapPaystackResponseToPayment(response);
948
+ return ok(payment);
949
+ } catch (e) {
950
+ return err(mapMapperError(e, { provider: this.id, context: "verify response" }));
951
+ }
952
+ }
953
+ async fetch(id) {
954
+ const correlationId = this.idGenerator.generate();
955
+ this.logger.info("fetching payment", {
956
+ provider: "paystack",
957
+ paymentId: id,
958
+ correlationId
959
+ });
960
+ const result = await this.httpClient.send({
961
+ method: "GET",
962
+ url: `${this.baseUrl}/transaction/${encodeURIComponent(id)}`,
963
+ headers: this.authHeaders(),
964
+ timeoutMs: this.timeoutMs,
965
+ correlationId
966
+ });
967
+ if (!result.ok) return result;
968
+ try {
969
+ const response = JSON.parse(result.value.body);
970
+ const payment = mapPaystackResponseToPayment(response);
971
+ return ok(payment);
972
+ } catch (e) {
973
+ return err(mapMapperError(e, { provider: this.id, context: "fetch response" }));
974
+ }
975
+ }
976
+ async list(query = {}) {
977
+ const correlationId = this.idGenerator.generate();
978
+ const params = new URLSearchParams();
979
+ if (query.perPage) params.set("perPage", String(query.perPage));
980
+ if (query.page) params.set("page", String(query.page));
981
+ if (query.from) params.set("from", query.from.toISOString());
982
+ if (query.to) params.set("to", query.to.toISOString());
983
+ if (query.status) params.set("status", query.status);
984
+ if (query.customer) params.set("customer", query.customer);
985
+ const queryStr = params.toString();
986
+ const url = `${this.baseUrl}/transaction${queryStr ? `?${queryStr}` : ""}`;
987
+ this.logger.info("listing payments", {
988
+ provider: "paystack",
989
+ correlationId,
990
+ query: queryStr
991
+ });
992
+ const result = await this.httpClient.send({
993
+ method: "GET",
994
+ url,
995
+ headers: this.authHeaders(),
996
+ timeoutMs: this.timeoutMs,
997
+ correlationId
998
+ });
999
+ if (!result.ok) return result;
1000
+ try {
1001
+ const response = JSON.parse(result.value.body);
1002
+ const page = mapPaystackListResponse(response);
1003
+ return ok(page);
1004
+ } catch (e) {
1005
+ return err(mapMapperError(e, { provider: this.id, context: "list response" }));
1006
+ }
1007
+ }
1008
+ /**
1009
+ * Paystack has no `currency` on the refund object but accepts one on the
1010
+ * request, so the currency of the caller's `Money` is forwarded rather than
1011
+ * silently reinterpreted in the charge currency.
1012
+ */
1013
+ async refund(input) {
1014
+ const correlationId = input.correlationId ?? this.idGenerator.generate();
1015
+ const body = JSON.stringify({
1016
+ transaction: input.paymentId,
1017
+ amount: input.amount?.amount,
1018
+ currency: input.amount?.currency,
1019
+ merchant_note: input.reason
1020
+ });
1021
+ this.logger.info("refunding payment", {
1022
+ provider: "paystack",
1023
+ paymentId: input.paymentId,
1024
+ correlationId
1025
+ });
1026
+ const result = await this.httpClient.send({
1027
+ method: "POST",
1028
+ url: `${this.baseUrl}/refund`,
1029
+ headers: this.authHeaders(),
1030
+ body,
1031
+ timeoutMs: this.timeoutMs,
1032
+ correlationId,
1033
+ idempotencyKey: input.idempotencyKey
1034
+ });
1035
+ if (!result.ok) return result;
1036
+ try {
1037
+ const response = JSON.parse(result.value.body);
1038
+ const refund = mapPaystackRefundResponse(response, this.clock.now());
1039
+ return ok(refund);
1040
+ } catch (e) {
1041
+ return err(mapMapperError(e, { provider: this.id, context: "refund response" }));
1042
+ }
1043
+ }
1044
+ async parseWebhook(headers, rawBody, signature) {
1045
+ return parsePaystackWebhook(
1046
+ headers,
1047
+ rawBody,
1048
+ this.webhookSecret,
1049
+ this.clock.now(),
1050
+ signature
1051
+ );
1052
+ }
1053
+ async fetchRefund(refundId) {
1054
+ const correlationId = this.idGenerator.generate();
1055
+ this.logger.info("fetching refund", {
1056
+ provider: "paystack",
1057
+ refundId,
1058
+ correlationId
1059
+ });
1060
+ const result = await this.httpClient.send({
1061
+ method: "GET",
1062
+ url: `${this.baseUrl}/refund/${encodeURIComponent(refundId)}`,
1063
+ headers: this.authHeaders(),
1064
+ timeoutMs: this.timeoutMs,
1065
+ correlationId
1066
+ });
1067
+ if (!result.ok) return result;
1068
+ try {
1069
+ const response = JSON.parse(result.value.body);
1070
+ const refund = mapPaystackRefundResponse(response, this.clock.now());
1071
+ return ok(refund);
1072
+ } catch (e) {
1073
+ return err(mapMapperError(e, { provider: this.id, context: "fetch refund response" }));
1074
+ }
1075
+ }
1076
+ /**
1077
+ * `GET /bank` paginates by cursor and caps `perPage` at 100, so a single
1078
+ * request silently drops the rest of the list. Follow `meta.next` until the
1079
+ * provider stops offering one, with a defensive page ceiling.
1080
+ */
1081
+ async listBankCodes(input) {
1082
+ const correlationId = this.idGenerator.generate();
1083
+ this.logger.info("listing bank codes", {
1084
+ provider: this.id,
1085
+ currency: input.currency,
1086
+ correlationId
1087
+ });
1088
+ const banks = [];
1089
+ let cursor;
1090
+ let truncated = false;
1091
+ for (let page = 1; page <= MAX_BANK_PAGES; page++) {
1092
+ const params = new URLSearchParams({
1093
+ currency: input.currency,
1094
+ perPage: String(BANK_PAGE_SIZE),
1095
+ use_cursor: "true"
1096
+ });
1097
+ if (cursor) params.set("next", cursor);
1098
+ const result = await this.httpClient.send({
1099
+ method: "GET",
1100
+ url: `${this.baseUrl}/bank?${params.toString()}`,
1101
+ headers: this.authHeaders(),
1102
+ timeoutMs: this.timeoutMs,
1103
+ correlationId
1104
+ });
1105
+ if (!result.ok) return result;
1106
+ let next;
1107
+ try {
1108
+ const response = JSON.parse(result.value.body);
1109
+ banks.push(...mapPaystackBankListResponse(response));
1110
+ next = response.meta?.next ?? void 0;
1111
+ } catch (e) {
1112
+ return err(mapMapperError(e, { provider: this.id, context: "bank list response" }));
1113
+ }
1114
+ if (!next) break;
1115
+ cursor = next;
1116
+ if (page === MAX_BANK_PAGES) truncated = true;
1117
+ }
1118
+ if (truncated) {
1119
+ this.logger.warn("bank list truncated", {
1120
+ provider: this.id,
1121
+ currency: input.currency,
1122
+ pages: MAX_BANK_PAGES,
1123
+ correlationId
1124
+ });
1125
+ }
1126
+ return ok(Object.freeze(banks));
1127
+ }
1128
+ async resolveAccount(input) {
1129
+ const correlationId = this.idGenerator.generate();
1130
+ const params = new URLSearchParams({
1131
+ account_number: input.accountNumber,
1132
+ bank_code: input.bankCode
1133
+ });
1134
+ this.logger.info("resolving account", {
1135
+ provider: this.id,
1136
+ bankCode: input.bankCode,
1137
+ correlationId
1138
+ });
1139
+ const result = await this.httpClient.send({
1140
+ method: "GET",
1141
+ url: `${this.baseUrl}/bank/resolve?${params.toString()}`,
1142
+ headers: this.authHeaders(),
1143
+ timeoutMs: this.timeoutMs,
1144
+ correlationId
1145
+ });
1146
+ if (!result.ok) return result;
1147
+ try {
1148
+ const response = JSON.parse(result.value.body);
1149
+ if (!response.status) {
1150
+ return err(new ProviderError(response.message, {
1151
+ provider: this.id,
1152
+ httpStatus: 422,
1153
+ isRetryable: false
1154
+ }));
1155
+ }
1156
+ return ok({
1157
+ accountName: response.data.account_name,
1158
+ accountNumber: response.data.account_number,
1159
+ bankId: response.data.bank_id
1160
+ });
1161
+ } catch (e) {
1162
+ return err(mapMapperError(e, { provider: this.id, context: "resolve account response" }));
1163
+ }
1164
+ }
1165
+ async createRecipient(input) {
1166
+ const correlationId = this.idGenerator.generate();
1167
+ const type = resolveRecipientType(input);
1168
+ const body = {
1169
+ type,
1170
+ name: input.name,
1171
+ account_number: input.accountNumber,
1172
+ bank_code: input.bankCode,
1173
+ currency: input.currency,
1174
+ metadata: input.metadata ? input.metadata : void 0
1175
+ };
1176
+ this.logger.info("creating transfer recipient", {
1177
+ provider: this.id,
1178
+ bankCode: input.bankCode,
1179
+ type,
1180
+ correlationId
1181
+ });
1182
+ const result = await this.httpClient.send({
1183
+ method: "POST",
1184
+ url: `${this.baseUrl}/transferrecipient`,
1185
+ headers: this.authHeaders(),
1186
+ body: JSON.stringify(body),
1187
+ timeoutMs: this.timeoutMs,
1188
+ correlationId
1189
+ });
1190
+ if (!result.ok) return result;
1191
+ try {
1192
+ const response = JSON.parse(result.value.body);
1193
+ const recipient = mapPaystackCreateRecipientResponse(response, this.clock.now());
1194
+ return ok(recipient);
1195
+ } catch (e) {
1196
+ return err(mapMapperError(e, { provider: this.id, context: "create recipient response" }));
1197
+ }
1198
+ }
1199
+ async initiateTransfer(input) {
1200
+ if (input.quoteId) {
1201
+ return err(
1202
+ new UnsupportedProviderError(
1203
+ "Paystack payouts are always in the transfer currency; quoteId is only supported by providers with cross-currency payouts (Bachs)",
1204
+ { provider: this.id }
1205
+ )
1206
+ );
1207
+ }
1208
+ const amount = input.amount;
1209
+ if (!amount) {
1210
+ throw new ValidationError(
1211
+ "Paystack payouts require an amount: pass amount, or a quoteId for a provider that supports cross-currency payouts"
1212
+ );
1213
+ }
1214
+ if (input.currency !== amount.currency) {
1215
+ throw new ValidationError(
1216
+ `Transfer currency ${input.currency} does not match amount currency ${amount.currency}`
1217
+ );
1218
+ }
1219
+ assertTransferReference(input.reference);
1220
+ const correlationId = input.correlationId ?? this.idGenerator.generate();
1221
+ const body = {
1222
+ source: "balance",
1223
+ amount: amount.amount,
1224
+ recipient: input.recipientCode,
1225
+ reference: input.reference,
1226
+ reason: input.reason,
1227
+ currency: input.currency,
1228
+ account_reference: input.accountReference
1229
+ };
1230
+ this.logger.info("initiating transfer", {
1231
+ provider: this.id,
1232
+ reference: input.reference,
1233
+ correlationId
1234
+ });
1235
+ const result = await this.httpClient.send({
1236
+ method: "POST",
1237
+ url: `${this.baseUrl}/transfer`,
1238
+ headers: this.authHeaders(),
1239
+ body: JSON.stringify(body),
1240
+ timeoutMs: this.timeoutMs,
1241
+ correlationId,
1242
+ idempotencyKey: input.idempotencyKey
1243
+ });
1244
+ if (!result.ok) return result;
1245
+ try {
1246
+ const response = JSON.parse(result.value.body);
1247
+ const now = this.clock.now();
1248
+ const recipient = await this.lookupRecipient(input.recipientCode, now);
1249
+ if (!recipient) {
1250
+ this.logger.warn("transfer recipient could not be resolved; returning a code-only stub", {
1251
+ provider: this.id,
1252
+ recipientCode: input.recipientCode,
1253
+ correlationId
1254
+ });
1255
+ }
1256
+ const transfer = mapPaystackTransferResponse(response, now, recipient);
1257
+ return ok(transfer);
1258
+ } catch (e) {
1259
+ return err(mapMapperError(e, { provider: this.id, context: "initiate transfer response" }));
1260
+ }
1261
+ }
1262
+ async fetchTransfer(id) {
1263
+ const correlationId = this.idGenerator.generate();
1264
+ this.logger.info("fetching transfer", {
1265
+ provider: this.id,
1266
+ transferId: id,
1267
+ correlationId
1268
+ });
1269
+ const result = await this.httpClient.send({
1270
+ method: "GET",
1271
+ url: `${this.baseUrl}/transfer/${encodeURIComponent(id)}`,
1272
+ headers: this.authHeaders(),
1273
+ timeoutMs: this.timeoutMs,
1274
+ correlationId
1275
+ });
1276
+ if (!result.ok) return result;
1277
+ try {
1278
+ const response = JSON.parse(result.value.body);
1279
+ return ok(mapPaystackTransferResponse(response, this.clock.now()));
1280
+ } catch (e) {
1281
+ return err(mapMapperError(e, { provider: this.id, context: "fetch transfer response" }));
1282
+ }
1283
+ }
1284
+ async listTransfers(query = {}) {
1285
+ const correlationId = this.idGenerator.generate();
1286
+ const params = new URLSearchParams();
1287
+ if (query.perPage) params.set("perPage", String(query.perPage));
1288
+ if (query.page) params.set("page", String(query.page));
1289
+ if (query.from) params.set("from", query.from.toISOString());
1290
+ if (query.to) params.set("to", query.to.toISOString());
1291
+ const queryStr = params.toString();
1292
+ const url = `${this.baseUrl}/transfer${queryStr ? `?${queryStr}` : ""}`;
1293
+ this.logger.info("listing transfers", {
1294
+ provider: this.id,
1295
+ correlationId,
1296
+ query: queryStr
1297
+ });
1298
+ const result = await this.httpClient.send({
1299
+ method: "GET",
1300
+ url,
1301
+ headers: this.authHeaders(),
1302
+ timeoutMs: this.timeoutMs,
1303
+ correlationId
1304
+ });
1305
+ if (!result.ok) return result;
1306
+ try {
1307
+ const response = JSON.parse(result.value.body);
1308
+ return ok(mapPaystackTransferListResponse(response, this.clock.now()));
1309
+ } catch (e) {
1310
+ return err(mapMapperError(e, { provider: this.id, context: "list transfers response" }));
1311
+ }
1312
+ }
1313
+ async health() {
1314
+ const start = Date.now();
1315
+ try {
1316
+ const result = await this.httpClient.send({
1317
+ method: "GET",
1318
+ url: `${this.baseUrl}/transaction`,
1319
+ headers: this.authHeaders(),
1320
+ timeoutMs: 5e3
1321
+ });
1322
+ if (!result.ok) {
1323
+ this.logger.warn("health check failed", {
1324
+ provider: this.id,
1325
+ code: result.error.code,
1326
+ httpStatus: result.error.httpStatus,
1327
+ message: result.error.message
1328
+ });
1329
+ }
1330
+ return {
1331
+ healthy: result.ok,
1332
+ latencyMs: Date.now() - start,
1333
+ timestamp: this.clock.now()
1334
+ };
1335
+ } catch (error) {
1336
+ this.logger.warn("health check threw", {
1337
+ provider: this.id,
1338
+ message: error instanceof Error ? error.message : String(error)
1339
+ });
1340
+ return {
1341
+ healthy: false,
1342
+ latencyMs: Date.now() - start,
1343
+ timestamp: this.clock.now()
1344
+ };
1345
+ }
1346
+ }
1347
+ /** Best-effort recipient lookup; a failure must never fail the transfer. */
1348
+ async lookupRecipient(code, now) {
1349
+ const result = await this.httpClient.send({
1350
+ method: "GET",
1351
+ url: `${this.baseUrl}/transferrecipient/${encodeURIComponent(code)}`,
1352
+ headers: this.authHeaders(),
1353
+ timeoutMs: this.timeoutMs
1354
+ });
1355
+ if (!result.ok) return void 0;
1356
+ try {
1357
+ const response = JSON.parse(result.value.body);
1358
+ if (!response.status) return void 0;
1359
+ return mapPaystackRecipient(response.data, now);
1360
+ } catch {
1361
+ return void 0;
1362
+ }
1363
+ }
1364
+ authHeaders() {
1365
+ return {
1366
+ Authorization: `Bearer ${this.secretKey}`
1367
+ };
1368
+ }
1369
+ };
1370
+ function getEmail(cr) {
1371
+ switch (cr.kind) {
1372
+ case "inline":
1373
+ return cr.customer.email;
1374
+ case "new":
1375
+ return cr.email;
1376
+ case "existing":
1377
+ return "";
1378
+ }
1379
+ }
1380
+ function resolveRecipientType(input) {
1381
+ if (input.type === "mobile_money") return "mobile_money";
1382
+ const type = PAYSTACK_BANK_TYPES_BY_CURRENCY[input.currency];
1383
+ if (!type) {
1384
+ throw new ValidationError(
1385
+ `Paystack has no bank recipient type for ${input.currency}; pass type: "mobile_money" for a wallet destination, or use one of ${Object.keys(PAYSTACK_BANK_TYPES_BY_CURRENCY).join(", ")}`
1386
+ );
1387
+ }
1388
+ return type;
1389
+ }
1390
+ function assertTransferReference(reference) {
1391
+ if (!PAYSTACK_TRANSFER_REFERENCE_RE.test(reference)) {
1392
+ throw new ValidationError(
1393
+ 'Paystack transfer references must be 16-50 characters of lowercase letters, digits, "-" or "_" (for example "payout_2026_10_17_0012")'
1394
+ );
1395
+ }
1396
+ }
1397
+
1398
+ // src/infrastructure/providers/paystack/register.ts
1399
+ var PAYSTACK_ID = "paystack";
1400
+ registerProvider(PAYSTACK_ID, (config, deps) => new PaystackAdapter(config, deps));
1401
+
1402
+ // src/infrastructure/providers/bachs/bachs-connection.ts
1403
+ var BACHS_LIVE_BASE_URL = "https://api.bachs.io";
1404
+ var BACHS_SANDBOX_BASE_URL = "https://sandbox-api.bachs.io";
1405
+ var DEFAULT_TIMEOUT_MS = 3e4;
1406
+ function createBachsConnection(config) {
1407
+ const baseUrl = config.baseUrl ?? (config.secretKey.startsWith("sk_sandbox_") ? BACHS_SANDBOX_BASE_URL : BACHS_LIVE_BASE_URL);
1408
+ return {
1409
+ baseUrl,
1410
+ secretKey: config.secretKey,
1411
+ webhookSecret: config.webhookSecret ?? "",
1412
+ webhookToleranceSeconds: readTolerance(config.options),
1413
+ timeoutMs: config.timeoutMs ?? DEFAULT_TIMEOUT_MS,
1414
+ environment: baseUrl === BACHS_SANDBOX_BASE_URL ? "sandbox" : "live"
1415
+ };
1416
+ }
1417
+ function readTolerance(options) {
1418
+ const value = options?.["webhookToleranceSeconds"];
1419
+ return typeof value === "number" ? value : void 0;
1420
+ }
1421
+
1422
+ // src/infrastructure/providers/bachs/bachs-pagination.ts
1423
+ var DEFAULT_PAGE_SIZE = 50;
1424
+ var MAX_PAGE_SIZE = 100;
1425
+ function resolveBachsPagination(query) {
1426
+ const requested = query.perPage ?? DEFAULT_PAGE_SIZE;
1427
+ const limit = Math.min(
1428
+ Math.max(Number.isFinite(requested) ? Math.trunc(requested) : DEFAULT_PAGE_SIZE, 1),
1429
+ MAX_PAGE_SIZE
1430
+ );
1431
+ const offset = query.cursor ? 0 : Math.max((query.page ?? 1) - 1, 0) * limit;
1432
+ return { limit, offset, clamped: limit !== requested };
1433
+ }
1434
+
1435
+ // src/domain/product/recurring-cadence.ts
1436
+ var INTERVALS = /* @__PURE__ */ new Set(["day", "week", "month", "year"]);
1437
+ function RecurringCadence(input) {
1438
+ if (!INTERVALS.has(input.interval)) {
1439
+ throw new ValidationError(
1440
+ `Invalid billing interval "${input.interval}": must be day, week, month, or year`
1441
+ );
1442
+ }
1443
+ if (!Number.isInteger(input.frequency) || input.frequency < 1) {
1444
+ throw new ValidationError(
1445
+ `Invalid billing frequency "${input.frequency}": must be a positive integer`
1446
+ );
1447
+ }
1448
+ return { interval: input.interval, frequency: input.frequency };
1449
+ }
1450
+
1451
+ // src/infrastructure/providers/bachs/bachs-money.ts
1452
+ var ZERO_DECIMAL_CURRENCIES = /* @__PURE__ */ new Set([]);
1453
+ var THREE_DECIMAL_CURRENCIES = /* @__PURE__ */ new Set([
1454
+ "BHD",
1455
+ "IQD",
1456
+ "JOD",
1457
+ "KWD",
1458
+ "LYD",
1459
+ "OMR",
1460
+ "TND"
1461
+ ]);
1462
+ var DECIMAL_RE = /^(\d+)(?:\.(\d+))?$/;
1463
+ function currencyExponent(currency) {
1464
+ if (THREE_DECIMAL_CURRENCIES.has(currency)) {
1465
+ throw new ValidationError(
1466
+ `Bachs amounts are two-decimal; ${currency} needs three decimal places and cannot be represented`
1467
+ );
1468
+ }
1469
+ return ZERO_DECIMAL_CURRENCIES.has(currency) ? 0 : 2;
1470
+ }
1471
+ function toBachsAmount(money) {
1472
+ const exponent = currencyExponent(money.currency);
1473
+ const minor = String(money.amount);
1474
+ if (exponent === 0) return minor;
1475
+ const padded = minor.padStart(exponent + 1, "0");
1476
+ return `${padded.slice(0, -exponent)}.${padded.slice(-exponent)}`;
1477
+ }
1478
+ function fromBachsAmount(value, currency) {
1479
+ const match = DECIMAL_RE.exec(value);
1480
+ if (!match) {
1481
+ throw new ValidationError(`Invalid amount from Bachs: "${value}"`);
1482
+ }
1483
+ const exponent = currencyExponent(currency);
1484
+ const whole = match[1] ?? "0";
1485
+ const fraction = match[2] ?? "";
1486
+ const significantFraction = fraction.slice(0, exponent);
1487
+ const surplus = fraction.slice(exponent);
1488
+ if (surplus.length > 0 && !/^0+$/.test(surplus)) {
1489
+ throw new ValidationError(
1490
+ `Amount "${value}" carries more precision than ${currency} allows`
1491
+ );
1492
+ }
1493
+ const fractionPadded = significantFraction.padEnd(exponent, "0");
1494
+ const scaled = BigInt(whole) * 10n ** BigInt(exponent) + (fractionPadded.length > 0 ? BigInt(fractionPadded) : 0n);
1495
+ if (scaled > BigInt(Number.MAX_SAFE_INTEGER)) {
1496
+ throw new ValidationError(`Amount "${value}" exceeds the maximum supported value`);
1497
+ }
1498
+ return Money({ amount: Number(scaled), currency });
1499
+ }
1500
+
1501
+ // src/infrastructure/providers/bachs/bachs-primitives.ts
1502
+ function toBachsDate(value) {
1503
+ if (!value) return void 0;
1504
+ const parsed = new Date(value);
1505
+ return Number.isNaN(parsed.getTime()) ? void 0 : parsed;
1506
+ }
1507
+ function emptyMetadata3() {
1508
+ return Object.freeze({});
1509
+ }
1510
+ function mapBachsMetadata(raw) {
1511
+ if (!raw || typeof raw !== "object") return emptyMetadata3();
1512
+ const mapped = {};
1513
+ for (const [key, value] of Object.entries(raw)) {
1514
+ if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
1515
+ mapped[key] = value;
1516
+ }
1517
+ }
1518
+ return Object.freeze(mapped);
1519
+ }
1520
+
1521
+ // src/infrastructure/providers/bachs/bachs-subscription-mapper.ts
1522
+ var BACHS = Provider("bachs");
1523
+ var EPOCH = /* @__PURE__ */ new Date(0);
1524
+ function mapBachsPrice(price) {
1525
+ const currency = price.currency;
1526
+ return {
1527
+ priceType: price.price_type ?? "fixed",
1528
+ currency,
1529
+ amount: price.amount ? fromBachsAmount(price.amount, currency) : void 0,
1530
+ presetAmount: price.preset_amount ? fromBachsAmount(price.preset_amount, currency) : void 0,
1531
+ minimumAmount: price.minimum_amount ? fromBachsAmount(price.minimum_amount, currency) : void 0,
1532
+ maximumAmount: price.maximum_amount ? fromBachsAmount(price.maximum_amount, currency) : void 0,
1533
+ currencyOptions: (price.currency_options ?? []).map(mapBachsCurrencyOption)
1534
+ };
1535
+ }
1536
+ function mapBachsCurrencyOption(option) {
1537
+ const currency = option.currency;
1538
+ return {
1539
+ currency,
1540
+ amount: option.amount ? fromBachsAmount(option.amount, currency) : void 0,
1541
+ minimumAmount: option.minimum_amount ? fromBachsAmount(option.minimum_amount, currency) : void 0,
1542
+ maximumAmount: option.maximum_amount ? fromBachsAmount(option.maximum_amount, currency) : void 0
1543
+ };
1544
+ }
1545
+ function mapBachsProduct(product) {
1546
+ return {
1547
+ id: product.id,
1548
+ providerId: BACHS,
1549
+ name: product.name,
1550
+ description: product.description ?? void 0,
1551
+ price: mapBachsPrice(product.price),
1552
+ // An unrecognised status must never look sellable, so it maps to archived.
1553
+ status: product.status === "archived" ? "archived" : product.status === "active" ? "active" : "archived",
1554
+ billingCycle: product.billing_cycle ? RecurringCadence(product.billing_cycle) : void 0,
1555
+ trialPeriod: product.trial_period ? RecurringCadence(product.trial_period) : void 0,
1556
+ metadata: mapBachsMetadata(product.metadata),
1557
+ createdAt: toBachsDate(product.created_at) ?? EPOCH,
1558
+ updatedAt: toBachsDate(product.updated_at) ?? toBachsDate(product.created_at) ?? EPOCH,
1559
+ archivedAt: toBachsDate(product.archived_at)
1560
+ };
1561
+ }
1562
+ function mapBachsProductListResponse(response) {
1563
+ const pagination = response.pagination;
1564
+ const limit = pagination.limit ?? response.items.length;
1565
+ const offset = pagination.offset ?? 0;
1566
+ return {
1567
+ items: response.items.map(mapBachsProduct),
1568
+ total: pagination.total ?? response.items.length,
1569
+ page: limit > 0 ? Math.floor(offset / limit) + 1 : 1,
1570
+ perPage: limit,
1571
+ nextCursor: pagination.next_cursor ?? null
1572
+ };
1573
+ }
1574
+ function mapBachsSubscriptionCustomer(customer) {
1575
+ return {
1576
+ id: customer.customer_id,
1577
+ email: customer.email,
1578
+ phone: customer.phone_number ?? void 0,
1579
+ name: customer.name ?? void 0,
1580
+ metadata: mapBachsMetadata(customer.metadata)
1581
+ };
1582
+ }
1583
+ function mapBachsSubscriptionStatus(status, trialEnd, canceledAt, fallback) {
1584
+ switch (status) {
1585
+ case "trialing":
1586
+ return { kind: "trialing", trialEnd: trialEnd ?? fallback };
1587
+ case "active":
1588
+ return { kind: "active" };
1589
+ case "past_due":
1590
+ return { kind: "pastDue" };
1591
+ case "unpaid":
1592
+ return { kind: "unpaid" };
1593
+ case "canceled":
1594
+ return { kind: "canceled", canceledAt: canceledAt ?? fallback };
1595
+ case "paused":
1596
+ return { kind: "paused" };
1597
+ default:
1598
+ return { kind: "paused" };
1599
+ }
1600
+ }
1601
+ function mapBachsSubscription(subscription) {
1602
+ const createdAt = toBachsDate(subscription.created_at) ?? EPOCH;
1603
+ const trialEnd = toBachsDate(subscription.trial_end);
1604
+ const canceledAt = toBachsDate(subscription.canceled_at);
1605
+ const periodStart = toBachsDate(subscription.current_period_start) ?? createdAt;
1606
+ return {
1607
+ id: subscription.id,
1608
+ providerId: BACHS,
1609
+ customer: mapBachsSubscriptionCustomer(subscription.customer),
1610
+ productId: subscription.product?.id,
1611
+ productName: subscription.product?.name,
1612
+ status: mapBachsSubscriptionStatus(subscription.status, trialEnd, canceledAt, createdAt),
1613
+ amount: fromBachsAmount(subscription.amount, subscription.currency),
1614
+ billingCycle: RecurringCadence(subscription.billing_cycle),
1615
+ quantity: subscription.quantity ?? 1,
1616
+ currentPeriodStart: periodStart,
1617
+ currentPeriodEnd: toBachsDate(subscription.current_period_end) ?? periodStart,
1618
+ nextBilledAt: toBachsDate(subscription.next_billed_at),
1619
+ cancelAtPeriodEnd: subscription.cancel_at_period_end ?? false,
1620
+ canceledAt,
1621
+ createdAt,
1622
+ metadata: mapBachsMetadata(subscription.metadata)
1623
+ };
1624
+ }
1625
+ function mapBachsSubscriptionListResponse(response) {
1626
+ const pagination = response.pagination;
1627
+ const limit = pagination.limit ?? response.items.length;
1628
+ const offset = pagination.offset ?? 0;
1629
+ return {
1630
+ items: response.items.map(mapBachsSubscription),
1631
+ total: pagination.total ?? response.items.length,
1632
+ page: limit > 0 ? Math.floor(offset / limit) + 1 : 1,
1633
+ perPage: limit,
1634
+ nextCursor: pagination.next_cursor ?? null
1635
+ };
1636
+ }
1637
+ function mapBachsCustomer(customer) {
1638
+ return {
1639
+ id: customer.customer_id,
1640
+ email: customer.email,
1641
+ phone: "phone_number" in customer ? customer.phone_number ?? void 0 : void 0,
1642
+ name: customer.name ?? void 0,
1643
+ metadata: mapBachsMetadata(customer.metadata)
1644
+ };
1645
+ }
1646
+ function mapBachsCustomerListResponse(response) {
1647
+ const pagination = response.pagination;
1648
+ const limit = pagination.limit ?? response.items.length;
1649
+ const offset = pagination.offset ?? 0;
1650
+ return {
1651
+ items: response.items.map(mapBachsCustomer),
1652
+ total: pagination.total ?? response.items.length,
1653
+ page: limit > 0 ? Math.floor(offset / limit) + 1 : 1,
1654
+ perPage: limit,
1655
+ nextCursor: pagination.next_cursor ?? null
1656
+ };
1657
+ }
1658
+ function mapBachsPortalSession(session) {
1659
+ return { id: session.id, url: session.url };
1660
+ }
1661
+ function buildCurrencyOptionInput(option) {
1662
+ return {
1663
+ currency: option.currency,
1664
+ amount: option.amount ? toBachsAmount(option.amount) : void 0,
1665
+ minimum_amount: option.minimumAmount ? toBachsAmount(option.minimumAmount) : void 0,
1666
+ maximum_amount: option.maximumAmount ? toBachsAmount(option.maximumAmount) : void 0
1667
+ };
1668
+ }
1669
+ function buildPriceInput(price) {
1670
+ return {
1671
+ currency: price.currency,
1672
+ price_type: price.priceType,
1673
+ amount: price.amount ? toBachsAmount(price.amount) : void 0,
1674
+ preset_amount: price.presetAmount ? toBachsAmount(price.presetAmount) : void 0,
1675
+ minimum_amount: price.minimumAmount ? toBachsAmount(price.minimumAmount) : void 0,
1676
+ maximum_amount: price.maximumAmount ? toBachsAmount(price.maximumAmount) : void 0,
1677
+ currency_options: price.currencyOptions?.map(buildCurrencyOptionInput)
1678
+ };
1679
+ }
1680
+ function buildBachsCreateProduct(input) {
1681
+ return {
1682
+ name: input.name,
1683
+ description: input.description,
1684
+ price: buildPriceInput(input.price),
1685
+ billing_cycle: input.billingCycle,
1686
+ trial_period: input.trialPeriod,
1687
+ metadata: input.metadata ? { ...input.metadata } : void 0
1688
+ };
1689
+ }
1690
+ function buildBachsUpdateProduct(input) {
1691
+ const price = input.amount !== void 0 || input.currencyOptions !== void 0 ? {
1692
+ amount: input.amount ? toBachsAmount(input.amount) : void 0,
1693
+ currency_options: input.currencyOptions?.map(buildCurrencyOptionInput)
1694
+ } : void 0;
1695
+ return {
1696
+ name: input.name,
1697
+ description: input.description,
1698
+ price,
1699
+ trial_period: input.trialPeriod,
1700
+ metadata: input.metadata ? { ...input.metadata } : void 0
1701
+ };
1702
+ }
1703
+ function buildBachsUpdateSubscription(input) {
1704
+ return {
1705
+ product_id: input.productId,
1706
+ trial_end: input.trialEnd?.toISOString(),
1707
+ payment_method_id: input.paymentMethodId,
1708
+ metadata: input.metadata ? { ...input.metadata } : void 0,
1709
+ proration_behavior: input.prorationBehavior
1710
+ };
1711
+ }
1712
+ function buildBachsCancelSubscription(input) {
1713
+ if (input.atPeriodEnd === void 0 && input.reason === void 0) return void 0;
1714
+ return { cancel_at_period_end: input.atPeriodEnd, reason: input.reason };
1715
+ }
1716
+ function buildBachsCreateCustomer(input) {
1717
+ return {
1718
+ email: input.email,
1719
+ name: input.name,
1720
+ phone_number: input.phone,
1721
+ metadata: input.metadata ? { ...input.metadata } : void 0
1722
+ };
1723
+ }
1724
+ function buildBachsUpdateCustomer(input) {
1725
+ return {
1726
+ email: input.email,
1727
+ name: input.name,
1728
+ phone_number: input.phone,
1729
+ metadata: input.metadata ? { ...input.metadata } : void 0
1730
+ };
1731
+ }
1732
+
1733
+ // src/infrastructure/providers/bachs/bachs-subscription-client.ts
1734
+ var BachsSubscriptionClient = class {
1735
+ httpClient;
1736
+ logger;
1737
+ idGenerator;
1738
+ connection;
1739
+ constructor(connection, deps) {
1740
+ this.connection = connection;
1741
+ this.httpClient = deps.httpClient;
1742
+ this.logger = deps.logger;
1743
+ this.idGenerator = deps.idGenerator;
1744
+ }
1745
+ async listProducts(query) {
1746
+ const { limit } = resolveBachsPagination({ perPage: query.limit, cursor: query.cursor });
1747
+ const params = new URLSearchParams({ limit: String(limit) });
1748
+ if (query.cursor) params.set("cursor", query.cursor);
1749
+ if (query.includeArchived) params.set("include_archived", "true");
1750
+ this.logger.info("listing products", { provider: "bachs", query: params.toString() });
1751
+ const response = await this.request(
1752
+ "GET",
1753
+ `/v1/products?${params.toString()}`,
1754
+ "list products response"
1755
+ );
1756
+ return response.ok ? this.mapped(response.value, mapBachsProductListResponse, "list products response") : response;
1757
+ }
1758
+ async fetchProduct(id) {
1759
+ this.logger.info("fetching product", { provider: "bachs", productId: id });
1760
+ const response = await this.request(
1761
+ "GET",
1762
+ `/v1/products/${encodeURIComponent(id)}`,
1763
+ "fetch product response"
1764
+ );
1765
+ return response.ok ? this.mapped(response.value, mapBachsProduct, "product response") : response;
1766
+ }
1767
+ async createProduct(input) {
1768
+ this.logger.info("creating product", { provider: "bachs", recurring: input.billingCycle !== void 0 });
1769
+ const response = await this.request(
1770
+ "POST",
1771
+ "/v1/products",
1772
+ "create product response",
1773
+ buildBachsCreateProduct(input)
1774
+ );
1775
+ return response.ok ? this.mapped(response.value, mapBachsProduct, "product response") : response;
1776
+ }
1777
+ async updateProduct(id, input) {
1778
+ this.logger.info("updating product", { provider: "bachs", productId: id });
1779
+ const response = await this.request(
1780
+ "PATCH",
1781
+ `/v1/products/${encodeURIComponent(id)}`,
1782
+ "update product response",
1783
+ buildBachsUpdateProduct(input)
1784
+ );
1785
+ return response.ok ? this.mapped(response.value, mapBachsProduct, "product response") : response;
1786
+ }
1787
+ async archiveProduct(id) {
1788
+ this.logger.info("archiving product", { provider: "bachs", productId: id });
1789
+ const response = await this.request(
1790
+ "POST",
1791
+ `/v1/products/${encodeURIComponent(id)}/archive`,
1792
+ "archive product response"
1793
+ );
1794
+ return response.ok ? this.mapped(response.value, mapBachsProduct, "product response") : response;
1795
+ }
1796
+ async unarchiveProduct(id) {
1797
+ this.logger.info("unarchiving product", { provider: "bachs", productId: id });
1798
+ const response = await this.request(
1799
+ "POST",
1800
+ `/v1/products/${encodeURIComponent(id)}/unarchive`,
1801
+ "unarchive product response"
1802
+ );
1803
+ return response.ok ? this.mapped(response.value, mapBachsProduct, "product response") : response;
1804
+ }
1805
+ async listSubscriptions(query) {
1806
+ const { limit, offset } = resolveBachsPagination({ page: query.page, perPage: query.limit });
1807
+ const params = new URLSearchParams({
1808
+ limit: String(limit),
1809
+ offset: String(offset)
1810
+ });
1811
+ if (query.customerId) params.set("customer_id", query.customerId);
1812
+ if (query.status) params.set("status", query.status);
1813
+ this.logger.info("listing subscriptions", { provider: "bachs", query: params.toString() });
1814
+ const response = await this.request(
1815
+ "GET",
1816
+ `/v1/subscriptions?${params.toString()}`,
1817
+ "list subscriptions response"
1818
+ );
1819
+ return response.ok ? this.mapped(response.value, mapBachsSubscriptionListResponse, "list subscriptions response") : response;
1820
+ }
1821
+ async fetchSubscription(id) {
1822
+ this.logger.info("fetching subscription", { provider: "bachs", subscriptionId: id });
1823
+ const response = await this.request(
1824
+ "GET",
1825
+ `/v1/subscriptions/${encodeURIComponent(id)}`,
1826
+ "fetch subscription response"
1827
+ );
1828
+ return response.ok ? this.mapped(response.value, mapBachsSubscription, "subscription response") : response;
1829
+ }
1830
+ async updateSubscription(id, input) {
1831
+ this.logger.info("updating subscription", { provider: "bachs", subscriptionId: id });
1832
+ const response = await this.request(
1833
+ "PATCH",
1834
+ `/v1/subscriptions/${encodeURIComponent(id)}`,
1835
+ "update subscription response",
1836
+ buildBachsUpdateSubscription(input)
1837
+ );
1838
+ return response.ok ? this.mapped(response.value, mapBachsSubscription, "subscription response") : response;
1839
+ }
1840
+ async cancelSubscription(id, input) {
1841
+ this.logger.info("canceling subscription", {
1842
+ provider: "bachs",
1843
+ subscriptionId: id,
1844
+ atPeriodEnd: input.atPeriodEnd ?? false
1845
+ });
1846
+ const response = await this.request(
1847
+ "DELETE",
1848
+ `/v1/subscriptions/${encodeURIComponent(id)}`,
1849
+ "cancel subscription response",
1850
+ buildBachsCancelSubscription(input)
1851
+ );
1852
+ return response.ok ? this.mapped(response.value, mapBachsSubscription, "subscription response") : response;
1853
+ }
1854
+ async listCustomers(query) {
1855
+ const { limit, offset } = resolveBachsPagination({ page: query.page, perPage: query.limit });
1856
+ const params = new URLSearchParams({
1857
+ limit: String(limit),
1858
+ offset: String(offset)
1859
+ });
1860
+ if (query.search) params.set("search", query.search);
1861
+ this.logger.info("listing customers", { provider: "bachs", query: params.toString() });
1862
+ const response = await this.request(
1863
+ "GET",
1864
+ `/v1/customers?${params.toString()}`,
1865
+ "list customers response"
1866
+ );
1867
+ return response.ok ? this.mapped(response.value, mapBachsCustomerListResponse, "list customers response") : response;
1868
+ }
1869
+ async fetchCustomer(id) {
1870
+ this.logger.info("fetching customer", { provider: "bachs", customerId: id });
1871
+ const response = await this.request(
1872
+ "GET",
1873
+ `/v1/customers/${encodeURIComponent(id)}`,
1874
+ "fetch customer response"
1875
+ );
1876
+ return response.ok ? this.mapped(response.value, mapBachsCustomer, "customer response") : response;
1877
+ }
1878
+ async createCustomer(input) {
1879
+ this.logger.info("creating customer", { provider: "bachs" });
1880
+ const response = await this.request(
1881
+ "POST",
1882
+ "/v1/customers",
1883
+ "create customer response",
1884
+ buildBachsCreateCustomer(input)
1885
+ );
1886
+ return response.ok ? this.mapped(response.value, mapBachsCustomer, "customer response") : response;
1887
+ }
1888
+ async updateCustomer(id, input) {
1889
+ this.logger.info("updating customer", { provider: "bachs", customerId: id });
1890
+ const response = await this.request(
1891
+ "PATCH",
1892
+ `/v1/customers/${encodeURIComponent(id)}`,
1893
+ "update customer response",
1894
+ buildBachsUpdateCustomer(input)
1895
+ );
1896
+ return response.ok ? this.mapped(response.value, mapBachsCustomer, "customer response") : response;
1897
+ }
1898
+ async createPortalSession(customerId) {
1899
+ this.logger.info("creating customer portal session", { provider: "bachs", customerId });
1900
+ const response = await this.request(
1901
+ "POST",
1902
+ `/v1/customers/${encodeURIComponent(customerId)}/portal-sessions`,
1903
+ "create portal session response"
1904
+ );
1905
+ return response.ok ? this.mapped(response.value, mapBachsPortalSession, "create portal session response") : response;
1906
+ }
1907
+ mapped(value, mapper, context) {
1908
+ try {
1909
+ return ok(mapper(value));
1910
+ } catch (e) {
1911
+ return err(mapMapperError(e, { provider: "bachs", context }));
1912
+ }
1913
+ }
1914
+ async request(method, path, context, body) {
1915
+ const correlationId = this.idGenerator.generate();
1916
+ const result = await this.httpClient.send({
1917
+ method,
1918
+ url: `${this.connection.baseUrl}${path}`,
1919
+ headers: { Authorization: `Bearer ${this.connection.secretKey}` },
1920
+ body: body !== void 0 ? JSON.stringify(body) : void 0,
1921
+ timeoutMs: this.connection.timeoutMs,
1922
+ correlationId
1923
+ });
1924
+ if (!result.ok) return result;
1925
+ try {
1926
+ return ok(JSON.parse(result.value.body));
1927
+ } catch (e) {
1928
+ return err(mapMapperError(e, { provider: "bachs", context }));
1929
+ }
1930
+ }
1931
+ };
1932
+
1933
+ // src/infrastructure/providers/bachs/bachs-mapper.ts
1934
+ var BACHS2 = Provider("bachs");
1935
+ function mapBachsPaymentStatus(status, context) {
1936
+ switch (status) {
1937
+ case "created":
1938
+ return { kind: "initialized" };
1939
+ case "processing":
1940
+ case "underpaid":
1941
+ return { kind: "pending" };
1942
+ case "succeeded":
1943
+ case "accepted":
1944
+ case "overpaid":
1945
+ return { kind: "success", paidAt: context.completedAt ?? context.updatedAt };
1946
+ case "failed":
1947
+ return {
1948
+ kind: "failed",
1949
+ reason: context.message ?? "payment_failed",
1950
+ failedAt: context.completedAt ?? context.updatedAt
1951
+ };
1952
+ case "expired":
1953
+ case "cancelled":
1954
+ return { kind: "abandoned" };
1955
+ case "refunded":
1956
+ case "partially_refunded":
1957
+ case "auto_refunded":
1958
+ return {
1959
+ kind: "refunded",
1960
+ refundedAt: context.completedAt ?? context.updatedAt,
1961
+ refundId: context.refunds?.[0] ?? "unknown"
1962
+ };
1963
+ default:
1964
+ return { kind: "pending" };
1965
+ }
1966
+ }
1967
+ function mapBachsChannel(method) {
1968
+ const raw = typeof method === "string" ? method : method?.type;
1969
+ if (typeof raw !== "string" || raw.length === 0) return void 0;
1970
+ const value = raw.toUpperCase();
1971
+ if (value === "CARD" || value.endsWith("_CARD")) return "card";
1972
+ if (value === "BANK" || value === "BANK_TRANSFER" || value.endsWith("_BANK_TRANSFER")) {
1973
+ return "bank_transfer";
1974
+ }
1975
+ if (value === "MOBILE_MONEY" || value.startsWith("MOMO")) return "mobile_money";
1976
+ if (value === "CRYPTO" || value.startsWith("CRYPTO")) return "crypto";
1977
+ return void 0;
1978
+ }
1979
+ function mapFee2(fees, amount) {
1980
+ if (!fees?.amount) return {};
1981
+ try {
1982
+ const fee = fromBachsAmount(fees.amount, fees.currency);
1983
+ if (fee.currency !== amount.currency) return { fees: fee };
1984
+ const net = amount.amount - fee.amount;
1985
+ return {
1986
+ fees: fee,
1987
+ netAmount: net >= 0 ? Money({ amount: net, currency: amount.currency }) : void 0
1988
+ };
1989
+ } catch {
1990
+ return {};
1991
+ }
1992
+ }
1993
+ function mapPaymentCustomer(customer) {
1994
+ return {
1995
+ // The Bachs payment object does not carry the customer id, only the
1996
+ // denormalised name and email.
1997
+ id: "unknown",
1998
+ email: customer?.email ?? "",
1999
+ name: customer?.name ?? void 0
2000
+ };
2001
+ }
2002
+ function mapBachsPaymentResponse(payment) {
2003
+ const currency = payment.currency;
2004
+ const amount = fromBachsAmount(payment.amount, currency);
2005
+ const createdAt = toBachsDate(payment.created_at) ?? /* @__PURE__ */ new Date();
2006
+ const updatedAt = toBachsDate(payment.updated_at) ?? createdAt;
2007
+ const completedAt = toBachsDate(payment.completed_at);
2008
+ const status = mapBachsPaymentStatus(payment.status, {
2009
+ message: payment.message,
2010
+ updatedAt,
2011
+ completedAt,
2012
+ refunds: payment.refunds
2013
+ });
2014
+ return {
2015
+ id: payment.payment_id,
2016
+ providerId: BACHS2,
2017
+ reference: PaymentReference(payment.reference ?? payment.payment_id),
2018
+ amount,
2019
+ ...mapFee2(payment.fees, amount),
2020
+ status,
2021
+ customer: mapPaymentCustomer(payment.customer),
2022
+ channel: mapBachsChannel(payment.payment_method),
2023
+ attempts: Object.freeze([]),
2024
+ metadata: mapBachsMetadata(payment.meta),
2025
+ createdAt,
2026
+ updatedAt,
2027
+ paidAt: status.kind === "success" ? status.paidAt : void 0,
2028
+ failureReason: status.kind === "failed" ? status.reason : void 0
2029
+ };
2030
+ }
2031
+ function mapBachsCheckoutSessionCreated(response, request, now) {
2032
+ const createdAt = toBachsDate(response.created_at) ?? now;
2033
+ return {
2034
+ id: response.checkout_id,
2035
+ providerId: BACHS2,
2036
+ reference: request.reference,
2037
+ // A catalog checkout is priced by Bachs; the total arrives with the
2038
+ // payment (verify/fetch/webhook) rather than from the request.
2039
+ ...request.amount ? { amount: request.amount } : {},
2040
+ status: { kind: "initialized" },
2041
+ customer: request.customer.kind === "inline" ? request.customer.customer : {
2042
+ id: "pending",
2043
+ email: request.customer.kind === "new" ? request.customer.email : "unknown",
2044
+ phone: request.customer.kind === "new" ? request.customer.phone : void 0,
2045
+ name: request.customer.kind === "new" ? request.customer.name : void 0
2046
+ },
2047
+ authorizationUrl: response.checkout_url,
2048
+ attempts: Object.freeze([]),
2049
+ metadata: request.metadata ? Object.freeze({ ...request.metadata }) : emptyMetadata3(),
2050
+ createdAt,
2051
+ updatedAt: createdAt
2052
+ };
2053
+ }
2054
+ function mapBachsCheckoutSession(session) {
2055
+ if (session.charge) {
2056
+ return mapBachsPaymentResponse(session.charge);
2057
+ }
2058
+ const currency = session.currency;
2059
+ const amount = fromBachsAmount(session.amount, currency);
2060
+ const createdAt = toBachsDate(session.created_at) ?? /* @__PURE__ */ new Date();
2061
+ const updatedAt = toBachsDate(session.updated_at) ?? createdAt;
2062
+ const completedAt = toBachsDate(session.completed_at);
2063
+ const paymentFailed = session.payment_status === "failed";
2064
+ const status = paymentFailed ? { kind: "failed", reason: "checkout_failed", failedAt: completedAt ?? updatedAt } : session.status === "expired" || session.status === "cancelled" ? { kind: "abandoned" } : session.status === "completed" ? { kind: "success", paidAt: completedAt ?? updatedAt } : { kind: "pending" };
2065
+ const customer = session.customer;
2066
+ const details = session.customer_details;
2067
+ return {
2068
+ id: session.checkout_id,
2069
+ providerId: BACHS2,
2070
+ reference: PaymentReference(session.reference ?? session.checkout_id),
2071
+ amount,
2072
+ status,
2073
+ customer: {
2074
+ id: customer?.id ?? "unknown",
2075
+ email: customer?.email ?? details?.email ?? "",
2076
+ name: customer?.name ?? details?.name ?? void 0
2077
+ },
2078
+ channel: mapBachsChannel(session.payment_method),
2079
+ attempts: Object.freeze([]),
2080
+ metadata: mapBachsMetadata(session.metadata),
2081
+ createdAt,
2082
+ updatedAt,
2083
+ paidAt: status.kind === "success" ? status.paidAt : void 0,
2084
+ failureReason: status.kind === "failed" ? status.reason : void 0
2085
+ };
2086
+ }
2087
+ function mapBachsPaymentListItem(item) {
2088
+ const currency = item.currency;
2089
+ const amount = fromBachsAmount(item.amount, currency);
2090
+ const completedAt = toBachsDate(item.completed_at);
2091
+ const createdAt = toBachsDate(item.transaction_date) ?? completedAt ?? /* @__PURE__ */ new Date();
2092
+ const updatedAt = completedAt ?? createdAt;
2093
+ const id = item.id ?? item.reference ?? "unknown";
2094
+ const status = mapBachsPaymentStatus(item.status, { updatedAt, completedAt });
2095
+ return {
2096
+ id,
2097
+ providerId: BACHS2,
2098
+ reference: PaymentReference(item.reference ?? id),
2099
+ amount,
2100
+ ...item.fee ? mapFee2({ amount: item.fee, currency: item.currency }, amount) : {},
2101
+ ...mapSettlementAmount(item),
2102
+ status,
2103
+ channel: mapBachsChannel(item.payment_method),
2104
+ customer: {
2105
+ id: "unknown",
2106
+ email: item.customer_email,
2107
+ name: item.customer_name
2108
+ },
2109
+ attempts: Object.freeze([]),
2110
+ metadata: mapBachsMetadata(item.meta),
2111
+ createdAt,
2112
+ updatedAt,
2113
+ paidAt: status.kind === "success" ? status.paidAt : void 0,
2114
+ failureReason: status.kind === "failed" ? status.reason : void 0
2115
+ };
2116
+ }
2117
+ function mapSettlementAmount(item) {
2118
+ const value = item.settlement_amount;
2119
+ const currency = item.settlement_currency;
2120
+ if (!value || !currency) return {};
2121
+ try {
2122
+ return { settlementAmount: fromBachsAmount(value, Currency(currency)) };
2123
+ } catch {
2124
+ return {};
2125
+ }
2126
+ }
2127
+ function mapBachsPaymentListResponse(response) {
2128
+ const pagination = response.pagination;
2129
+ const limit = pagination.limit ?? response.items.length;
2130
+ const offset = pagination.offset ?? 0;
2131
+ return {
2132
+ items: response.items.map(mapBachsPaymentListItem),
2133
+ total: pagination.total ?? response.items.length,
2134
+ page: limit > 0 ? Math.floor(offset / limit) + 1 : 1,
2135
+ perPage: limit,
2136
+ nextCursor: pagination.next_cursor ?? null
2137
+ };
2138
+ }
2139
+ function mapBachsRefundResponse(refund, currency) {
2140
+ return {
2141
+ id: refund.refund_id,
2142
+ paymentId: refund.charge_id,
2143
+ amount: fromBachsAmount(refund.requested_amount, currency),
2144
+ status: mapBachsRefundStatus(refund.status),
2145
+ reason: refund.reason ?? "",
2146
+ reference: refund.reference,
2147
+ createdAt: toBachsDate(refund.created_at) ?? /* @__PURE__ */ new Date(),
2148
+ completedAt: toBachsDate(refund.completed_at)
2149
+ };
2150
+ }
2151
+ function mapBachsRefundStatus(status) {
2152
+ switch (status) {
2153
+ case "success":
2154
+ return "succeeded";
2155
+ case "failed":
2156
+ return "failed";
2157
+ case "processing":
2158
+ return "processing";
2159
+ default:
2160
+ return "processing";
2161
+ }
2162
+ }
2163
+ function mapBachsPayoutResponse(payout, fallbackRecipientCode, now = /* @__PURE__ */ new Date()) {
2164
+ const currency = payout.currency;
2165
+ const amount = fromBachsAmount(payout.amount, currency);
2166
+ const createdAt = toBachsDate(payout.created_at) ?? now;
2167
+ const completedAt = toBachsDate(payout.completed_at);
2168
+ const status = mapBachsPayoutStatus(payout.status, payout.failure_reason, completedAt, createdAt);
2169
+ const sourceCurrency = payout.source_currency ?? void 0;
2170
+ const fee = mapSecondaryAmount(payout.fee, sourceCurrency);
2171
+ const totalDebited = mapSecondaryAmount(payout.total_debited, sourceCurrency);
2172
+ return {
2173
+ id: payout.id,
2174
+ providerId: BACHS2,
2175
+ amount,
2176
+ recipient: {
2177
+ code: payout.destination ?? fallbackRecipientCode,
2178
+ name: "unknown",
2179
+ accountNumber: "unknown",
2180
+ bankCode: "unknown",
2181
+ currency,
2182
+ createdAt,
2183
+ metadata: emptyMetadata3()
2184
+ },
2185
+ status,
2186
+ reference: payout.reference ?? payout.id,
2187
+ transferCode: payout.id,
2188
+ ...fee ? { fee } : {},
2189
+ ...totalDebited ? { totalDebited } : {},
2190
+ ...sourceCurrency ? { sourceCurrency } : {},
2191
+ createdAt,
2192
+ completedAt,
2193
+ failureReason: status.kind === "failed" ? status.reason : void 0,
2194
+ metadata: emptyMetadata3()
2195
+ };
2196
+ }
2197
+ function mapSecondaryAmount(value, currency) {
2198
+ if (!value || !currency) return void 0;
2199
+ try {
2200
+ return fromBachsAmount(value, currency);
2201
+ } catch {
2202
+ return void 0;
2203
+ }
2204
+ }
2205
+ function mapBachsPayoutStatus(status, failureReason, completedAt, createdAt) {
2206
+ switch (status) {
2207
+ case "pending":
2208
+ return { kind: "pending" };
2209
+ case "processing":
2210
+ return { kind: "processing" };
2211
+ case "completed":
2212
+ return { kind: "succeeded", settledAt: completedAt ?? createdAt };
2213
+ case "failed":
2214
+ return {
2215
+ kind: "failed",
2216
+ reason: failureReason ?? "payout_failed",
2217
+ failedAt: completedAt ?? createdAt
2218
+ };
2219
+ default:
2220
+ return { kind: "pending" };
2221
+ }
2222
+ }
2223
+ function mapBachsPayoutListResponse(response, options) {
2224
+ return {
2225
+ items: response.items.map((payout) => mapBachsPayoutResponse(payout, "unknown", options.now)),
2226
+ total: response.total,
2227
+ page: options.page,
2228
+ perPage: options.perPage,
2229
+ nextCursor: null
2230
+ };
2231
+ }
2232
+ function mapBachsChargeSettlement(charge) {
2233
+ const settlement = charge.settlement_currency;
2234
+ if (!settlement) return void 0;
2235
+ try {
2236
+ return {
2237
+ settlementCurrency: Currency(settlement),
2238
+ chargeCurrency: charge.currency ? Currency(charge.currency) : void 0
2239
+ };
2240
+ } catch {
2241
+ return void 0;
2242
+ }
2243
+ }
2244
+ function mapBachsDestinationResponse(destination, input, now) {
2245
+ return {
2246
+ code: destination.id,
2247
+ name: destination.account_name ?? destination.name ?? input.name,
2248
+ accountNumber: destination.account_number ?? input.accountNumber,
2249
+ bankCode: destination.bank_code ?? input.bankCode,
2250
+ // Prefer what the provider stored: it normalises and may reject values.
2251
+ currency: destination.currency ? Currency(destination.currency) : input.currency,
2252
+ status: destination.status,
2253
+ createdAt: toBachsDate(destination.created_at) ?? now,
2254
+ metadata: input.metadata ? Object.freeze({ ...input.metadata }) : emptyMetadata3()
2255
+ };
2256
+ }
2257
+ function mapBachsBankListResponse(response, currency) {
2258
+ return Object.freeze(
2259
+ response.banks.map((bank) => ({
2260
+ code: bank.code,
2261
+ name: bank.name,
2262
+ currency
2263
+ }))
2264
+ );
2265
+ }
2266
+ function normalizeBachsWebhookType(eventType) {
2267
+ switch (eventType) {
2268
+ case "collection.succeeded":
2269
+ return "payment.succeeded";
2270
+ case "collection.failed":
2271
+ return "payment.failed";
2272
+ case "collection.underpaid":
2273
+ return "payment.underpaid";
2274
+ case "checkout.completed":
2275
+ return "checkout.completed";
2276
+ case "checkout.expired":
2277
+ return "checkout.expired";
2278
+ case "refund.created":
2279
+ return "refund.initiated";
2280
+ case "refund.paid":
2281
+ return "refund.succeeded";
2282
+ case "refund.failed":
2283
+ return "refund.failed";
2284
+ case "payout.created":
2285
+ return "transfer.initiated";
2286
+ case "payout.paid":
2287
+ return "transfer.succeeded";
2288
+ case "payout.failed":
2289
+ return "transfer.failed";
2290
+ case "customer.subscription.created":
2291
+ return "subscription.created";
2292
+ case "customer.subscription.updated":
2293
+ return "subscription.updated";
2294
+ case "customer.subscription.deleted":
2295
+ return "subscription.canceled";
2296
+ case "invoice.created":
2297
+ return "invoice.created";
2298
+ case "invoice.paid":
2299
+ return "invoice.paid";
2300
+ case "invoice.payment_failed":
2301
+ return "invoice.payment_failed";
2302
+ case "customer.created":
2303
+ return "customer.created";
2304
+ case "customer.updated":
2305
+ return "customer.updated";
2306
+ case "dispute.created":
2307
+ return "dispute.created";
2308
+ case "dispute.updated":
2309
+ return "dispute.updated";
2310
+ case "conversion.completed":
2311
+ return "conversion.completed";
2312
+ case "conversion.failed":
2313
+ return "conversion.failed";
2314
+ case "payment_method.saved":
2315
+ return "payment_method.saved";
2316
+ default:
2317
+ return "unknown";
2318
+ }
2319
+ }
2320
+ function mapBachsWebhookEvent(envelope, receivedAt) {
2321
+ return {
2322
+ id: envelope.id,
2323
+ provider: BACHS2,
2324
+ type: normalizeBachsWebhookType(envelope.type),
2325
+ originalType: envelope.type,
2326
+ createdAt: toBachsDate(envelope.created_at) ?? receivedAt,
2327
+ receivedAt,
2328
+ payload: envelope.data ?? {},
2329
+ raw: envelope
2330
+ };
2331
+ }
2332
+ var BACHS_DEFAULT_TOLERANCE_SECONDS = 300;
2333
+ var V2_HEADER = "x-bachs-signature-v2";
2334
+ var SIGNATURE_HEADER2 = "x-bachs-signature";
2335
+ var TIMESTAMP_HEADER = "x-bachs-timestamp";
2336
+ function parseBachsWebhook(headers, rawBody, config, clock) {
2337
+ if (!config.webhookSecret) {
2338
+ return err(
2339
+ new WebhookValidationError(
2340
+ "Bachs webhook verification requires the endpoint signing secret (whsec_...)"
2341
+ )
2342
+ );
2343
+ }
2344
+ const candidates = collectSignatures(headers);
2345
+ if (!candidates) {
2346
+ return err(new WebhookValidationError("Missing Bachs webhook signature headers"));
2347
+ }
2348
+ const nowSeconds = Math.floor(clock.now().getTime() / 1e3);
2349
+ const tolerance = normalizeTolerance(config.toleranceSeconds);
2350
+ if (Math.abs(nowSeconds - candidates.timestamp) > tolerance) {
2351
+ return err(new WebhookValidationError("Bachs webhook timestamp is outside the tolerance window"));
2352
+ }
2353
+ const expected = sign(`${candidates.timestamp}.${rawBody}`, config.webhookSecret);
2354
+ const matched = candidates.signatures.some((signature) => constantTimeEquals(signature, expected));
2355
+ if (!matched) {
2356
+ return err(new WebhookValidationError("Invalid Bachs webhook signature"));
2357
+ }
2358
+ let envelope;
2359
+ try {
2360
+ envelope = JSON.parse(rawBody);
2361
+ } catch {
2362
+ return err(new WebhookValidationError("Invalid webhook body: not valid JSON"));
2363
+ }
2364
+ if (!envelope.id || !envelope.type) {
2365
+ return err(new WebhookValidationError("Invalid webhook body: missing event id or type"));
2366
+ }
2367
+ try {
2368
+ return ok(mapBachsWebhookEvent(envelope, clock.now()));
2369
+ } catch (e) {
2370
+ return err(
2371
+ new WebhookValidationError(
2372
+ `Failed to parse Bachs webhook payload: ${e instanceof Error ? e.message : String(e)}`
2373
+ )
2374
+ );
2375
+ }
2376
+ }
2377
+ function collectSignatures(headers) {
2378
+ const v2 = findHeader2(headers, V2_HEADER);
2379
+ if (v2) {
2380
+ const parsed = parseSignatureV2(v2);
2381
+ if (parsed) return parsed;
2382
+ }
2383
+ const signature = findHeader2(headers, SIGNATURE_HEADER2);
2384
+ const timestamp = findHeader2(headers, TIMESTAMP_HEADER);
2385
+ if (!signature || !timestamp) return void 0;
2386
+ const seconds = Number.parseInt(timestamp, 10);
2387
+ if (!Number.isFinite(seconds)) return void 0;
2388
+ return { timestamp: seconds, signatures: [signature] };
2389
+ }
2390
+ function parseSignatureV2(header) {
2391
+ let timestamp;
2392
+ const signatures = [];
2393
+ for (const part of header.split(",")) {
2394
+ const separator = part.indexOf("=");
2395
+ if (separator < 0) continue;
2396
+ const key = part.slice(0, separator).trim();
2397
+ const value = part.slice(separator + 1).trim();
2398
+ if (key === "t") {
2399
+ const seconds = Number.parseInt(value, 10);
2400
+ if (Number.isFinite(seconds)) timestamp = seconds;
2401
+ } else if (key === "v1" && value.length > 0) {
2402
+ signatures.push(value);
2403
+ }
2404
+ }
2405
+ if (timestamp === void 0 || signatures.length === 0) return void 0;
2406
+ return { timestamp, signatures };
2407
+ }
2408
+ function normalizeTolerance(configured) {
2409
+ if (configured === void 0 || !Number.isFinite(configured) || configured <= 0) {
2410
+ return BACHS_DEFAULT_TOLERANCE_SECONDS;
2411
+ }
2412
+ return configured;
2413
+ }
2414
+ function sign(message, secret) {
2415
+ return crypto.createHmac("sha256", secret).update(message, "utf8").digest("hex");
2416
+ }
2417
+ function constantTimeEquals(a, b) {
2418
+ const left = Buffer.from(a, "utf8");
2419
+ const right = Buffer.from(b, "utf8");
2420
+ if (left.length !== right.length) return false;
2421
+ return crypto.timingSafeEqual(left, right);
2422
+ }
2423
+ function findHeader2(headers, name) {
2424
+ const lower = name.toLowerCase();
2425
+ for (const key of Object.keys(headers)) {
2426
+ if (key.toLowerCase() === lower) {
2427
+ return headers[key];
2428
+ }
2429
+ }
2430
+ return void 0;
2431
+ }
2432
+
2433
+ // src/infrastructure/providers/bachs/bachs-adapter.ts
2434
+ var COLLECTION_CURRENCIES = [
2435
+ "USD",
2436
+ "NGN",
2437
+ "GHS",
2438
+ "KES",
2439
+ "MWK",
2440
+ "RWF",
2441
+ "TZS",
2442
+ "UGX",
2443
+ "XAF",
2444
+ "XOF",
2445
+ "ZMW"
2446
+ ].map((code) => code);
2447
+ var PAYOUT_CURRENCIES = [
2448
+ "NGN",
2449
+ "GHS",
2450
+ "KES",
2451
+ "TZS",
2452
+ "UGX",
2453
+ "USD",
2454
+ "GBP",
2455
+ "EUR",
2456
+ "CAD"
2457
+ ].map((code) => code);
2458
+ var CHANNELS = [
2459
+ "card",
2460
+ "bank_transfer",
2461
+ "mobile_money",
2462
+ "crypto"
2463
+ ];
2464
+ var BACHS_CAPABILITIES = {
2465
+ supportsAuthorizationUrl: true,
2466
+ supportsRecurring: true,
2467
+ supportsPartialRefund: true,
2468
+ supportsWebhooks: true,
2469
+ supportsTransfers: true,
2470
+ // Bachs documents `Idempotency-Key` on public POST/PATCH and a per-refund
2471
+ // `idempotency_key`, so retries are deduplicated by the provider.
2472
+ supportsIdempotencyKey: true,
2473
+ supportedCurrencies: COLLECTION_CURRENCIES,
2474
+ supportedChannels: CHANNELS,
2475
+ supportedTransferCurrencies: PAYOUT_CURRENCIES
2476
+ };
2477
+ var COUNTRY_BY_CURRENCY = {
2478
+ NGN: "NG",
2479
+ GHS: "GH",
2480
+ KES: "KE",
2481
+ TZS: "TZ",
2482
+ UGX: "UG",
2483
+ ZMW: "ZM",
2484
+ MWK: "MW",
2485
+ RWF: "RW"
2486
+ };
2487
+ var CARD_CORRIDORS = {
2488
+ USD: "USD_CARD",
2489
+ NGN: "NGN_CARD"
2490
+ };
2491
+ var MOMO_CORRIDORS = {
2492
+ GHS: "MOMO_GHS",
2493
+ KES: "MOMO_KES",
2494
+ TZS: "MOMO_TZS",
2495
+ UGX: "MOMO_UGX",
2496
+ XAF: "MOMO_XAF",
2497
+ XOF: "MOMO_XOF",
2498
+ RWF: "MOMO_RWF",
2499
+ MWK: "MOMO_MWK",
2500
+ ZMW: "MOMO_ZMW"
2501
+ };
2502
+ var BachsAdapter = class {
2503
+ id;
2504
+ capabilities;
2505
+ httpClient;
2506
+ logger;
2507
+ clock;
2508
+ idGenerator;
2509
+ connection;
2510
+ billing;
2511
+ constructor(config, deps) {
2512
+ const connection = createBachsConnection(config);
2513
+ this.id = "bachs";
2514
+ this.capabilities = BACHS_CAPABILITIES;
2515
+ this.httpClient = deps.httpClient;
2516
+ this.logger = deps.logger;
2517
+ this.clock = deps.clock;
2518
+ this.idGenerator = deps.idGenerator;
2519
+ this.connection = connection;
2520
+ this.billing = new BachsSubscriptionClient(connection, deps);
2521
+ this.logger.debug("bachs adapter configured", {
2522
+ provider: this.id,
2523
+ environment: connection.environment
2524
+ });
2525
+ }
2526
+ async initialize(req) {
2527
+ const correlationId = req.correlationId ?? this.idGenerator.generate();
2528
+ const body = buildCheckoutSessionRequest(req, this.clock.now());
2529
+ if (req.channels && !body.payment_method_types) {
2530
+ this.logger.warn("bachs cannot restrict to the requested channels; offering all corridors", {
2531
+ provider: this.id,
2532
+ currency: req.amount?.currency ?? "unknown",
2533
+ channels: req.channels.join(","),
2534
+ correlationId
2535
+ });
2536
+ }
2537
+ this.logger.info("initializing payment", {
2538
+ provider: this.id,
2539
+ reference: req.reference,
2540
+ correlationId,
2541
+ // A catalog checkout is priced by Bachs, so the amount may be unknown here.
2542
+ amount: req.amount ? String(req.amount.amount) : "provider-priced",
2543
+ currency: req.amount?.currency ?? "unknown"
2544
+ });
2545
+ const result = await this.httpClient.send({
2546
+ method: "POST",
2547
+ url: `${this.connection.baseUrl}/v1/checkout-sessions`,
2548
+ headers: this.authHeaders(),
2549
+ body: JSON.stringify(body),
2550
+ timeoutMs: this.connection.timeoutMs,
2551
+ correlationId,
2552
+ idempotencyKey: req.idempotencyKey
2553
+ });
2554
+ if (!result.ok) {
2555
+ this.logger.error("initialize failed", result.error, {
2556
+ provider: this.id,
2557
+ reference: req.reference,
2558
+ correlationId
2559
+ });
2560
+ return result;
2561
+ }
2562
+ try {
2563
+ const response = JSON.parse(result.value.body);
2564
+ return ok(mapBachsCheckoutSessionCreated(response, req, this.clock.now()));
2565
+ } catch (e) {
2566
+ return err(mapMapperError(e, { provider: this.id, context: "initialize response" }));
2567
+ }
2568
+ }
2569
+ /**
2570
+ * Bachs has no lookup by your own reference on any endpoint. Verification is
2571
+ * therefore by provider id: a checkout id (`chk_`) reads the checkout
2572
+ * session, and a payment id (`ch_`, `pay_`, `chrg_`) reads the payment.
2573
+ * Fulfilment should still come from webhooks, not from this call.
2574
+ */
2575
+ async verify(reference) {
2576
+ const value = String(reference);
2577
+ if (value.startsWith("pay_") || value.startsWith("ch_") || value.startsWith("chrg_")) {
2578
+ return this.fetch(value);
2579
+ }
2580
+ if (!value.startsWith("chk_")) {
2581
+ return err(
2582
+ new ProviderBadRequestError(
2583
+ "Bachs can only verify by checkout id (chk_) or payment id (ch_/pay_/chrg_); keep the id returned by initialize() or sent in the webhook",
2584
+ { provider: this.id }
2585
+ )
2586
+ );
2587
+ }
2588
+ const correlationId = this.idGenerator.generate();
2589
+ this.logger.info("verifying checkout session", {
2590
+ provider: this.id,
2591
+ checkoutId: value,
2592
+ correlationId
2593
+ });
2594
+ const result = await this.httpClient.send({
2595
+ method: "GET",
2596
+ url: `${this.connection.baseUrl}/v1/checkout-sessions/${encodeURIComponent(value)}`,
2597
+ headers: this.authHeaders(),
2598
+ timeoutMs: this.connection.timeoutMs,
2599
+ correlationId
2600
+ });
2601
+ if (!result.ok) return result;
2602
+ try {
2603
+ const response = JSON.parse(result.value.body);
2604
+ return ok(mapBachsCheckoutSession(response));
2605
+ } catch (e) {
2606
+ return err(mapMapperError(e, { provider: this.id, context: "verify response" }));
2607
+ }
2608
+ }
2609
+ async fetch(id) {
2610
+ const correlationId = this.idGenerator.generate();
2611
+ this.logger.info("fetching payment", {
2612
+ provider: this.id,
2613
+ paymentId: id,
2614
+ correlationId
2615
+ });
2616
+ const result = await this.httpClient.send({
2617
+ method: "GET",
2618
+ url: `${this.connection.baseUrl}/v1/payments/${encodeURIComponent(id)}`,
2619
+ headers: this.authHeaders(),
2620
+ timeoutMs: this.connection.timeoutMs,
2621
+ correlationId
2622
+ });
2623
+ if (!result.ok) return result;
2624
+ try {
2625
+ const response = JSON.parse(result.value.body);
2626
+ return ok(mapBachsPaymentResponse(response));
2627
+ } catch (e) {
2628
+ return err(mapMapperError(e, { provider: this.id, context: "fetch response" }));
2629
+ }
2630
+ }
2631
+ async list(query = {}) {
2632
+ const correlationId = this.idGenerator.generate();
2633
+ const { limit, offset, clamped } = resolveBachsPagination(query);
2634
+ const params = new URLSearchParams({ limit: String(limit) });
2635
+ if (clamped) {
2636
+ this.logger.warn("perPage clamped to the provider maximum", {
2637
+ provider: this.id,
2638
+ requested: String(query.perPage),
2639
+ limit,
2640
+ correlationId
2641
+ });
2642
+ }
2643
+ if (query.cursor) {
2644
+ params.set("cursor", query.cursor);
2645
+ } else if (query.page) {
2646
+ params.set("offset", String(offset));
2647
+ }
2648
+ if (query.status) params.set("status_filter", query.status);
2649
+ if (query.from || query.to || query.customer) {
2650
+ this.logger.warn("bachs payments list does not support from/to/customer filters; ignoring them", {
2651
+ provider: this.id,
2652
+ correlationId
2653
+ });
2654
+ }
2655
+ this.logger.info("listing payments", {
2656
+ provider: this.id,
2657
+ correlationId,
2658
+ query: params.toString()
2659
+ });
2660
+ const result = await this.httpClient.send({
2661
+ method: "GET",
2662
+ url: `${this.connection.baseUrl}/v1/payments?${params.toString()}`,
2663
+ headers: this.authHeaders(),
2664
+ timeoutMs: this.connection.timeoutMs,
2665
+ correlationId
2666
+ });
2667
+ if (!result.ok) return result;
2668
+ try {
2669
+ const response = JSON.parse(result.value.body);
2670
+ return ok(mapBachsPaymentListResponse(response));
2671
+ } catch (e) {
2672
+ return err(mapMapperError(e, { provider: this.id, context: "list response" }));
2673
+ }
2674
+ }
2675
+ /**
2676
+ * Bachs allows one non-failed refund per charge and settles refunds
2677
+ * asynchronously. The charge is read first for its `is_refundable`
2678
+ * pre-check, and the settlement side is read for the currency a partial
2679
+ * refund must be expressed in (it differs from the charge currency
2680
+ * whenever Bachs' adaptive pricing converts the charge).
2681
+ */
2682
+ async refund(input) {
2683
+ const correlationId = input.correlationId ?? this.idGenerator.generate();
2684
+ this.logger.info("refunding payment", {
2685
+ provider: this.id,
2686
+ paymentId: input.paymentId,
2687
+ correlationId
2688
+ });
2689
+ const chargeResult = await this.httpClient.send({
2690
+ method: "GET",
2691
+ url: `${this.connection.baseUrl}/v1/payments/${encodeURIComponent(input.paymentId)}`,
2692
+ headers: this.authHeaders(),
2693
+ timeoutMs: this.connection.timeoutMs,
2694
+ correlationId
2695
+ });
2696
+ if (!chargeResult.ok) return chargeResult;
2697
+ try {
2698
+ const charge = JSON.parse(chargeResult.value.body);
2699
+ if (charge.is_refundable === false) {
2700
+ return err(
2701
+ new ProviderBadRequestError(
2702
+ `Bachs payment ${input.paymentId} is not refundable`,
2703
+ { provider: this.id }
2704
+ )
2705
+ );
2706
+ }
2707
+ const chargeCurrency = Currency(charge.currency);
2708
+ const settlement = await this.resolveSettlement(input.paymentId, correlationId);
2709
+ const refundCurrency = settlement ?? chargeCurrency;
2710
+ if (settlement && settlement !== chargeCurrency) {
2711
+ this.logger.info("refund sized in the settlement currency", {
2712
+ provider: this.id,
2713
+ chargeCurrency,
2714
+ settlementCurrency: settlement,
2715
+ correlationId
2716
+ });
2717
+ }
2718
+ if (input.amount && input.amount.currency !== refundCurrency) {
2719
+ return err(
2720
+ new ValidationError(
2721
+ `Refund amount is in ${input.amount.currency} but Bachs refunds payment ${input.paymentId} in ${refundCurrency}; pass the amount in ${refundCurrency}`
2722
+ )
2723
+ );
2724
+ }
2725
+ const body = {
2726
+ charge_id: input.paymentId,
2727
+ reference: input.reference,
2728
+ amount: input.amount ? toBachsAmount(input.amount) : void 0,
2729
+ reason: input.reason,
2730
+ idempotency_key: input.idempotencyKey
2731
+ };
2732
+ const result = await this.httpClient.send({
2733
+ method: "POST",
2734
+ url: `${this.connection.baseUrl}/v1/refunds`,
2735
+ headers: this.authHeaders(),
2736
+ body: JSON.stringify(body),
2737
+ timeoutMs: this.connection.timeoutMs,
2738
+ correlationId,
2739
+ idempotencyKey: input.idempotencyKey
2740
+ });
2741
+ if (!result.ok) return result;
2742
+ const response = JSON.parse(result.value.body);
2743
+ return ok(mapBachsRefundResponse(response, refundCurrency));
2744
+ } catch (e) {
2745
+ return err(mapMapperError(e, { provider: this.id, context: "refund response" }));
2746
+ }
2747
+ }
2748
+ async fetchRefund(refundId) {
2749
+ const correlationId = this.idGenerator.generate();
2750
+ this.logger.info("fetching refund", {
2751
+ provider: this.id,
2752
+ refundId,
2753
+ correlationId
2754
+ });
2755
+ const result = await this.httpClient.send({
2756
+ method: "GET",
2757
+ url: `${this.connection.baseUrl}/v1/refunds/${encodeURIComponent(refundId)}`,
2758
+ headers: this.authHeaders(),
2759
+ timeoutMs: this.connection.timeoutMs,
2760
+ correlationId
2761
+ });
2762
+ if (!result.ok) return result;
2763
+ try {
2764
+ const refund = JSON.parse(result.value.body);
2765
+ const currency = await this.resolveRefundCurrency(refund.charge_id, correlationId);
2766
+ if (!currency.ok) return currency;
2767
+ return ok(mapBachsRefundResponse(refund, currency.value));
2768
+ } catch (e) {
2769
+ return err(mapMapperError(e, { provider: this.id, context: "fetch refund response" }));
2770
+ }
2771
+ }
2772
+ async createTransferQuote(input) {
2773
+ const correlationId = this.idGenerator.generate();
2774
+ if (input.fromCurrency === input.toCurrency) {
2775
+ return err(
2776
+ new ValidationError(
2777
+ `A payout quote converts between two currencies; ${input.fromCurrency} to ${input.fromCurrency} needs none (send the payout amount directly)`
2778
+ )
2779
+ );
2780
+ }
2781
+ const body = {
2782
+ from_currency: input.fromCurrency,
2783
+ to_currency: input.toCurrency,
2784
+ amount: toBachsAmount(input.amount)
2785
+ };
2786
+ this.logger.info("creating payout quote", {
2787
+ provider: this.id,
2788
+ fromCurrency: input.fromCurrency,
2789
+ toCurrency: input.toCurrency,
2790
+ correlationId
2791
+ });
2792
+ const result = await this.httpClient.send({
2793
+ method: "POST",
2794
+ url: `${this.connection.baseUrl}/v1/payouts/quotes`,
2795
+ headers: this.authHeaders(),
2796
+ body: JSON.stringify(body),
2797
+ timeoutMs: this.connection.timeoutMs,
2798
+ correlationId
2799
+ });
2800
+ if (!result.ok) return result;
2801
+ try {
2802
+ const response = JSON.parse(result.value.body);
2803
+ return ok({
2804
+ id: response.quote_id,
2805
+ providerId: this.id,
2806
+ fromCurrency: Currency(response.from_currency),
2807
+ toCurrency: Currency(response.to_currency),
2808
+ fromAmount: fromBachsQuoteAmount(response.from_amount, response.from_currency),
2809
+ toAmount: fromBachsQuoteAmount(response.to_amount, response.to_currency),
2810
+ exchangeRate: response.exchange_rate,
2811
+ expiresAt: response.expires_at ? new Date(response.expires_at) : void 0
2812
+ });
2813
+ } catch (e) {
2814
+ return err(mapMapperError(e, { provider: this.id, context: "payout quote response" }));
2815
+ }
2816
+ }
2817
+ async parseWebhook(headers, rawBody) {
2818
+ return parseBachsWebhook(
2819
+ headers,
2820
+ rawBody,
2821
+ {
2822
+ webhookSecret: this.connection.webhookSecret,
2823
+ toleranceSeconds: this.connection.webhookToleranceSeconds
2824
+ },
2825
+ this.clock
2826
+ );
2827
+ }
2828
+ // -------------------------------------------------------------------------
2829
+ // SubscriptionProvider — delegated to the billing client
2830
+ // -------------------------------------------------------------------------
2831
+ listProducts(query = {}) {
2832
+ return this.billing.listProducts(query);
2833
+ }
2834
+ fetchProduct(id) {
2835
+ return this.billing.fetchProduct(id);
2836
+ }
2837
+ createProduct(input) {
2838
+ return this.billing.createProduct(input);
2839
+ }
2840
+ updateProduct(id, input) {
2841
+ return this.billing.updateProduct(id, input);
2842
+ }
2843
+ archiveProduct(id) {
2844
+ return this.billing.archiveProduct(id);
2845
+ }
2846
+ unarchiveProduct(id) {
2847
+ return this.billing.unarchiveProduct(id);
2848
+ }
2849
+ listSubscriptions(query = {}) {
2850
+ return this.billing.listSubscriptions(query);
2851
+ }
2852
+ fetchSubscription(id) {
2853
+ return this.billing.fetchSubscription(id);
2854
+ }
2855
+ updateSubscription(id, input) {
2856
+ return this.billing.updateSubscription(id, input);
2857
+ }
2858
+ cancelSubscription(id, input = {}) {
2859
+ return this.billing.cancelSubscription(id, input);
2860
+ }
2861
+ listCustomers(query = {}) {
2862
+ return this.billing.listCustomers(query);
2863
+ }
2864
+ fetchCustomer(id) {
2865
+ return this.billing.fetchCustomer(id);
2866
+ }
2867
+ createCustomer(input) {
2868
+ return this.billing.createCustomer(input);
2869
+ }
2870
+ updateCustomer(id, input) {
2871
+ return this.billing.updateCustomer(id, input);
2872
+ }
2873
+ createPortalSession(customerId) {
2874
+ return this.billing.createPortalSession(customerId);
2875
+ }
2876
+ async health() {
2877
+ const start = Date.now();
2878
+ try {
2879
+ const result = await this.httpClient.send({
2880
+ method: "GET",
2881
+ url: `${this.connection.baseUrl}/v1/payments?limit=1`,
2882
+ headers: this.authHeaders(),
2883
+ timeoutMs: 5e3
2884
+ });
2885
+ if (!result.ok) {
2886
+ this.logger.warn("health check failed", {
2887
+ provider: this.id,
2888
+ code: result.error.code,
2889
+ httpStatus: result.error.httpStatus,
2890
+ message: result.error.message
2891
+ });
2892
+ }
2893
+ return {
2894
+ healthy: result.ok,
2895
+ latencyMs: Date.now() - start,
2896
+ timestamp: this.clock.now()
2897
+ };
2898
+ } catch (error) {
2899
+ this.logger.warn("health check threw", {
2900
+ provider: this.id,
2901
+ message: error instanceof Error ? error.message : String(error)
2902
+ });
2903
+ return {
2904
+ healthy: false,
2905
+ latencyMs: Date.now() - start,
2906
+ timestamp: this.clock.now()
2907
+ };
2908
+ }
2909
+ }
2910
+ /**
2911
+ * Banks are resolved by country: `/v1/reference/banks` falls back to the
2912
+ * platform's own country (or 400s) when none is given, so labelling the
2913
+ * response with an unrelated currency would be wrong. The country comes from
2914
+ * the caller when given, and from the currency map otherwise.
2915
+ */
2916
+ async listBankCodes(input) {
2917
+ const correlationId = this.idGenerator.generate();
2918
+ const country = input.country ?? COUNTRY_BY_CURRENCY[input.currency];
2919
+ if (!country) {
2920
+ return err(
2921
+ new ValidationError(
2922
+ `Bachs lists banks by country, and ${input.currency} does not identify one; pass { currency, country: "NG" }`
2923
+ )
2924
+ );
2925
+ }
2926
+ this.logger.info("listing bank codes", {
2927
+ provider: this.id,
2928
+ currency: input.currency,
2929
+ country,
2930
+ correlationId
2931
+ });
2932
+ const result = await this.httpClient.send({
2933
+ method: "GET",
2934
+ url: `${this.connection.baseUrl}/v1/reference/banks?country=${encodeURIComponent(country)}`,
2935
+ headers: this.authHeaders(),
2936
+ timeoutMs: this.connection.timeoutMs,
2937
+ correlationId
2938
+ });
2939
+ if (!result.ok) return result;
2940
+ try {
2941
+ const response = JSON.parse(result.value.body);
2942
+ return ok(mapBachsBankListResponse(response, input.currency));
2943
+ } catch (e) {
2944
+ return err(mapMapperError(e, { provider: this.id, context: "bank list response" }));
2945
+ }
2946
+ }
2947
+ async resolveAccount(input) {
2948
+ const correlationId = this.idGenerator.generate();
2949
+ const country = input.country ?? COUNTRY_BY_CURRENCY[input.currency];
2950
+ const body = {
2951
+ account_number: input.accountNumber,
2952
+ bank_code: input.bankCode,
2953
+ country
2954
+ };
2955
+ this.logger.info("resolving account", {
2956
+ provider: this.id,
2957
+ bankCode: input.bankCode,
2958
+ country,
2959
+ correlationId
2960
+ });
2961
+ const result = await this.httpClient.send({
2962
+ method: "POST",
2963
+ url: `${this.connection.baseUrl}/v1/misc/bank-accounts/resolve`,
2964
+ headers: this.authHeaders(),
2965
+ body: JSON.stringify(body),
2966
+ timeoutMs: this.connection.timeoutMs,
2967
+ correlationId
2968
+ });
2969
+ if (!result.ok) return result;
2970
+ try {
2971
+ const response = JSON.parse(result.value.body);
2972
+ if (!response.resolved) {
2973
+ return err(
2974
+ new ProviderError(response.message ?? "Account could not be resolved", {
2975
+ provider: this.id,
2976
+ httpStatus: 422,
2977
+ isRetryable: false
2978
+ })
2979
+ );
2980
+ }
2981
+ return ok({
2982
+ accountName: response.account_name ?? "",
2983
+ accountNumber: response.account_number ?? input.accountNumber
2984
+ });
2985
+ } catch (e) {
2986
+ return err(mapMapperError(e, { provider: this.id, context: "resolve account response" }));
2987
+ }
2988
+ }
2989
+ async createRecipient(input) {
2990
+ const correlationId = this.idGenerator.generate();
2991
+ const body = buildPayoutDestinationRequest(input);
2992
+ this.logger.info("creating payout destination", {
2993
+ provider: this.id,
2994
+ type: body.type,
2995
+ bankCode: input.bankCode,
2996
+ correlationId
2997
+ });
2998
+ const result = await this.httpClient.send({
2999
+ method: "POST",
3000
+ url: `${this.connection.baseUrl}/v1/payouts/destinations`,
3001
+ headers: this.authHeaders(),
3002
+ body: JSON.stringify(body),
3003
+ timeoutMs: this.connection.timeoutMs,
3004
+ correlationId
3005
+ });
3006
+ if (!result.ok) return result;
3007
+ try {
3008
+ const response = JSON.parse(result.value.body);
3009
+ return ok(mapBachsDestinationResponse(response, input, this.clock.now()));
3010
+ } catch (e) {
3011
+ return err(mapMapperError(e, { provider: this.id, context: "create destination response" }));
3012
+ }
3013
+ }
3014
+ async initiateTransfer(input) {
3015
+ const hasAmount = input.amount !== void 0;
3016
+ const hasQuote = input.quoteId !== void 0;
3017
+ if (hasAmount === hasQuote) {
3018
+ throw new ValidationError(
3019
+ "A Bachs payout takes exactly one of amount (same-currency) or quoteId (cross-currency)"
3020
+ );
3021
+ }
3022
+ if (input.amount && input.currency !== input.amount.currency) {
3023
+ throw new ValidationError(
3024
+ `Transfer currency ${input.currency} does not match amount currency ${input.amount.currency}`
3025
+ );
3026
+ }
3027
+ if (input.reference.length > 128) {
3028
+ throw new ValidationError(
3029
+ `Bachs payout references are limited to 128 characters (got ${input.reference.length})`
3030
+ );
3031
+ }
3032
+ if (input.accountReference) {
3033
+ this.logger.warn("accountReference is ignored by Bachs (Paystack-only field)", {
3034
+ provider: this.id,
3035
+ correlationId: input.correlationId ?? "unknown"
3036
+ });
3037
+ }
3038
+ const correlationId = input.correlationId ?? this.idGenerator.generate();
3039
+ const body = {
3040
+ destination: input.recipientCode,
3041
+ amount: input.amount ? toBachsAmount(input.amount) : void 0,
3042
+ quote_id: input.quoteId,
3043
+ reference: input.reference,
3044
+ metadata: input.metadata ? { ...input.metadata } : void 0
3045
+ };
3046
+ this.logger.info("initiating payout", {
3047
+ provider: this.id,
3048
+ reference: input.reference,
3049
+ correlationId
3050
+ });
3051
+ const result = await this.httpClient.send({
3052
+ method: "POST",
3053
+ url: `${this.connection.baseUrl}/v1/payouts`,
3054
+ headers: this.authHeaders(),
3055
+ body: JSON.stringify(body),
3056
+ timeoutMs: this.connection.timeoutMs,
3057
+ correlationId,
3058
+ idempotencyKey: input.idempotencyKey
3059
+ });
3060
+ if (!result.ok) return result;
3061
+ try {
3062
+ const response = JSON.parse(result.value.body);
3063
+ const now = this.clock.now();
3064
+ const recipient = await this.lookupDestination(response.destination, now);
3065
+ return ok(mapBachsPayoutResponse(response, recipient?.code ?? input.recipientCode, now));
3066
+ } catch (e) {
3067
+ return err(mapMapperError(e, { provider: this.id, context: "initiate payout response" }));
3068
+ }
3069
+ }
3070
+ async fetchTransfer(id) {
3071
+ const correlationId = this.idGenerator.generate();
3072
+ this.logger.info("fetching payout", {
3073
+ provider: this.id,
3074
+ payoutId: id,
3075
+ correlationId
3076
+ });
3077
+ const result = await this.httpClient.send({
3078
+ method: "GET",
3079
+ url: `${this.connection.baseUrl}/v1/payouts/${encodeURIComponent(id)}`,
3080
+ headers: this.authHeaders(),
3081
+ timeoutMs: this.connection.timeoutMs,
3082
+ correlationId
3083
+ });
3084
+ if (!result.ok) return result;
3085
+ try {
3086
+ const response = JSON.parse(result.value.body);
3087
+ const now = this.clock.now();
3088
+ const recipient = await this.lookupDestination(response.destination, now);
3089
+ const transfer = mapBachsPayoutResponse(response, recipient?.code ?? "unknown", now);
3090
+ return ok(recipient ? { ...transfer, recipient } : transfer);
3091
+ } catch (e) {
3092
+ return err(mapMapperError(e, { provider: this.id, context: "fetch payout response" }));
3093
+ }
3094
+ }
3095
+ async listTransfers(query = {}) {
3096
+ const correlationId = this.idGenerator.generate();
3097
+ const page = query.page ?? 1;
3098
+ const { limit, offset, clamped } = resolveBachsPagination(query);
3099
+ const params = new URLSearchParams({
3100
+ limit: String(limit),
3101
+ offset: String(offset)
3102
+ });
3103
+ if (clamped) {
3104
+ this.logger.warn("perPage clamped to the provider maximum", {
3105
+ provider: this.id,
3106
+ requested: String(query.perPage),
3107
+ limit,
3108
+ correlationId
3109
+ });
3110
+ }
3111
+ this.logger.info("listing payouts", {
3112
+ provider: this.id,
3113
+ correlationId,
3114
+ query: params.toString()
3115
+ });
3116
+ const result = await this.httpClient.send({
3117
+ method: "GET",
3118
+ url: `${this.connection.baseUrl}/v1/payouts?${params.toString()}`,
3119
+ headers: this.authHeaders(),
3120
+ timeoutMs: this.connection.timeoutMs,
3121
+ correlationId
3122
+ });
3123
+ if (!result.ok) return result;
3124
+ try {
3125
+ const response = JSON.parse(result.value.body);
3126
+ return ok(mapBachsPayoutListResponse(response, { page, perPage: limit, now: this.clock.now() }));
3127
+ } catch (e) {
3128
+ return err(mapMapperError(e, { provider: this.id, context: "list payouts response" }));
3129
+ }
3130
+ }
3131
+ /**
3132
+ * Resolves the settlement currency for a charge.
3133
+ *
3134
+ * `GET /v1/payments/charges/{charge_id}` publishes it, but it accepts only a
3135
+ * charge id (`ch_`/`chrg_`): passing a checkout id (`chk_`) returns
3136
+ * `404 Charge not found` (verified against the sandbox). A caller who only
3137
+ * holds the checkout id is therefore served from the payment's own currency,
3138
+ * which is the same currency for every non-converted charge.
3139
+ */
3140
+ async resolveSettlement(chargeId, correlationId) {
3141
+ if (!chargeId.startsWith("ch_") && !chargeId.startsWith("chrg_")) {
3142
+ this.logger.debug("charge-status needs a charge id; skipping settlement lookup", {
3143
+ provider: this.id,
3144
+ chargeId,
3145
+ correlationId
3146
+ });
3147
+ return void 0;
3148
+ }
3149
+ const result = await this.httpClient.send({
3150
+ method: "GET",
3151
+ url: `${this.connection.baseUrl}/v1/payments/charges/${encodeURIComponent(chargeId)}`,
3152
+ headers: this.authHeaders(),
3153
+ timeoutMs: this.connection.timeoutMs,
3154
+ correlationId
3155
+ });
3156
+ if (!result.ok) {
3157
+ this.logger.warn("settlement currency unavailable; falling back to the charge currency", {
3158
+ provider: this.id,
3159
+ chargeId,
3160
+ correlationId,
3161
+ error: result.error.code
3162
+ });
3163
+ return void 0;
3164
+ }
3165
+ try {
3166
+ const response = JSON.parse(result.value.body);
3167
+ return mapBachsChargeSettlement(response)?.settlementCurrency;
3168
+ } catch {
3169
+ return void 0;
3170
+ }
3171
+ }
3172
+ /**
3173
+ * `GET /v1/refunds/{id}` carries no currency, so it is read from the
3174
+ * settlement side of the charge, falling back to the payment's own currency.
3175
+ */
3176
+ async resolveRefundCurrency(chargeId, correlationId) {
3177
+ const settlement = await this.resolveSettlement(chargeId, correlationId);
3178
+ if (settlement) return ok(settlement);
3179
+ const paymentResult = await this.httpClient.send({
3180
+ method: "GET",
3181
+ url: `${this.connection.baseUrl}/v1/payments/${encodeURIComponent(chargeId)}`,
3182
+ headers: this.authHeaders(),
3183
+ timeoutMs: this.connection.timeoutMs,
3184
+ correlationId
3185
+ });
3186
+ if (!paymentResult.ok) return paymentResult;
3187
+ try {
3188
+ const payment = JSON.parse(paymentResult.value.body);
3189
+ return ok(Currency(payment.currency));
3190
+ } catch (e) {
3191
+ return err(mapMapperError(e, { provider: this.id, context: "refund currency lookup" }));
3192
+ }
3193
+ }
3194
+ /** Best-effort destination lookup; a failure must never fail the payout read. */
3195
+ async lookupDestination(destinationId, now) {
3196
+ if (!destinationId) return void 0;
3197
+ const result = await this.httpClient.send({
3198
+ method: "GET",
3199
+ url: `${this.connection.baseUrl}/v1/payouts/destinations/${encodeURIComponent(destinationId)}`,
3200
+ headers: this.authHeaders(),
3201
+ timeoutMs: this.connection.timeoutMs
3202
+ });
3203
+ if (!result.ok) return void 0;
3204
+ try {
3205
+ const destination = JSON.parse(result.value.body);
3206
+ return mapBachsDestinationResponse(destination, {
3207
+ name: destination.name,
3208
+ accountNumber: destination.account_number ?? "",
3209
+ bankCode: destination.bank_code ?? "",
3210
+ currency: destination.currency
3211
+ }, now);
3212
+ } catch {
3213
+ return void 0;
3214
+ }
3215
+ }
3216
+ authHeaders() {
3217
+ return {
3218
+ Authorization: `Bearer ${this.connection.secretKey}`
3219
+ };
3220
+ }
3221
+ };
3222
+ function buildCheckoutSessionRequest(req, now) {
3223
+ const productCart = req.products?.length ? req.products.map((item) => ({
3224
+ product_id: item.productId,
3225
+ quantity: item.quantity,
3226
+ amount: item.amount ? toBachsAmount(item.amount) : void 0
3227
+ })) : void 0;
3228
+ let pricing;
3229
+ if (!productCart) {
3230
+ const amount = req.amount;
3231
+ if (!amount) {
3232
+ throw new ValidationError("A Bachs checkout session needs either an amount or a product cart");
3233
+ }
3234
+ pricing = {
3235
+ currency: amount.currency,
3236
+ amount: toBachsAmount(amount),
3237
+ price_type: "fixed"
3238
+ };
3239
+ }
3240
+ const corridorCurrency = req.amount?.currency;
3241
+ return {
3242
+ ...productCart ? { product_cart: productCart } : { pricing },
3243
+ reference: req.reference,
3244
+ success_url: req.callbackUrl,
3245
+ customer: mapCustomerRequest(req.customer),
3246
+ metadata: req.metadata ? { ...req.metadata } : void 0,
3247
+ expires_in_minutes: expiresInMinutes(req.expiresAt, now),
3248
+ payment_method_types: req.channels && corridorCurrency ? mapChannelsToCorridors(req.channels, corridorCurrency) : void 0
3249
+ };
3250
+ }
3251
+ function mapCustomerRequest(customer) {
3252
+ switch (customer.kind) {
3253
+ case "existing":
3254
+ return { customer_id: customer.providerCustomerId };
3255
+ case "inline":
3256
+ return {
3257
+ email: customer.customer.email,
3258
+ name: customer.customer.name,
3259
+ phone_number: customer.customer.phone
3260
+ };
3261
+ case "new":
3262
+ return {
3263
+ email: customer.email,
3264
+ name: customer.name,
3265
+ phone_number: customer.phone
3266
+ };
3267
+ }
3268
+ }
3269
+ function mapChannelsToCorridors(channels, currencyCode) {
3270
+ const corridors = /* @__PURE__ */ new Set();
3271
+ for (const channel of channels) {
3272
+ switch (channel) {
3273
+ case "card": {
3274
+ const corridor = CARD_CORRIDORS[currencyCode];
3275
+ if (corridor) corridors.add(corridor);
3276
+ break;
3277
+ }
3278
+ case "bank_transfer":
3279
+ if (currencyCode === "NGN") corridors.add("NGN_BANK_TRANSFER");
3280
+ break;
3281
+ case "mobile_money": {
3282
+ const corridor = MOMO_CORRIDORS[currencyCode];
3283
+ if (corridor) corridors.add(corridor);
3284
+ break;
3285
+ }
3286
+ }
3287
+ }
3288
+ return corridors.size > 0 ? [...corridors] : void 0;
3289
+ }
3290
+ function buildPayoutDestinationRequest(input) {
3291
+ const type = input.type ?? "bank_account";
3292
+ if (type === "mobile_money" && !input.phoneNumber) {
3293
+ throw new ValidationError(
3294
+ 'A mobile-money payout destination needs phoneNumber (the wallet number); pass { type: "mobile_money", phoneNumber }'
3295
+ );
3296
+ }
3297
+ return {
3298
+ name: input.name,
3299
+ currency: input.currency,
3300
+ type,
3301
+ account_number: input.accountNumber,
3302
+ bank_code: input.bankCode,
3303
+ account_name: input.accountName,
3304
+ bank_name: input.bankName,
3305
+ phone_number: input.phoneNumber,
3306
+ mobile_provider: input.mobileProvider,
3307
+ sort_code: input.sortCode,
3308
+ routing_number: input.routingNumber,
3309
+ scheme: input.scheme,
3310
+ metadata: input.metadata ? { ...input.metadata } : void 0
3311
+ };
3312
+ }
3313
+ function expiresInMinutes(expiresAt, now) {
3314
+ if (!expiresAt) return void 0;
3315
+ const minutes = Math.ceil((expiresAt.getTime() - now.getTime()) / 6e4);
3316
+ return Math.min(Math.max(minutes, 1), 1440);
3317
+ }
3318
+ function fromBachsQuoteAmount(value, currency) {
3319
+ return fromBachsAmount(value, Currency(currency));
3320
+ }
3321
+
3322
+ // src/infrastructure/providers/bachs/register.ts
3323
+ var BACHS_ID = "bachs";
3324
+ registerProvider(BACHS_ID, (config, deps) => new BachsAdapter(config, deps));
3325
+
3326
+ // src/application/use-cases/initialize-payment.ts
3327
+ async function initializePayment(deps, input) {
3328
+ deps.logger.info("use-case: initializePayment", {
3329
+ reference: input.reference
3330
+ });
3331
+ const result = await deps.provider.initialize(input);
3332
+ if (!result.ok) {
3333
+ return result;
3334
+ }
3335
+ deps.eventBus.emit({
3336
+ type: "payment.initialized",
3337
+ payment: result.value,
3338
+ occurredAt: deps.clock.now(),
3339
+ correlationId: input.correlationId ?? deps.idGenerator.generate()
3340
+ });
3341
+ return result;
3342
+ }
3343
+
3344
+ // src/application/use-cases/verify-payment.ts
3345
+ async function verifyPayment(deps, reference) {
3346
+ deps.logger.info("use-case: verifyPayment", { reference });
3347
+ const result = await deps.provider.verify(reference);
3348
+ if (!result.ok) return result;
3349
+ const payment = result.value;
3350
+ if (payment.status.kind === "success") {
3351
+ deps.eventBus.emit({
3352
+ type: "payment.succeeded",
3353
+ payment,
3354
+ occurredAt: deps.clock.now(),
3355
+ correlationId: deps.idGenerator.generate()
3356
+ });
3357
+ } else if (payment.status.kind === "failed") {
3358
+ deps.eventBus.emit({
3359
+ type: "payment.failed",
3360
+ payment,
3361
+ reason: payment.failureReason ?? "unknown",
3362
+ occurredAt: deps.clock.now(),
3363
+ correlationId: deps.idGenerator.generate()
3364
+ });
3365
+ }
3366
+ return result;
3367
+ }
3368
+
3369
+ // src/application/use-cases/fetch-payment.ts
3370
+ async function fetchPayment(deps, id) {
3371
+ deps.logger.info("use-case: fetchPayment", { paymentId: id });
3372
+ return deps.provider.fetch(id);
3373
+ }
3374
+
3375
+ // src/application/use-cases/list-payments.ts
3376
+ async function listPayments(deps, query) {
3377
+ deps.logger.info("use-case: listPayments", {
3378
+ page: query.page ? String(query.page) : "1",
3379
+ perPage: query.perPage ? String(query.perPage) : "50"
3380
+ });
3381
+ return deps.provider.list(query);
3382
+ }
3383
+
3384
+ // src/application/services/payment-service.ts
3385
+ var PaymentService = class {
3386
+ constructor(provider, eventBus, logger, clock, idGenerator) {
3387
+ this.provider = provider;
3388
+ this.eventBus = eventBus;
3389
+ this.logger = logger;
3390
+ this.clock = clock;
3391
+ this.idGenerator = idGenerator;
3392
+ }
3393
+ provider;
3394
+ eventBus;
3395
+ logger;
3396
+ clock;
3397
+ idGenerator;
3398
+ async initialize(req) {
3399
+ return initializePayment(
3400
+ {
3401
+ provider: this.provider,
3402
+ eventBus: this.eventBus,
3403
+ logger: this.logger,
3404
+ clock: this.clock,
3405
+ idGenerator: this.idGenerator
3406
+ },
3407
+ req
3408
+ );
3409
+ }
3410
+ async verify(reference) {
3411
+ return verifyPayment(
3412
+ {
3413
+ provider: this.provider,
3414
+ eventBus: this.eventBus,
3415
+ logger: this.logger,
3416
+ clock: this.clock,
3417
+ idGenerator: this.idGenerator
3418
+ },
3419
+ reference
3420
+ );
3421
+ }
3422
+ async fetch(id) {
3423
+ return fetchPayment({ provider: this.provider, logger: this.logger }, id);
3424
+ }
3425
+ async list(query) {
3426
+ return listPayments({ provider: this.provider, logger: this.logger }, query);
3427
+ }
3428
+ };
3429
+
3430
+ // src/application/mappers/refund-result-mapper.ts
3431
+ function mapRefundResultToRefund(result, providerId, clock) {
3432
+ const status = mapDomainRefundStatus(result.status, result.completedAt, clock);
3433
+ return {
3434
+ id: result.id,
3435
+ paymentId: result.paymentId,
3436
+ providerId,
3437
+ amount: result.amount,
3438
+ reason: result.reason,
3439
+ status,
3440
+ ...result.providerStatus ? { providerStatus: result.providerStatus } : {},
3441
+ initiatedAt: result.createdAt,
3442
+ completedAt: result.completedAt,
3443
+ failureReason: result.status === "failed" ? result.reason : void 0,
3444
+ metadata: Object.freeze({})
3445
+ };
3446
+ }
3447
+ function mapDomainRefundStatus(status, completedAt, clock) {
3448
+ switch (status) {
3449
+ case "succeeded":
3450
+ return { kind: "succeeded", settledAt: completedAt ?? clock.now() };
3451
+ case "failed":
3452
+ return { kind: "failed", reason: "refund_failed", failedAt: completedAt ?? clock.now() };
3453
+ case "pending":
3454
+ case "processing":
3455
+ default:
3456
+ return { kind: "processing" };
3457
+ }
3458
+ }
3459
+
3460
+ // src/application/use-cases/refund-payment.ts
3461
+ async function refundPayment(deps, input) {
3462
+ deps.logger.info("use-case: refundPayment", {
3463
+ provider: deps.provider.id,
3464
+ paymentId: input.paymentId
3465
+ });
3466
+ if (input.amount && input.amount.amount <= 0) {
3467
+ return err(new ValidationError("Refund amount must be greater than zero"));
3468
+ }
3469
+ const correlationId = input.correlationId ?? deps.idGenerator.generate();
3470
+ const providerInput = {
3471
+ paymentId: input.paymentId,
3472
+ amount: input.amount,
3473
+ reason: input.reason,
3474
+ reference: input.reference ?? correlationId,
3475
+ idempotencyKey: input.idempotencyKey,
3476
+ correlationId
3477
+ };
3478
+ const result = await deps.provider.refund(providerInput);
3479
+ if (!result.ok) {
3480
+ deps.logger.error("use-case: refundPayment failed", result.error, {
3481
+ provider: deps.provider.id,
3482
+ paymentId: input.paymentId
3483
+ });
3484
+ return result;
3485
+ }
3486
+ const refund = mapRefundResultToRefund(result.value, deps.provider.id, deps.clock);
3487
+ const now = deps.clock.now();
3488
+ if (refund.status.kind === "succeeded") {
3489
+ deps.eventBus.emit({
3490
+ type: "refund.succeeded",
3491
+ refund,
3492
+ occurredAt: now,
3493
+ correlationId
3494
+ });
3495
+ } else if (refund.status.kind === "failed") {
3496
+ deps.eventBus.emit({
3497
+ type: "refund.failed",
3498
+ refund,
3499
+ reason: refund.failureReason ?? "refund_failed",
3500
+ occurredAt: now,
3501
+ correlationId
3502
+ });
3503
+ } else {
3504
+ deps.eventBus.emit({
3505
+ type: "refund.initiated",
3506
+ refund,
3507
+ occurredAt: now,
3508
+ correlationId
3509
+ });
3510
+ }
3511
+ return ok(refund);
3512
+ }
3513
+
3514
+ // src/application/use-cases/fetch-refund.ts
3515
+ async function fetchRefund(deps, refundId) {
3516
+ deps.logger.info("use-case: fetchRefund", {
3517
+ provider: deps.provider.id,
3518
+ refundId
3519
+ });
3520
+ if (!deps.provider.fetchRefund) {
3521
+ return err(new InternalError(
3522
+ `Provider ${deps.provider.id} does not support fetching individual refunds`
3523
+ ));
3524
+ }
3525
+ const result = await deps.provider.fetchRefund(refundId);
3526
+ if (!result.ok) {
3527
+ deps.logger.error("use-case: fetchRefund failed", result.error, {
3528
+ provider: deps.provider.id,
3529
+ refundId
3530
+ });
3531
+ return result;
3532
+ }
3533
+ const refund = mapRefundResultToRefund(
3534
+ result.value,
3535
+ deps.provider.id,
3536
+ deps.clock
3537
+ );
3538
+ return ok(refund);
3539
+ }
3540
+
3541
+ // src/application/services/refund-service.ts
3542
+ var RefundService = class {
3543
+ provider;
3544
+ eventBus;
3545
+ logger;
3546
+ clock;
3547
+ idGenerator;
3548
+ constructor(provider, deps) {
3549
+ this.provider = provider;
3550
+ this.eventBus = deps.eventBus;
3551
+ this.logger = deps.logger;
3552
+ this.clock = deps.clock;
3553
+ this.idGenerator = deps.idGenerator;
3554
+ }
3555
+ async create(input) {
3556
+ return refundPayment(
3557
+ {
3558
+ provider: this.provider,
3559
+ eventBus: this.eventBus,
3560
+ logger: this.logger.child({ component: "refund-service" }),
3561
+ clock: this.clock,
3562
+ idGenerator: this.idGenerator
3563
+ },
3564
+ input
3565
+ );
3566
+ }
3567
+ async fetch(id) {
3568
+ return fetchRefund(
3569
+ {
3570
+ provider: this.provider,
3571
+ logger: this.logger.child({ component: "refund-service" }),
3572
+ clock: this.clock
3573
+ },
3574
+ id
3575
+ );
3576
+ }
3577
+ };
3578
+
3579
+ // src/application/use-cases/parse-webhook.ts
3580
+ async function parseWebhook(deps, input) {
3581
+ deps.logger.info("use-case: parseWebhook", {
3582
+ provider: deps.provider.id
3583
+ });
3584
+ let bodyString;
3585
+ if (typeof input.rawBody === "string") {
3586
+ bodyString = input.rawBody;
3587
+ } else {
3588
+ const converted = tryConvertBuffer(input.rawBody);
3589
+ if (!converted.ok) return converted;
3590
+ bodyString = converted.value;
3591
+ }
3592
+ const result = await deps.provider.parseWebhook(
3593
+ joinHeaders(input.headers ?? {}),
3594
+ bodyString,
3595
+ input.signature
3596
+ );
3597
+ if (!result.ok) {
3598
+ deps.logger.warn("use-case: parseWebhook failed", {
3599
+ provider: deps.provider.id,
3600
+ error: result.error.message
3601
+ });
3602
+ return result;
3603
+ }
3604
+ const event = result.value;
3605
+ deps.eventBus.emit({
3606
+ type: "webhook.received",
3607
+ provider: event.provider,
3608
+ eventId: event.id,
3609
+ eventType: event.type,
3610
+ originalType: event.originalType,
3611
+ payload: event.payload,
3612
+ occurredAt: deps.clock.now(),
3613
+ correlationId: deps.idGenerator.generate()
3614
+ });
3615
+ return result;
3616
+ }
3617
+ function tryConvertBuffer(body) {
3618
+ try {
3619
+ const decoder = new TextDecoder("utf-8", { fatal: true });
3620
+ return ok(decoder.decode(body));
3621
+ } catch {
3622
+ return err(new WebhookValidationError("Invalid webhook body: not valid UTF-8"));
3623
+ }
3624
+ }
3625
+ function joinHeaders(raw) {
3626
+ const result = {};
3627
+ for (const [key, value] of Object.entries(raw)) {
3628
+ if (value === void 0) continue;
3629
+ result[key] = typeof value === "string" ? value : value.join(", ");
3630
+ }
3631
+ return result;
3632
+ }
3633
+
3634
+ // src/application/services/webhook-service.ts
3635
+ var WebhookService = class {
3636
+ providers;
3637
+ eventBus;
3638
+ logger;
3639
+ clock;
3640
+ idGenerator;
3641
+ constructor(providers, deps) {
3642
+ this.providers = providers;
3643
+ this.eventBus = deps.eventBus;
3644
+ this.logger = deps.logger;
3645
+ this.clock = deps.clock;
3646
+ this.idGenerator = deps.idGenerator;
3647
+ }
3648
+ async receive(input) {
3649
+ const deps = {
3650
+ eventBus: this.eventBus,
3651
+ logger: this.logger.child({ component: "webhook-service" }),
3652
+ clock: this.clock,
3653
+ idGenerator: this.idGenerator
3654
+ };
3655
+ if (input.provider) {
3656
+ const provider = this.providers.get(input.provider);
3657
+ if (!provider) {
3658
+ return err(new WebhookValidationError(
3659
+ `Unknown provider: ${input.provider}`
3660
+ ));
3661
+ }
3662
+ return parseWebhook({ ...deps, provider }, input);
3663
+ }
3664
+ const errors = [];
3665
+ for (const [id, provider] of this.providers) {
3666
+ this.logger.debug("trying webhook provider", { provider: id });
3667
+ const result = await parseWebhook({ ...deps, provider }, input);
3668
+ if (result.ok) {
3669
+ this.logger.info("webhook matched provider", { provider: id });
3670
+ return result;
3671
+ }
3672
+ if (!result.ok) {
3673
+ errors.push(result.error);
3674
+ }
3675
+ }
3676
+ this.logger.warn("webhook rejected by all providers", {
3677
+ count: this.providers.size,
3678
+ errorMessages: errors.map((e) => e.message).join(", ")
3679
+ });
3680
+ return err(new WebhookValidationError(
3681
+ `Webhook rejected by all ${this.providers.size} configured provider(s)`
3682
+ ));
3683
+ }
3684
+ };
3685
+
3686
+ // src/application/use-cases/list-bank-codes.ts
3687
+ async function listBankCodes(deps, currency, options = {}) {
3688
+ deps.logger.info("use-case: listBankCodes", {
3689
+ provider: deps.provider.id,
3690
+ currency,
3691
+ country: options.country
3692
+ });
3693
+ return deps.provider.listBankCodes({ currency, country: options.country });
3694
+ }
3695
+
3696
+ // src/application/use-cases/resolve-account.ts
3697
+ async function resolveAccount(deps, input) {
3698
+ deps.logger.info("use-case: resolveAccount", {
3699
+ provider: deps.provider.id,
3700
+ bankCode: input.bankCode
3701
+ });
3702
+ return deps.provider.resolveAccount(input);
3703
+ }
3704
+
3705
+ // src/application/use-cases/create-recipient.ts
3706
+ async function createRecipient(deps, input) {
3707
+ deps.logger.info("use-case: createRecipient", {
3708
+ provider: deps.provider.id,
3709
+ bankCode: input.bankCode
3710
+ });
3711
+ return deps.provider.createRecipient(input);
3712
+ }
3713
+
3714
+ // src/application/use-cases/create-transfer-quote.ts
3715
+ async function createTransferQuote(deps, input) {
3716
+ deps.logger.info("use-case: createTransferQuote", {
3717
+ provider: deps.provider.id,
3718
+ fromCurrency: input.fromCurrency,
3719
+ toCurrency: input.toCurrency
3720
+ });
3721
+ if (!deps.provider.createTransferQuote) {
3722
+ return err(
3723
+ new UnsupportedProviderError(
3724
+ `Provider ${deps.provider.id} does not support cross-currency payout quotes`,
3725
+ { provider: deps.provider.id }
3726
+ )
3727
+ );
3728
+ }
3729
+ return deps.provider.createTransferQuote(input);
3730
+ }
3731
+
3732
+ // src/application/use-cases/initiate-transfer.ts
3733
+ async function initiateTransfer(deps, input) {
3734
+ deps.logger.info("use-case: initiateTransfer", {
3735
+ provider: deps.provider.id,
3736
+ reference: input.reference
3737
+ });
3738
+ const result = await deps.provider.initiateTransfer(input);
3739
+ if (!result.ok) {
3740
+ deps.logger.error("use-case: initiateTransfer failed", result.error, {
3741
+ provider: deps.provider.id,
3742
+ reference: input.reference
3743
+ });
3744
+ return result;
3745
+ }
3746
+ const correlationId = input.correlationId ?? deps.idGenerator.generate();
3747
+ if (result.value.status.kind === "failed") {
3748
+ deps.eventBus.emit({
3749
+ type: "transfer.failed",
3750
+ transfer: result.value,
3751
+ reason: result.value.failureReason ?? "transfer_failed",
3752
+ occurredAt: deps.clock.now(),
3753
+ correlationId
3754
+ });
3755
+ } else {
3756
+ deps.eventBus.emit({
3757
+ type: "transfer.initiated",
3758
+ transfer: result.value,
3759
+ occurredAt: deps.clock.now(),
3760
+ correlationId
3761
+ });
3762
+ }
3763
+ return result;
3764
+ }
3765
+
3766
+ // src/application/use-cases/fetch-transfer.ts
3767
+ async function fetchTransfer(deps, id) {
3768
+ deps.logger.info("use-case: fetchTransfer", {
3769
+ provider: deps.provider.id,
3770
+ transferId: id
3771
+ });
3772
+ return deps.provider.fetchTransfer(id);
3773
+ }
3774
+
3775
+ // src/application/use-cases/list-transfers.ts
3776
+ async function listTransfers(deps, query) {
3777
+ deps.logger.info("use-case: listTransfers", {
3778
+ provider: deps.provider.id
3779
+ });
3780
+ return deps.provider.listTransfers(query);
3781
+ }
3782
+
3783
+ // src/application/services/transfer-service.ts
3784
+ var TransferService = class {
3785
+ constructor(provider, eventBus, logger, clock, idGenerator) {
3786
+ this.provider = provider;
3787
+ this.eventBus = eventBus;
3788
+ this.logger = logger;
3789
+ this.clock = clock;
3790
+ this.idGenerator = idGenerator;
3791
+ }
3792
+ provider;
3793
+ eventBus;
3794
+ logger;
3795
+ clock;
3796
+ idGenerator;
3797
+ async listBankCodes(currency, options = {}) {
3798
+ return listBankCodes(
3799
+ { provider: this.provider, logger: this.logger },
3800
+ currency,
3801
+ options
3802
+ );
3803
+ }
3804
+ async resolveAccount(input) {
3805
+ return resolveAccount(
3806
+ { provider: this.provider, logger: this.logger },
3807
+ input
3808
+ );
3809
+ }
3810
+ async createRecipient(input) {
3811
+ return createRecipient(
3812
+ { provider: this.provider, logger: this.logger, clock: this.clock },
3813
+ input
3814
+ );
3815
+ }
3816
+ /**
3817
+ * Locks an exchange rate for a cross-currency payout. Pass the returned id
3818
+ * as `quoteId` to {@link initiate} (and omit `amount`).
3819
+ */
3820
+ async createQuote(input) {
3821
+ return createTransferQuote(
3822
+ { provider: this.provider, logger: this.logger },
3823
+ input
3824
+ );
3825
+ }
3826
+ async initiate(input) {
3827
+ return initiateTransfer(
3828
+ {
3829
+ provider: this.provider,
3830
+ eventBus: this.eventBus,
3831
+ logger: this.logger,
3832
+ clock: this.clock,
3833
+ idGenerator: this.idGenerator
3834
+ },
3835
+ input
3836
+ );
3837
+ }
3838
+ async fetch(id) {
3839
+ return fetchTransfer(
3840
+ { provider: this.provider, logger: this.logger },
3841
+ id
3842
+ );
3843
+ }
3844
+ async list(query) {
3845
+ return listTransfers(
3846
+ { provider: this.provider, logger: this.logger },
3847
+ query
3848
+ );
3849
+ }
3850
+ };
3851
+
3852
+ // src/application/services/subscription-facade-deps.ts
3853
+ function unsupportedProviderError(providerId, feature) {
3854
+ return new UnsupportedProviderError(
3855
+ `Provider "${providerId}" does not support ${feature}. Configure a provider that implements the subscription capability (Bachs does).`,
3856
+ { provider: providerId }
3857
+ );
3858
+ }
3859
+
3860
+ // src/application/services/product-service.ts
3861
+ var ProductService = class {
3862
+ providerId;
3863
+ products;
3864
+ logger;
3865
+ constructor(deps) {
3866
+ this.providerId = deps.providerId;
3867
+ this.products = deps.subscriptionProvider;
3868
+ this.logger = deps.logger;
3869
+ }
3870
+ async list(query = {}) {
3871
+ if (!this.products) return err(unsupportedProviderError(this.providerId, "products"));
3872
+ this.logger.info("listing products", { provider: this.providerId, ...query });
3873
+ return this.products.listProducts(query);
3874
+ }
3875
+ async fetch(id) {
3876
+ if (!this.products) return err(unsupportedProviderError(this.providerId, "products"));
3877
+ this.logger.info("fetching product", { provider: this.providerId, productId: id });
3878
+ return this.products.fetchProduct(id);
3879
+ }
3880
+ async create(input) {
3881
+ if (!this.products) return err(unsupportedProviderError(this.providerId, "products"));
3882
+ this.logger.info("creating product", {
3883
+ provider: this.providerId,
3884
+ recurring: input.billingCycle !== void 0
3885
+ });
3886
+ return this.products.createProduct(input);
3887
+ }
3888
+ async update(id, input) {
3889
+ if (!this.products) return err(unsupportedProviderError(this.providerId, "products"));
3890
+ this.logger.info("updating product", { provider: this.providerId, productId: id });
3891
+ return this.products.updateProduct(id, input);
3892
+ }
3893
+ /** Archived products stop selling but keep billing existing subscriptions. */
3894
+ async archive(id) {
3895
+ if (!this.products) return err(unsupportedProviderError(this.providerId, "products"));
3896
+ this.logger.info("archiving product", { provider: this.providerId, productId: id });
3897
+ return this.products.archiveProduct(id);
3898
+ }
3899
+ async unarchive(id) {
3900
+ if (!this.products) return err(unsupportedProviderError(this.providerId, "products"));
3901
+ this.logger.info("unarchiving product", { provider: this.providerId, productId: id });
3902
+ return this.products.unarchiveProduct(id);
3903
+ }
3904
+ };
3905
+
3906
+ // src/application/services/subscription-service.ts
3907
+ var SubscriptionService = class {
3908
+ providerId;
3909
+ subscriptions;
3910
+ logger;
3911
+ eventBus;
3912
+ clock;
3913
+ idGenerator;
3914
+ constructor(deps) {
3915
+ this.providerId = deps.providerId;
3916
+ this.subscriptions = deps.subscriptionProvider;
3917
+ this.logger = deps.logger;
3918
+ this.eventBus = deps.eventBus;
3919
+ this.clock = deps.clock;
3920
+ this.idGenerator = deps.idGenerator;
3921
+ }
3922
+ async list(query = {}) {
3923
+ if (!this.subscriptions) return err(unsupportedProviderError(this.providerId, "subscriptions"));
3924
+ this.logger.info("listing subscriptions", { provider: this.providerId, ...query });
3925
+ return this.subscriptions.listSubscriptions(query);
3926
+ }
3927
+ async fetch(id) {
3928
+ if (!this.subscriptions) return err(unsupportedProviderError(this.providerId, "subscriptions"));
3929
+ this.logger.info("fetching subscription", { provider: this.providerId, subscriptionId: id });
3930
+ return this.subscriptions.fetchSubscription(id);
3931
+ }
3932
+ /**
3933
+ * Applies exactly one change. Bachs rejects combined intents, so combining
3934
+ * `productId`, `trialEnd`, `paymentMethodId`, or `metadata` in one call
3935
+ * throws rather than sending a request the provider will refuse.
3936
+ *
3937
+ * Emits `subscription.updated` on success.
3938
+ */
3939
+ async update(id, input) {
3940
+ if (!this.subscriptions) return err(unsupportedProviderError(this.providerId, "subscriptions"));
3941
+ const intents = [
3942
+ input.productId !== void 0,
3943
+ input.trialEnd !== void 0,
3944
+ input.paymentMethodId !== void 0,
3945
+ input.metadata !== void 0
3946
+ ].filter(Boolean).length;
3947
+ if (intents === 0) {
3948
+ throw new ValidationError(
3949
+ "Subscription update requires exactly one intent: productId, trialEnd, paymentMethodId, or metadata"
3950
+ );
3951
+ }
3952
+ if (intents > 1) {
3953
+ throw new ValidationError(
3954
+ "Bachs accepts exactly one subscription intent per call; send productId, trialEnd, paymentMethodId, and metadata in separate calls"
3955
+ );
3956
+ }
3957
+ this.logger.info("updating subscription", { provider: this.providerId, subscriptionId: id });
3958
+ const result = await this.subscriptions.updateSubscription(id, input);
3959
+ if (result.ok) this.emit("subscription.updated", result.value);
3960
+ return result;
3961
+ }
3962
+ /**
3963
+ * Cancels immediately, or at the period end when `atPeriodEnd` is true.
3964
+ * Emits `subscription.canceled` on success.
3965
+ */
3966
+ async cancel(id, input = {}) {
3967
+ if (!this.subscriptions) return err(unsupportedProviderError(this.providerId, "subscriptions"));
3968
+ this.logger.info("canceling subscription", {
3969
+ provider: this.providerId,
3970
+ subscriptionId: id,
3971
+ atPeriodEnd: input.atPeriodEnd ?? false
3972
+ });
3973
+ const result = await this.subscriptions.cancelSubscription(id, input);
3974
+ if (result.ok) this.emit("subscription.canceled", result.value);
3975
+ return result;
3976
+ }
3977
+ emit(type, subscription) {
3978
+ if (!this.eventBus) return;
3979
+ const occurredAt = this.clock?.now() ?? /* @__PURE__ */ new Date();
3980
+ const correlationId = this.idGenerator?.generate() ?? "unknown";
3981
+ if (type === "subscription.updated") {
3982
+ this.eventBus.emit({ type: "subscription.updated", subscription, occurredAt, correlationId });
3983
+ } else {
3984
+ this.eventBus.emit({ type: "subscription.canceled", subscription, occurredAt, correlationId });
3985
+ }
3986
+ }
3987
+ };
3988
+
3989
+ // src/application/services/customer-service.ts
3990
+ var CustomerService = class {
3991
+ providerId;
3992
+ customers;
3993
+ logger;
3994
+ constructor(deps) {
3995
+ this.providerId = deps.providerId;
3996
+ this.customers = deps.subscriptionProvider;
3997
+ this.logger = deps.logger;
3998
+ }
3999
+ async list(query = {}) {
4000
+ if (!this.customers) return err(unsupportedProviderError(this.providerId, "customers"));
4001
+ this.logger.info("listing customers", { provider: this.providerId, ...query });
4002
+ return this.customers.listCustomers(query);
4003
+ }
4004
+ async fetch(id) {
4005
+ if (!this.customers) return err(unsupportedProviderError(this.providerId, "customers"));
4006
+ this.logger.info("fetching customer", { provider: this.providerId, customerId: id });
4007
+ return this.customers.fetchCustomer(id);
4008
+ }
4009
+ async create(input) {
4010
+ if (!this.customers) return err(unsupportedProviderError(this.providerId, "customers"));
4011
+ this.logger.info("creating customer", { provider: this.providerId });
4012
+ return this.customers.createCustomer(input);
4013
+ }
4014
+ async update(id, input) {
4015
+ if (!this.customers) return err(unsupportedProviderError(this.providerId, "customers"));
4016
+ this.logger.info("updating customer", { provider: this.providerId, customerId: id });
4017
+ return this.customers.updateCustomer(id, input);
4018
+ }
4019
+ /**
4020
+ * Mints a short-lived, pre-authenticated portal URL for one customer.
4021
+ *
4022
+ * The URL is a credential. It is deliberately not logged, and callers must
4023
+ * not cache or persist it — mint a fresh session per request.
4024
+ */
4025
+ async createPortalSession(customerId) {
4026
+ if (!this.customers) return err(unsupportedProviderError(this.providerId, "the customer portal"));
4027
+ this.logger.info("creating customer portal session", {
4028
+ provider: this.providerId,
4029
+ customerId
4030
+ });
4031
+ return this.customers.createPortalSession(customerId);
4032
+ }
4033
+ };
4034
+
4035
+ // src/application/ports/subscription-provider.ts
4036
+ function isSubscriptionProvider(value) {
4037
+ const candidate = value;
4038
+ return typeof candidate?.listSubscriptions === "function" && typeof candidate.createProduct === "function";
4039
+ }
4040
+
4041
+ // src/application/services/provider-registry.ts
4042
+ var ProviderRegistry = class {
4043
+ constructor(factory, providers, logger) {
4044
+ this.factory = factory;
4045
+ this.providers = providers;
4046
+ this.logger = logger;
4047
+ }
4048
+ factory;
4049
+ providers;
4050
+ logger;
4051
+ get(id) {
4052
+ const provider = id;
4053
+ const instance = this.providers.get(provider);
4054
+ if (!instance) {
4055
+ const available = [...this.providers.keys()].join(", ") || "none";
4056
+ throw new ConfigurationError(
4057
+ `Unknown provider "${id}". Available: ${available}`
4058
+ );
4059
+ }
4060
+ return instance;
4061
+ }
4062
+ list() {
4063
+ return this.factory.supported();
4064
+ }
4065
+ capabilities(id) {
4066
+ return this.get(id).capabilities;
4067
+ }
4068
+ async health(id) {
4069
+ return this.get(id).health();
4070
+ }
4071
+ };
4072
+
4073
+ // src/application/services/event-subscription-view.ts
4074
+ var EventSubscriptionView = class {
4075
+ constructor(bus) {
4076
+ this.bus = bus;
4077
+ }
4078
+ bus;
4079
+ on(type, handler) {
4080
+ return this.bus.on(type, handler);
4081
+ }
4082
+ onAny(handler) {
4083
+ return this.bus.onAny(handler);
4084
+ }
4085
+ };
4086
+
4087
+ // src/infrastructure/http/retry-policy.ts
4088
+ var DEFAULT_RETRY_DELAY_MS = 500;
4089
+ var RETRY_JITTER_MS = 250;
4090
+ var MAX_RETRY_AFTER_MS = 1e4;
4091
+ function parseRetryAfterMs(header, nowMs) {
4092
+ if (header === void 0) return void 0;
4093
+ const trimmed = header.trim();
4094
+ if (trimmed.length === 0) return void 0;
4095
+ if (/^\d+$/.test(trimmed)) {
4096
+ return Number(trimmed) * 1e3;
4097
+ }
4098
+ const date = new Date(trimmed);
4099
+ if (Number.isNaN(date.getTime()) || !/[A-Za-z]/.test(trimmed)) return void 0;
4100
+ return Math.max(0, date.getTime() - nowMs);
4101
+ }
4102
+ function computeRetryDelayMs(input = {}) {
4103
+ const base = input.baseDelayMs ?? DEFAULT_RETRY_DELAY_MS;
4104
+ const jitter = input.jitterMs ?? RETRY_JITTER_MS;
4105
+ const max = input.maxDelayMs ?? MAX_RETRY_AFTER_MS;
4106
+ const random = input.random ?? Math.random;
4107
+ const candidate = input.retryAfterMs !== void 0 ? input.retryAfterMs : base + Math.floor(random() * jitter);
4108
+ return Math.min(Math.max(candidate, 0), max);
4109
+ }
4110
+
4111
+ // src/infrastructure/http/fetch-http-client.ts
4112
+ var IDEMPOTENT_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
4113
+ var DEFAULT_TIMEOUT_MS2 = 3e4;
4114
+ var DEFAULT_MAX_RETRIES = 1;
4115
+ var FetchHttpClient = class {
4116
+ baseUrl;
4117
+ defaultTimeoutMs;
4118
+ maxRetries;
4119
+ retryBaseDelayMs;
4120
+ correlationId;
4121
+ provider;
4122
+ logger;
4123
+ constructor(config = {}) {
4124
+ this.baseUrl = config.baseUrl;
4125
+ this.defaultTimeoutMs = config.defaultTimeoutMs ?? DEFAULT_TIMEOUT_MS2;
4126
+ this.maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;
4127
+ this.retryBaseDelayMs = config.retryBaseDelayMs;
4128
+ this.correlationId = config.correlationId;
4129
+ this.provider = config.provider;
4130
+ this.logger = config.logger;
4131
+ }
4132
+ async send(request) {
4133
+ const builtUrl = this.tryBuildUrl(request.url);
4134
+ if (!builtUrl.ok) return builtUrl;
4135
+ const url = builtUrl.value;
4136
+ const timeoutMs = request.timeoutMs ?? this.defaultTimeoutMs;
4137
+ const isRetryable = request.isRetryable ?? IDEMPOTENT_METHODS.has(request.method);
4138
+ let lastError;
4139
+ const maxAttempts = isRetryable ? 1 + this.maxRetries : 1;
4140
+ for (let attempt2 = 0; attempt2 < maxAttempts; attempt2++) {
4141
+ if (attempt2 > 0) {
4142
+ const delayMs = computeRetryDelayMs({
4143
+ retryAfterMs: retryAfterFromError(lastError),
4144
+ baseDelayMs: this.retryBaseDelayMs
4145
+ });
4146
+ this.logger?.debug("retrying HTTP request", {
4147
+ method: request.method,
4148
+ url,
4149
+ attempt: String(attempt2),
4150
+ delayMs
4151
+ });
4152
+ await sleep(delayMs);
4153
+ }
4154
+ const result = await this.attempt(request, url, timeoutMs, attempt2);
4155
+ if (result.ok) return result;
4156
+ lastError = result.error;
4157
+ if (!isRetryable || !isRetryableError(lastError)) {
4158
+ return result;
4159
+ }
4160
+ }
4161
+ this.logger?.error("HTTP request failed after retries", lastError, {
4162
+ method: request.method,
4163
+ url
4164
+ });
4165
+ return err(lastError);
4166
+ }
4167
+ async attempt(request, url, timeoutMs, _attempt) {
4168
+ const controller = new AbortController();
4169
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
4170
+ try {
4171
+ const headers = {
4172
+ "Content-Type": "application/json",
4173
+ Accept: "application/json",
4174
+ ...request.headers
4175
+ };
4176
+ if (request.correlationId) {
4177
+ headers["X-TEC-Correlation-Id"] = request.correlationId;
4178
+ }
4179
+ if (request.idempotencyKey) {
4180
+ headers["Idempotency-Key"] = request.idempotencyKey;
4181
+ }
4182
+ const response = await fetch(url, {
4183
+ method: request.method,
4184
+ headers,
4185
+ body: request.body,
4186
+ signal: controller.signal,
4187
+ // API endpoints must not redirect: a 30x can point at http:// (breaking
4188
+ // the HTTPS-only rule) or at another origin. Surface it as an error.
4189
+ redirect: "manual"
4190
+ });
4191
+ const body = await response.text();
4192
+ if (response.status >= 300 && response.status < 400) {
4193
+ return err(new ProviderError(
4194
+ `Provider responded with a redirect (${response.status}); redirects are not followed`,
4195
+ {
4196
+ provider: this.provider,
4197
+ providerCode: String(response.status),
4198
+ httpStatus: response.status,
4199
+ isRetryable: false,
4200
+ meta: { url, status: response.status }
4201
+ }
4202
+ ));
4203
+ }
4204
+ if (!response.ok) {
4205
+ return this.mapError(response.status, body, url, response.headers);
4206
+ }
4207
+ const respHeaders = {};
4208
+ response.headers.forEach((value, key) => {
4209
+ respHeaders[key] = value;
4210
+ });
4211
+ return ok({
4212
+ status: response.status,
4213
+ headers: respHeaders,
4214
+ body
4215
+ });
4216
+ } catch (e) {
4217
+ if (isAbortError(e)) {
4218
+ return err(new TimeoutError(`Request to ${url} timed out after ${timeoutMs}ms`, {
4219
+ provider: this.provider,
4220
+ meta: { url, timeoutMs }
4221
+ }));
4222
+ }
4223
+ const message = e instanceof Error ? e.message : String(e);
4224
+ return err(new NetworkError(`Network error for ${url}: ${message}`, {
4225
+ provider: this.provider,
4226
+ meta: { url },
4227
+ cause: e instanceof Error ? e : void 0
4228
+ }));
4229
+ } finally {
4230
+ clearTimeout(timer);
4231
+ }
4232
+ }
4233
+ /**
4234
+ * Resolves the request URL, reporting an insecure one as a `Result` rather
4235
+ * than throwing out of `send`. `createPaymentClient` already rejects insecure
4236
+ * base URLs at construction; this is the last line of defence for URLs built
4237
+ * by an adapter.
4238
+ */
4239
+ tryBuildUrl(pathOrUrl) {
4240
+ const resolved = pathOrUrl.startsWith("http://") || pathOrUrl.startsWith("https://") ? pathOrUrl : this.baseUrl ? `${this.baseUrl.replace(/\/$/, "")}/${pathOrUrl.replace(/^\//, "")}` : pathOrUrl;
4241
+ if (resolved.startsWith("http://")) {
4242
+ return err(new NetworkError(`HTTP URLs are not allowed: ${resolved}`, {
4243
+ provider: this.provider,
4244
+ meta: { url: resolved }
4245
+ }));
4246
+ }
4247
+ return ok(resolved);
4248
+ }
4249
+ mapError(status, body, url, headers) {
4250
+ const meta = { url, status, body: body.slice(0, 500) };
4251
+ const retryAfterMs = parseRetryAfterMs(headers.get("retry-after") ?? void 0, Date.now());
4252
+ if (retryAfterMs !== void 0 && (status === 429 || status >= 500)) {
4253
+ meta["retryAfterMs"] = retryAfterMs;
4254
+ }
4255
+ if (status >= 500) {
4256
+ return err(new ProviderUnavailableError(
4257
+ `Provider returned ${status} for ${url}`,
4258
+ {
4259
+ provider: this.provider,
4260
+ providerCode: String(status),
4261
+ meta
4262
+ }
4263
+ ));
4264
+ }
4265
+ if (status === 429) {
4266
+ return err(new ProviderRateLimitError(
4267
+ `Rate limited (${status}) by provider`,
4268
+ {
4269
+ provider: this.provider,
4270
+ providerCode: String(status),
4271
+ meta
4272
+ }
4273
+ ));
4274
+ }
4275
+ if (status === 400) {
4276
+ return err(new ProviderBadRequestError(
4277
+ `Bad request (${status}) to provider`,
4278
+ {
4279
+ provider: this.provider,
4280
+ providerCode: String(status),
4281
+ meta
4282
+ }
4283
+ ));
4284
+ }
4285
+ if (status === 401 || status === 403) {
4286
+ return err(new ProviderUnauthorizedError(
4287
+ `Unauthorized (${status}) to provider`,
4288
+ {
4289
+ provider: this.provider,
4290
+ providerCode: String(status),
4291
+ httpStatus: status,
4292
+ meta
4293
+ }
4294
+ ));
4295
+ }
4296
+ if (status === 404) {
4297
+ return err(new ProviderNotFoundError(
4298
+ `Not found (${status}) at provider`,
4299
+ {
4300
+ provider: this.provider,
4301
+ providerCode: String(status),
4302
+ meta
4303
+ }
4304
+ ));
4305
+ }
4306
+ if (status === 409) {
4307
+ return err(new ProviderConflictError(
4308
+ `Conflict (${status}) at provider`,
4309
+ {
4310
+ provider: this.provider,
4311
+ providerCode: String(status),
4312
+ meta
4313
+ }
4314
+ ));
4315
+ }
4316
+ return err(new ProviderError(
4317
+ `Provider returned error ${status}`,
4318
+ {
4319
+ provider: this.provider,
4320
+ providerCode: String(status),
4321
+ httpStatus: status,
4322
+ isRetryable: false,
4323
+ meta
4324
+ }
4325
+ ));
4326
+ }
4327
+ };
4328
+ function isAbortError(e) {
4329
+ if (e instanceof Error && e.name === "AbortError") return true;
4330
+ return false;
4331
+ }
4332
+ function retryAfterFromError(error) {
4333
+ const value = error?.meta?.["retryAfterMs"];
4334
+ return typeof value === "number" ? value : void 0;
4335
+ }
4336
+ function isRetryableError(error) {
4337
+ if (error.isRetryable) return true;
4338
+ if (error instanceof ProviderUnavailableError) return true;
4339
+ if (error instanceof ProviderRateLimitError) return true;
4340
+ if (error instanceof NetworkError) return true;
4341
+ if (error instanceof TimeoutError) return true;
4342
+ return false;
4343
+ }
4344
+ function sleep(ms) {
4345
+ return new Promise((resolve) => setTimeout(resolve, ms));
4346
+ }
4347
+
4348
+ // src/infrastructure/logging/console-logger.ts
4349
+ var SENSITIVE_RE = /(secret|authorization|password|signature|api[_-]?key|card|pan|cvv)/i;
4350
+ var REPLACEMENT = "[REDACTED]";
4351
+ function redactValue(value) {
4352
+ if (Array.isArray(value)) {
4353
+ return value.map(redactValue);
4354
+ }
4355
+ if (value !== null && typeof value === "object") {
4356
+ return redact(value);
4357
+ }
4358
+ return value;
4359
+ }
4360
+ function redact(obj) {
4361
+ const result = {};
4362
+ for (const key of Object.keys(obj)) {
4363
+ const value = obj[key];
4364
+ if (SENSITIVE_RE.test(key)) {
4365
+ result[key] = REPLACEMENT;
4366
+ } else {
4367
+ result[key] = redactValue(value);
4368
+ }
4369
+ }
4370
+ return result;
4371
+ }
4372
+ function formatJson(entry) {
4373
+ try {
4374
+ return JSON.stringify(redact(entry));
4375
+ } catch {
4376
+ return JSON.stringify({ message: "log serialization error" });
4377
+ }
4378
+ }
4379
+ var ConsoleLogger = class _ConsoleLogger {
4380
+ bindings;
4381
+ constructor(bindings = {}) {
4382
+ this.bindings = bindings;
4383
+ }
4384
+ debug(message, context) {
4385
+ console.log(formatJson({ level: "debug", message, ...this.bindings, ...context }));
4386
+ }
4387
+ info(message, context) {
4388
+ console.log(formatJson({ level: "info", message, ...this.bindings, ...context }));
4389
+ }
4390
+ warn(message, context) {
4391
+ console.warn(formatJson({ level: "warn", message, ...this.bindings, ...context }));
4392
+ }
4393
+ error(message, error, context) {
4394
+ const errObj = { level: "error", message, ...this.bindings, ...context };
4395
+ if (error instanceof Error) {
4396
+ errObj.error = { name: error.name, message: error.message };
4397
+ } else if (error !== void 0) {
4398
+ errObj.error = String(error);
4399
+ }
4400
+ console.error(formatJson(errObj));
4401
+ }
4402
+ child(bindings) {
4403
+ return new _ConsoleLogger({ ...this.bindings, ...bindings });
4404
+ }
4405
+ };
4406
+
4407
+ // src/infrastructure/logging/noop-logger.ts
4408
+ var NoopLogger = class {
4409
+ debug(_message, _context) {
4410
+ }
4411
+ info(_message, _context) {
4412
+ }
4413
+ warn(_message, _context) {
4414
+ }
4415
+ error(_message, _error, _context) {
4416
+ }
4417
+ child(_bindings) {
4418
+ return this;
4419
+ }
4420
+ };
4421
+
4422
+ // src/infrastructure/clock/system-clock.ts
4423
+ var SystemClock = class {
4424
+ now() {
4425
+ return /* @__PURE__ */ new Date();
4426
+ }
4427
+ };
4428
+ var UlidIdGenerator = class {
4429
+ generate() {
4430
+ return crypto.randomUUID();
4431
+ }
4432
+ };
4433
+
4434
+ // src/infrastructure/event-bus/in-memory-event-bus.ts
4435
+ var InMemoryEventBus = class {
4436
+ subscriptions = [];
4437
+ logger;
4438
+ dispatching = false;
4439
+ pending = [];
4440
+ constructor(logger) {
4441
+ this.logger = logger;
4442
+ }
4443
+ emit(event) {
4444
+ if (this.dispatching) {
4445
+ this.pending.push(event);
4446
+ return;
4447
+ }
4448
+ this.dispatching = true;
4449
+ try {
4450
+ this.dispatch(event);
4451
+ } finally {
4452
+ this.dispatching = false;
4453
+ while (this.pending.length > 0) {
4454
+ const next = this.pending.shift();
4455
+ this.emit(next);
4456
+ }
4457
+ }
4458
+ }
4459
+ on(type, handler) {
4460
+ const sub = { type, handler };
4461
+ this.subscriptions.push(sub);
4462
+ return () => {
4463
+ const idx = this.subscriptions.indexOf(sub);
4464
+ if (idx >= 0) this.subscriptions.splice(idx, 1);
4465
+ };
4466
+ }
4467
+ onAny(handler) {
4468
+ const sub = { type: "*", handler };
4469
+ this.subscriptions.push(sub);
4470
+ return () => {
4471
+ const idx = this.subscriptions.indexOf(sub);
4472
+ if (idx >= 0) this.subscriptions.splice(idx, 1);
4473
+ };
4474
+ }
4475
+ dispatch(event) {
4476
+ for (const sub of [...this.subscriptions]) {
4477
+ if (sub.type !== "*" && sub.type !== event.type) continue;
4478
+ try {
4479
+ const result = sub.handler(event);
4480
+ if (result instanceof Promise) {
4481
+ result.catch((err2) => {
4482
+ this.logger.error("event handler rejected", err2, {
4483
+ eventType: event.type,
4484
+ correlationId: event.correlationId
4485
+ });
4486
+ });
4487
+ }
4488
+ } catch (err2) {
4489
+ this.logger.error("event handler threw", err2 instanceof Error ? err2 : void 0, {
4490
+ eventType: event.type,
4491
+ correlationId: event.correlationId
4492
+ });
4493
+ }
4494
+ }
4495
+ }
4496
+ };
4497
+
4498
+ // src/public-api/client.ts
4499
+ function createLogger(config) {
4500
+ if (config.logger) return config.logger;
4501
+ if (config.logging?.level === "debug") {
4502
+ return new ConsoleLogger({ provider: "tec-payment" });
4503
+ }
4504
+ return new NoopLogger();
4505
+ }
4506
+ function resolveRetryConfig(config) {
4507
+ const maxRetries = config.retry?.maxRetries;
4508
+ const delayMs = config.retry?.delayMs;
4509
+ if (maxRetries !== void 0 && (!Number.isInteger(maxRetries) || maxRetries < 0)) {
4510
+ throw new ConfigurationError(
4511
+ `retry.maxRetries must be a non-negative integer, got ${String(maxRetries)}`
4512
+ );
4513
+ }
4514
+ if (delayMs !== void 0 && (!Number.isFinite(delayMs) || delayMs < 0)) {
4515
+ throw new ConfigurationError(
4516
+ `retry.delayMs must be a non-negative number, got ${String(delayMs)}`
4517
+ );
4518
+ }
4519
+ return { maxRetries: maxRetries ?? 1, delayMs };
4520
+ }
4521
+ function resolveHttpConfig(config) {
4522
+ const timeoutMs = config.http?.timeoutMs;
4523
+ if (timeoutMs !== void 0 && (!Number.isInteger(timeoutMs) || timeoutMs <= 0)) {
4524
+ throw new ConfigurationError(
4525
+ `http.timeoutMs must be a positive integer, got ${String(timeoutMs)}`
4526
+ );
4527
+ }
4528
+ return { timeoutMs, baseUrl: config.http?.baseUrl };
4529
+ }
4530
+ function assertSecureBaseUrl(providerId, baseUrl, allowInsecure) {
4531
+ if (!baseUrl || !baseUrl.startsWith("http://")) return;
4532
+ if (allowInsecure) return;
4533
+ throw new ConfigurationError(
4534
+ `Provider "${providerId}" is configured with an insecure base URL (${baseUrl}). Set allowInsecureBaseUrl: true on that provider to use it (tests and local stubs only), or use an https URL.`
4535
+ );
4536
+ }
4537
+ function createPaymentClient(config) {
4538
+ const logger = createLogger(config);
4539
+ if (!config.providers || Object.keys(config.providers).length === 0) {
4540
+ throw new ConfigurationError("At least one provider must be configured");
4541
+ }
4542
+ const retry = resolveRetryConfig(config);
4543
+ const httpDefaults = resolveHttpConfig(config);
4544
+ const clock = config.clock ?? new SystemClock();
4545
+ const idGenerator = config.idGenerator ?? new UlidIdGenerator();
4546
+ const eventBus = config.eventBus ?? new InMemoryEventBus(
4547
+ logger.child({ component: "event-bus" })
4548
+ );
4549
+ const providerFactory = createProviderFactory();
4550
+ const providerMap = /* @__PURE__ */ new Map();
4551
+ for (const [providerId, providerConfig] of Object.entries(config.providers)) {
4552
+ if (!providerConfig || providerConfig.enabled === false) continue;
4553
+ const baseUrl = providerConfig.baseUrl ?? httpDefaults.baseUrl;
4554
+ assertSecureBaseUrl(providerId, baseUrl, providerConfig.allowInsecureBaseUrl);
4555
+ const httpClient = config.httpClient ?? new FetchHttpClient({
4556
+ baseUrl,
4557
+ defaultTimeoutMs: providerConfig.timeoutMs ?? httpDefaults.timeoutMs,
4558
+ maxRetries: retry.maxRetries,
4559
+ retryBaseDelayMs: retry.delayMs,
4560
+ provider: providerId,
4561
+ logger: logger.child({ provider: providerId })
4562
+ });
4563
+ const webhookSecret = providerConfig.webhookSecret ?? providerConfig.secretKey;
4564
+ const webhookVerifier = new HmacWebhookVerifier(webhookSecret, "sha512");
4565
+ const provider = providerFactory.create(providerId, providerConfig, {
4566
+ httpClient,
4567
+ logger: logger.child({ provider: providerId }),
4568
+ clock,
4569
+ idGenerator,
4570
+ eventBus,
4571
+ webhookVerifier
4572
+ });
4573
+ providerMap.set(providerId, provider);
4574
+ }
4575
+ if (providerMap.size === 0) {
4576
+ throw new ConfigurationError("No providers are enabled. Check your configuration.");
4577
+ }
4578
+ const defaultProviderId = config.defaultProvider ? config.defaultProvider : providerMap.keys().next().value;
4579
+ if (!providerMap.has(defaultProviderId)) {
4580
+ throw new ConfigurationError(
4581
+ `Default provider "${config.defaultProvider}" is not configured or enabled.`
4582
+ );
4583
+ }
4584
+ const defaultProvider = providerMap.get(defaultProviderId);
4585
+ const providers = new ProviderRegistry(providerFactory, providerMap, logger);
4586
+ const payments = new PaymentService(
4587
+ defaultProvider,
4588
+ eventBus,
4589
+ logger.child({ component: "payment-service" }),
4590
+ clock,
4591
+ idGenerator
4592
+ );
4593
+ const serviceDeps = {
4594
+ eventBus,
4595
+ logger,
4596
+ clock,
4597
+ idGenerator
4598
+ };
4599
+ const refunds = new RefundService(defaultProvider, serviceDeps);
4600
+ const webhooks = new WebhookService(providerMap, serviceDeps);
4601
+ const transferDeps = {
4602
+ eventBus,
4603
+ logger: logger.child({ component: "transfer-service" }),
4604
+ clock,
4605
+ idGenerator
4606
+ };
4607
+ const transfers = new TransferService(defaultProvider, transferDeps.eventBus, transferDeps.logger, transferDeps.clock, transferDeps.idGenerator);
4608
+ const subscriptionProvider = isSubscriptionProvider(defaultProvider) ? defaultProvider : void 0;
4609
+ const catalogDeps = {
4610
+ providerId: defaultProviderId,
4611
+ subscriptionProvider,
4612
+ logger: logger.child({ component: "product-service" })
4613
+ };
4614
+ const products = new ProductService(catalogDeps);
4615
+ const subscriptions = new SubscriptionService({
4616
+ ...catalogDeps,
4617
+ logger: logger.child({ component: "subscription-service" }),
4618
+ eventBus,
4619
+ clock,
4620
+ idGenerator
4621
+ });
4622
+ const customers = new CustomerService({
4623
+ ...catalogDeps,
4624
+ logger: logger.child({ component: "customer-service" })
4625
+ });
4626
+ const events = new EventSubscriptionView(eventBus);
4627
+ return {
4628
+ payments,
4629
+ refunds,
4630
+ webhooks,
4631
+ transfers,
4632
+ products,
4633
+ subscriptions,
4634
+ customers,
4635
+ events,
4636
+ providers,
4637
+ async health() {
4638
+ const results = [];
4639
+ for (const [_id, provider] of providerMap) {
4640
+ try {
4641
+ results.push(await provider.health());
4642
+ } catch {
4643
+ results.push({
4644
+ healthy: false,
4645
+ latencyMs: 0,
4646
+ timestamp: clock.now()
4647
+ });
4648
+ }
4649
+ }
4650
+ return results;
4651
+ }
4652
+ };
4653
+ }
4654
+ function createClientFromEnv() {
4655
+ const defaultProvider = process.env.TEC_PAYMENT_DEFAULT_PROVIDER ?? "paystack";
4656
+ const logLevel = process.env.TEC_PAYMENT_LOGGING_LEVEL ?? "info";
4657
+ const providers = {};
4658
+ const paystackKey = process.env.TEC_PAYMENT_PAYSTACK_SECRET_KEY ?? process.env.PAYSTACK_SECRET_KEY;
4659
+ if (paystackKey) {
4660
+ providers.paystack = {
4661
+ secretKey: paystackKey,
4662
+ webhookSecret: process.env.TEC_PAYMENT_PAYSTACK_WEBHOOK_SECRET ?? process.env.PAYSTACK_WEBHOOK_SECRET,
4663
+ baseUrl: process.env.TEC_PAYMENT_PAYSTACK_BASE_URL ?? process.env.PAYSTACK_BASE_URL
4664
+ };
4665
+ }
4666
+ const bachsKey = process.env.TEC_PAYMENT_BACHS_SECRET_KEY ?? process.env.BACHS_SECRET_KEY;
4667
+ if (bachsKey) {
4668
+ providers.bachs = {
4669
+ secretKey: bachsKey,
4670
+ // Bachs signs webhooks with the endpoint signing secret (whsec_...),
4671
+ // never with the API key, so there is no fallback here.
4672
+ webhookSecret: process.env.TEC_PAYMENT_BACHS_WEBHOOK_SECRET ?? process.env.BACHS_WEBHOOK_SECRET,
4673
+ baseUrl: process.env.TEC_PAYMENT_BACHS_BASE_URL ?? process.env.BACHS_BASE_URL,
4674
+ timeoutMs: process.env.TEC_PAYMENT_BACHS_TIMEOUT_MS ? Number(process.env.TEC_PAYMENT_BACHS_TIMEOUT_MS) : void 0
4675
+ };
4676
+ }
4677
+ return createPaymentClient({
4678
+ providers,
4679
+ defaultProvider,
4680
+ logging: { level: logLevel }
4681
+ });
4682
+ }
4683
+ createPaymentClient.fromEnv = createClientFromEnv;
4684
+
4685
+ // src/adapters/nestjs/constants.ts
4686
+ var TEC_PAYMENT_CLIENT = "TEC_PAYMENT_CLIENT";
4687
+ var DEFAULT_WEBHOOK_PATH = "webhooks/payment";
4688
+ exports.PaymentService = class PaymentService2 {
4689
+ constructor(client) {
4690
+ this.client = client;
4691
+ }
4692
+ client;
4693
+ get payments() {
4694
+ return this.client.payments;
4695
+ }
4696
+ get refunds() {
4697
+ return this.client.refunds;
4698
+ }
4699
+ get webhooks() {
4700
+ return this.client.webhooks;
4701
+ }
4702
+ get transfers() {
4703
+ return this.client.transfers;
4704
+ }
4705
+ /** Catalog and billing. Returns `UnsupportedProviderError` per call when the provider lacks the capability. */
4706
+ get products() {
4707
+ return this.client.products;
4708
+ }
4709
+ get subscriptions() {
4710
+ return this.client.subscriptions;
4711
+ }
4712
+ get customers() {
4713
+ return this.client.customers;
4714
+ }
4715
+ get events() {
4716
+ return this.client.events;
4717
+ }
4718
+ health() {
4719
+ return this.client.health();
4720
+ }
4721
+ };
4722
+ exports.PaymentService = __decorateClass([
4723
+ common.Injectable(),
4724
+ __decorateParam(0, common.Inject(TEC_PAYMENT_CLIENT))
4725
+ ], exports.PaymentService);
4726
+ exports.WebhookController = class WebhookController {
4727
+ constructor(client, logger) {
4728
+ this.client = client;
4729
+ this.logger = logger;
4730
+ }
4731
+ client;
4732
+ logger;
4733
+ async handle(req, res) {
4734
+ const typedRes = res;
4735
+ const rawBody = req.rawBody ?? "";
4736
+ const result = await this.client.webhooks.receive({
4737
+ rawBody,
4738
+ headers: req.headers
4739
+ });
4740
+ if (!result.ok) {
4741
+ this.logger?.warn(
4742
+ `Webhook signature verification failed: ${result.error.message}`,
4743
+ { error: result.error.meta }
4744
+ );
4745
+ typedRes.status(401).json({ error: result.error.message });
4746
+ return;
4747
+ }
4748
+ this.logger?.log(`Webhook received: ${result.value.type}`, {
4749
+ provider: result.value.provider,
4750
+ type: result.value.type,
4751
+ originalType: result.value.originalType,
4752
+ eventId: result.value.id
4753
+ });
4754
+ typedRes.json({ received: true });
4755
+ }
4756
+ };
4757
+ __decorateClass([
4758
+ common.Post(),
4759
+ __decorateParam(0, common.Req()),
4760
+ __decorateParam(1, common.Res())
4761
+ ], exports.WebhookController.prototype, "handle", 1);
4762
+ exports.WebhookController = __decorateClass([
4763
+ common.Controller(DEFAULT_WEBHOOK_PATH),
4764
+ __decorateParam(0, common.Inject(TEC_PAYMENT_CLIENT))
4765
+ ], exports.WebhookController);
4766
+ var WEBHOOK_RATE_LIMIT_OPTIONS = "TEC_PAYMENT_WEBHOOK_RATE_LIMIT_OPTIONS";
4767
+ var MAX_BUCKETS = 1e4;
4768
+ exports.WebhookRateLimitGuard = class WebhookRateLimitGuard {
4769
+ buckets = /* @__PURE__ */ new Map();
4770
+ options;
4771
+ constructor(options) {
4772
+ if (!Number.isInteger(options.limit) || options.limit <= 0) {
4773
+ throw new TypeError(`rateLimit.limit must be a positive integer, got ${options.limit}`);
4774
+ }
4775
+ if (!Number.isInteger(options.ttlMs) || options.ttlMs <= 0) {
4776
+ throw new TypeError(`rateLimit.ttlMs must be a positive integer, got ${options.ttlMs}`);
4777
+ }
4778
+ this.options = options;
4779
+ }
4780
+ canActivate(context) {
4781
+ const request = context.switchToHttp().getRequest();
4782
+ const key = request.ip ?? "unknown";
4783
+ const now = Date.now();
4784
+ this.sweep(now);
4785
+ const bucket = this.buckets.get(key);
4786
+ if (!bucket || bucket.resetAt <= now) {
4787
+ this.buckets.set(key, { count: 1, resetAt: now + this.options.ttlMs });
4788
+ return true;
4789
+ }
4790
+ if (bucket.count >= this.options.limit) {
4791
+ throw new common.HttpException("Too many webhook requests", common.HttpStatus.TOO_MANY_REQUESTS);
4792
+ }
4793
+ bucket.count += 1;
4794
+ return true;
4795
+ }
4796
+ sweep(now) {
4797
+ if (this.buckets.size < MAX_BUCKETS) {
4798
+ return;
4799
+ }
4800
+ for (const [key, bucket] of this.buckets) {
4801
+ if (bucket.resetAt <= now) {
4802
+ this.buckets.delete(key);
4803
+ }
4804
+ }
4805
+ if (this.buckets.size < MAX_BUCKETS) {
4806
+ return;
4807
+ }
4808
+ const overflow = this.buckets.size - Math.floor(MAX_BUCKETS * 0.9);
4809
+ const oldest = [...this.buckets.entries()].sort((a, b) => a[1].resetAt - b[1].resetAt).slice(0, overflow);
4810
+ for (const [key] of oldest) {
4811
+ this.buckets.delete(key);
4812
+ }
4813
+ }
4814
+ };
4815
+ exports.WebhookRateLimitGuard = __decorateClass([
4816
+ common.Injectable(),
4817
+ __decorateParam(0, common.Inject(WEBHOOK_RATE_LIMIT_OPTIONS))
4818
+ ], exports.WebhookRateLimitGuard);
4819
+
4820
+ // src/adapters/nestjs/payment.module.ts
4821
+ var WEBHOOK_LOGGER = "TEC_PAYMENT_WEBHOOK_LOGGER";
4822
+ function createPaymentClientFactory(config) {
4823
+ return () => createPaymentClient(config);
4824
+ }
4825
+ function createAsyncPaymentClientFactory(options) {
4826
+ return async (...args) => {
4827
+ const config = await options.useFactory(...args);
4828
+ return createPaymentClient(config);
4829
+ };
4830
+ }
4831
+ var EXPORTED_PROVIDERS = [TEC_PAYMENT_CLIENT, exports.PaymentService];
4832
+ function createWebhookControllerClass(path, rateLimit) {
4833
+ let DynamicWebhookController = class extends exports.WebhookController {
4834
+ constructor(client) {
4835
+ super(client);
4836
+ }
4837
+ };
4838
+ DynamicWebhookController = __decorateClass([
4839
+ common.Controller(path),
4840
+ __decorateParam(0, common.Inject(TEC_PAYMENT_CLIENT))
4841
+ ], DynamicWebhookController);
4842
+ if (rateLimit) {
4843
+ common.UseGuards(exports.WebhookRateLimitGuard)(DynamicWebhookController);
4844
+ }
4845
+ return DynamicWebhookController;
4846
+ }
4847
+ function buildWebhookProviders(clientFactory, path, rateLimit) {
4848
+ const controllerClass = path !== DEFAULT_WEBHOOK_PATH || rateLimit !== void 0 ? createWebhookControllerClass(path, rateLimit) : exports.WebhookController;
4849
+ const providers = [
4850
+ {
4851
+ provide: WEBHOOK_LOGGER,
4852
+ useFactory: () => new common.Logger("WebhookController")
4853
+ },
4854
+ {
4855
+ provide: controllerClass,
4856
+ useFactory: (client, logger) => new controllerClass(client, logger),
4857
+ inject: [TEC_PAYMENT_CLIENT, WEBHOOK_LOGGER]
4858
+ }
4859
+ ];
4860
+ if (rateLimit) {
4861
+ providers.push({
4862
+ provide: WEBHOOK_RATE_LIMIT_OPTIONS,
4863
+ useValue: rateLimit
4864
+ });
4865
+ }
4866
+ return { providers, controllerClass };
4867
+ }
4868
+ exports.PaymentModule = class PaymentModule {
4869
+ /**
4870
+ * Registers a {@link PaymentClient} synchronously from a static
4871
+ * {@link PaymentClientConfig}.
4872
+ */
4873
+ static forRoot(config, options) {
4874
+ const shouldRegisterController = options?.registerWebhookController === void 0 ? true : options.registerWebhookController;
4875
+ const webhookPath = options?.webhookPath ?? DEFAULT_WEBHOOK_PATH;
4876
+ const rateLimit = options?.rateLimit;
4877
+ const providers = [
4878
+ {
4879
+ provide: TEC_PAYMENT_CLIENT,
4880
+ useFactory: createPaymentClientFactory(config)
4881
+ },
4882
+ {
4883
+ provide: exports.PaymentService,
4884
+ useFactory: (client) => new exports.PaymentService(client),
4885
+ inject: [TEC_PAYMENT_CLIENT]
4886
+ }
4887
+ ];
4888
+ const controllers = [];
4889
+ if (shouldRegisterController) {
4890
+ const built = buildWebhookProviders(
4891
+ createPaymentClientFactory(config),
4892
+ webhookPath,
4893
+ rateLimit
4894
+ );
4895
+ providers.push(...built.providers);
4896
+ controllers.push(built.controllerClass);
4897
+ }
4898
+ return {
4899
+ module: exports.PaymentModule,
4900
+ providers,
4901
+ exports: [...EXPORTED_PROVIDERS],
4902
+ controllers
4903
+ };
4904
+ }
4905
+ /**
4906
+ * Registers a {@link PaymentClient} asynchronously, typically
4907
+ * pulling secrets from `ConfigService` or a similar provider.
4908
+ */
4909
+ static forRootAsync(options) {
4910
+ const shouldRegisterController = options.registerWebhookController === void 0 ? true : options.registerWebhookController;
4911
+ const webhookPath = options.webhookPath ?? DEFAULT_WEBHOOK_PATH;
4912
+ const rateLimit = options.rateLimit;
4913
+ const providers = [
4914
+ {
4915
+ provide: TEC_PAYMENT_CLIENT,
4916
+ useFactory: createAsyncPaymentClientFactory(options),
4917
+ inject: options.inject ?? []
4918
+ },
4919
+ {
4920
+ provide: exports.PaymentService,
4921
+ useFactory: (client) => new exports.PaymentService(client),
4922
+ inject: [TEC_PAYMENT_CLIENT]
4923
+ }
4924
+ ];
4925
+ const controllers = [];
4926
+ if (shouldRegisterController) {
4927
+ const built = buildWebhookProviders(
4928
+ createAsyncPaymentClientFactory(options),
4929
+ webhookPath,
4930
+ rateLimit
4931
+ );
4932
+ providers.push(...built.providers);
4933
+ controllers.push(built.controllerClass);
4934
+ }
4935
+ return {
4936
+ module: exports.PaymentModule,
4937
+ imports: [...options.imports ?? []],
4938
+ providers,
4939
+ exports: [...EXPORTED_PROVIDERS],
4940
+ controllers
4941
+ };
4942
+ }
4943
+ };
4944
+ exports.PaymentModule = __decorateClass([
4945
+ common.Module({})
4946
+ ], exports.PaymentModule);
4947
+ var NestLoggerAdapter = class _NestLoggerAdapter {
4948
+ logger;
4949
+ constructor(context) {
4950
+ this.logger = new common.Logger(context ?? "PaymentClient");
4951
+ }
4952
+ debug(message, context) {
4953
+ this.logger.debug(context ? `${message} ${JSON.stringify(context)}` : message);
4954
+ }
4955
+ info(message, context) {
4956
+ this.logger.log(context ? `${message} ${JSON.stringify(context)}` : message);
4957
+ }
4958
+ warn(message, context) {
4959
+ this.logger.warn(context ? `${message} ${JSON.stringify(context)}` : message);
4960
+ }
4961
+ error(message, error, context) {
4962
+ this.logger.error(
4963
+ context ? `${message} ${JSON.stringify(context)}` : message,
4964
+ error instanceof Error ? error.stack : void 0,
4965
+ "PaymentClient"
4966
+ );
4967
+ }
4968
+ child(bindings) {
4969
+ const childContext = Object.entries(bindings).map(([k, v]) => `${k}:${v}`).join(",");
4970
+ return new _NestLoggerAdapter(childContext || "PaymentClient");
4971
+ }
4972
+ };
4973
+
4974
+ exports.DEFAULT_WEBHOOK_PATH = DEFAULT_WEBHOOK_PATH;
4975
+ exports.NestLoggerAdapter = NestLoggerAdapter;
4976
+ exports.TEC_PAYMENT_CLIENT = TEC_PAYMENT_CLIENT;
4977
+ exports.WEBHOOK_RATE_LIMIT_OPTIONS = WEBHOOK_RATE_LIMIT_OPTIONS;
4978
+ //# sourceMappingURL=index.cjs.map
4979
+ //# sourceMappingURL=index.cjs.map