@nehorai/payments 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/LICENSE +21 -0
  2. package/dist/config/index.cjs +116 -0
  3. package/dist/config/index.cjs.map +1 -0
  4. package/dist/config/index.d.cts +125 -0
  5. package/dist/config/index.d.ts +125 -0
  6. package/dist/config/index.js +83 -0
  7. package/dist/config/index.js.map +1 -0
  8. package/dist/factory.cjs +807 -0
  9. package/dist/factory.cjs.map +1 -0
  10. package/dist/factory.d.cts +96 -0
  11. package/dist/factory.d.ts +96 -0
  12. package/dist/factory.js +777 -0
  13. package/dist/factory.js.map +1 -0
  14. package/dist/index.cjs +1341 -0
  15. package/dist/index.cjs.map +1 -0
  16. package/dist/index.d.cts +40 -0
  17. package/dist/index.d.ts +40 -0
  18. package/dist/index.js +1260 -0
  19. package/dist/index.js.map +1 -0
  20. package/dist/payment-orchestrator-CPaLmDM5.d.ts +404 -0
  21. package/dist/payment-orchestrator-Co_X6T_V.d.cts +404 -0
  22. package/dist/payment-types-68W-PlGg.d.cts +211 -0
  23. package/dist/payment-types-68W-PlGg.d.ts +211 -0
  24. package/dist/providers/interfaces/index.cjs +19 -0
  25. package/dist/providers/interfaces/index.cjs.map +1 -0
  26. package/dist/providers/interfaces/index.d.cts +80 -0
  27. package/dist/providers/interfaces/index.d.ts +80 -0
  28. package/dist/providers/interfaces/index.js +1 -0
  29. package/dist/providers/interfaces/index.js.map +1 -0
  30. package/dist/repository/interfaces/index.cjs +19 -0
  31. package/dist/repository/interfaces/index.cjs.map +1 -0
  32. package/dist/repository/interfaces/index.d.cts +556 -0
  33. package/dist/repository/interfaces/index.d.ts +556 -0
  34. package/dist/repository/interfaces/index.js +1 -0
  35. package/dist/repository/interfaces/index.js.map +1 -0
  36. package/dist/routing-engine.interface-DJzGXor9.d.cts +194 -0
  37. package/dist/routing-engine.interface-h9_GmQ4b.d.ts +194 -0
  38. package/dist/services/index.cjs +806 -0
  39. package/dist/services/index.cjs.map +1 -0
  40. package/dist/services/index.d.cts +75 -0
  41. package/dist/services/index.d.ts +75 -0
  42. package/dist/services/index.js +763 -0
  43. package/dist/services/index.js.map +1 -0
  44. package/dist/state-machine-Cu6_qKnv.d.cts +109 -0
  45. package/dist/state-machine-Cu6_qKnv.d.ts +109 -0
  46. package/dist/types/index.cjs +173 -0
  47. package/dist/types/index.cjs.map +1 -0
  48. package/dist/types/index.d.cts +127 -0
  49. package/dist/types/index.d.ts +127 -0
  50. package/dist/types/index.js +130 -0
  51. package/dist/types/index.js.map +1 -0
  52. package/dist/utils/index.cjs +167 -0
  53. package/dist/utils/index.cjs.map +1 -0
  54. package/dist/utils/index.d.cts +102 -0
  55. package/dist/utils/index.d.ts +102 -0
  56. package/dist/utils/index.js +127 -0
  57. package/dist/utils/index.js.map +1 -0
  58. package/package.json +68 -0
