@classytic/revenue 1.0.2 → 1.1.2

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 (53) hide show
  1. package/README.md +603 -486
  2. package/dist/application/services/index.d.ts +6 -0
  3. package/dist/application/services/index.js +3288 -0
  4. package/dist/application/services/index.js.map +1 -0
  5. package/dist/core/events.d.ts +455 -0
  6. package/dist/core/events.js +122 -0
  7. package/dist/core/events.js.map +1 -0
  8. package/dist/core/index.d.ts +12 -889
  9. package/dist/core/index.js +2361 -705
  10. package/dist/core/index.js.map +1 -1
  11. package/dist/enums/index.d.ts +54 -25
  12. package/dist/enums/index.js +143 -14
  13. package/dist/enums/index.js.map +1 -1
  14. package/dist/escrow.enums-CE0VQsfe.d.ts +76 -0
  15. package/dist/{index-BnJWVXuw.d.ts → index-DxIK0UmZ.d.ts} +281 -26
  16. package/dist/index-EnfKzDbs.d.ts +806 -0
  17. package/dist/{index-ChVD3P9k.d.ts → index-cLJBLUvx.d.ts} +55 -81
  18. package/dist/index.d.ts +16 -15
  19. package/dist/index.js +2583 -2066
  20. package/dist/index.js.map +1 -1
  21. package/dist/infrastructure/plugins/index.d.ts +267 -0
  22. package/dist/infrastructure/plugins/index.js +292 -0
  23. package/dist/infrastructure/plugins/index.js.map +1 -0
  24. package/dist/money-widWVD7r.d.ts +111 -0
  25. package/dist/payment.enums-C1BiGlRa.d.ts +69 -0
  26. package/dist/plugin-Bb9HOE10.d.ts +336 -0
  27. package/dist/providers/index.d.ts +19 -6
  28. package/dist/providers/index.js +22 -3
  29. package/dist/providers/index.js.map +1 -1
  30. package/dist/reconciliation/index.d.ts +215 -0
  31. package/dist/reconciliation/index.js +140 -0
  32. package/dist/reconciliation/index.js.map +1 -0
  33. package/dist/{retry-80lBCmSe.d.ts → retry-D4hFUwVk.d.ts} +1 -41
  34. package/dist/schemas/index.d.ts +1927 -166
  35. package/dist/schemas/index.js +357 -40
  36. package/dist/schemas/index.js.map +1 -1
  37. package/dist/schemas/validation.d.ts +87 -12
  38. package/dist/schemas/validation.js +71 -17
  39. package/dist/schemas/validation.js.map +1 -1
  40. package/dist/settlement.enums-ByC1x0ye.d.ts +130 -0
  41. package/dist/settlement.schema-CpamV7ZY.d.ts +343 -0
  42. package/dist/split.enums-DG3TxQf9.d.ts +42 -0
  43. package/dist/tax-CV8A0sxl.d.ts +60 -0
  44. package/dist/utils/index.d.ts +487 -13
  45. package/dist/utils/index.js +370 -235
  46. package/dist/utils/index.js.map +1 -1
  47. package/package.json +27 -13
  48. package/dist/actions-CwG-b7fR.d.ts +0 -519
  49. package/dist/services/index.d.ts +0 -3
  50. package/dist/services/index.js +0 -1632
  51. package/dist/services/index.js.map +0 -1
  52. package/dist/split.enums-Bh24jw8p.d.ts +0 -255
  53. package/dist/split.schema-DYVP7Wu2.d.ts +0 -958
