@classytic/revenue 0.2.3 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/README.md +498 -499
  2. package/dist/actions-CwG-b7fR.d.ts +519 -0
  3. package/dist/core/index.d.ts +884 -0
  4. package/dist/core/index.js +2941 -0
  5. package/dist/core/index.js.map +1 -0
  6. package/dist/enums/index.d.ts +130 -0
  7. package/dist/enums/index.js +167 -0
  8. package/dist/enums/index.js.map +1 -0
  9. package/dist/index-BnJWVXuw.d.ts +378 -0
  10. package/dist/index-ChVD3P9k.d.ts +504 -0
  11. package/dist/index.d.ts +42 -0
  12. package/dist/index.js +4353 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/providers/index.d.ts +132 -0
  15. package/dist/providers/index.js +122 -0
  16. package/dist/providers/index.js.map +1 -0
  17. package/dist/retry-80lBCmSe.d.ts +234 -0
  18. package/dist/schemas/index.d.ts +894 -0
  19. package/dist/schemas/index.js +524 -0
  20. package/dist/schemas/index.js.map +1 -0
  21. package/dist/schemas/validation.d.ts +309 -0
  22. package/dist/schemas/validation.js +249 -0
  23. package/dist/schemas/validation.js.map +1 -0
  24. package/dist/services/index.d.ts +3 -0
  25. package/dist/services/index.js +1632 -0
  26. package/dist/services/index.js.map +1 -0
  27. package/dist/split.enums-DHdM1YAV.d.ts +255 -0
  28. package/dist/split.schema-BPdFZMbU.d.ts +958 -0
  29. package/dist/utils/index.d.ts +24 -0
  30. package/dist/utils/index.js +1067 -0
  31. package/dist/utils/index.js.map +1 -0
  32. package/package.json +48 -32
  33. package/core/builder.js +0 -219
  34. package/core/container.js +0 -119
  35. package/core/errors.js +0 -262
  36. package/dist/types/core/builder.d.ts +0 -97
  37. package/dist/types/core/container.d.ts +0 -57
  38. package/dist/types/core/errors.d.ts +0 -122
  39. package/dist/types/enums/escrow.enums.d.ts +0 -24
  40. package/dist/types/enums/index.d.ts +0 -69
  41. package/dist/types/enums/monetization.enums.d.ts +0 -6
  42. package/dist/types/enums/payment.enums.d.ts +0 -16
  43. package/dist/types/enums/split.enums.d.ts +0 -25
  44. package/dist/types/enums/subscription.enums.d.ts +0 -15
  45. package/dist/types/enums/transaction.enums.d.ts +0 -24
  46. package/dist/types/index.d.ts +0 -22
  47. package/dist/types/providers/base.d.ts +0 -126
  48. package/dist/types/schemas/escrow/hold.schema.d.ts +0 -54
  49. package/dist/types/schemas/escrow/index.d.ts +0 -6
  50. package/dist/types/schemas/index.d.ts +0 -506
  51. package/dist/types/schemas/split/index.d.ts +0 -8
  52. package/dist/types/schemas/split/split.schema.d.ts +0 -142
  53. package/dist/types/schemas/subscription/index.d.ts +0 -152
  54. package/dist/types/schemas/subscription/info.schema.d.ts +0 -128
  55. package/dist/types/schemas/subscription/plan.schema.d.ts +0 -39
  56. package/dist/types/schemas/transaction/common.schema.d.ts +0 -12
  57. package/dist/types/schemas/transaction/gateway.schema.d.ts +0 -86
  58. package/dist/types/schemas/transaction/index.d.ts +0 -202
  59. package/dist/types/schemas/transaction/payment.schema.d.ts +0 -145
  60. package/dist/types/services/escrow.service.d.ts +0 -51
  61. package/dist/types/services/monetization.service.d.ts +0 -193
  62. package/dist/types/services/payment.service.d.ts +0 -112
  63. package/dist/types/services/transaction.service.d.ts +0 -40
  64. package/dist/types/utils/category-resolver.d.ts +0 -46
  65. package/dist/types/utils/commission-split.d.ts +0 -56
  66. package/dist/types/utils/commission.d.ts +0 -29
  67. package/dist/types/utils/hooks.d.ts +0 -17
  68. package/dist/types/utils/index.d.ts +0 -6
  69. package/dist/types/utils/logger.d.ts +0 -12
  70. package/dist/types/utils/subscription/actions.d.ts +0 -28
  71. package/dist/types/utils/subscription/index.d.ts +0 -2
  72. package/dist/types/utils/subscription/period.d.ts +0 -47
  73. package/dist/types/utils/transaction-type.d.ts +0 -102
  74. package/enums/escrow.enums.js +0 -36
  75. package/enums/index.d.ts +0 -116
  76. package/enums/index.js +0 -110
  77. package/enums/monetization.enums.js +0 -15
  78. package/enums/payment.enums.js +0 -64
  79. package/enums/split.enums.js +0 -37
  80. package/enums/subscription.enums.js +0 -33
  81. package/enums/transaction.enums.js +0 -69
  82. package/index.js +0 -76
  83. package/providers/base.js +0 -162
  84. package/schemas/escrow/hold.schema.js +0 -62
  85. package/schemas/escrow/index.js +0 -15
  86. package/schemas/index.d.ts +0 -33
  87. package/schemas/index.js +0 -27
  88. package/schemas/split/index.js +0 -16
  89. package/schemas/split/split.schema.js +0 -86
  90. package/schemas/subscription/index.js +0 -17
  91. package/schemas/subscription/info.schema.js +0 -115
  92. package/schemas/subscription/plan.schema.js +0 -48
  93. package/schemas/transaction/common.schema.js +0 -22
  94. package/schemas/transaction/gateway.schema.js +0 -69
  95. package/schemas/transaction/index.js +0 -20
  96. package/schemas/transaction/payment.schema.js +0 -110
  97. package/services/escrow.service.js +0 -353
  98. package/services/monetization.service.js +0 -671
  99. package/services/payment.service.js +0 -517
  100. package/services/transaction.service.js +0 -142
  101. package/utils/category-resolver.js +0 -74
  102. package/utils/commission-split.js +0 -180
  103. package/utils/commission.js +0 -83
  104. package/utils/hooks.js +0 -44
  105. package/utils/index.d.ts +0 -164
  106. package/utils/index.js +0 -16
  107. package/utils/logger.js +0 -36
  108. package/utils/subscription/actions.js +0 -68
  109. package/utils/subscription/index.js +0 -20
  110. package/utils/subscription/period.js +0 -123
  111. package/utils/transaction-type.js +0 -254
