@nehorai/credits 1.5.0 → 1.7.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/LICENSE +21 -21
- 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 +102 -7
- 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 +102 -7
- package/dist/index.js.map +1 -1
- package/dist/repository/index.cjs +21 -5
- package/dist/repository/index.cjs.map +1 -1
- package/dist/repository/index.d.cts +5 -5
- package/dist/repository/index.d.ts +5 -5
- package/dist/repository/index.js +21 -5
- 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 +81 -2
- package/dist/service/index.cjs.map +1 -1
- package/dist/service/index.d.cts +46 -4
- package/dist/service/index.d.ts +46 -4
- package/dist/service/index.js +81 -2
- package/dist/service/index.js.map +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-DFe5BoJY.d.cts} +27 -3
- package/dist/{types-KgNdBuEF.d.cts → types-_bSybQnb.d.ts} +27 -3
- package/package.json +1 -1
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 { A as AddCreditsAtomicOptions, 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-DFe5BoJY.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 { A as AddCreditsAtomicOptions, 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-_bSybQnb.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
|
@@ -798,23 +798,39 @@ var InMemoryCreditRepository = class {
|
|
|
798
798
|
this.users.set(userId, credits);
|
|
799
799
|
await this.updateReservationStatus(userId, reservationId, "released", /* @__PURE__ */ new Date());
|
|
800
800
|
}
|
|
801
|
-
async addCreditsAtomic(userId, amount, description, paymentRef) {
|
|
801
|
+
async addCreditsAtomic(userId, amount, description, paymentRef, options) {
|
|
802
802
|
const credits = this.users.get(userId);
|
|
803
803
|
if (!credits) {
|
|
804
804
|
throw new Error(`User ${userId} not found`);
|
|
805
805
|
}
|
|
806
|
-
const
|
|
806
|
+
const previousTotal = credits.balance + credits.bonusCredits;
|
|
807
807
|
credits.bonusCredits += amount;
|
|
808
808
|
credits.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
809
809
|
this.users.set(userId, credits);
|
|
810
|
-
|
|
810
|
+
const newTotal = credits.balance + credits.bonusCredits;
|
|
811
|
+
const transaction = await this.createTransaction({
|
|
811
812
|
userId,
|
|
812
813
|
type: "purchase",
|
|
813
814
|
amount,
|
|
814
815
|
description,
|
|
815
816
|
paymentRef,
|
|
816
|
-
previousBalance,
|
|
817
|
-
newBalance:
|
|
817
|
+
previousBalance: previousTotal,
|
|
818
|
+
newBalance: newTotal
|
|
819
|
+
});
|
|
820
|
+
const journalMetadata = {
|
|
821
|
+
...paymentRef ? { paymentRef } : {},
|
|
822
|
+
...options?.metadata ?? {}
|
|
823
|
+
};
|
|
824
|
+
await this.createJournalEntry({
|
|
825
|
+
userId,
|
|
826
|
+
entryType: "credit",
|
|
827
|
+
amount,
|
|
828
|
+
balanceAfter: newTotal,
|
|
829
|
+
source: options?.source ?? "purchase",
|
|
830
|
+
referenceId: transaction.id ?? paymentRef ?? "unknown",
|
|
831
|
+
referenceType: options?.referenceType ?? "transaction",
|
|
832
|
+
description,
|
|
833
|
+
metadata: Object.keys(journalMetadata).length > 0 ? journalMetadata : void 0
|
|
818
834
|
});
|
|
819
835
|
}
|
|
820
836
|
async deductCreditsAtomic(userId, amount) {
|
|
@@ -1396,9 +1412,88 @@ var CreditsService = class {
|
|
|
1396
1412
|
* @param amount - Credits to add
|
|
1397
1413
|
* @param description - Transaction description
|
|
1398
1414
|
* @param paymentRef - Optional payment reference
|
|
1415
|
+
* @param options - Optional journal source / reference type / extra metadata
|
|
1416
|
+
* for the credit journal entry (e.g. revenue-attribution fields).
|
|
1399
1417
|
*/
|
|
1400
|
-
async addCredits(userId, amount, description, paymentRef) {
|
|
1401
|
-
return this.repository.addCreditsAtomic(userId, amount, description, paymentRef);
|
|
1418
|
+
async addCredits(userId, amount, description, paymentRef, options) {
|
|
1419
|
+
return this.repository.addCreditsAtomic(userId, amount, description, paymentRef, options);
|
|
1420
|
+
}
|
|
1421
|
+
/**
|
|
1422
|
+
* One-shot atomic "deduct-if-sufficient" credit charge.
|
|
1423
|
+
*
|
|
1424
|
+
* Unlike the reserve/commit/release two-phase flow, this performs a single
|
|
1425
|
+
* atomic check-and-deduct against the repository — suited for synchronous,
|
|
1426
|
+
* in-request operations that don't need a hold across an async job. Exactly
|
|
1427
|
+
* one call is made to `repository.deductCreditsAtomic`, which enforces
|
|
1428
|
+
* atomicity so concurrent callers can never both succeed against the same
|
|
1429
|
+
* limited balance.
|
|
1430
|
+
*
|
|
1431
|
+
* On success, creates a journal entry (same audit trail as `commitCredits`)
|
|
1432
|
+
* and, if `options.operationType` is provided, a usage log entry via the
|
|
1433
|
+
* same `logUsage` path.
|
|
1434
|
+
*
|
|
1435
|
+
* @param userId - User ID
|
|
1436
|
+
* @param amount - Credits to deduct (must be > 0)
|
|
1437
|
+
* @param options - Optional usage-log / journal metadata
|
|
1438
|
+
* @returns Typed result: `{ success: true, newBalance }` or
|
|
1439
|
+
* `{ success: false, reason: 'insufficient', available, required, shortfall }`
|
|
1440
|
+
* @throws Error if amount is not a positive number
|
|
1441
|
+
*/
|
|
1442
|
+
async deductCredits(userId, amount, options) {
|
|
1443
|
+
if (!(amount > 0)) {
|
|
1444
|
+
throw new Error(`deductCredits amount must be positive (got ${amount})`);
|
|
1445
|
+
}
|
|
1446
|
+
let deduction;
|
|
1447
|
+
try {
|
|
1448
|
+
deduction = await this.repository.deductCreditsAtomic(userId, amount);
|
|
1449
|
+
} catch (error) {
|
|
1450
|
+
const credits = await this.repository.getUserCredits(userId);
|
|
1451
|
+
const available = credits ? credits.balance + credits.bonusCredits - credits.reserved : 0;
|
|
1452
|
+
if (available >= amount) {
|
|
1453
|
+
throw error;
|
|
1454
|
+
}
|
|
1455
|
+
return {
|
|
1456
|
+
success: false,
|
|
1457
|
+
reason: "insufficient",
|
|
1458
|
+
available,
|
|
1459
|
+
required: amount,
|
|
1460
|
+
shortfall: amount - available
|
|
1461
|
+
};
|
|
1462
|
+
}
|
|
1463
|
+
const operationType = options?.operationType;
|
|
1464
|
+
await this.repository.createJournalEntry({
|
|
1465
|
+
userId,
|
|
1466
|
+
entryType: "debit",
|
|
1467
|
+
amount,
|
|
1468
|
+
balanceAfter: deduction.newBalance,
|
|
1469
|
+
source: "operation_commit",
|
|
1470
|
+
referenceId: options?.requestId ?? `deduct-${Date.now()}`,
|
|
1471
|
+
referenceType: "adjustment",
|
|
1472
|
+
description: operationType ? `Deducted ${amount} credits for ${getOperationLabel(operationType)}` : `Deducted ${amount} credits`,
|
|
1473
|
+
metadata: {
|
|
1474
|
+
...operationType && { operationType },
|
|
1475
|
+
...options?.metadata
|
|
1476
|
+
}
|
|
1477
|
+
});
|
|
1478
|
+
if (operationType) {
|
|
1479
|
+
await this.logUsage({
|
|
1480
|
+
userId,
|
|
1481
|
+
operationType,
|
|
1482
|
+
provider: "gemini",
|
|
1483
|
+
creditsUsed: amount,
|
|
1484
|
+
success: true,
|
|
1485
|
+
resourceId: options?.resourceId,
|
|
1486
|
+
resourceType: options?.resourceType,
|
|
1487
|
+
requestId: options?.requestId,
|
|
1488
|
+
metadata: options?.metadata
|
|
1489
|
+
});
|
|
1490
|
+
}
|
|
1491
|
+
if (this.lowBalanceCallback) {
|
|
1492
|
+
this.lowBalanceCallback(userId, deduction.newBalance).catch((error) => {
|
|
1493
|
+
console.error("[Credits] Failed to send low balance notification:", error);
|
|
1494
|
+
});
|
|
1495
|
+
}
|
|
1496
|
+
return { success: true, newBalance: deduction.newBalance };
|
|
1402
1497
|
}
|
|
1403
1498
|
/**
|
|
1404
1499
|
* Update user subscription tier
|