@@ -0,0 +1,777 @@
1
+ // src/services/payment-orchestrator.ts
2
+ import { randomUUID } from "crypto";
3
+
4
+ // src/config/payment-config.ts
5
+ function createPartialConfig(partial) {
6
+ return {
7
+ providers: partial.providers ?? {},
8
+ environment: partial.environment ?? "sandbox",
9
+ defaultCurrency: partial.defaultCurrency ?? "USD"
10
+ };
11
+ }
12
+ function getConfiguredProviders(config) {
13
+ const availability = {};
14
+ for (const [name, providerConfig] of Object.entries(config.providers)) {
15
+ availability[name] = providerConfig !== void 0 && Object.keys(providerConfig).length > 0;
16
+ }
17
+ return availability;
18
+ }
19
+
20
+ // src/services/circuit-breaker-storage.interface.ts
21
+ function createDefaultState(provider) {
22
+ return {
23
+ provider,
24
+ state: "closed",
25
+ failureCount: 0,
26
+ successCount: 0,
27
+ lastFailure: null,
28
+ openedAt: null,
29
+ nextRetryAt: null
30
+ };
31
+ }
32
+
33
+ // src/services/in-memory-storage.ts
34
+ var InMemoryCircuitBreakerStorage = class {
35
+ internalStates;
36
+ constructor() {
37
+ this.internalStates = /* @__PURE__ */ new Map();
38
+ }
39
+ async getState(provider) {
40
+ return this.internalStates.get(provider) ?? null;
41
+ }
42
+ async setState(provider, state) {
43
+ this.internalStates.set(provider, { ...state });
44
+ }
45
+ async getAllStates() {
46
+ return new Map(this.internalStates);
47
+ }
48
+ async deleteState(provider) {
49
+ this.internalStates.delete(provider);
50
+ }
51
+ async getOpenCircuits() {
52
+ const open = [];
53
+ for (const [provider, state] of this.internalStates) {
54
+ if (state.state === "open") {
55
+ open.push(provider);
56
+ }
57
+ }
58
+ return open;
59
+ }
60
+ async isHealthy() {
61
+ return true;
62
+ }
63
+ /**
64
+ * Clear all stored states (useful for testing)
65
+ */
66
+ clear() {
67
+ this.internalStates.clear();
68
+ }
69
+ /**
70
+ * Get current state count (useful for testing/debugging)
71
+ */
72
+ get size() {
73
+ return this.internalStates.size;
74
+ }
75
+ /**
76
+ * Synchronous state access (for backward compatibility with CircuitBreaker.isOpen)
77
+ *
78
+ * Note: Only available on InMemoryCircuitBreakerStorage.
79
+ * Database-backed storage cannot provide sync access.
80
+ */
81
+ getStateSync(provider) {
82
+ return this.internalStates.get(provider) ?? null;
83
+ }
84
+ };
85
+
86
+ // src/services/circuit-breaker.ts
87
+ var DEFAULT_CONFIG = {
88
+ failureThreshold: 5,
89
+ resetTimeoutMs: 6e4,
90
+ // 1 minute
91
+ halfOpenMaxRequests: 3
92
+ };
93
+ var CircuitBreaker = class {
94
+ config;
95
+ storage;
96
+ constructor(deps = {}) {
97
+ this.config = { ...DEFAULT_CONFIG, ...deps.config };
98
+ this.storage = deps.storage ?? new InMemoryCircuitBreakerStorage();
99
+ }
100
+ /**
101
+ * Check if a request can be executed for a provider
102
+ */
103
+ async canExecute(provider) {
104
+ const state = await this.getState(provider);
105
+ switch (state.state) {
106
+ case "closed":
107
+ return true;
108
+ case "open":
109
+ if (state.nextRetryAt && Date.now() >= state.nextRetryAt.getTime()) {
110
+ await this.transitionTo(provider, "half_open");
111
+ return true;
112
+ }
113
+ return false;
114
+ case "half_open":
115
+ return state.failureCount < this.config.halfOpenMaxRequests;
116
+ }
117
+ }
118
+ /**
119
+ * Record a successful request
120
+ */
121
+ async recordSuccess(provider) {
122
+ const state = await this.getState(provider);
123
+ if (state.state === "half_open") {
124
+ state.successCount++;
125
+ if (state.successCount >= this.config.halfOpenMaxRequests) {
126
+ await this.transitionTo(provider, "closed");
127
+ return;
128
+ }
129
+ } else if (state.state === "closed") {
130
+ state.failureCount = 0;
131
+ }
132
+ await this.storage.setState(provider, state);
133
+ }
134
+ /**
135
+ * Record a failed request
136
+ */
137
+ async recordFailure(provider) {
138
+ const state = await this.getState(provider);
139
+ state.failureCount++;
140
+ state.lastFailure = /* @__PURE__ */ new Date();
141
+ if (state.state === "half_open") {
142
+ await this.transitionTo(provider, "open");
143
+ } else if (state.state === "closed") {
144
+ if (state.failureCount >= this.config.failureThreshold) {
145
+ await this.transitionTo(provider, "open");
146
+ } else {
147
+ await this.storage.setState(provider, state);
148
+ }
149
+ } else {
150
+ await this.storage.setState(provider, state);
151
+ }
152
+ }
153
+ /**
154
+ * Get current state for a provider
155
+ */
156
+ async getState(provider) {
157
+ const stored = await this.storage.getState(provider);
158
+ return stored ?? createDefaultState(provider);
159
+ }
160
+ /**
161
+ * Check if circuit is open (provider unavailable)
162
+ */
163
+ isOpen(provider) {
164
+ return this.isOpenSync(provider);
165
+ }
166
+ /**
167
+ * Async version of isOpen
168
+ */
169
+ async isOpenAsync(provider) {
170
+ const state = await this.getState(provider);
171
+ return state.state === "open";
172
+ }
173
+ /**
174
+ * Manually reset a provider's circuit
175
+ */
176
+ async reset(provider) {
177
+ await this.storage.setState(provider, createDefaultState(provider));
178
+ }
179
+ /**
180
+ * Get all providers with open circuits
181
+ */
182
+ async getOpenCircuits() {
183
+ return this.storage.getOpenCircuits();
184
+ }
185
+ /**
186
+ * Get the storage instance (useful for testing)
187
+ */
188
+ getStorage() {
189
+ return this.storage;
190
+ }
191
+ /**
192
+ * Get configuration (useful for testing)
193
+ */
194
+ getConfig() {
195
+ return { ...this.config };
196
+ }
197
+ // ==========================================================================
198
+ // Private Methods
199
+ // ==========================================================================
200
+ async transitionTo(provider, newState) {
201
+ const state = await this.getState(provider);
202
+ const now = /* @__PURE__ */ new Date();
203
+ state.state = newState;
204
+ if (newState === "open") {
205
+ state.openedAt = now;
206
+ state.nextRetryAt = new Date(now.getTime() + this.config.resetTimeoutMs);
207
+ console.warn(
208
+ `[CIRCUIT_BREAKER] Circuit OPENED for ${provider}. Retry at: ${state.nextRetryAt.toISOString()}`
209
+ );
210
+ } else if (newState === "half_open") {
211
+ state.failureCount = 0;
212
+ state.successCount = 0;
213
+ console.info(`[CIRCUIT_BREAKER] Circuit HALF_OPEN for ${provider}`);
214
+ } else if (newState === "closed") {
215
+ state.failureCount = 0;
216
+ state.successCount = 0;
217
+ state.openedAt = null;
218
+ state.nextRetryAt = null;
219
+ console.info(`[CIRCUIT_BREAKER] Circuit CLOSED for ${provider}`);
220
+ }
221
+ await this.storage.setState(provider, state);
222
+ }
223
+ /**
224
+ * Synchronous check for backward compatibility
225
+ * Note: This always returns false for database-backed storage
226
+ */
227
+ isOpenSync(provider) {
228
+ if (this.storage instanceof InMemoryCircuitBreakerStorage) {
229
+ const state = this.storage.getStateSync(provider);
230
+ return state?.state === "open";
231
+ }
232
+ return false;
233
+ }
234
+ };
235
+ var circuitBreakerInstance = null;
236
+ var defaultStorage = null;
237
+ function getCircuitBreaker(config) {
238
+ if (!circuitBreakerInstance) {
239
+ if (!defaultStorage) {
240
+ defaultStorage = new InMemoryCircuitBreakerStorage();
241
+ }
242
+ circuitBreakerInstance = new CircuitBreaker({
243
+ storage: defaultStorage,
244
+ config
245
+ });
246
+ }
247
+ return circuitBreakerInstance;
248
+ }
249
+ function createCircuitBreaker(deps = {}) {
250
+ return new CircuitBreaker(deps);
251
+ }
252
+ function resetCircuitBreaker() {
253
+ circuitBreakerInstance = null;
254
+ if (defaultStorage) {
255
+ defaultStorage.clear();
256
+ }
257
+ defaultStorage = null;
258
+ }
259
+
260
+ // src/services/routing-engine.ts
261
+ function matchCardBinToRule(bin, rules) {
262
+ if (!bin || bin.length < 6) return null;
263
+ const binPrefix = bin.substring(0, 6);
264
+ for (const rule of rules) {
265
+ for (const range of rule.ranges) {
266
+ if (binPrefix >= range.start && binPrefix <= range.end) {
267
+ return { rule, issuer: range.issuer, country: range.country };
268
+ }
269
+ }
270
+ }
271
+ return null;
272
+ }
273
+ function getOptimalProviderFromPriorities(matchedBin, currency, requiresRecurring, availableProviders, priorities) {
274
+ const candidates = priorities.filter(
275
+ (p) => availableProviders.includes(p.provider)
276
+ );
277
+ if (candidates.length === 0) return availableProviders[0] ?? null;
278
+ const suitable = candidates.filter((p) => {
279
+ if (!p.supportsCurrency.includes(currency)) return false;
280
+ if (requiresRecurring && !p.supportsRecurring) return false;
281
+ return true;
282
+ });
283
+ if (suitable.length === 0) {
284
+ return candidates.sort((a, b) => a.priority - b.priority)[0]?.provider ?? null;
285
+ }
286
+ if (matchedBin) {
287
+ const localProviders = suitable.filter((p) => p.isLocalGateway);
288
+ if (localProviders.length > 0) {
289
+ return localProviders.sort((a, b) => a.priority - b.priority)[0].provider;
290
+ }
291
+ }
292
+ return suitable.sort((a, b) => a.priority - b.priority)[0].provider;
293
+ }
294
+ function getFallbackProvidersFromPriorities(primaryProvider, availableProviders, priorities) {
295
+ return priorities.filter(
296
+ (p) => p.provider !== primaryProvider && availableProviders.includes(p.provider)
297
+ ).sort((a, b) => a.priority - b.priority).map((p) => p.provider);
298
+ }
299
+ function getProviderFeeFromPriorities(provider, priorities) {
300
+ const config = priorities.find((p) => p.provider === provider);
301
+ return config?.maxFeePercent ?? 3;
302
+ }
303
+ var RoutingEngine = class {
304
+ config;
305
+ circuitBreaker;
306
+ routingRules;
307
+ constructor(deps = {}) {
308
+ this.config = deps.config ?? createPartialConfig({});
309
+ this.circuitBreaker = deps.circuitBreaker ?? getCircuitBreaker();
310
+ this.routingRules = deps.routingRules ?? {};
311
+ }
312
+ /**
313
+ * Determine optimal provider for a transaction
314
+ */
315
+ async route(context) {
316
+ const availability = getConfiguredProviders(this.config);
317
+ const availableProviders = this.getProviderList(availability);
318
+ if (availableProviders.length === 0) {
319
+ throw new Error("No payment providers configured");
320
+ }
321
+ if (context.savedPaymentMethodId && context.savedPaymentMethodProvider) {
322
+ return this.routeToSavedMethodProvider(context, availableProviders);
323
+ }
324
+ const binMatch = context.cardBin && this.routingRules.cardBinRules ? matchCardBinToRule(context.cardBin, this.routingRules.cardBinRules) : null;
325
+ const currencyRule = this.routingRules.currencyRules?.find(
326
+ (r) => r.currency === context.amount.currency
327
+ );
328
+ const healthyProviders = await this.getHealthyProviders(availableProviders);
329
+ const availableHealthy = availableProviders.filter((p) => healthyProviders.includes(p));
330
+ const effectiveProviders = availableHealthy.length > 0 ? availableHealthy : availableProviders;
331
+ if (binMatch && effectiveProviders.includes(binMatch.rule.preferredProvider)) {
332
+ const provider2 = binMatch.rule.preferredProvider;
333
+ const fallbacks2 = this.getFallbackProviders(provider2, availableProviders);
334
+ const feePercent = this.getProviderFee(provider2);
335
+ return {
336
+ provider: provider2,
337
+ reason: binMatch.issuer ? `Card (${binMatch.issuer}) matched BIN rule, routed to preferred provider` : "Card matched BIN rule, routed to preferred provider",
338
+ fallbackProviders: fallbacks2,
339
+ estimatedFeePercent: feePercent,
340
+ metadata: {
341
+ matchedBinRule: true,
342
+ cardIssuer: binMatch.issuer,
343
+ cardCountry: binMatch.country
344
+ }
345
+ };
346
+ }
347
+ if (currencyRule && effectiveProviders.includes(currencyRule.preferredProvider)) {
348
+ const provider2 = currencyRule.preferredProvider;
349
+ const fallbacks2 = this.getFallbackProviders(provider2, availableProviders);
350
+ const feePercent = this.getProviderFee(provider2);
351
+ return {
352
+ provider: provider2,
353
+ reason: `Currency ${context.amount.currency} routed to preferred provider`,
354
+ fallbackProviders: fallbacks2,
355
+ estimatedFeePercent: feePercent
356
+ };
357
+ }
358
+ const priorities = this.routingRules.providerPriorities;
359
+ if (priorities && priorities.length > 0) {
360
+ const provider2 = getOptimalProviderFromPriorities(
361
+ !!binMatch,
362
+ context.amount.currency,
363
+ context.isRecurring,
364
+ effectiveProviders,
365
+ priorities
366
+ );
367
+ if (provider2) {
368
+ const fallbacks2 = getFallbackProvidersFromPriorities(provider2, availableProviders, priorities);
369
+ const feePercent = getProviderFeeFromPriorities(provider2, priorities);
370
+ return {
371
+ provider: provider2,
372
+ reason: `Selected ${provider2} based on priority rules`,
373
+ fallbackProviders: fallbacks2,
374
+ estimatedFeePercent: feePercent,
375
+ metadata: {
376
+ matchedBinRule: !!binMatch,
377
+ cardIssuer: binMatch?.issuer,
378
+ cardCountry: binMatch?.country
379
+ }
380
+ };
381
+ }
382
+ }
383
+ const provider = effectiveProviders[0];
384
+ const fallbacks = effectiveProviders.slice(1);
385
+ return {
386
+ provider,
387
+ reason: `Default routing to ${provider}`,
388
+ fallbackProviders: fallbacks,
389
+ estimatedFeePercent: this.getProviderFee(provider)
390
+ };
391
+ }
392
+ /**
393
+ * Get next provider after a failure
394
+ */
395
+ async getFailoverProvider(failedProvider, _context) {
396
+ const availability = getConfiguredProviders(this.config);
397
+ const availableProviders = this.getProviderList(availability);
398
+ const healthyProviders = await this.getHealthyProviders(availableProviders);
399
+ const fallbacks = this.getFallbackProviders(failedProvider, availableProviders);
400
+ for (const provider of fallbacks) {
401
+ if (healthyProviders.includes(provider)) {
402
+ return provider;
403
+ }
404
+ }
405
+ return fallbacks[0] ?? null;
406
+ }
407
+ /**
408
+ * Check if a card BIN matches any configured rule
409
+ */
410
+ matchCardBin(bin) {
411
+ if (!this.routingRules.cardBinRules) return false;
412
+ return matchCardBinToRule(bin, this.routingRules.cardBinRules) !== null;
413
+ }
414
+ /**
415
+ * Get all available (healthy) providers
416
+ */
417
+ async getAvailableProviders() {
418
+ const availability = getConfiguredProviders(this.config);
419
+ const configured = this.getProviderList(availability);
420
+ return this.getHealthyProviders(configured);
421
+ }
422
+ /**
423
+ * Quick recommendation without full context
424
+ */
425
+ async getQuickRecommendation(currency, isRecurring) {
426
+ const availability = getConfiguredProviders(this.config);
427
+ const available = this.getProviderList(availability);
428
+ if (available.length === 0) return null;
429
+ const currencyRule = this.routingRules.currencyRules?.find(
430
+ (r) => r.currency === currency
431
+ );
432
+ if (currencyRule && available.includes(currencyRule.preferredProvider)) {
433
+ return currencyRule.preferredProvider;
434
+ }
435
+ const priorities = this.routingRules.providerPriorities;
436
+ if (priorities && priorities.length > 0) {
437
+ return getOptimalProviderFromPriorities(false, currency, isRecurring, available, priorities);
438
+ }
439
+ return available[0] ?? null;
440
+ }
441
+ /**
442
+ * Get current configuration (for testing/debugging)
443
+ */
444
+ getConfig() {
445
+ return this.config;
446
+ }
447
+ /**
448
+ * Get circuit breaker instance (for testing/debugging)
449
+ */
450
+ getCircuitBreaker() {
451
+ return this.circuitBreaker;
452
+ }
453
+ /**
454
+ * Get routing rules (for testing/debugging)
455
+ */
456
+ getRoutingRules() {
457
+ return this.routingRules;
458
+ }
459
+ // ==========================================================================
460
+ // Private Methods
461
+ // ==========================================================================
462
+ getProviderList(availability) {
463
+ const providers = [];
464
+ for (const [name, isAvailable] of Object.entries(availability)) {
465
+ if (isAvailable) providers.push(name);
466
+ }
467
+ return providers;
468
+ }
469
+ async getHealthyProviders(providers) {
470
+ const healthy = [];
471
+ for (const provider of providers) {
472
+ const isOpen = await this.circuitBreaker.isOpenAsync(provider);
473
+ if (!isOpen) {
474
+ healthy.push(provider);
475
+ }
476
+ }
477
+ return healthy;
478
+ }
479
+ routeToSavedMethodProvider(context, availableProviders) {
480
+ const provider = context.savedPaymentMethodProvider;
481
+ if (!availableProviders.includes(provider)) {
482
+ throw new Error(`Saved payment method provider '${provider}' is not available`);
483
+ }
484
+ return {
485
+ provider,
486
+ reason: "Using saved payment method provider",
487
+ fallbackProviders: [],
488
+ estimatedFeePercent: this.getProviderFee(provider)
489
+ };
490
+ }
491
+ getFallbackProviders(primaryProvider, availableProviders) {
492
+ const priorities = this.routingRules.providerPriorities;
493
+ if (priorities && priorities.length > 0) {
494
+ return getFallbackProvidersFromPriorities(primaryProvider, availableProviders, priorities);
495
+ }
496
+ return availableProviders.filter((p) => p !== primaryProvider);
497
+ }
498
+ getProviderFee(provider) {
499
+ const priorities = this.routingRules.providerPriorities;
500
+ if (priorities && priorities.length > 0) {
501
+ return getProviderFeeFromPriorities(provider, priorities);
502
+ }
503
+ return 3;
504
+ }
505
+ };
506
+ var routingEngineInstance = null;
507
+ function getRoutingEngine() {
508
+ if (!routingEngineInstance) {
509
+ routingEngineInstance = new RoutingEngine();
510
+ }
511
+ return routingEngineInstance;
512
+ }
513
+ function createRoutingEngine(deps = {}) {
514
+ return new RoutingEngine(deps);
515
+ }
516
+ function resetRoutingEngine() {
517
+ routingEngineInstance = null;
518
+ }
519
+
520
+ // src/services/payment-orchestrator.ts
521
+ var PaymentOrchestrator = class {
522
+ providers;
523
+ routingEngine;
524
+ circuitBreaker;
525
+ constructor(deps) {
526
+ this.providers = deps.providers;
527
+ this.routingEngine = deps.routingEngine ?? getRoutingEngine();
528
+ this.circuitBreaker = deps.circuitBreaker ?? getCircuitBreaker();
529
+ }
530
+ /**
531
+ * Initiate a new payment
532
+ */
533
+ async initiatePayment(params) {
534
+ const internalPaymentId = `pay_${randomUUID()}`;
535
+ const idempotencyKey = `idem_${randomUUID()}`;
536
+ try {
537
+ const routing = await this.routingEngine.route({
538
+ userId: params.userId,
539
+ amount: params.amount,
540
+ cardBin: params.cardBin,
541
+ preferredProvider: params.preferredProvider,
542
+ isRecurring: params.transactionType !== "one_time_purchase"
543
+ });
544
+ const provider = this.getProvider(routing.provider);
545
+ if (!provider) {
546
+ return this.tryFailover(params, routing, internalPaymentId);
547
+ }
548
+ if (!await this.circuitBreaker.canExecute(routing.provider)) {
549
+ return this.tryFailover(params, routing, internalPaymentId);
550
+ }
551
+ const result = await provider.createPaymentIntent({
552
+ amount: params.amount,
553
+ userId: params.userId,
554
+ idempotencyKey,
555
+ description: params.description,
556
+ metadata: params.metadata,
557
+ returnUrl: params.returnUrl,
558
+ captureMethod: params.autoCapture ? "automatic" : "manual"
559
+ });
560
+ if (!result.success) {
561
+ await this.circuitBreaker.recordFailure(routing.provider);
562
+ return this.tryFailover(params, routing, internalPaymentId);
563
+ }
564
+ await this.circuitBreaker.recordSuccess(routing.provider);
565
+ return {
566
+ success: true,
567
+ transactionId: result.providerIntentId,
568
+ internalPaymentId,
569
+ provider: routing.provider,
570
+ clientSecret: result.clientSecret,
571
+ redirectUrl: result.redirectUrl
572
+ };
573
+ } catch (error) {
574
+ return {
575
+ success: false,
576
+ transactionId: "",
577
+ internalPaymentId,
578
+ provider: "unknown",
579
+ error: error instanceof Error ? error.message : "Unknown error"
580
+ };
581
+ }
582
+ }
583
+ /**
584
+ * Confirm a payment after user authorization
585
+ */
586
+ async confirmPayment(params) {
587
+ const provider = this.getProvider(params.provider);
588
+ if (!provider) {
589
+ return {
590
+ success: false,
591
+ transactionId: params.transactionId,
592
+ status: "failed",
593
+ error: `Provider ${params.provider} not available`
594
+ };
595
+ }
596
+ const result = await provider.authorize({
597
+ providerIntentId: params.providerIntentId,
598
+ idempotencyKey: `auth_${params.internalPaymentId}`
599
+ });
600
+ if (!result.success) {
601
+ return {
602
+ success: false,
603
+ transactionId: params.transactionId,
604
+ status: "failed",
605
+ error: result.error
606
+ };
607
+ }
608
+ return {
609
+ success: true,
610
+ transactionId: params.transactionId,
611
+ status: result.status ?? "authorized"
612
+ };
613
+ }
614
+ /**
615
+ * Capture an authorized payment (J5 completion)
616
+ */
617
+ async capturePayment(params) {
618
+ const provider = this.getProvider(params.provider);
619
+ if (!provider) {
620
+ return {
621
+ success: false,
622
+ status: "failed",
623
+ error: `Provider ${params.provider} not available`
624
+ };
625
+ }
626
+ const result = await provider.capture({
627
+ providerIntentId: params.providerIntentId,
628
+ authorizationCode: params.providerIntentId,
629
+ amount: params.amount,
630
+ idempotencyKey: `cap_${params.transactionId}`
631
+ });
632
+ if (!result.success) {
633
+ return {
634
+ success: false,
635
+ status: "failed",
636
+ error: result.error
637
+ };
638
+ }
639
+ return {
640
+ success: true,
641
+ status: "captured",
642
+ capturedAmount: result.capturedAmount
643
+ };
644
+ }
645
+ /**
646
+ * Get the routing engine (for testing/debugging)
647
+ */
648
+ getRoutingEngine() {
649
+ return this.routingEngine;
650
+ }
651
+ /**
652
+ * Get the circuit breaker (for testing/debugging)
653
+ */
654
+ getCircuitBreaker() {
655
+ return this.circuitBreaker;
656
+ }
657
+ /**
658
+ * Get available providers (for testing/debugging)
659
+ */
660
+ getProviders() {
661
+ return new Map(this.providers);
662
+ }
663
+ // ==========================================================================
664
+ // Private Methods
665
+ // ==========================================================================
666
+ getProvider(name) {
667
+ return this.providers.get(name);
668
+ }
669
+ async tryFailover(params, routing, internalPaymentId) {
670
+ for (const fallback of routing.fallbackProviders) {
671
+ const provider = this.getProvider(fallback);
672
+ if (!provider) continue;
673
+ if (!await this.circuitBreaker.canExecute(fallback)) continue;
674
+ const result = await provider.createPaymentIntent({
675
+ amount: params.amount,
676
+ userId: params.userId,
677
+ idempotencyKey: `idem_${randomUUID()}`,
678
+ description: params.description,
679
+ metadata: params.metadata,
680
+ returnUrl: params.returnUrl,
681
+ captureMethod: params.autoCapture ? "automatic" : "manual"
682
+ });
683
+ if (result.success) {
684
+ await this.circuitBreaker.recordSuccess(fallback);
685
+ return {
686
+ success: true,
687
+ transactionId: result.providerIntentId,
688
+ internalPaymentId,
689
+ provider: fallback,
690
+ clientSecret: result.clientSecret
691
+ };
692
+ }
693
+ await this.circuitBreaker.recordFailure(fallback);
694
+ }
695
+ return {
696
+ success: false,
697
+ transactionId: "",
698
+ internalPaymentId,
699
+ provider: routing.provider,
700
+ error: "All payment providers failed"
701
+ };
702
+ }
703
+ };
704
+
705
+ // src/factory.ts
706
+ function createPaymentServices(options) {
707
+ const config = options.config ?? createPartialConfig({});
708
+ const providers = options.providers;
709
+ const webhookHandlers = options.webhookHandlers ?? /* @__PURE__ */ new Map();
710
+ if (providers.size === 0) {
711
+ throw new Error("No payment providers provided. Pass at least one provider instance.");
712
+ }
713
+ const circuitBreakerStorage = options.circuitBreakerStorage ?? new InMemoryCircuitBreakerStorage();
714
+ const circuitBreaker = createCircuitBreaker({
715
+ storage: circuitBreakerStorage,
716
+ config: options.circuitBreaker
717
+ });
718
+ const routingEngine = createRoutingEngine({
719
+ config,
720
+ circuitBreaker,
721
+ routingRules: options.routingRules
722
+ });
723
+ const orchestrator = new PaymentOrchestrator({
724
+ providers,
725
+ routingEngine,
726
+ circuitBreaker
727
+ });
728
+ return {
729
+ orchestrator,
730
+ routingEngine,
731
+ circuitBreaker,
732
+ providers,
733
+ webhookHandlers,
734
+ config
735
+ };
736
+ }
737
+ function registerProvider(services, name, provider, webhookHandler) {
738
+ const newProviders = new Map(services.providers);
739
+ newProviders.set(name, provider);
740
+ const newWebhookHandlers = new Map(services.webhookHandlers);
741
+ if (webhookHandler) {
742
+ newWebhookHandlers.set(name, webhookHandler);
743
+ }
744
+ const orchestrator = new PaymentOrchestrator({
745
+ providers: newProviders,
746
+ routingEngine: services.routingEngine,
747
+ circuitBreaker: services.circuitBreaker
748
+ });
749
+ return {
750
+ ...services,
751
+ orchestrator,
752
+ providers: newProviders,
753
+ webhookHandlers: newWebhookHandlers
754
+ };
755
+ }
756
+ var servicesInstance = null;
757
+ function getPaymentServices(config) {
758
+ if (!servicesInstance) {
759
+ if (!config) {
760
+ throw new Error("PaymentServices not initialized. Call with config on first use.");
761
+ }
762
+ servicesInstance = createPaymentServices(config);
763
+ }
764
+ return servicesInstance;
765
+ }
766
+ function resetPaymentServices() {
767
+ servicesInstance = null;
768
+ resetCircuitBreaker();
769
+ resetRoutingEngine();
770
+ }
771
+ export {
772
+ createPaymentServices,
773
+ getPaymentServices,
774
+ registerProvider,
775
+ resetPaymentServices
776
+ };
777
+ //# sourceMappingURL=factory.js.map