@@ -0,0 +1,884 @@
1
+ import { M as MonetizationService, P as PaymentService, T as TransactionService, E as EscrowService, C as Container } from '../index-BnJWVXuw.js';
2
+ import { d as TransactionDocument, e as SubscriptionDocument, a as MongooseModel, w as PaymentProviderInterface } from '../index-ChVD3P9k.js';
3
+ import { PaymentResult, RefundResult, PaymentProvider } from '../providers/index.js';
4
+ import { x as RetryConfig, R as Result } from '../retry-80lBCmSe.js';
5
+ export { E as Err, O as Ok, g as all, e as err, f as flatMap, a as isErr, i as isOk, m as map, c as mapErr, h as match, o as ok, t as tryCatch, d as tryCatchSync, u as unwrap, b as unwrapOr } from '../retry-80lBCmSe.js';
6
+ import 'mongoose';
7
+
8
+ /**
9
+ * Event System - Type-safe pub/sub
10
+ * @classytic/revenue
11
+ *
12
+ * Strongly typed events with async handlers
13
+ * Inspired by: Node.js EventEmitter, mitt, EventTarget
14
+ */
15
+
16
+ /**
17
+ * All revenue events with their payload types
18
+ */
19
+ interface RevenueEvents {
20
+ 'payment.initiated': PaymentInitiatedEvent;
21
+ 'payment.succeeded': PaymentSucceededEvent;
22
+ 'payment.failed': PaymentFailedEvent;
23
+ 'payment.refunded': PaymentRefundedEvent;
24
+ 'subscription.created': SubscriptionCreatedEvent;
25
+ 'subscription.activated': SubscriptionActivatedEvent;
26
+ 'subscription.renewed': SubscriptionRenewedEvent;
27
+ 'subscription.cancelled': SubscriptionCancelledEvent;
28
+ 'subscription.paused': SubscriptionPausedEvent;
29
+ 'subscription.resumed': SubscriptionResumedEvent;
30
+ 'subscription.expired': SubscriptionExpiredEvent;
31
+ 'transaction.created': TransactionCreatedEvent;
32
+ 'transaction.verified': TransactionVerifiedEvent;
33
+ 'transaction.completed': TransactionCompletedEvent;
34
+ 'transaction.failed': TransactionFailedEvent;
35
+ 'escrow.held': EscrowHeldEvent;
36
+ 'escrow.released': EscrowReleasedEvent;
37
+ 'escrow.cancelled': EscrowCancelledEvent;
38
+ 'commission.calculated': CommissionCalculatedEvent;
39
+ 'commission.paid': CommissionPaidEvent;
40
+ 'webhook.received': WebhookReceivedEvent;
41
+ 'webhook.processed': WebhookProcessedEvent;
42
+ '*': BaseEvent;
43
+ }
44
+ interface BaseEvent {
45
+ readonly type: string;
46
+ readonly timestamp: Date;
47
+ readonly metadata?: Record<string, unknown>;
48
+ }
49
+ interface PaymentInitiatedEvent extends BaseEvent {
50
+ type: 'payment.initiated';
51
+ transactionId: string;
52
+ amount: number;
53
+ currency: string;
54
+ provider: string;
55
+ intentId: string;
56
+ }
57
+ interface PaymentSucceededEvent extends BaseEvent {
58
+ type: 'payment.succeeded';
59
+ transactionId: string;
60
+ transaction: TransactionDocument;
61
+ result: PaymentResult;
62
+ }
63
+ interface PaymentFailedEvent extends BaseEvent {
64
+ type: 'payment.failed';
65
+ transactionId: string;
66
+ error: Error;
67
+ provider: string;
68
+ }
69
+ interface PaymentRefundedEvent extends BaseEvent {
70
+ type: 'payment.refunded';
71
+ transactionId: string;
72
+ result: RefundResult;
73
+ amount: number;
74
+ isPartial: boolean;
75
+ }
76
+ interface SubscriptionCreatedEvent extends BaseEvent {
77
+ type: 'subscription.created';
78
+ subscriptionId: string;
79
+ subscription: SubscriptionDocument;
80
+ transactionId?: string;
81
+ }
82
+ interface SubscriptionActivatedEvent extends BaseEvent {
83
+ type: 'subscription.activated';
84
+ subscriptionId: string;
85
+ subscription: SubscriptionDocument;
86
+ transactionId: string;
87
+ }
88
+ interface SubscriptionRenewedEvent extends BaseEvent {
89
+ type: 'subscription.renewed';
90
+ subscriptionId: string;
91
+ subscription: SubscriptionDocument;
92
+ transactionId: string;
93
+ period: {
94
+ start: Date;
95
+ end: Date;
96
+ };
97
+ }
98
+ interface SubscriptionCancelledEvent extends BaseEvent {
99
+ type: 'subscription.cancelled';
100
+ subscriptionId: string;
101
+ subscription: SubscriptionDocument;
102
+ reason?: string;
103
+ immediate: boolean;
104
+ }
105
+ interface SubscriptionPausedEvent extends BaseEvent {
106
+ type: 'subscription.paused';
107
+ subscriptionId: string;
108
+ subscription: SubscriptionDocument;
109
+ resumeAt?: Date;
110
+ }
111
+ interface SubscriptionResumedEvent extends BaseEvent {
112
+ type: 'subscription.resumed';
113
+ subscriptionId: string;
114
+ subscription: SubscriptionDocument;
115
+ }
116
+ interface SubscriptionExpiredEvent extends BaseEvent {
117
+ type: 'subscription.expired';
118
+ subscriptionId: string;
119
+ subscription: SubscriptionDocument;
120
+ }
121
+ interface TransactionCreatedEvent extends BaseEvent {
122
+ type: 'transaction.created';
123
+ transactionId: string;
124
+ transaction: TransactionDocument;
125
+ }
126
+ interface TransactionVerifiedEvent extends BaseEvent {
127
+ type: 'transaction.verified';
128
+ transactionId: string;
129
+ transaction: TransactionDocument;
130
+ }
131
+ interface TransactionCompletedEvent extends BaseEvent {
132
+ type: 'transaction.completed';
133
+ transactionId: string;
134
+ transaction: TransactionDocument;
135
+ }
136
+ interface TransactionFailedEvent extends BaseEvent {
137
+ type: 'transaction.failed';
138
+ transactionId: string;
139
+ error: Error;
140
+ }
141
+ interface EscrowHeldEvent extends BaseEvent {
142
+ type: 'escrow.held';
143
+ transactionId: string;
144
+ amount: number;
145
+ holdUntil?: Date;
146
+ }
147
+ interface EscrowReleasedEvent extends BaseEvent {
148
+ type: 'escrow.released';
149
+ transactionId: string;
150
+ releasedAmount: number;
151
+ recipientId: string;
152
+ }
153
+ interface EscrowCancelledEvent extends BaseEvent {
154
+ type: 'escrow.cancelled';
155
+ transactionId: string;
156
+ reason: string;
157
+ }
158
+ interface CommissionCalculatedEvent extends BaseEvent {
159
+ type: 'commission.calculated';
160
+ transactionId: string;
161
+ grossAmount: number;
162
+ netAmount: number;
163
+ platformFee: number;
164
+ gatewayFee: number;
165
+ }
166
+ interface CommissionPaidEvent extends BaseEvent {
167
+ type: 'commission.paid';
168
+ transactionId: string;
169
+ recipientId: string;
170
+ amount: number;
171
+ }
172
+ interface WebhookReceivedEvent extends BaseEvent {
173
+ type: 'webhook.received';
174
+ provider: string;
175
+ eventType: string;
176
+ payload: unknown;
177
+ }
178
+ interface WebhookProcessedEvent extends BaseEvent {
179
+ type: 'webhook.processed';
180
+ provider: string;
181
+ eventType: string;
182
+ transactionId?: string;
183
+ success: boolean;
184
+ }
185
+ type EventHandler<T> = (event: T) => void | Promise<void>;
186
+ type EventKey = keyof RevenueEvents;
187
+ /**
188
+ * Type-safe event bus
189
+ */
190
+ declare class EventBus {
191
+ private handlers;
192
+ private onceHandlers;
193
+ /**
194
+ * Subscribe to an event
195
+ */
196
+ on<K extends EventKey>(event: K, handler: EventHandler<RevenueEvents[K]>): () => void;
197
+ /**
198
+ * Subscribe to an event once
199
+ */
200
+ once<K extends EventKey>(event: K, handler: EventHandler<RevenueEvents[K]>): () => void;
201
+ /**
202
+ * Unsubscribe from an event
203
+ */
204
+ off<K extends EventKey>(event: K, handler: EventHandler<RevenueEvents[K]>): void;
205
+ /**
206
+ * Emit an event (fire and forget, non-blocking)
207
+ */
208
+ emit<K extends EventKey>(event: K, payload: Omit<RevenueEvents[K], 'timestamp'>): void;
209
+ /**
210
+ * Emit and wait for all handlers to complete
211
+ */
212
+ emitAsync<K extends EventKey>(event: K, payload: Omit<RevenueEvents[K], 'timestamp'>): Promise<void>;
213
+ /**
214
+ * Remove all handlers
215
+ */
216
+ clear(): void;
217
+ /**
218
+ * Get handler count for an event
219
+ */
220
+ listenerCount(event: EventKey): number;
221
+ }
222
+ /**
223
+ * Create a new event bus
224
+ */
225
+ declare function createEventBus(): EventBus;
226
+
227
+ /**
228
+ * Plugin System
229
+ * @classytic/revenue
230
+ *
231
+ * Composable, type-safe plugin architecture
232
+ * Inspired by: Hono middleware, Fastify plugins, Redux middleware
233
+ */
234
+
235
+ /**
236
+ * Plugin context passed to hooks
237
+ */
238
+ interface PluginContext {
239
+ /** Event bus for emitting events */
240
+ events: EventBus;
241
+ /** Logger instance */
242
+ logger: PluginLogger;
243
+ /** Get registered service */
244
+ get<T>(key: string): T;
245
+ /** Plugin-specific storage */
246
+ storage: Map<string, unknown>;
247
+ /** Request metadata */
248
+ meta: {
249
+ idempotencyKey?: string;
250
+ requestId: string;
251
+ timestamp: Date;
252
+ [key: string]: unknown;
253
+ };
254
+ }
255
+ /**
256
+ * Plugin logger interface
257
+ */
258
+ interface PluginLogger {
259
+ debug(message: string, data?: unknown): void;
260
+ info(message: string, data?: unknown): void;
261
+ warn(message: string, data?: unknown): void;
262
+ error(message: string, data?: unknown): void;
263
+ }
264
+ /**
265
+ * Hook function type
266
+ */
267
+ type HookFn<TInput = unknown, TOutput = unknown> = (ctx: PluginContext, input: TInput, next: () => Promise<TOutput>) => Promise<TOutput>;
268
+ /**
269
+ * Available hook points
270
+ */
271
+ interface PluginHooks {
272
+ 'payment.create.before': HookFn<PaymentCreateInput>;
273
+ 'payment.create.after': HookFn<PaymentCreateInput, PaymentCreateOutput>;
274
+ 'payment.verify.before': HookFn<PaymentVerifyInput>;
275
+ 'payment.verify.after': HookFn<PaymentVerifyInput, PaymentVerifyOutput>;
276
+ 'payment.refund.before': HookFn<RefundInput>;
277
+ 'payment.refund.after': HookFn<RefundInput, RefundOutput>;
278
+ 'subscription.create.before': HookFn<SubscriptionCreateInput>;
279
+ 'subscription.create.after': HookFn<SubscriptionCreateInput, SubscriptionCreateOutput>;
280
+ 'subscription.cancel.before': HookFn<SubscriptionCancelInput>;
281
+ 'subscription.cancel.after': HookFn<SubscriptionCancelInput, SubscriptionCancelOutput>;
282
+ 'transaction.create.before': HookFn<TransactionCreateInput>;
283
+ 'transaction.create.after': HookFn<TransactionCreateInput, TransactionCreateOutput>;
284
+ 'escrow.hold.before': HookFn<EscrowHoldInput>;
285
+ 'escrow.hold.after': HookFn<EscrowHoldInput, EscrowHoldOutput>;
286
+ 'escrow.release.before': HookFn<EscrowReleaseInput>;
287
+ 'escrow.release.after': HookFn<EscrowReleaseInput, EscrowReleaseOutput>;
288
+ }
289
+ interface PaymentCreateInput {
290
+ amount: number;
291
+ currency: string;
292
+ [key: string]: unknown;
293
+ }
294
+ interface PaymentCreateOutput {
295
+ transactionId: string;
296
+ intentId: string;
297
+ [key: string]: unknown;
298
+ }
299
+ interface PaymentVerifyInput {
300
+ id: string;
301
+ [key: string]: unknown;
302
+ }
303
+ interface PaymentVerifyOutput {
304
+ verified: boolean;
305
+ [key: string]: unknown;
306
+ }
307
+ interface RefundInput {
308
+ transactionId: string;
309
+ amount?: number;
310
+ [key: string]: unknown;
311
+ }
312
+ interface RefundOutput {
313
+ refundId: string;
314
+ [key: string]: unknown;
315
+ }
316
+ interface SubscriptionCreateInput {
317
+ planKey: string;
318
+ [key: string]: unknown;
319
+ }
320
+ interface SubscriptionCreateOutput {
321
+ subscriptionId: string;
322
+ [key: string]: unknown;
323
+ }
324
+ interface SubscriptionCancelInput {
325
+ subscriptionId: string;
326
+ [key: string]: unknown;
327
+ }
328
+ interface SubscriptionCancelOutput {
329
+ cancelled: boolean;
330
+ [key: string]: unknown;
331
+ }
332
+ interface TransactionCreateInput {
333
+ amount: number;
334
+ [key: string]: unknown;
335
+ }
336
+ interface TransactionCreateOutput {
337
+ transactionId: string;
338
+ [key: string]: unknown;
339
+ }
340
+ interface EscrowHoldInput {
341
+ transactionId: string;
342
+ [key: string]: unknown;
343
+ }
344
+ interface EscrowHoldOutput {
345
+ held: boolean;
346
+ [key: string]: unknown;
347
+ }
348
+ interface EscrowReleaseInput {
349
+ transactionId: string;
350
+ [key: string]: unknown;
351
+ }
352
+ interface EscrowReleaseOutput {
353
+ released: boolean;
354
+ [key: string]: unknown;
355
+ }
356
+ /**
357
+ * Plugin definition
358
+ */
359
+ interface RevenuePlugin {
360
+ /** Unique plugin name */
361
+ name: string;
362
+ /** Plugin version */
363
+ version?: string;
364
+ /** Plugin description */
365
+ description?: string;
366
+ /** Dependencies on other plugins */
367
+ dependencies?: string[];
368
+ /** Hook implementations */
369
+ hooks?: Partial<PluginHooks>;
370
+ /** Event listeners */
371
+ events?: Partial<{
372
+ [K in keyof RevenueEvents]: (event: RevenueEvents[K]) => void | Promise<void>;
373
+ }>;
374
+ /** Initialize plugin */
375
+ init?: (ctx: PluginContext) => void | Promise<void>;
376
+ /** Cleanup plugin */
377
+ destroy?: () => void | Promise<void>;
378
+ }
379
+ /**
380
+ * Plugin manager - handles registration and execution
381
+ */
382
+ declare class PluginManager {
383
+ private plugins;
384
+ private hooks;
385
+ private initialized;
386
+ /**
387
+ * Register a plugin
388
+ */
389
+ register(plugin: RevenuePlugin): this;
390
+ /**
391
+ * Initialize all plugins
392
+ */
393
+ init(ctx: PluginContext): Promise<void>;
394
+ /**
395
+ * Execute a hook chain
396
+ */
397
+ executeHook<TInput, TOutput>(hookName: string, ctx: PluginContext, input: TInput, execute: () => Promise<TOutput>): Promise<TOutput>;
398
+ /**
399
+ * Check if plugin is registered
400
+ */
401
+ has(name: string): boolean;
402
+ /**
403
+ * Get a plugin by name
404
+ */
405
+ get(name: string): RevenuePlugin | undefined;
406
+ /**
407
+ * Get all registered plugins
408
+ */
409
+ list(): RevenuePlugin[];
410
+ /**
411
+ * Destroy all plugins
412
+ */
413
+ destroy(): Promise<void>;
414
+ }
415
+ /**
416
+ * Logging plugin - logs all operations
417
+ */
418
+ declare function loggingPlugin(options?: {
419
+ level?: 'debug' | 'info';
420
+ }): RevenuePlugin;
421
+ /**
422
+ * Audit plugin - records all operations for compliance
423
+ */
424
+ declare function auditPlugin(options?: {
425
+ store?: (entry: AuditEntry) => Promise<void>;
426
+ }): RevenuePlugin;
427
+ interface AuditEntry {
428
+ action: string;
429
+ requestId: string;
430
+ timestamp: Date;
431
+ input: Record<string, unknown>;
432
+ output: Record<string, unknown>;
433
+ idempotencyKey?: string;
434
+ }
435
+ /**
436
+ * Metrics plugin - collects operation metrics
437
+ */
438
+ declare function metricsPlugin(options?: {
439
+ onMetric?: (metric: Metric) => void;
440
+ }): RevenuePlugin;
441
+ interface Metric {
442
+ name: string;
443
+ duration: number;
444
+ success: boolean;
445
+ error?: string;
446
+ [key: string]: unknown;
447
+ }
448
+ /**
449
+ * Create a custom plugin
450
+ */
451
+ declare function definePlugin(plugin: RevenuePlugin): RevenuePlugin;
452
+
453
+ /**
454
+ * Revenue - Modern Payment Management
455
+ * @classytic/revenue
456
+ *
457
+ * Fluent Builder API with integrated services
458
+ * Less code, more power
459
+ *
460
+ * Inspired by: Vercel AI SDK, Stripe SDK, tRPC
461
+ */
462
+
463
+ /** Internal config for Revenue instance */
464
+ interface InternalConfig {
465
+ defaultCurrency: string;
466
+ commissionRate: number;
467
+ gatewayFeeRate: number;
468
+ targetModels?: string[];
469
+ categoryMappings?: Record<string, string>;
470
+ }
471
+ interface RevenueOptions {
472
+ /** Default currency (ISO 4217) */
473
+ defaultCurrency?: string;
474
+ /** Environment */
475
+ environment?: 'development' | 'staging' | 'production';
476
+ /** Debug mode */
477
+ debug?: boolean;
478
+ /** Retry configuration */
479
+ retry?: Partial<RetryConfig>;
480
+ /** Idempotency TTL in ms */
481
+ idempotencyTtl?: number;
482
+ /** Enable circuit breaker */
483
+ circuitBreaker?: boolean;
484
+ /** Custom logger */
485
+ logger?: PluginLogger;
486
+ /** Commission rate (0-100) */
487
+ commissionRate?: number;
488
+ /** Gateway fee rate (0-100) */
489
+ gatewayFeeRate?: number;
490
+ }
491
+ interface ModelsConfig {
492
+ Transaction: MongooseModel<any>;
493
+ Subscription?: MongooseModel<any>;
494
+ [key: string]: MongooseModel<any> | undefined;
495
+ }
496
+ interface ProvidersConfig {
497
+ [name: string]: PaymentProvider;
498
+ }
499
+ interface HooksConfig {
500
+ [key: string]: ((...args: any[]) => void | Promise<void>) | undefined;
501
+ }
502
+ /**
503
+ * Revenue - Main entry point
504
+ *
505
+ * @example
506
+ * ```typescript
507
+ * const revenue = Revenue
508
+ * .create({ defaultCurrency: 'USD' })
509
+ * .withModels({ Transaction, Subscription })
510
+ * .withProvider('stripe', new StripeProvider({ apiKey: '...' }))
511
+ * .withProvider('manual', new ManualProvider())
512
+ * .withPlugin(auditPlugin())
513
+ * .build();
514
+ *
515
+ * // Access services directly
516
+ * await revenue.monetization.create({ ... });
517
+ * await revenue.payments.verify({ ... });
518
+ *
519
+ * // Or use events
520
+ * revenue.on('payment.succeeded', (event) => { ... });
521
+ * ```
522
+ */
523
+ declare class Revenue {
524
+ private readonly _container;
525
+ private readonly _events;
526
+ private readonly _plugins;
527
+ private readonly _idempotency;
528
+ private readonly _circuitBreaker?;
529
+ private readonly _options;
530
+ private readonly _logger;
531
+ private readonly _providers;
532
+ private readonly _config;
533
+ /** Monetization service - purchases, subscriptions, free items */
534
+ readonly monetization: MonetizationService;
535
+ /** Payment service - verify, refund, webhooks */
536
+ readonly payments: PaymentService;
537
+ /** Transaction service - query, update transactions */
538
+ readonly transactions: TransactionService;
539
+ /** Escrow service - hold, release, splits */
540
+ readonly escrow: EscrowService;
541
+ private constructor();
542
+ /**
543
+ * Create a new Revenue builder
544
+ *
545
+ * @example
546
+ * ```typescript
547
+ * const revenue = Revenue
548
+ * .create({ defaultCurrency: 'BDT' })
549
+ * .withModels({ Transaction, Subscription })
550
+ * .withProvider('manual', new ManualProvider())
551
+ * .build();
552
+ * ```
553
+ */
554
+ static create(options?: RevenueOptions): RevenueBuilder;
555
+ /** DI container (for advanced usage) */
556
+ get container(): Container;
557
+ /** Event bus */
558
+ get events(): EventBus;
559
+ /** Registered providers (frozen) */
560
+ get providers(): Readonly<ProvidersConfig>;
561
+ /** Configuration (frozen) */
562
+ get config(): Readonly<InternalConfig>;
563
+ /** Default currency */
564
+ get defaultCurrency(): string;
565
+ /** Current environment */
566
+ get environment(): string;
567
+ /**
568
+ * Get a provider by name
569
+ */
570
+ getProvider(name: string): PaymentProviderInterface;
571
+ /**
572
+ * Get all provider names
573
+ */
574
+ getProviderNames(): string[];
575
+ /**
576
+ * Check if provider exists
577
+ */
578
+ hasProvider(name: string): boolean;
579
+ /**
580
+ * Subscribe to events
581
+ *
582
+ * @example
583
+ * ```typescript
584
+ * revenue.on('payment.succeeded', (event) => {
585
+ * console.log('Payment:', event.transactionId);
586
+ * });
587
+ * ```
588
+ */
589
+ on: EventBus['on'];
590
+ /**
591
+ * Subscribe once
592
+ */
593
+ once: EventBus['once'];
594
+ /**
595
+ * Unsubscribe
596
+ */
597
+ off: EventBus['off'];
598
+ /**
599
+ * Emit an event
600
+ */
601
+ emit: EventBus['emit'];
602
+ /**
603
+ * Execute operation with retry and idempotency
604
+ */
605
+ execute<T>(operation: () => Promise<T>, options?: {
606
+ idempotencyKey?: string;
607
+ params?: unknown;
608
+ useRetry?: boolean;
609
+ useCircuitBreaker?: boolean;
610
+ }): Promise<Result<T, Error>>;
611
+ /**
612
+ * Create plugin context (for advanced usage)
613
+ */
614
+ createContext(meta?: {
615
+ idempotencyKey?: string;
616
+ }): PluginContext;
617
+ /**
618
+ * Destroy instance and cleanup
619
+ */
620
+ destroy(): Promise<void>;
621
+ }
622
+ /**
623
+ * Revenue Builder - Fluent configuration API
624
+ */
625
+ declare class RevenueBuilder {
626
+ private options;
627
+ private models;
628
+ private providers;
629
+ private plugins;
630
+ private hooks;
631
+ private categoryMappings;
632
+ constructor(options?: RevenueOptions);
633
+ /**
634
+ * Register models (required)
635
+ *
636
+ * @example
637
+ * ```typescript
638
+ * .withModels({
639
+ * Transaction: TransactionModel,
640
+ * Subscription: SubscriptionModel,
641
+ * })
642
+ * ```
643
+ */
644
+ withModels(models: ModelsConfig): this;
645
+ /**
646
+ * Register a single model
647
+ */
648
+ withModel(name: string, model: MongooseModel<any>): this;
649
+ /**
650
+ * Register a payment provider
651
+ *
652
+ * @example
653
+ * ```typescript
654
+ * .withProvider('stripe', new StripeProvider({ apiKey: '...' }))
655
+ * .withProvider('manual', new ManualProvider())
656
+ * ```
657
+ */
658
+ withProvider(name: string, provider: PaymentProvider): this;
659
+ /**
660
+ * Register multiple providers at once
661
+ */
662
+ withProviders(providers: ProvidersConfig): this;
663
+ /**
664
+ * Register a plugin
665
+ *
666
+ * @example
667
+ * ```typescript
668
+ * .withPlugin(loggingPlugin())
669
+ * .withPlugin(auditPlugin({ store: saveToDb }))
670
+ * ```
671
+ */
672
+ withPlugin(plugin: RevenuePlugin): this;
673
+ /**
674
+ * Register multiple plugins
675
+ */
676
+ withPlugins(plugins: RevenuePlugin[]): this;
677
+ /**
678
+ * Register event hooks (for backward compatibility)
679
+ *
680
+ * @example
681
+ * ```typescript
682
+ * .withHooks({
683
+ * onPaymentVerified: async (tx) => { ... },
684
+ * onSubscriptionRenewed: async (sub) => { ... },
685
+ * })
686
+ * ```
687
+ */
688
+ withHooks(hooks: HooksConfig): this;
689
+ /**
690
+ * Set retry configuration
691
+ *
692
+ * @example
693
+ * ```typescript
694
+ * .withRetry({ maxAttempts: 5, baseDelay: 2000 })
695
+ * ```
696
+ */
697
+ withRetry(config: Partial<RetryConfig>): this;
698
+ /**
699
+ * Enable circuit breaker
700
+ */
701
+ withCircuitBreaker(enabled?: boolean): this;
702
+ /**
703
+ * Set custom logger
704
+ */
705
+ withLogger(logger: PluginLogger): this;
706
+ /**
707
+ * Set environment
708
+ */
709
+ forEnvironment(env: 'development' | 'staging' | 'production'): this;
710
+ /**
711
+ * Enable debug mode
712
+ */
713
+ withDebug(enabled?: boolean): this;
714
+ /**
715
+ * Set commission rate (0-100)
716
+ */
717
+ withCommission(rate: number, gatewayFeeRate?: number): this;
718
+ /**
719
+ * Set category mappings (entity → category)
720
+ *
721
+ * @example
722
+ * ```typescript
723
+ * .withCategoryMappings({
724
+ * PlatformSubscription: 'platform_subscription',
725
+ * CourseEnrollment: 'course_enrollment',
726
+ * ProductOrder: 'product_order',
727
+ * })
728
+ * ```
729
+ */
730
+ withCategoryMappings(mappings: Record<string, string>): this;
731
+ /**
732
+ * Build the Revenue instance
733
+ */
734
+ build(): Revenue;
735
+ }
736
+ /**
737
+ * Create Revenue instance (shorthand)
738
+ *
739
+ * @example
740
+ * ```typescript
741
+ * const revenue = createRevenue({
742
+ * models: { Transaction, Subscription },
743
+ * providers: { manual: new ManualProvider() },
744
+ * });
745
+ * ```
746
+ */
747
+ declare function createRevenue(config: {
748
+ models: ModelsConfig;
749
+ providers: ProvidersConfig;
750
+ options?: RevenueOptions;
751
+ plugins?: RevenuePlugin[];
752
+ hooks?: HooksConfig;
753
+ }): Revenue;
754
+
755
+ /**
756
+ * Revenue Error Classes
757
+ * @classytic/revenue
758
+ *
759
+ * Typed errors with codes for better error handling
760
+ */
761
+ interface RevenueErrorOptions {
762
+ retryable?: boolean;
763
+ metadata?: Record<string, unknown>;
764
+ }
765
+ /**
766
+ * Base Revenue Error
767
+ */
768
+ declare class RevenueError extends Error {
769
+ readonly code: string;
770
+ readonly retryable: boolean;
771
+ readonly metadata: Record<string, unknown>;
772
+ constructor(message: string, code: string, options?: RevenueErrorOptions);
773
+ toJSON(): Record<string, unknown>;
774
+ }
775
+ /**
776
+ * Configuration Errors
777
+ */
778
+ declare class ConfigurationError extends RevenueError {
779
+ constructor(message: string, metadata?: Record<string, unknown>);
780
+ }
781
+ declare class ModelNotRegisteredError extends ConfigurationError {
782
+ constructor(modelName: string);
783
+ }
784
+ /**
785
+ * Provider Errors
786
+ */
787
+ declare class ProviderError extends RevenueError {
788
+ constructor(message: string, code: string, options?: RevenueErrorOptions);
789
+ }
790
+ declare class ProviderNotFoundError extends ProviderError {
791
+ constructor(providerName: string, availableProviders?: string[]);
792
+ }
793
+ declare class ProviderCapabilityError extends ProviderError {
794
+ constructor(providerName: string, capability: string);
795
+ }
796
+ declare class PaymentIntentCreationError extends ProviderError {
797
+ constructor(providerName: string, originalError: Error);
798
+ }
799
+ declare class PaymentVerificationError extends ProviderError {
800
+ constructor(paymentIntentId: string, reason: string);
801
+ }
802
+ /**
803
+ * Resource Not Found Errors
804
+ */
805
+ declare class NotFoundError extends RevenueError {
806
+ constructor(message: string, code: string, metadata?: Record<string, unknown>);
807
+ }
808
+ declare class SubscriptionNotFoundError extends NotFoundError {
809
+ constructor(subscriptionId: string);
810
+ }
811
+ declare class TransactionNotFoundError extends NotFoundError {
812
+ constructor(transactionId: string);
813
+ }
814
+ /**
815
+ * Validation Errors
816
+ */
817
+ declare class ValidationError extends RevenueError {
818
+ constructor(message: string, metadata?: Record<string, unknown>);
819
+ }
820
+ declare class InvalidAmountError extends ValidationError {
821
+ constructor(amount: number, message?: string);
822
+ }
823
+ declare class MissingRequiredFieldError extends ValidationError {
824
+ constructor(fieldName: string);
825
+ }
826
+ /**
827
+ * State Errors
828
+ */
829
+ declare class StateError extends RevenueError {
830
+ constructor(message: string, code: string, metadata?: Record<string, unknown>);
831
+ }
832
+ declare class AlreadyVerifiedError extends StateError {
833
+ constructor(transactionId: string);
834
+ }
835
+ declare class InvalidStateTransitionError extends StateError {
836
+ constructor(resourceType: string, resourceId: string, fromState: string, toState: string);
837
+ }
838
+ declare class SubscriptionNotActiveError extends StateError {
839
+ constructor(subscriptionId: string, message?: string);
840
+ }
841
+ /**
842
+ * Operation Errors
843
+ */
844
+ declare class OperationError extends RevenueError {
845
+ constructor(message: string, code: string, options?: RevenueErrorOptions);
846
+ }
847
+ declare class RefundNotSupportedError extends OperationError {
848
+ constructor(providerName: string);
849
+ }
850
+ declare class RefundError extends OperationError {
851
+ constructor(transactionId: string, reason: string);
852
+ }
853
+ /**
854
+ * Error Code Constants
855
+ */
856
+ declare const ERROR_CODES: {
857
+ readonly CONFIGURATION_ERROR: "CONFIGURATION_ERROR";
858
+ readonly MODEL_NOT_REGISTERED: "MODEL_NOT_REGISTERED";
859
+ readonly PROVIDER_NOT_FOUND: "PROVIDER_NOT_FOUND";
860
+ readonly PROVIDER_CAPABILITY_NOT_SUPPORTED: "PROVIDER_CAPABILITY_NOT_SUPPORTED";
861
+ readonly PAYMENT_INTENT_CREATION_FAILED: "PAYMENT_INTENT_CREATION_FAILED";
862
+ readonly PAYMENT_VERIFICATION_FAILED: "PAYMENT_VERIFICATION_FAILED";
863
+ readonly SUBSCRIPTION_NOT_FOUND: "SUBSCRIPTION_NOT_FOUND";
864
+ readonly TRANSACTION_NOT_FOUND: "TRANSACTION_NOT_FOUND";
865
+ readonly VALIDATION_ERROR: "VALIDATION_ERROR";
866
+ readonly INVALID_AMOUNT: "INVALID_AMOUNT";
867
+ readonly MISSING_REQUIRED_FIELD: "MISSING_REQUIRED_FIELD";
868
+ readonly ALREADY_VERIFIED: "ALREADY_VERIFIED";
869
+ readonly INVALID_STATE_TRANSITION: "INVALID_STATE_TRANSITION";
870
+ readonly SUBSCRIPTION_NOT_ACTIVE: "SUBSCRIPTION_NOT_ACTIVE";
871
+ readonly REFUND_NOT_SUPPORTED: "REFUND_NOT_SUPPORTED";
872
+ readonly REFUND_FAILED: "REFUND_FAILED";
873
+ };
874
+ type ErrorCode = typeof ERROR_CODES[keyof typeof ERROR_CODES];
875
+ /**
876
+ * Check if error is retryable
877
+ */
878
+ declare function isRetryable(error: unknown): boolean;
879
+ /**
880
+ * Check if error is from revenue package
881
+ */
882
+ declare function isRevenueError(error: unknown): error is RevenueError;
883
+
884
+ export { AlreadyVerifiedError, type BaseEvent, type CommissionCalculatedEvent, type CommissionPaidEvent, ConfigurationError, Container, ERROR_CODES, type ErrorCode, type EscrowCancelledEvent, type EscrowHeldEvent, type EscrowReleasedEvent, EventBus, type HookFn, type HooksConfig, InvalidAmountError, InvalidStateTransitionError, MissingRequiredFieldError, ModelNotRegisteredError, type ModelsConfig, NotFoundError, OperationError, type PaymentFailedEvent, type PaymentInitiatedEvent, PaymentIntentCreationError, type PaymentRefundedEvent, type PaymentSucceededEvent, PaymentVerificationError, type PluginContext, type PluginHooks, type PluginLogger, PluginManager, ProviderCapabilityError, ProviderError, ProviderNotFoundError, type ProvidersConfig, RefundError, RefundNotSupportedError, Result, Revenue, RevenueBuilder, RevenueError, type RevenueErrorOptions, type RevenueEvents, type RevenueOptions, type RevenuePlugin, StateError, type SubscriptionActivatedEvent, type SubscriptionCancelledEvent, type SubscriptionCreatedEvent, type SubscriptionExpiredEvent, SubscriptionNotActiveError, SubscriptionNotFoundError, type SubscriptionPausedEvent, type SubscriptionRenewedEvent, type SubscriptionResumedEvent, type TransactionCompletedEvent, type TransactionCreatedEvent, type TransactionFailedEvent, TransactionNotFoundError, type TransactionVerifiedEvent, ValidationError, type WebhookProcessedEvent, type WebhookReceivedEvent, auditPlugin, createEventBus, createRevenue, definePlugin, isRetryable, isRevenueError, loggingPlugin, metricsPlugin };