@nehorai/credits 1.6.0 → 2.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 (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +226 -2
  3. package/dist/adapters/index.cjs +298 -40
  4. package/dist/adapters/index.cjs.map +1 -1
  5. package/dist/adapters/index.d.cts +2 -2
  6. package/dist/adapters/index.d.ts +2 -2
  7. package/dist/adapters/index.js +298 -40
  8. package/dist/adapters/index.js.map +1 -1
  9. package/dist/core/index.cjs +696 -74
  10. package/dist/core/index.cjs.map +1 -1
  11. package/dist/core/index.d.cts +583 -5
  12. package/dist/core/index.d.ts +583 -5
  13. package/dist/core/index.js +648 -74
  14. package/dist/core/index.js.map +1 -1
  15. package/dist/index.cjs +1779 -364
  16. package/dist/index.cjs.map +1 -1
  17. package/dist/index.d.cts +41 -6
  18. package/dist/index.d.ts +41 -6
  19. package/dist/index.js +1723 -364
  20. package/dist/index.js.map +1 -1
  21. package/dist/repository/index.cjs +1413 -181
  22. package/dist/repository/index.cjs.map +1 -1
  23. package/dist/repository/index.d.cts +142 -16
  24. package/dist/repository/index.d.ts +142 -16
  25. package/dist/repository/index.js +1406 -181
  26. package/dist/repository/index.js.map +1 -1
  27. package/dist/sdk/index.cjs +23 -1
  28. package/dist/sdk/index.cjs.map +1 -1
  29. package/dist/sdk/index.d.cts +2 -2
  30. package/dist/sdk/index.d.ts +2 -2
  31. package/dist/sdk/index.js +23 -1
  32. package/dist/sdk/index.js.map +1 -1
  33. package/dist/service/index.cjs +483 -105
  34. package/dist/service/index.cjs.map +1 -1
  35. package/dist/service/index.d.cts +70 -10
  36. package/dist/service/index.d.ts +70 -10
  37. package/dist/service/index.js +483 -105
  38. package/dist/service/index.js.map +1 -1
  39. package/dist/types-BmG5Omzj.d.ts +646 -0
  40. package/dist/types-C8hZMe8a.d.cts +646 -0
  41. package/dist/{types-CjLj3GW5.d.cts → types-DJ8yqaVr.d.cts} +39 -1
  42. package/dist/{types-CjLj3GW5.d.ts → types-DJ8yqaVr.d.ts} +39 -1
  43. package/package.json +9 -10
  44. package/dist/types-CZNv1U3e.d.cts +0 -305
  45. package/dist/types-G4WK0rM-.d.ts +0 -305
@@ -1,305 +0,0 @@
1
- import { C as CreditSource, J as JournalReferenceType, a as CreditOperationType, P as PortableTransaction, A as AIProviderType, S as SubscriptionTier, b as PortableUserCredits, c as PortableReservation, R as ReservationStatus, d as PortableUsageLog, M as MonthlyResetResult, e as SubscriptionExpiryResult, f as PortableJournalEntry } from './types-CjLj3GW5.js';
2
-
3
- /**
4
- * Input for creating a credit reservation
5
- */
6
- interface CreateReservationInput {
7
- userId: string;
8
- amount: number;
9
- operationType: CreditOperationType;
10
- expiresAt: Date;
11
- }
12
- /**
13
- * Input for creating a credit transaction
14
- */
15
- interface CreateTransactionInput {
16
- userId: string;
17
- type: PortableTransaction["type"];
18
- amount: number;
19
- description: string;
20
- paymentRef?: string;
21
- previousBalance: number;
22
- newBalance: number;
23
- }
24
- /**
25
- * Input for logging usage
26
- */
27
- interface CreateUsageLogInput {
28
- userId: string;
29
- operationType: CreditOperationType;
30
- provider: AIProviderType;
31
- creditsUsed: number;
32
- success: boolean;
33
- errorMessage?: string;
34
- resourceId?: string;
35
- resourceType?: string;
36
- requestId?: string;
37
- metadata?: Record<string, unknown>;
38
- }
39
- /**
40
- * Query options for usage logs
41
- */
42
- interface UsageLogQuery {
43
- userId?: string;
44
- operationType?: CreditOperationType;
45
- success?: boolean;
46
- limit?: number;
47
- offset?: number;
48
- startDate?: Date;
49
- endDate?: Date;
50
- }
51
- /**
52
- * Input for creating a journal entry
53
- */
54
- interface CreateJournalEntryInput {
55
- userId: string;
56
- entryType: "debit" | "credit";
57
- amount: number;
58
- balanceAfter: number;
59
- source: CreditSource;
60
- referenceId: string;
61
- referenceType: JournalReferenceType;
62
- description: string;
63
- metadata?: Record<string, unknown>;
64
- }
65
- /**
66
- * Query options for journal entries
67
- */
68
- interface JournalEntryQuery {
69
- userId: string;
70
- source?: CreditSource;
71
- referenceType?: JournalReferenceType;
72
- limit?: number;
73
- offset?: number;
74
- startDate?: Date;
75
- endDate?: Date;
76
- }
77
- /**
78
- * Partial update for user credits balance
79
- */
80
- interface CreditBalanceUpdate {
81
- balance?: number;
82
- bonusCredits?: number;
83
- reserved?: number;
84
- tier?: SubscriptionTier;
85
- monthlyLimit?: number;
86
- monthlyUsed?: number;
87
- monthlyResetAt?: Date | string;
88
- subscriptionExpiresAt?: Date | string | null;
89
- /** Increment balance by this amount (alternative to absolute value) */
90
- balanceIncrement?: number;
91
- /** Increment bonusCredits by this amount (alternative to absolute value) */
92
- bonusCreditsIncrement?: number;
93
- /** Increment reserved by this amount (alternative to absolute value) */
94
- reservedIncrement?: number;
95
- /** Increment monthlyUsed by this amount */
96
- monthlyUsedIncrement?: number;
97
- }
98
- /**
99
- * Input for tier update
100
- */
101
- interface TierUpdateInput {
102
- tier: SubscriptionTier;
103
- monthlyLimit: number;
104
- balance?: number;
105
- monthlyUsed?: number;
106
- subscriptionExpiresAt?: Date | string | null;
107
- }
108
- /**
109
- * Repository interface for credits database operations
110
- *
111
- * Implementations can use any database (Firestore, PostgreSQL, etc.)
112
- * All methods should handle their own error handling and transactions
113
- */
114
- interface ICreditRepository {
115
- /**
116
- * Get user credits balance
117
- * @param userId - User ID
118
- * @returns User credits or null if not found
119
- */
120
- getUserCredits(userId: string): Promise<PortableUserCredits | null>;
121
- /**
122
- * Initialize credits for a new user
123
- * @param userId - User ID
124
- * @param tier - Initial subscription tier
125
- * @param initialBalance - Initial credit balance
126
- * @returns Initialized user credits
127
- */
128
- initializeUserCredits(userId: string, tier: SubscriptionTier, initialBalance: number): Promise<PortableUserCredits>;
129
- /**
130
- * Update user credits balance
131
- * @param userId - User ID
132
- * @param updates - Partial updates to apply
133
- */
134
- updateUserCredits(userId: string, updates: CreditBalanceUpdate): Promise<void>;
135
- /**
136
- * Update user subscription tier
137
- * @param userId - User ID
138
- * @param input - Tier update data
139
- */
140
- updateUserTier(userId: string, input: TierUpdateInput): Promise<void>;
141
- /**
142
- * Create a credit reservation (phase 1 of two-phase commit)
143
- * @param input - Reservation data
144
- * @returns Created reservation
145
- */
146
- createReservation(input: CreateReservationInput): Promise<PortableReservation>;
147
- /**
148
- * Get a reservation by ID
149
- * @param userId - User ID
150
- * @param reservationId - Reservation ID
151
- * @returns Reservation or null
152
- */
153
- getReservation(userId: string, reservationId: string): Promise<PortableReservation | null>;
154
- /**
155
- * Update reservation status
156
- * @param userId - User ID
157
- * @param reservationId - Reservation ID
158
- * @param status - New status
159
- * @param completedAt - Completion timestamp
160
- */
161
- updateReservationStatus(userId: string, reservationId: string, status: ReservationStatus, completedAt?: Date): Promise<void>;
162
- /**
163
- * Reserve credits atomically (creates reservation + updates balance in transaction)
164
- * @param userId - User ID
165
- * @param amount - Credits to reserve
166
- * @param operationType - Operation type for tracking
167
- * @param expiresAt - Reservation expiry time
168
- * @returns Created reservation
169
- * @throws Error if insufficient credits
170
- */
171
- reserveCreditsAtomic(userId: string, amount: number, operationType: CreditOperationType, expiresAt: Date): Promise<PortableReservation>;
172
- /**
173
- * Commit a reservation atomically (deducts credits + marks reservation committed)
174
- * @param userId - User ID
175
- * @param reservationId - Reservation ID
176
- * @throws Error if reservation not found or not in reserved state
177
- */
178
- commitReservationAtomic(userId: string, reservationId: string): Promise<void>;
179
- /**
180
- * Release a reservation atomically (releases reserved credits + marks reservation released)
181
- * @param userId - User ID
182
- * @param reservationId - Reservation ID
183
- */
184
- releaseReservationAtomic(userId: string, reservationId: string): Promise<void>;
185
- /**
186
- * Add credits atomically (creates transaction + updates balance)
187
- * @param userId - User ID
188
- * @param amount - Credits to add
189
- * @param description - Transaction description
190
- * @param paymentRef - Optional payment reference
191
- */
192
- addCreditsAtomic(userId: string, amount: number, description: string, paymentRef?: string): Promise<void>;
193
- /**
194
- * Deduct credits from a user's balance atomically.
195
- *
196
- * Splits the deduction across `balance` and `bonusCredits`, draining
197
- * `balance` (monthly, resets each cycle) first so persistent bonus
198
- * credits survive longer. Runs in a single atomic transaction so
199
- * concurrent deducts cannot drive either field negative.
200
- *
201
- * Callers are responsible for writing any audit record (journal /
202
- * transaction) — this method only moves credits.
203
- *
204
- * @param userId - User ID
205
- * @param amount - Credits to deduct (positive)
206
- * @returns Combined totals (balance + bonusCredits) before and after.
207
- * @throws If user has no credits doc or insufficient credits
208
- */
209
- deductCreditsAtomic(userId: string, amount: number): Promise<{
210
- previousBalance: number;
211
- newBalance: number;
212
- }>;
213
- /**
214
- * Create a credit transaction record
215
- * @param input - Transaction data
216
- * @returns Created transaction
217
- */
218
- createTransaction(input: CreateTransactionInput): Promise<PortableTransaction>;
219
- /**
220
- * Get user's transaction history
221
- * @param userId - User ID
222
- * @param limit - Max results
223
- * @param offset - Skip results
224
- * @returns List of transactions
225
- */
226
- getTransactions(userId: string, limit?: number, offset?: number): Promise<PortableTransaction[]>;
227
- /**
228
- * Log a usage event
229
- * @param input - Usage log data
230
- * @returns Created usage log
231
- */
232
- logUsage(input: CreateUsageLogInput): Promise<PortableUsageLog>;
233
- /**
234
- * Query usage logs
235
- * @param query - Query parameters
236
- * @returns List of usage logs
237
- */
238
- getUsageLogs(query: UsageLogQuery): Promise<PortableUsageLog[]>;
239
- /**
240
- * Get usage log count (for pagination)
241
- * @param query - Query parameters (without limit/offset)
242
- * @returns Count of matching logs
243
- */
244
- getUsageLogsCount(query: Omit<UsageLogQuery, "limit" | "offset">): Promise<number>;
245
- /**
246
- * Find and expire reservations past their expiration time
247
- * Used by cron job to clean up stale reservations
248
- * @param batchSize - Maximum number of reservations to process per batch (default: 100)
249
- * @param maxIterations - Maximum number of pagination iterations to prevent infinite loops (default: 100)
250
- * @returns Cleanup results with counts and errors
251
- */
252
- findAndExpireReservations(batchSize?: number, maxIterations?: number): Promise<{
253
- expiredCount: number;
254
- creditsReleased: number;
255
- errors: string[];
256
- }>;
257
- /**
258
- * Atomically perform monthly reset if needed
259
- * Uses optimistic locking to prevent race conditions
260
- *
261
- * @param userId - User ID
262
- * @param tier - User's current subscription tier (for determining new balance)
263
- * @param expectedResetAt - The expected monthlyResetAt value (for optimistic locking)
264
- * @returns Result indicating whether reset was performed and updated credits
265
- */
266
- atomicMonthlyReset(userId: string, tier: SubscriptionTier, expectedResetAt: Date | string): Promise<MonthlyResetResult>;
267
- /**
268
- * Check and handle subscription expiry with grace period
269
- * Auto-downgrades expired subscriptions after grace period
270
- *
271
- * @param userId - User ID
272
- * @param gracePeriodDays - Days to allow after expiry before downgrade (default: 3)
273
- * @returns Result indicating whether downgrade occurred
274
- */
275
- checkAndHandleSubscriptionExpiry(userId: string, gracePeriodDays?: number): Promise<SubscriptionExpiryResult>;
276
- /**
277
- * Create a journal entry for audit trail
278
- * @param input - Journal entry data
279
- * @returns Created journal entry
280
- */
281
- createJournalEntry(input: CreateJournalEntryInput): Promise<PortableJournalEntry>;
282
- /**
283
- * Get journal entries for a user
284
- * @param query - Query parameters
285
- * @returns List of journal entries
286
- */
287
- getJournalEntries(query: JournalEntryQuery): Promise<PortableJournalEntry[]>;
288
- /**
289
- * Get journal entry count for pagination
290
- * @param query - Query parameters (without limit/offset)
291
- * @returns Count of matching entries
292
- */
293
- getJournalEntriesCount(query: Omit<JournalEntryQuery, "limit" | "offset">): Promise<number>;
294
- }
295
- /**
296
- * Factory type for creating repository instances
297
- */
298
- type CreditRepositoryFactory = () => ICreditRepository;
299
- /**
300
- * Convert PortableUserCredits to client-safe format
301
- * Utility function that implementations can use
302
- */
303
- declare function toClientUserCredits(credits: PortableUserCredits): PortableUserCredits;
304
-
305
- export { type CreateJournalEntryInput as C, type ICreditRepository as I, type JournalEntryQuery as J, type TierUpdateInput as T, type UsageLogQuery as U, type CreateReservationInput as a, type CreateTransactionInput as b, type CreateUsageLogInput as c, type CreditBalanceUpdate as d, type CreditRepositoryFactory as e, toClientUserCredits as t };