@nehorai/credits 1.5.0 → 1.6.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.
- package/README.md +153 -153
- package/dist/adapters/index.cjs.map +1 -1
- package/dist/adapters/index.d.cts +2 -2
- package/dist/adapters/index.d.ts +2 -2
- package/dist/adapters/index.js.map +1 -1
- package/dist/auth/index.cjs.map +1 -1
- package/dist/auth/index.js.map +1 -1
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.d.cts +3 -3
- package/dist/core/index.d.ts +3 -3
- package/dist/core/index.js.map +1 -1
- package/dist/index.cjs +77 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +77 -0
- package/dist/index.js.map +1 -1
- package/dist/repository/index.cjs.map +1 -1
- package/dist/repository/index.d.cts +3 -3
- package/dist/repository/index.d.ts +3 -3
- package/dist/repository/index.js.map +1 -1
- package/dist/sdk/index.cjs.map +1 -1
- package/dist/sdk/index.d.cts +2 -2
- package/dist/sdk/index.d.ts +2 -2
- package/dist/sdk/index.js.map +1 -1
- package/dist/service/index.cjs +77 -0
- package/dist/service/index.cjs.map +1 -1
- package/dist/service/index.d.cts +43 -3
- package/dist/service/index.d.ts +43 -3
- package/dist/service/index.js +77 -0
- package/dist/service/index.js.map +1 -1
- package/dist/{types-KgNdBuEF.d.cts → types-CZNv1U3e.d.cts} +1 -1
- package/dist/{types-DgQtamEe.d.cts → types-CjLj3GW5.d.cts} +22 -1
- package/dist/{types-DgQtamEe.d.ts → types-CjLj3GW5.d.ts} +22 -1
- package/dist/{types-fW2JNmmr.d.ts → types-G4WK0rM-.d.ts} +1 -1
- package/package.json +10 -9
- package/LICENSE +0 -21
package/dist/index.d.cts
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import { S as SubscriptionTier, T as TierConfig, c as PortableReservation } from './types-
|
|
2
|
-
export { A as AIProviderType, B as BuiltinTier, g as CreditCheckResult, a as CreditOperationType, C as CreditSource, J as JournalReferenceType, M as MonthlyResetResult, f as PortableJournalEntry, P as PortableTransaction, d as PortableUsageLog, b as PortableUserCredits, R as ReservationStatus, h as ResourceType, g as SDKCreditCheckResult, e as SubscriptionExpiryResult, i as TransactionType, U as UsageHistoryEntry, j as UsageHistoryResponse, b as UserCredits, W as WithCreditsOptions, k as calculateAvailableCredits, t as toDate, l as toPortableTimestamp } from './types-
|
|
1
|
+
import { S as SubscriptionTier, T as TierConfig, c as PortableReservation } from './types-CjLj3GW5.cjs';
|
|
2
|
+
export { A as AIProviderType, B as BuiltinTier, g as CreditCheckResult, a as CreditOperationType, C as CreditSource, D as DeductCreditsResult, J as JournalReferenceType, M as MonthlyResetResult, f as PortableJournalEntry, P as PortableTransaction, d as PortableUsageLog, b as PortableUserCredits, R as ReservationStatus, h as ResourceType, g as SDKCreditCheckResult, e as SubscriptionExpiryResult, i as TransactionType, U as UsageHistoryEntry, j as UsageHistoryResponse, b as UserCredits, W as WithCreditsOptions, k as calculateAvailableCredits, t as toDate, l as toPortableTimestamp } from './types-CjLj3GW5.cjs';
|
|
3
3
|
export { CreditError, CreditErrorCode, CreditErrorCodeType, commitReservationWithJournal, createInsufficientCreditsError, createInvalidOperationTypeError, createReservationAlreadyProcessedError, createReservationExpiredError, createReservationNotFoundError, createUserNotFoundError, isCreditError, isInsufficientCreditsError, releaseReservationWithJournal, reserveCreditsForOperation } from './core/index.cjs';
|
|
4
4
|
export { D as DeferredExecutor, c as createDeferredExecutor, g as genericDeferred, n as noopDeferred, s as synchronousDeferred } from './deferred-C7rrRfkm.cjs';
|
|
5
5
|
import { z } from 'zod';
|
|
6
|
-
export { C as CreateJournalEntryInput, a as CreateReservationInput, b as CreateTransactionInput, c as CreateUsageLogInput, d as CreditBalanceUpdate, e as CreditRepositoryFactory, I as ICreditRepository, J as JournalEntryQuery, T as TierUpdateInput, U as UsageLogQuery, t as toClientUserCredits } from './types-
|
|
6
|
+
export { C as CreateJournalEntryInput, a as CreateReservationInput, b as CreateTransactionInput, c as CreateUsageLogInput, d as CreditBalanceUpdate, e as CreditRepositoryFactory, I as ICreditRepository, J as JournalEntryQuery, T as TierUpdateInput, U as UsageLogQuery, t as toClientUserCredits } from './types-CZNv1U3e.cjs';
|
|
7
7
|
export { InMemoryCreditRepository, createInMemoryCreditRepository, generateId, getNextMonthlyReset } from './repository/index.cjs';
|
|
8
8
|
export { C as CreditsAuthProviderFactory, a as CreditsUser, I as ICreditsAuthProvider } from './types-OZU3I5OM.cjs';
|
|
9
9
|
export { ApiKeyCreditsProvider, createApiKeyProvider, verifyAdminApiKey, verifyBearerToken } from './auth/index.cjs';
|
|
10
|
-
export { CreditsService, LowBalanceNotificationCallback, SubscriptionExpiredNotificationCallback, createCreditsService } from './service/index.cjs';
|
|
10
|
+
export { CreditsService, DeductCreditsOptions, LowBalanceNotificationCallback, ReserveCreditsOptions, SubscriptionExpiredNotificationCallback, createCreditsService } from './service/index.cjs';
|
|
11
11
|
export { ActionResult, CreditActionHandler, CreditsAdapter, CreditsAdapterConfig, createGenericAdapter } from './adapters/index.cjs';
|
|
12
12
|
export { AdminCreditsClient, AdminCreditsClientConfig, ApiResponse, AuthenticationError, AuthorizationError, CreditsClient, CreditsClientConfig, CreditsConfig, CreditsSDKError, ListUsersOptions, ListUsersResponse, NetworkError, PaginationOptions, ReservationResult, SDKErrorCode, SDKErrorCodeType, InsufficientCreditsError as SDKInsufficientCreditsError, ReservationExpiredError as SDKReservationExpiredError, ReservationNotFoundError as SDKReservationNotFoundError, UsageHistoryEntry as SDKUsageHistoryEntry, UsageHistoryResponse as SDKUsageHistoryResponse, ServerError, ValidationError, parseApiError } from './sdk/index.cjs';
|
|
13
13
|
|
package/dist/index.d.ts
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import { S as SubscriptionTier, T as TierConfig, c as PortableReservation } from './types-
|
|
2
|
-
export { A as AIProviderType, B as BuiltinTier, g as CreditCheckResult, a as CreditOperationType, C as CreditSource, J as JournalReferenceType, M as MonthlyResetResult, f as PortableJournalEntry, P as PortableTransaction, d as PortableUsageLog, b as PortableUserCredits, R as ReservationStatus, h as ResourceType, g as SDKCreditCheckResult, e as SubscriptionExpiryResult, i as TransactionType, U as UsageHistoryEntry, j as UsageHistoryResponse, b as UserCredits, W as WithCreditsOptions, k as calculateAvailableCredits, t as toDate, l as toPortableTimestamp } from './types-
|
|
1
|
+
import { S as SubscriptionTier, T as TierConfig, c as PortableReservation } from './types-CjLj3GW5.js';
|
|
2
|
+
export { A as AIProviderType, B as BuiltinTier, g as CreditCheckResult, a as CreditOperationType, C as CreditSource, D as DeductCreditsResult, J as JournalReferenceType, M as MonthlyResetResult, f as PortableJournalEntry, P as PortableTransaction, d as PortableUsageLog, b as PortableUserCredits, R as ReservationStatus, h as ResourceType, g as SDKCreditCheckResult, e as SubscriptionExpiryResult, i as TransactionType, U as UsageHistoryEntry, j as UsageHistoryResponse, b as UserCredits, W as WithCreditsOptions, k as calculateAvailableCredits, t as toDate, l as toPortableTimestamp } from './types-CjLj3GW5.js';
|
|
3
3
|
export { CreditError, CreditErrorCode, CreditErrorCodeType, commitReservationWithJournal, createInsufficientCreditsError, createInvalidOperationTypeError, createReservationAlreadyProcessedError, createReservationExpiredError, createReservationNotFoundError, createUserNotFoundError, isCreditError, isInsufficientCreditsError, releaseReservationWithJournal, reserveCreditsForOperation } from './core/index.js';
|
|
4
4
|
export { D as DeferredExecutor, c as createDeferredExecutor, g as genericDeferred, n as noopDeferred, s as synchronousDeferred } from './deferred-C7rrRfkm.js';
|
|
5
5
|
import { z } from 'zod';
|
|
6
|
-
export { C as CreateJournalEntryInput, a as CreateReservationInput, b as CreateTransactionInput, c as CreateUsageLogInput, d as CreditBalanceUpdate, e as CreditRepositoryFactory, I as ICreditRepository, J as JournalEntryQuery, T as TierUpdateInput, U as UsageLogQuery, t as toClientUserCredits } from './types-
|
|
6
|
+
export { C as CreateJournalEntryInput, a as CreateReservationInput, b as CreateTransactionInput, c as CreateUsageLogInput, d as CreditBalanceUpdate, e as CreditRepositoryFactory, I as ICreditRepository, J as JournalEntryQuery, T as TierUpdateInput, U as UsageLogQuery, t as toClientUserCredits } from './types-G4WK0rM-.js';
|
|
7
7
|
export { InMemoryCreditRepository, createInMemoryCreditRepository, generateId, getNextMonthlyReset } from './repository/index.js';
|
|
8
8
|
export { C as CreditsAuthProviderFactory, a as CreditsUser, I as ICreditsAuthProvider } from './types-OZU3I5OM.js';
|
|
9
9
|
export { ApiKeyCreditsProvider, createApiKeyProvider, verifyAdminApiKey, verifyBearerToken } from './auth/index.js';
|
|
10
|
-
export { CreditsService, LowBalanceNotificationCallback, SubscriptionExpiredNotificationCallback, createCreditsService } from './service/index.js';
|
|
10
|
+
export { CreditsService, DeductCreditsOptions, LowBalanceNotificationCallback, ReserveCreditsOptions, SubscriptionExpiredNotificationCallback, createCreditsService } from './service/index.js';
|
|
11
11
|
export { ActionResult, CreditActionHandler, CreditsAdapter, CreditsAdapterConfig, createGenericAdapter } from './adapters/index.js';
|
|
12
12
|
export { AdminCreditsClient, AdminCreditsClientConfig, ApiResponse, AuthenticationError, AuthorizationError, CreditsClient, CreditsClientConfig, CreditsConfig, CreditsSDKError, ListUsersOptions, ListUsersResponse, NetworkError, PaginationOptions, ReservationResult, SDKErrorCode, SDKErrorCodeType, InsufficientCreditsError as SDKInsufficientCreditsError, ReservationExpiredError as SDKReservationExpiredError, ReservationNotFoundError as SDKReservationNotFoundError, UsageHistoryEntry as SDKUsageHistoryEntry, UsageHistoryResponse as SDKUsageHistoryResponse, ServerError, ValidationError, parseApiError } from './sdk/index.js';
|
|
13
13
|
|
package/dist/index.js
CHANGED
|
@@ -1400,6 +1400,83 @@ var CreditsService = class {
|
|
|
1400
1400
|
async addCredits(userId, amount, description, paymentRef) {
|
|
1401
1401
|
return this.repository.addCreditsAtomic(userId, amount, description, paymentRef);
|
|
1402
1402
|
}
|
|
1403
|
+
/**
|
|
1404
|
+
* One-shot atomic "deduct-if-sufficient" credit charge.
|
|
1405
|
+
*
|
|
1406
|
+
* Unlike the reserve/commit/release two-phase flow, this performs a single
|
|
1407
|
+
* atomic check-and-deduct against the repository — suited for synchronous,
|
|
1408
|
+
* in-request operations that don't need a hold across an async job. Exactly
|
|
1409
|
+
* one call is made to `repository.deductCreditsAtomic`, which enforces
|
|
1410
|
+
* atomicity so concurrent callers can never both succeed against the same
|
|
1411
|
+
* limited balance.
|
|
1412
|
+
*
|
|
1413
|
+
* On success, creates a journal entry (same audit trail as `commitCredits`)
|
|
1414
|
+
* and, if `options.operationType` is provided, a usage log entry via the
|
|
1415
|
+
* same `logUsage` path.
|
|
1416
|
+
*
|
|
1417
|
+
* @param userId - User ID
|
|
1418
|
+
* @param amount - Credits to deduct (must be > 0)
|
|
1419
|
+
* @param options - Optional usage-log / journal metadata
|
|
1420
|
+
* @returns Typed result: `{ success: true, newBalance }` or
|
|
1421
|
+
* `{ success: false, reason: 'insufficient', available, required, shortfall }`
|
|
1422
|
+
* @throws Error if amount is not a positive number
|
|
1423
|
+
*/
|
|
1424
|
+
async deductCredits(userId, amount, options) {
|
|
1425
|
+
if (!(amount > 0)) {
|
|
1426
|
+
throw new Error(`deductCredits amount must be positive (got ${amount})`);
|
|
1427
|
+
}
|
|
1428
|
+
let deduction;
|
|
1429
|
+
try {
|
|
1430
|
+
deduction = await this.repository.deductCreditsAtomic(userId, amount);
|
|
1431
|
+
} catch (error) {
|
|
1432
|
+
const credits = await this.repository.getUserCredits(userId);
|
|
1433
|
+
const available = credits ? credits.balance + credits.bonusCredits - credits.reserved : 0;
|
|
1434
|
+
if (available >= amount) {
|
|
1435
|
+
throw error;
|
|
1436
|
+
}
|
|
1437
|
+
return {
|
|
1438
|
+
success: false,
|
|
1439
|
+
reason: "insufficient",
|
|
1440
|
+
available,
|
|
1441
|
+
required: amount,
|
|
1442
|
+
shortfall: amount - available
|
|
1443
|
+
};
|
|
1444
|
+
}
|
|
1445
|
+
const operationType = options?.operationType;
|
|
1446
|
+
await this.repository.createJournalEntry({
|
|
1447
|
+
userId,
|
|
1448
|
+
entryType: "debit",
|
|
1449
|
+
amount,
|
|
1450
|
+
balanceAfter: deduction.newBalance,
|
|
1451
|
+
source: "operation_commit",
|
|
1452
|
+
referenceId: options?.requestId ?? `deduct-${Date.now()}`,
|
|
1453
|
+
referenceType: "adjustment",
|
|
1454
|
+
description: operationType ? `Deducted ${amount} credits for ${getOperationLabel(operationType)}` : `Deducted ${amount} credits`,
|
|
1455
|
+
metadata: {
|
|
1456
|
+
...operationType && { operationType },
|
|
1457
|
+
...options?.metadata
|
|
1458
|
+
}
|
|
1459
|
+
});
|
|
1460
|
+
if (operationType) {
|
|
1461
|
+
await this.logUsage({
|
|
1462
|
+
userId,
|
|
1463
|
+
operationType,
|
|
1464
|
+
provider: "gemini",
|
|
1465
|
+
creditsUsed: amount,
|
|
1466
|
+
success: true,
|
|
1467
|
+
resourceId: options?.resourceId,
|
|
1468
|
+
resourceType: options?.resourceType,
|
|
1469
|
+
requestId: options?.requestId,
|
|
1470
|
+
metadata: options?.metadata
|
|
1471
|
+
});
|
|
1472
|
+
}
|
|
1473
|
+
if (this.lowBalanceCallback) {
|
|
1474
|
+
this.lowBalanceCallback(userId, deduction.newBalance).catch((error) => {
|
|
1475
|
+
console.error("[Credits] Failed to send low balance notification:", error);
|
|
1476
|
+
});
|
|
1477
|
+
}
|
|
1478
|
+
return { success: true, newBalance: deduction.newBalance };
|
|
1479
|
+
}
|
|
1403
1480
|
/**
|
|
1404
1481
|
* Update user subscription tier
|
|
1405
1482
|
* @param userId - User ID
|