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