import { b as PortableUserCredits, g as CreditCheckResult } from '../types-DgQtamEe.js'; export { c as CreditReservation, S as SubscriptionTier } from '../types-DgQtamEe.js'; /** * SDK types for the credits system * * These types are used by the client SDKs for REST API consumption. */ /** * Configuration for CreditsClient */ interface CreditsClientConfig { /** Base URL of the credits API (e.g., "https://api.example.com") */ baseUrl: string; /** Function to get the auth token for session-based auth */ getAuthToken?: () => Promise; /** Optional custom fetch function for testing */ fetch?: typeof fetch; } /** * Configuration for AdminCreditsClient */ interface AdminCreditsClientConfig { /** Base URL of the credits API */ baseUrl: string; /** Admin API key */ apiKey: string; /** Optional custom fetch function for testing */ fetch?: typeof fetch; } /** * Result of a credit reservation */ interface ReservationResult { /** The reservation ID */ reservationId: string; /** Amount of credits reserved */ amount: number; /** When the reservation expires (ISO 8601) */ expiresAt: string; } /** * Pagination options for API requests */ interface PaginationOptions { /** Page number (1-indexed) */ page?: number; /** Number of items per page */ limit?: number; } /** * Usage history entry */ interface UsageHistoryEntry { /** Unique ID of the usage log */ id: string; /** Type of operation */ operationType: string; /** AI provider used */ provider: string; /** Credits consumed */ creditsUsed: number; /** Whether the operation was successful */ success: boolean; /** Error message if unsuccessful */ errorMessage?: string; /** ID of the related resource */ resourceId?: string; /** Type of the related resource */ resourceType?: string; /** When the operation occurred (ISO 8601) */ createdAt: string; } /** * Response from usage history endpoint */ interface UsageHistoryResponse { /** List of usage entries */ entries: UsageHistoryEntry[]; /** Whether there are more results */ hasMore: boolean; /** Total count (if available) */ total?: number; } /** * Generic API response wrapper */ interface ApiResponse { success: boolean; data?: T; error?: { code: string; message: string; details?: unknown; }; } /** * SDK error codes */ declare const SDKErrorCode: { readonly NETWORK_ERROR: "NETWORK_ERROR"; readonly AUTHENTICATION_ERROR: "AUTHENTICATION_ERROR"; readonly AUTHORIZATION_ERROR: "AUTHORIZATION_ERROR"; readonly INSUFFICIENT_CREDITS: "INSUFFICIENT_CREDITS"; readonly RESERVATION_NOT_FOUND: "RESERVATION_NOT_FOUND"; readonly RESERVATION_EXPIRED: "RESERVATION_EXPIRED"; readonly VALIDATION_ERROR: "VALIDATION_ERROR"; readonly SERVER_ERROR: "SERVER_ERROR"; readonly UNKNOWN_ERROR: "UNKNOWN_ERROR"; }; type SDKErrorCodeType = (typeof SDKErrorCode)[keyof typeof SDKErrorCode]; /** * CreditsClient - REST API client for the credits system * * Provides a type-safe interface for consuming credits API endpoints * from external services or other applications. * * @example * ```typescript * const client = new CreditsClient({ * baseUrl: process.env.CREDITS_API_URL, * getAuthToken: async () => session.accessToken, * }); * * // Check if user has sufficient credits * const check = await client.checkAvailability("story_generation"); * if (!check.hasCredits) { * console.log("Insufficient credits"); * return; * } * * // Two-phase commit pattern * const reservation = await client.reserve("story_generation"); * try { * const result = await doExpensiveWork(); * await client.commit(reservation.reservationId); * return result; * } catch (error) { * await client.release(reservation.reservationId); * throw error; * } * ``` */ declare class CreditsClient { private readonly baseUrl; private readonly getAuthToken?; private readonly fetchFn; constructor(config: CreditsClientConfig); /** * Make an authenticated request to the API */ private request; /** * Get the current user's credit balance * * @returns User's credit information * @throws AuthenticationError if not authenticated */ getBalance(): Promise; /** * Check if the user has sufficient credits for an operation * * @param operationType - Type of operation to check * @param customCost - Optional custom cost to check against * @returns Credit availability status * @throws AuthenticationError if not authenticated */ checkAvailability(operationType: string, customCost?: number): Promise; /** * Reserve credits for an operation * * This is the first step in the two-phase commit pattern. * Reserved credits are held for 5 minutes before expiring. * * @param operationType - Type of operation * @param options - Optional reservation options * @returns Reservation details including ID and expiry * @throws InsufficientCreditsError if not enough credits * @throws AuthenticationError if not authenticated */ reserve(operationType: string, options?: { customCost?: number; resourceId?: string; resourceType?: string; }): Promise; /** * Commit a reservation (deduct credits) * * This is the second step in the two-phase commit pattern. * Call this after your operation succeeds. * * @param reservationId - ID of the reservation to commit * @throws ReservationNotFoundError if reservation doesn't exist * @throws ReservationExpiredError if reservation has expired * @throws AuthenticationError if not authenticated */ commit(reservationId: string): Promise; /** * Release a reservation (refund credits) * * Call this if your operation fails after reserving credits. * * @param reservationId - ID of the reservation to release * @throws ReservationNotFoundError if reservation doesn't exist * @throws AuthenticationError if not authenticated */ release(reservationId: string): Promise; /** * Get usage history for the current user * * @param options - Optional pagination options * @returns Paginated list of usage entries * @throws AuthenticationError if not authenticated */ getHistory(options?: PaginationOptions): Promise; /** * Get the available credits (balance + bonus - reserved) * * Convenience method that calculates available credits from balance. * * @returns Number of available credits * @throws AuthenticationError if not authenticated */ getAvailableCredits(): Promise; /** * Execute an operation with automatic credit handling * * This is a convenience method that handles the full two-phase commit * pattern automatically. * * @param operationType - Type of operation * @param operation - The operation to execute * @param options - Optional reservation options * @returns Result of the operation * @throws InsufficientCreditsError if not enough credits * @throws AuthenticationError if not authenticated * * @example * ```typescript * const result = await client.withCredits( * "story_generation", * async () => { * return generateStory(data); * } * ); * ``` */ withCredits(operationType: string, operation: () => Promise, options?: { customCost?: number; resourceId?: string; resourceType?: string; }): Promise; } /** * AdminCreditsClient - Admin REST API client for the credits system * * Provides administrative access to the credits system for managing * user credits, configurations, and subscriptions. * * @example * ```typescript * const adminClient = new AdminCreditsClient({ * baseUrl: process.env.CREDITS_API_URL, * apiKey: process.env.CREDITS_ADMIN_API_KEY, * }); * * // Add credits to a user * await adminClient.addCredits("user-123", 100, "Support credit grant"); * * // Update subscription tier * await adminClient.updateSubscription("user-123", "premium", "2027-01-01T00:00:00Z"); * * // Update operation costs * await adminClient.updateCosts({ * story_generation: 8, * image_generation: 12, * }); * ``` */ /** * Credits configuration returned by the API */ interface CreditsConfig { operationCosts: Record; tierConfigs: Record; } /** * Response from listing users */ interface ListUsersResponse { users: Array<{ userId: string; balance: number; bonusCredits?: number; tier: string; monthlyUsed?: number; }>; hasMore: boolean; total?: number; } /** * Options for listing users */ interface ListUsersOptions { page?: number; limit?: number; tier?: string; search?: string; } declare class AdminCreditsClient { private readonly baseUrl; private readonly apiKey; private readonly fetchFn; constructor(config: AdminCreditsClientConfig); /** * Make an authenticated admin request to the API */ private request; /** * Get a specific user's credits * * @param userId - ID of the user * @returns User's credit information * @throws AuthorizationError if API key is invalid */ getUserCredits(userId: string): Promise; /** * Add credits to a user's account * * Credits are added to bonusCredits, which don't expire on monthly reset. * * @param userId - ID of the user * @param amount - Amount of credits to add * @param description - Reason for adding credits * @throws AuthorizationError if API key is invalid */ addCredits(userId: string, amount: number, description: string): Promise; /** * Update a user's subscription tier * * @param userId - ID of the user * @param tier - New subscription tier * @param expiresAt - Optional expiration date (ISO 8601) * @throws AuthorizationError if API key is invalid */ updateSubscription(userId: string, tier: string, expiresAt?: string): Promise; /** * Get the current credits configuration * * @returns Credits system configuration * @throws AuthorizationError if API key is invalid */ getConfig(): Promise; /** * Update operation costs * * @param costs - New operation costs (operation type -> cost) * @throws AuthorizationError if API key is invalid */ updateCosts(costs: Record): Promise; /** * List all users with their credits * * @param options - Pagination and filtering options * @returns Paginated list of users * @throws AuthorizationError if API key is invalid */ listUsers(options?: ListUsersOptions): Promise; /** * Deduct credits from a user's account * * @param userId - ID of the user * @param amount - Amount of credits to deduct * @param description - Reason for deducting credits * @throws AuthorizationError if API key is invalid */ deductCredits(userId: string, amount: number, description: string): Promise; /** * Get usage statistics for a user * * @param userId - ID of the user * @param options - Optional date range * @returns Usage statistics * @throws AuthorizationError if API key is invalid */ getUserStats(userId: string, options?: { startDate?: string; endDate?: string; }): Promise<{ totalCreditsUsed: number; operationBreakdown: Record; successRate: number; }>; } /** * SDK error classes * * Provides typed error handling for SDK operations. */ /** * Base error class for SDK errors */ declare class CreditsSDKError extends Error { readonly code: SDKErrorCodeType; readonly details?: Record; readonly statusCode?: number; constructor(message: string, code: SDKErrorCodeType, options?: { details?: Record; statusCode?: number; cause?: Error; }); /** * Check if this is a specific error type */ is(code: SDKErrorCodeType): boolean; /** * Create a JSON representation for logging */ toJSON(): Record; } /** * Error thrown when a network request fails */ declare class NetworkError extends CreditsSDKError { constructor(message: string, cause?: Error); } /** * Error thrown when authentication fails */ declare class AuthenticationError extends CreditsSDKError { constructor(message?: string); } /** * Error thrown when authorization fails */ declare class AuthorizationError extends CreditsSDKError { constructor(message?: string); } /** * Error thrown when credits are insufficient */ declare class InsufficientCreditsError extends CreditsSDKError { readonly available: number; readonly required: number; constructor(available: number, required: number); } /** * Error thrown when a reservation is not found */ declare class ReservationNotFoundError extends CreditsSDKError { readonly reservationId: string; constructor(reservationId: string); } /** * Error thrown when a reservation has expired */ declare class ReservationExpiredError extends CreditsSDKError { readonly reservationId: string; constructor(reservationId: string); } /** * Error thrown for validation failures */ declare class ValidationError extends CreditsSDKError { readonly field?: string; constructor(message: string, field?: string); } /** * Error thrown for server errors */ declare class ServerError extends CreditsSDKError { constructor(message?: string); } /** * Parse an API error response into the appropriate SDK error */ declare function parseApiError(statusCode: number, body: { error?: { code?: string; message?: string; details?: unknown; }; }): CreditsSDKError; export { AdminCreditsClient, type AdminCreditsClientConfig, type ApiResponse, AuthenticationError, AuthorizationError, CreditCheckResult, CreditsClient, type CreditsClientConfig, type CreditsConfig, CreditsSDKError, InsufficientCreditsError, type ListUsersOptions, type ListUsersResponse, NetworkError, type PaginationOptions, ReservationExpiredError, ReservationNotFoundError, type ReservationResult, SDKErrorCode, type SDKErrorCodeType, ServerError, type UsageHistoryEntry, type UsageHistoryResponse, PortableUserCredits as UserCredits, ValidationError, parseApiError };