@@ -1,890 +1,13 @@
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, z as HooksRegistry, 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';
1
+ export { A as AlreadyVerifiedError, C as ConfigurationError, E as ERROR_CODES, D as ErrorCode, H as HOLD_STATE_MACHINE, I as InvalidAmountError, x as InvalidStateTransitionError, v as MissingRequiredFieldError, n as ModelNotRegisteredError, M as ModelsConfig, N as NotFoundError, O as OperationError, r as PaymentIntentCreationError, s as PaymentVerificationError, q as ProviderCapabilityError, o as ProviderError, p as ProviderNotFoundError, P as ProvidersConfig, B as RefundError, z as RefundNotSupportedError, R as Revenue, b as RevenueBuilder, a as RevenueError, m as RevenueErrorOptions, d as RevenueOptions, f as SETTLEMENT_STATE_MACHINE, g as SPLIT_STATE_MACHINE, e as SUBSCRIPTION_STATE_MACHINE, w as StateError, S as StateMachine, y as SubscriptionNotActiveError, t as SubscriptionNotFoundError, T as TRANSACTION_STATE_MACHINE, u as TransactionNotFoundError, V as ValidationError, c as createRevenue, F as isRetryable, G as isRevenueError } from '../index-EnfKzDbs.js';
2
+ export { C as Container } from '../index-DxIK0UmZ.js';
3
+ export { E as Err, O as Ok, R as Result, 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-D4hFUwVk.js';
4
+ export { BaseEvent, EscrowCancelledEvent, EscrowHeldEvent, EscrowReleasedEvent, EscrowSplitEvent, default as EventBus, FreeCreatedEvent, MonetizationCreatedEvent, PaymentFailedEvent, PaymentRefundedEvent, PaymentVerifiedEvent, PurchaseCreatedEvent, RevenueEvents, SettlementCompletedEvent, SettlementCreatedEvent, SettlementFailedEvent, SettlementProcessingEvent, SettlementScheduledEvent, SubscriptionActivatedEvent, SubscriptionCancelledEvent, SubscriptionCreatedEvent, SubscriptionPausedEvent, SubscriptionRenewedEvent, SubscriptionResumedEvent, TransactionUpdatedEvent, WebhookProcessedEvent, createEventBus } from './events.js';
5
+ export { H as HookFn, a as PluginContext, e as PluginHooks, P as PluginLogger, b as PluginManager, R as RevenuePlugin, c as auditPlugin, d as definePlugin, l as loggingPlugin, m as metricsPlugin } from '../plugin-Bb9HOE10.js';
6
+ import '../providers/index.js';
7
+ import '../index-cLJBLUvx.js';
6
8
  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
- type HookHandler = (data: unknown) => void | Promise<void>;
500
- /**
501
- * Hooks config accepted by the builder.
502
- *
503
- * At runtime, hooks are executed via the `HooksRegistry` shape (event -> handlers[]).
504
- * This type also accepts a legacy shorthand (event -> handler or handlers[]).
505
- */
506
- type HooksConfig = HooksRegistry | Record<string, HookHandler | HookHandler[] | undefined>;
507
- /**
508
- * Revenue - Main entry point
509
- *
510
- * @example
511
- * ```typescript
512
- * const revenue = Revenue
513
- * .create({ defaultCurrency: 'USD' })
514
- * .withModels({ Transaction, Subscription })
515
- * .withProvider('stripe', new StripeProvider({ apiKey: '...' }))
516
- * .withProvider('manual', new ManualProvider())
517
- * .withPlugin(auditPlugin())
518
- * .build();
519
- *
520
- * // Access services directly
521
- * await revenue.monetization.create({ ... });
522
- * await revenue.payments.verify({ ... });
523
- *
524
- * // Or use events
525
- * revenue.on('payment.succeeded', (event) => { ... });
526
- * ```
527
- */
528
- declare class Revenue {
529
- private readonly _container;
530
- private readonly _events;
531
- private readonly _plugins;
532
- private readonly _idempotency;
533
- private readonly _circuitBreaker?;
534
- private readonly _options;
535
- private readonly _logger;
536
- private readonly _providers;
537
- private readonly _config;
538
- /** Monetization service - purchases, subscriptions, free items */
539
- readonly monetization: MonetizationService;
540
- /** Payment service - verify, refund, webhooks */
541
- readonly payments: PaymentService;
542
- /** Transaction service - query, update transactions */
543
- readonly transactions: TransactionService;
544
- /** Escrow service - hold, release, splits */
545
- readonly escrow: EscrowService;
546
- private constructor();
547
- /**
548
- * Create a new Revenue builder
549
- *
550
- * @example
551
- * ```typescript
552
- * const revenue = Revenue
553
- * .create({ defaultCurrency: 'BDT' })
554
- * .withModels({ Transaction, Subscription })
555
- * .withProvider('manual', new ManualProvider())
556
- * .build();
557
- * ```
558
- */
559
- static create(options?: RevenueOptions): RevenueBuilder;
560
- /** DI container (for advanced usage) */
561
- get container(): Container;
562
- /** Event bus */
563
- get events(): EventBus;
564
- /** Registered providers (frozen) */
565
- get providers(): Readonly<ProvidersConfig>;
566
- /** Configuration (frozen) */
567
- get config(): Readonly<InternalConfig>;
568
- /** Default currency */
569
- get defaultCurrency(): string;
570
- /** Current environment */
571
- get environment(): string;
572
- /**
573
- * Get a provider by name
574
- */
575
- getProvider(name: string): PaymentProviderInterface;
576
- /**
577
- * Get all provider names
578
- */
579
- getProviderNames(): string[];
580
- /**
581
- * Check if provider exists
582
- */
583
- hasProvider(name: string): boolean;
584
- /**
585
- * Subscribe to events
586
- *
587
- * @example
588
- * ```typescript
589
- * revenue.on('payment.succeeded', (event) => {
590
- * console.log('Payment:', event.transactionId);
591
- * });
592
- * ```
593
- */
594
- on: EventBus['on'];
595
- /**
596
- * Subscribe once
597
- */
598
- once: EventBus['once'];
599
- /**
600
- * Unsubscribe
601
- */
602
- off: EventBus['off'];
603
- /**
604
- * Emit an event
605
- */
606
- emit: EventBus['emit'];
607
- /**
608
- * Execute operation with retry and idempotency
609
- */
610
- execute<T>(operation: () => Promise<T>, options?: {
611
- idempotencyKey?: string;
612
- params?: unknown;
613
- useRetry?: boolean;
614
- useCircuitBreaker?: boolean;
615
- }): Promise<Result<T, Error>>;
616
- /**
617
- * Create plugin context (for advanced usage)
618
- */
619
- createContext(meta?: {
620
- idempotencyKey?: string;
621
- }): PluginContext;
622
- /**
623
- * Destroy instance and cleanup
624
- */
625
- destroy(): Promise<void>;
626
- }
627
- /**
628
- * Revenue Builder - Fluent configuration API
629
- */
630
- declare class RevenueBuilder {
631
- private options;
632
- private models;
633
- private providers;
634
- private plugins;
635
- private hooks;
636
- private categoryMappings;
637
- constructor(options?: RevenueOptions);
638
- /**
639
- * Register models (required)
640
- *
641
- * @example
642
- * ```typescript
643
- * .withModels({
644
- * Transaction: TransactionModel,
645
- * Subscription: SubscriptionModel,
646
- * })
647
- * ```
648
- */
649
- withModels(models: ModelsConfig): this;
650
- /**
651
- * Register a single model
652
- */
653
- withModel(name: string, model: MongooseModel<any>): this;
654
- /**
655
- * Register a payment provider
656
- *
657
- * @example
658
- * ```typescript
659
- * .withProvider('stripe', new StripeProvider({ apiKey: '...' }))
660
- * .withProvider('manual', new ManualProvider())
661
- * ```
662
- */
663
- withProvider(name: string, provider: PaymentProvider): this;
664
- /**
665
- * Register multiple providers at once
666
- */
667
- withProviders(providers: ProvidersConfig): this;
668
- /**
669
- * Register a plugin
670
- *
671
- * @example
672
- * ```typescript
673
- * .withPlugin(loggingPlugin())
674
- * .withPlugin(auditPlugin({ store: saveToDb }))
675
- * ```
676
- */
677
- withPlugin(plugin: RevenuePlugin): this;
678
- /**
679
- * Register multiple plugins
680
- */
681
- withPlugins(plugins: RevenuePlugin[]): this;
682
- /**
683
- * Register event hooks (for backward compatibility)
684
- *
685
- * @example
686
- * ```typescript
687
- * .withHooks({
688
- * onPaymentVerified: async (tx) => { ... },
689
- * onSubscriptionRenewed: async (sub) => { ... },
690
- * })
691
- * ```
692
- */
693
- withHooks(hooks: HooksRegistry): this;
694
- withHooks(hooks: HooksConfig): this;
695
- /**
696
- * Set retry configuration
697
- *
698
- * @example
699
- * ```typescript
700
- * .withRetry({ maxAttempts: 5, baseDelay: 2000 })
701
- * ```
702
- */
703
- withRetry(config: Partial<RetryConfig>): this;
704
- /**
705
- * Enable circuit breaker
706
- */
707
- withCircuitBreaker(enabled?: boolean): this;
708
- /**
709
- * Set custom logger
710
- */
711
- withLogger(logger: PluginLogger): this;
712
- /**
713
- * Set environment
714
- */
715
- forEnvironment(env: 'development' | 'staging' | 'production'): this;
716
- /**
717
- * Enable debug mode
718
- */
719
- withDebug(enabled?: boolean): this;
720
- /**
721
- * Set commission rate (0-100)
722
- */
723
- withCommission(rate: number, gatewayFeeRate?: number): this;
724
- /**
725
- * Set category mappings (entity → category)
726
- *
727
- * @example
728
- * ```typescript
729
- * .withCategoryMappings({
730
- * PlatformSubscription: 'platform_subscription',
731
- * CourseEnrollment: 'course_enrollment',
732
- * ProductOrder: 'product_order',
733
- * })
734
- * ```
735
- */
736
- withCategoryMappings(mappings: Record<string, string>): this;
737
- /**
738
- * Build the Revenue instance
739
- */
740
- build(): Revenue;
741
- }
742
- /**
743
- * Create Revenue instance (shorthand)
744
- *
745
- * @example
746
- * ```typescript
747
- * const revenue = createRevenue({
748
- * models: { Transaction, Subscription },
749
- * providers: { manual: new ManualProvider() },
750
- * });
751
- * ```
752
- */
753
- declare function createRevenue(config: {
754
- models: ModelsConfig;
755
- providers: ProvidersConfig;
756
- options?: RevenueOptions;
757
- plugins?: RevenuePlugin[];
758
- hooks?: HooksConfig;
759
- }): Revenue;
760
-
761
- /**
762
- * Revenue Error Classes
763
- * @classytic/revenue
764
- *
765
- * Typed errors with codes for better error handling
766
- */
767
- interface RevenueErrorOptions {
768
- retryable?: boolean;
769
- metadata?: Record<string, unknown>;
770
- }
771
- /**
772
- * Base Revenue Error
773
- */
774
- declare class RevenueError extends Error {
775
- readonly code: string;
776
- readonly retryable: boolean;
777
- readonly metadata: Record<string, unknown>;
778
- constructor(message: string, code: string, options?: RevenueErrorOptions);
779
- toJSON(): Record<string, unknown>;
780
- }
781
- /**
782
- * Configuration Errors
783
- */
784
- declare class ConfigurationError extends RevenueError {
785
- constructor(message: string, metadata?: Record<string, unknown>);
786
- }
787
- declare class ModelNotRegisteredError extends ConfigurationError {
788
- constructor(modelName: string);
789
- }
790
- /**
791
- * Provider Errors
792
- */
793
- declare class ProviderError extends RevenueError {
794
- constructor(message: string, code: string, options?: RevenueErrorOptions);
795
- }
796
- declare class ProviderNotFoundError extends ProviderError {
797
- constructor(providerName: string, availableProviders?: string[]);
798
- }
799
- declare class ProviderCapabilityError extends ProviderError {
800
- constructor(providerName: string, capability: string);
801
- }
802
- declare class PaymentIntentCreationError extends ProviderError {
803
- constructor(providerName: string, originalError: Error);
804
- }
805
- declare class PaymentVerificationError extends ProviderError {
806
- constructor(paymentIntentId: string, reason: string);
807
- }
808
- /**
809
- * Resource Not Found Errors
810
- */
811
- declare class NotFoundError extends RevenueError {
812
- constructor(message: string, code: string, metadata?: Record<string, unknown>);
813
- }
814
- declare class SubscriptionNotFoundError extends NotFoundError {
815
- constructor(subscriptionId: string);
816
- }
817
- declare class TransactionNotFoundError extends NotFoundError {
818
- constructor(transactionId: string);
819
- }
820
- /**
821
- * Validation Errors
822
- */
823
- declare class ValidationError extends RevenueError {
824
- constructor(message: string, metadata?: Record<string, unknown>);
825
- }
826
- declare class InvalidAmountError extends ValidationError {
827
- constructor(amount: number, message?: string);
828
- }
829
- declare class MissingRequiredFieldError extends ValidationError {
830
- constructor(fieldName: string);
831
- }
832
- /**
833
- * State Errors
834
- */
835
- declare class StateError extends RevenueError {
836
- constructor(message: string, code: string, metadata?: Record<string, unknown>);
837
- }
838
- declare class AlreadyVerifiedError extends StateError {
839
- constructor(transactionId: string);
840
- }
841
- declare class InvalidStateTransitionError extends StateError {
842
- constructor(resourceType: string, resourceId: string, fromState: string, toState: string);
843
- }
844
- declare class SubscriptionNotActiveError extends StateError {
845
- constructor(subscriptionId: string, message?: string);
846
- }
847
- /**
848
- * Operation Errors
849
- */
850
- declare class OperationError extends RevenueError {
851
- constructor(message: string, code: string, options?: RevenueErrorOptions);
852
- }
853
- declare class RefundNotSupportedError extends OperationError {
854
- constructor(providerName: string);
855
- }
856
- declare class RefundError extends OperationError {
857
- constructor(transactionId: string, reason: string);
858
- }
859
- /**
860
- * Error Code Constants
861
- */
862
- declare const ERROR_CODES: {
863
- readonly CONFIGURATION_ERROR: "CONFIGURATION_ERROR";
864
- readonly MODEL_NOT_REGISTERED: "MODEL_NOT_REGISTERED";
865
- readonly PROVIDER_NOT_FOUND: "PROVIDER_NOT_FOUND";
866
- readonly PROVIDER_CAPABILITY_NOT_SUPPORTED: "PROVIDER_CAPABILITY_NOT_SUPPORTED";
867
- readonly PAYMENT_INTENT_CREATION_FAILED: "PAYMENT_INTENT_CREATION_FAILED";
868
- readonly PAYMENT_VERIFICATION_FAILED: "PAYMENT_VERIFICATION_FAILED";
869
- readonly SUBSCRIPTION_NOT_FOUND: "SUBSCRIPTION_NOT_FOUND";
870
- readonly TRANSACTION_NOT_FOUND: "TRANSACTION_NOT_FOUND";
871
- readonly VALIDATION_ERROR: "VALIDATION_ERROR";
872
- readonly INVALID_AMOUNT: "INVALID_AMOUNT";
873
- readonly MISSING_REQUIRED_FIELD: "MISSING_REQUIRED_FIELD";
874
- readonly ALREADY_VERIFIED: "ALREADY_VERIFIED";
875
- readonly INVALID_STATE_TRANSITION: "INVALID_STATE_TRANSITION";
876
- readonly SUBSCRIPTION_NOT_ACTIVE: "SUBSCRIPTION_NOT_ACTIVE";
877
- readonly REFUND_NOT_SUPPORTED: "REFUND_NOT_SUPPORTED";
878
- readonly REFUND_FAILED: "REFUND_FAILED";
879
- };
880
- type ErrorCode = typeof ERROR_CODES[keyof typeof ERROR_CODES];
881
- /**
882
- * Check if error is retryable
883
- */
884
- declare function isRetryable(error: unknown): boolean;
885
- /**
886
- * Check if error is from revenue package
887
- */
888
- declare function isRevenueError(error: unknown): error is RevenueError;
889
-
890
- 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 };
9
+ import '@classytic/shared-types';
10
+ import '../settlement.enums-ByC1x0ye.js';
11
+ import '../escrow.enums-CE0VQsfe.js';
12
+ import '../split.enums-DG3TxQf9.js';
13
+ import '../settlement.schema-CpamV7ZY.js';