@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 +1 @@
1
- {"version":3,"sources":["../../src/core/types.ts","../../src/core/errors.ts","../../src/core/deferred.ts","../../src/config/index.ts","../../src/config/provider.ts","../../src/core/operations.ts"],"sourcesContent":["/**\n * Portable credits types - framework and database agnostic\n *\n * These types use standard JavaScript types (string, Date) instead of\n * Firebase-specific types (Timestamp). This makes the credits system\n * portable to other environments without Firebase dependencies.\n *\n * Note: Firestore Timestamp is handled by the credits-firestore adapter.\n */\n\n// ==================== Utility Functions ====================\n\n/**\n * Calculate available credits from balance, bonus, and reserved amounts.\n *\n * Available = balance + bonusCredits - reserved\n *\n * @param balance - Regular monthly credits\n * @param bonusCredits - Purchased/admin credits\n * @param reserved - Credits locked for in-flight operations\n * @returns Available credits for new operations\n */\nexport function calculateAvailableCredits(\n balance: number,\n bonusCredits: number,\n reserved: number\n): number {\n return balance + bonusCredits - reserved;\n}\n\n/**\n * Convert various timestamp formats to ISO string.\n *\n * Handles:\n * - Date objects\n * - ISO string (returned as-is)\n * - Timestamp-like objects with toDate() method (Firebase)\n * - undefined/null (returns current time)\n *\n * @param value - Value to convert\n * @returns ISO 8601 string\n */\nexport function toPortableTimestamp(value: unknown): string {\n if (!value) {\n return new Date().toISOString();\n }\n\n if (typeof value === \"string\") {\n return value;\n }\n\n if (value instanceof Date) {\n return value.toISOString();\n }\n\n if (\n typeof value === \"object\" &&\n value !== null &&\n \"toDate\" in value &&\n typeof (value as { toDate: () => Date }).toDate === \"function\"\n ) {\n return (value as { toDate: () => Date }).toDate().toISOString();\n }\n\n return new Date().toISOString();\n}\n\n/**\n * Convert various timestamp formats to Date object.\n *\n * Handles:\n * - Date objects (returned as-is)\n * - ISO string\n * - Timestamp-like objects with toDate() method (Firebase)\n * - Invalid values (returns current date)\n *\n * @param value - Value to convert\n * @returns Date object\n */\nexport function toDate(value: unknown): Date {\n if (value instanceof Date) {\n return value;\n }\n\n if (typeof value === \"string\") {\n return new Date(value);\n }\n\n if (\n typeof value === \"object\" &&\n value !== null &&\n \"toDate\" in value &&\n typeof (value as { toDate: () => Date }).toDate === \"function\"\n ) {\n return (value as { toDate: () => Date }).toDate();\n }\n\n return new Date();\n}\n\n// ==================== Subscription Types ====================\n\n/**\n * Built-in tier ids (autocomplete) — apps may add more via config.\n */\nexport type BuiltinTier = \"free\" | \"basic\" | \"premium\" | \"unlimited\";\n\n/**\n * Subscription tiers for the credits system.\n *\n * Any built-in OR any config-defined tier id. The `(string & {})` keeps builtin\n * autocomplete while accepting arbitrary configured tiers.\n */\nexport type SubscriptionTier = BuiltinTier | (string & {});\n\n// ==================== Operation Types ====================\n\n/**\n * Operation types for cost tracking (provider-agnostic)\n *\n * Dynamic string type - any operation configured in the system is valid.\n */\nexport type CreditOperationType = string;\n\n/**\n * AI providers\n */\nexport type AIProviderType = \"gemini\";\n\n/**\n * Resource type for usage logging\n */\nexport type ResourceType = string;\n\n// ==================== User Credits ====================\n\n/**\n * Portable user credits balance\n *\n * Uses ISO string timestamps instead of Firebase Timestamp.\n * This type is safe for JSON serialization and works across frameworks.\n */\nexport interface PortableUserCredits {\n userId: string;\n /** Current available balance (monthly credits, reset each month) */\n balance: number;\n /** Bonus credits from purchases/admin (never reset, persist until used) */\n bonusCredits: number;\n /** Credits currently reserved for in-flight operations */\n reserved: number;\n /** User's subscription tier */\n tier: SubscriptionTier;\n /** Monthly credit limit based on tier (0 = unlimited) */\n monthlyLimit: number;\n /** Credits used this month (resets monthly) */\n monthlyUsed: number;\n /** When monthly credits reset (start of next month) - ISO 8601 */\n monthlyResetAt: string;\n /** Subscription expiry (null/undefined for free tier) - ISO 8601 or null */\n subscriptionExpiresAt?: string | null;\n /** Creation timestamp - ISO 8601 */\n createdAt: string;\n /** Last update timestamp - ISO 8601 */\n updatedAt: string;\n}\n\n// ==================== Reservation Types ====================\n\n/**\n * Credit reservation status for two-phase commit\n */\nexport type ReservationStatus = \"reserved\" | \"committed\" | \"released\" | \"expired\";\n\n/**\n * Portable credit reservation\n *\n * Used for two-phase commit to prevent double-spending.\n */\nexport interface PortableReservation {\n id: string;\n userId: string;\n /** Amount of credits reserved */\n amount: number;\n /** Operation type for tracking */\n operationType: CreditOperationType;\n /** Current status of reservation */\n status: ReservationStatus;\n /** When reservation was created - ISO 8601 */\n createdAt: string;\n /** When reservation expires (for cleanup) - ISO 8601 */\n expiresAt: string;\n /** When reservation was committed/released - ISO 8601 or undefined */\n completedAt?: string;\n}\n\n// ==================== Result Types ====================\n\n/**\n * Result of a credit check operation\n */\nexport interface CreditCheckResult {\n /** Whether user has sufficient credits */\n hasCredits: boolean;\n /** Current balance (balance + bonusCredits) */\n balance: number;\n /** Required credits for operation */\n required: number;\n /** Shortfall if insufficient */\n shortfall: number;\n}\n\n/**\n * Result of a one-shot atomic credit deduction (see `CreditsService.deductCredits`).\n *\n * Discriminated on `success` so callers get exhaustive narrowing:\n * - `success: true` -> `newBalance` is populated, `available`/`shortfall` are not present.\n * - `success: false` -> `available`/`shortfall` describe the shortfall, no mutation occurred.\n */\nexport type DeductCreditsResult =\n | {\n success: true;\n /** Combined balance (balance + bonusCredits) after the deduction */\n newBalance: number;\n }\n | {\n success: false;\n reason: \"insufficient\";\n /** Combined balance (balance + bonusCredits - reserved) available before the attempt */\n available: number;\n /** Credits that were requested */\n required: number;\n /** How many more credits would have been needed */\n shortfall: number;\n };\n\n/**\n * Result of monthly reset operation\n */\nexport interface MonthlyResetResult {\n /** Whether the reset was performed */\n wasReset: boolean;\n /** The user credits after the operation */\n credits: PortableUserCredits;\n}\n\n/**\n * Result of subscription expiry check\n */\nexport interface SubscriptionExpiryResult {\n /** Whether the subscription was downgraded */\n wasDowngraded: boolean;\n /** Whether user is in grace period */\n inGracePeriod: boolean;\n /** Days remaining in grace period (0 if not in grace) */\n graceDaysRemaining: number;\n /** The user credits after the operation */\n credits: PortableUserCredits;\n}\n\n// ==================== Transaction Types ====================\n\n/**\n * Credit transaction type\n */\nexport type TransactionType = \"purchase\" | \"subscription\" | \"bonus\" | \"refund\" | \"adjustment\";\n\n/**\n * Portable credit transaction\n */\nexport interface PortableTransaction {\n id: string;\n userId: string;\n type: TransactionType;\n /** Amount of credits (positive for additions, negative for deductions) */\n amount: number;\n description: string;\n /** Reference to payment provider */\n paymentRef?: string;\n previousBalance: number;\n newBalance: number;\n createdAt: string;\n}\n\n// ==================== Journal Types ====================\n\n/**\n * Source of a credit journal entry\n */\nexport type CreditSource =\n | \"operation_commit\"\n | \"operation_release\"\n | \"purchase\"\n | \"subscription_grant\"\n | \"subscription_upgrade\"\n | \"subscription_downgrade\"\n | \"monthly_reset\"\n | \"bonus\"\n | \"refund\"\n | \"admin_adjustment\"\n | \"expiry\"\n | \"reservation_expired\";\n\n/**\n * Type of reference for a journal entry\n */\nexport type JournalReferenceType =\n | \"reservation\"\n | \"transaction\"\n | \"adjustment\"\n | \"reset\"\n | \"subscription\";\n\n/**\n * Portable credit journal entry for audit trail\n */\nexport interface PortableJournalEntry {\n id: string;\n userId: string;\n /** Type of entry - debit decreases balance, credit increases balance */\n entryType: \"debit\" | \"credit\";\n /** Amount of credits involved */\n amount: number;\n /** Balance after this entry */\n balanceAfter: number;\n /** Source of the credit change */\n source: CreditSource;\n /** Reference ID (e.g., reservationId, transactionId) */\n referenceId: string;\n /** Type of reference */\n referenceType: JournalReferenceType;\n /** Human-readable description */\n description: string;\n /** Additional metadata */\n metadata?: Record<string, unknown>;\n /** When this entry was created - ISO 8601 */\n createdAt: string;\n}\n\n// ==================== Usage Types ====================\n\n/**\n * Portable usage log entry\n */\nexport interface PortableUsageLog {\n id: string;\n userId: string;\n operationType: CreditOperationType;\n provider: AIProviderType;\n creditsUsed: number;\n success: boolean;\n errorMessage?: string;\n resourceId?: string;\n resourceType?: ResourceType;\n requestId?: string;\n metadata?: Record<string, unknown>;\n createdAt: string;\n}\n\n/**\n * User-friendly usage history entry\n */\nexport interface UsageHistoryEntry {\n id: string;\n /** Type of entry for display */\n type: \"usage\" | \"purchase\" | \"bonus\" | \"reset\" | \"refund\" | \"adjustment\";\n /** Positive = earned, Negative = spent */\n creditsChange: number;\n /** Balance after this entry */\n balanceAfter: number;\n /** Human-readable description */\n description: string;\n /** When this occurred - ISO 8601 */\n createdAt: string;\n}\n\n/**\n * Paginated usage history response\n */\nexport interface UsageHistoryResponse {\n entries: UsageHistoryEntry[];\n pagination: {\n total: number;\n limit: number;\n offset: number;\n hasMore: boolean;\n };\n}\n\n// ==================== Tier Configuration ====================\n\n/**\n * Tier configuration for credit limits and pricing\n */\nexport interface TierConfig {\n tier: SubscriptionTier;\n monthlyCredits: number;\n priceUsd: number;\n features: string[];\n /** Free/default tier marker — no subscription expiry, balance untouched on tier change. Defaults to priceUsd === 0. */\n isFree?: boolean;\n /** Unlimited tier marker. Defaults to monthlyCredits === 0. */\n unlimited?: boolean;\n /** Tier assigned to brand-new users. Defaults to the tier flagged isFree. */\n isDefault?: boolean;\n}\n\n// ==================== Options Types ====================\n\n/**\n * Options for withCredits HOF\n */\nexport interface WithCreditsOptions {\n /** Operation type for cost lookup */\n operationType: CreditOperationType;\n /** AI provider (defaults to \"gemini\") */\n provider?: AIProviderType;\n /** Custom cost override (use with caution) */\n customCost?: number;\n /** Resource ID for usage logging */\n resourceId?: string;\n /** Resource type for usage logging */\n resourceType?: ResourceType;\n}\n\n// ==================== Constants ====================\n","/**\n * Credit system error classes - framework agnostic\n *\n * Provides typed error handling for credit operations.\n * These errors can be used across different environments.\n */\n\n/**\n * Error codes for credit operations\n */\nexport const CreditErrorCode = {\n INSUFFICIENT_CREDITS: \"INSUFFICIENT_CREDITS\",\n RESERVATION_NOT_FOUND: \"RESERVATION_NOT_FOUND\",\n RESERVATION_EXPIRED: \"RESERVATION_EXPIRED\",\n RESERVATION_ALREADY_PROCESSED: \"RESERVATION_ALREADY_PROCESSED\",\n USER_NOT_FOUND: \"USER_NOT_FOUND\",\n INVALID_OPERATION_TYPE: \"INVALID_OPERATION_TYPE\",\n CONFIGURATION_ERROR: \"CONFIGURATION_ERROR\",\n DATABASE_ERROR: \"DATABASE_ERROR\",\n} as const;\n\nexport type CreditErrorCodeType = (typeof CreditErrorCode)[keyof typeof CreditErrorCode];\n\n/**\n * Custom error class for credit operations\n *\n * Provides structured error information including:\n * - Error code for programmatic handling\n * - Human-readable message\n * - Optional details for debugging\n */\nexport class CreditError extends Error {\n public readonly code: CreditErrorCodeType;\n public readonly details?: Record<string, unknown>;\n\n constructor(\n message: string,\n code: CreditErrorCodeType,\n details?: Record<string, unknown>\n ) {\n super(message);\n this.name = \"CreditError\";\n this.code = code;\n this.details = details;\n\n // Maintains proper stack trace for where error was thrown\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, CreditError);\n }\n }\n\n /**\n * Convert to JSON-serializable object\n */\n toJSON(): { name: string; code: string; message: string; details?: Record<string, unknown> } {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n ...(this.details && { details: this.details }),\n };\n }\n}\n\n/**\n * Type guard to check if an error is a CreditError\n */\nexport function isCreditError(error: unknown): error is CreditError {\n return error instanceof CreditError;\n}\n\n/**\n * Check if an error represents insufficient credits\n *\n * Works with both CreditError and regular Error instances.\n * Useful for handling errors from different sources.\n */\nexport function isInsufficientCreditsError(error: unknown): boolean {\n if (isCreditError(error)) {\n return error.code === CreditErrorCode.INSUFFICIENT_CREDITS;\n }\n\n if (error instanceof Error) {\n return error.message.toLowerCase().includes(\"insufficient credits\");\n }\n\n return false;\n}\n\n/**\n * Create an insufficient credits error\n */\nexport function createInsufficientCreditsError(\n required: number,\n available: number\n): CreditError {\n return new CreditError(\n `Insufficient credits: available ${available}, required ${required}`,\n CreditErrorCode.INSUFFICIENT_CREDITS,\n { required, available, shortfall: required - available }\n );\n}\n\n/**\n * Create a reservation not found error\n */\nexport function createReservationNotFoundError(reservationId: string): CreditError {\n return new CreditError(\n `Reservation ${reservationId} not found`,\n CreditErrorCode.RESERVATION_NOT_FOUND,\n { reservationId }\n );\n}\n\n/**\n * Create a reservation expired error\n */\nexport function createReservationExpiredError(reservationId: string): CreditError {\n return new CreditError(\n `Reservation ${reservationId} has expired`,\n CreditErrorCode.RESERVATION_EXPIRED,\n { reservationId }\n );\n}\n\n/**\n * Create a reservation already processed error\n */\nexport function createReservationAlreadyProcessedError(\n reservationId: string,\n status: string\n): CreditError {\n return new CreditError(\n `Reservation ${reservationId} has already been ${status}`,\n CreditErrorCode.RESERVATION_ALREADY_PROCESSED,\n { reservationId, status }\n );\n}\n\n/**\n * Create a user not found error\n */\nexport function createUserNotFoundError(userId: string): CreditError {\n return new CreditError(\n `User ${userId} not found`,\n CreditErrorCode.USER_NOT_FOUND,\n { userId }\n );\n}\n\n/**\n * Create an invalid operation type error\n */\nexport function createInvalidOperationTypeError(\n operationType: string,\n validTypes: string[]\n): CreditError {\n return new CreditError(\n `Invalid operation type: ${operationType}. Valid types: ${validTypes.join(\", \")}`,\n CreditErrorCode.INVALID_OPERATION_TYPE,\n { operationType, validTypes }\n );\n}\n","/**\n * Deferred execution abstraction - framework agnostic\n *\n * Provides a way to schedule work to run after the current operation completes.\n * Different frameworks can provide their own implementations:\n * - Next.js: uses `after()` from `next/server`\n * - Generic: uses `setImmediate()` or `setTimeout()`\n * - Testing: can use synchronous execution\n */\n\n/**\n * Interface for deferred execution\n *\n * Implementations should schedule the function to run asynchronously\n * without blocking the current operation.\n */\nexport interface DeferredExecutor {\n /**\n * Schedule a function to run asynchronously\n *\n * The function should be executed after the current operation completes.\n * Errors should be caught and logged, not propagated.\n *\n * @param fn - Async function to execute\n */\n defer(fn: () => Promise<void>): void;\n}\n\n/**\n * Generic deferred executor using setImmediate/setTimeout\n *\n * Works in Node.js and browser environments.\n * Suitable for non-framework environments or testing.\n */\nexport const genericDeferred: DeferredExecutor = {\n defer(fn: () => Promise<void>): void {\n // Use setImmediate in Node.js, setTimeout as fallback\n const scheduler = typeof setImmediate !== \"undefined\" ? setImmediate : setTimeout;\n scheduler(() => {\n fn().catch((error) => {\n console.error(\"[Credits] Deferred task error:\", error);\n });\n });\n },\n};\n\n/**\n * Synchronous deferred executor\n *\n * Executes the function immediately (fire-and-forget).\n * Useful for testing or when deferred execution isn't needed.\n */\nexport const synchronousDeferred: DeferredExecutor = {\n defer(fn: () => Promise<void>): void {\n fn().catch((error) => {\n console.error(\"[Credits] Deferred task error:\", error);\n });\n },\n};\n\n/**\n * Create a custom deferred executor\n *\n * Allows frameworks to provide their own scheduling mechanism.\n *\n * @example\n * ```typescript\n * // Next.js adapter\n * import { after } from 'next/server';\n *\n * const nextJsDeferred = createDeferredExecutor((fn) => after(fn));\n * ```\n *\n * @param schedule - Function that schedules async work\n * @returns DeferredExecutor instance\n */\nexport function createDeferredExecutor(\n schedule: (fn: () => Promise<void>) => void\n): DeferredExecutor {\n return {\n defer: schedule,\n };\n}\n\n/**\n * No-op deferred executor\n *\n * Discards deferred work. Useful when you want to disable\n * background tasks (e.g., in certain test scenarios).\n */\nexport const noopDeferred: DeferredExecutor = {\n defer(_fn: () => Promise<void>): void {\n // Intentionally do nothing\n },\n};\n","import { z } from \"zod\";\nimport type { SubscriptionTier, TierConfig } from \"../core/types.js\";\nimport { getConfigProvider } from \"./provider.js\";\n\n/**\n * Schema for tier configuration\n */\nconst tierConfigSchema = z.object({\n tier: z.string().min(1),\n monthlyCredits: z.number().min(0),\n priceUsd: z.number().min(0),\n features: z.array(z.string()),\n isFree: z.boolean().optional(),\n unlimited: z.boolean().optional(),\n isDefault: z.boolean().optional(),\n});\n\n/**\n * Schema for credit system configuration\n */\nconst creditSystemConfigSchema = z.object({\n /**\n * Operation costs in credits\n * Keys are operation type names (any non-empty string)\n * Values are positive numbers representing credit cost\n */\n operationCosts: z.record(\n z.string().min(1),\n z.number().positive()\n ),\n\n /**\n * Display labels for operation types (English canonical labels).\n * Falls back to auto-generating from snake_case keys if not provided.\n */\n operationLabels: z.record(\n z.string().min(1),\n z.string().min(1)\n ).optional().default({}),\n\n /**\n * Tier configurations\n */\n tierConfigs: z.record(\n z.string().min(1),\n tierConfigSchema\n ),\n\n /**\n * Reservation expiry time in milliseconds\n */\n reservationExpiryMs: z.number().positive().default(5 * 60 * 1000),\n\n /**\n * Default credits for new users (free tier)\n */\n defaultFreeCredits: z.number().positive().default(25),\n\n /**\n * Grace period in days after subscription expires before downgrade\n */\n subscriptionGracePeriodDays: z.number().min(0).default(3),\n\n /**\n * Low balance notification threshold\n */\n lowBalanceThreshold: z.number().min(0).default(10),\n\n /**\n * Cooldown in hours between low balance notifications\n */\n lowBalanceNotificationCooldownHours: z.number().positive().default(24),\n\n /**\n * Feature flags for optional features\n */\n features: z.object({\n journalEntries: z.boolean().default(true),\n notifications: z.boolean().default(true),\n subscriptionExpiry: z.boolean().default(true),\n usageHistory: z.boolean().default(true),\n }).default({\n journalEntries: true,\n notifications: true,\n subscriptionExpiry: true,\n usageHistory: true,\n }),\n});\n\n/**\n * Credit system configuration type\n */\nexport type CreditSystemConfig = z.infer<typeof creditSystemConfigSchema>;\n\n/**\n * Default configuration\n */\nconst DEFAULT_CONFIG: CreditSystemConfig = {\n operationCosts: {\n story_generation: 5,\n conversation: 2,\n image_generation: 10,\n template_generation: 10,\n },\n operationLabels: {\n story_generation: \"Story generation\",\n conversation: \"Conversation\",\n image_generation: \"Image generation\",\n template_generation: \"Template generation\",\n },\n tierConfigs: {\n free: {\n tier: \"free\",\n monthlyCredits: 25,\n priceUsd: 0,\n isFree: true,\n isDefault: true,\n features: [\n \"25 credits per month\",\n \"Basic story generation\",\n \"Standard image quality\",\n ],\n },\n basic: {\n tier: \"basic\",\n monthlyCredits: 200,\n priceUsd: 9.99,\n features: [\n \"200 credits per month\",\n \"All story features\",\n \"High quality images\",\n \"Priority support\",\n ],\n },\n premium: {\n tier: \"premium\",\n monthlyCredits: 500,\n priceUsd: 19.99,\n features: [\n \"500 credits per month\",\n \"All features\",\n \"Highest quality images\",\n \"Early access to new features\",\n \"Priority support\",\n ],\n },\n unlimited: {\n tier: \"unlimited\",\n monthlyCredits: 0, // 0 = unlimited\n unlimited: true,\n priceUsd: 49.99,\n features: [\n \"Unlimited credits\",\n \"All features\",\n \"Highest quality images\",\n \"Early access to new features\",\n \"Dedicated support\",\n ],\n },\n },\n reservationExpiryMs: 5 * 60 * 1000, // 5 minutes\n defaultFreeCredits: 25,\n subscriptionGracePeriodDays: 3,\n lowBalanceThreshold: 10,\n lowBalanceNotificationCooldownHours: 24,\n features: {\n journalEntries: true,\n notifications: true,\n subscriptionExpiry: true,\n usageHistory: true,\n },\n};\n\n/**\n * Current configuration (can be overridden)\n */\nlet currentConfig: CreditSystemConfig = DEFAULT_CONFIG;\n\n/**\n * Load configuration from environment variables\n * Can be extended to load from other sources (file, remote config, etc.)\n *\n * Operation costs are loaded from CREDITS_OPERATION_COSTS as JSON:\n * CREDITS_OPERATION_COSTS={\"story_generation\":5,\"image_generation\":10}\n */\nexport function loadConfigFromEnv(): Partial<CreditSystemConfig> {\n const envConfig: Partial<CreditSystemConfig> = {};\n\n // Load operation costs from env as JSON\n const operationCostsEnv = process.env.CREDITS_OPERATION_COSTS;\n if (operationCostsEnv) {\n try {\n const parsed = JSON.parse(operationCostsEnv);\n if (typeof parsed === \"object\" && parsed !== null) {\n envConfig.operationCosts = {\n ...DEFAULT_CONFIG.operationCosts,\n ...parsed,\n };\n }\n } catch {\n console.warn(\"[Credits Config] Failed to parse CREDITS_OPERATION_COSTS env var as JSON\");\n }\n }\n\n // Load other settings from env\n const reservationExpiry = process.env.CREDITS_RESERVATION_EXPIRY_MS;\n if (reservationExpiry) {\n envConfig.reservationExpiryMs = parseInt(reservationExpiry, 10);\n }\n\n const defaultCredits = process.env.CREDITS_DEFAULT_FREE;\n if (defaultCredits) {\n envConfig.defaultFreeCredits = parseInt(defaultCredits, 10);\n }\n\n const gracePeriod = process.env.CREDITS_GRACE_PERIOD_DAYS;\n if (gracePeriod) {\n envConfig.subscriptionGracePeriodDays = parseInt(gracePeriod, 10);\n }\n\n const lowBalanceThreshold = process.env.CREDITS_LOW_BALANCE_THRESHOLD;\n if (lowBalanceThreshold) {\n envConfig.lowBalanceThreshold = parseInt(lowBalanceThreshold, 10);\n }\n\n // Load feature flags\n const featuresEnv = process.env.CREDITS_FEATURES;\n if (featuresEnv) {\n try {\n const features = JSON.parse(featuresEnv);\n envConfig.features = {\n ...DEFAULT_CONFIG.features,\n ...features,\n };\n } catch {\n console.warn(\"[Credits Config] Failed to parse CREDITS_FEATURES env var\");\n }\n }\n\n return envConfig;\n}\n\n/**\n * Initialize configuration\n * Merges default config with environment overrides\n */\nexport function initializeConfig(overrides?: Partial<CreditSystemConfig>): CreditSystemConfig {\n const envConfig = loadConfigFromEnv();\n\n const mergedConfig = {\n ...DEFAULT_CONFIG,\n ...envConfig,\n ...overrides,\n operationCosts: {\n ...DEFAULT_CONFIG.operationCosts,\n ...envConfig.operationCosts,\n ...overrides?.operationCosts,\n },\n operationLabels: {\n ...DEFAULT_CONFIG.operationLabels,\n ...envConfig.operationLabels,\n ...overrides?.operationLabels,\n },\n tierConfigs: {\n ...DEFAULT_CONFIG.tierConfigs,\n ...envConfig.tierConfigs,\n ...overrides?.tierConfigs,\n },\n features: {\n ...DEFAULT_CONFIG.features,\n ...envConfig.features,\n ...overrides?.features,\n },\n };\n\n // Validate configuration\n const result = creditSystemConfigSchema.safeParse(mergedConfig);\n if (!result.success) {\n console.error(\"[Credits Config] Invalid configuration:\", result.error.issues);\n throw new Error(\"Invalid credit system configuration\");\n }\n\n currentConfig = result.data;\n return currentConfig;\n}\n\n/**\n * Get the current configuration.\n * If an external provider is registered, delegates to it.\n * Otherwise falls back to the local currentConfig.\n */\nexport function getConfig(): CreditSystemConfig {\n const provider = getConfigProvider();\n if (provider) {\n return provider.getConfig();\n }\n return currentConfig;\n}\n\n/**\n * Get all valid operation types from configuration\n * Returns the keys of the operationCosts object\n */\nexport function getValidOperationTypes(): string[] {\n return Object.keys(getConfig().operationCosts);\n}\n\n/**\n * Check if an operation type is valid (configured in the system)\n * @param type - The operation type to check\n * @returns true if the operation type is configured\n */\nexport function isValidOperationType(type: string): boolean {\n return type in getConfig().operationCosts;\n}\n\n/**\n * Get operation cost from configuration\n * @throws Error if the operation type is not configured\n */\nexport function getConfigOperationCost(operationType: string): number {\n const cost = getConfig().operationCosts[operationType];\n if (cost === undefined) {\n throw new Error(\n `Unknown operation type: ${operationType}. Valid types: ${getValidOperationTypes().join(\", \")}`\n );\n }\n return cost;\n}\n\n/**\n * Get all valid tier ids from configuration\n * Returns the keys of the tierConfigs object\n */\nexport function getValidTiers(): string[] {\n return Object.keys(getConfig().tierConfigs);\n}\n\n/**\n * Check if a tier id is valid (configured in the system)\n */\nexport function isValidTier(tier: string): boolean {\n return tier in getConfig().tierConfigs;\n}\n\n/**\n * Check if a tier is the free/default tier.\n * Falls back to priceUsd === 0 when the isFree flag is not set.\n */\nexport function isFreeTier(tier: SubscriptionTier): boolean {\n const c = getConfig().tierConfigs[tier];\n if (!c) return false;\n return c.isFree ?? c.priceUsd === 0;\n}\n\n/**\n * Check if a tier is unlimited.\n * Falls back to monthlyCredits === 0 when the unlimited flag is not set.\n */\nexport function isUnlimitedTier(tier: SubscriptionTier): boolean {\n const c = getConfig().tierConfigs[tier];\n if (!c) return false;\n return c.unlimited ?? c.monthlyCredits === 0;\n}\n\n/**\n * Get the tier assigned to brand-new users.\n * Prefers the tier flagged isDefault, then the first isFree tier, then \"free\".\n */\nexport function getDefaultTier(): SubscriptionTier {\n const entries = Object.entries(getConfig().tierConfigs);\n const def =\n entries.find(([, c]) => c.isDefault)?.[0] ??\n entries.find(([, c]) => c.isFree ?? c.priceUsd === 0)?.[0];\n return def ?? \"free\";\n}\n\n/**\n * Magic balance assigned to unlimited tiers on upgrade.\n * Kept at 999999 for back-compat with stored/displayed balances.\n */\nexport const UNLIMITED_BALANCE_SENTINEL = 999999;\n\n/**\n * Get the magic balance assigned to unlimited tiers on upgrade.\n */\nexport function getUnlimitedSentinelBalance(): number {\n return UNLIMITED_BALANCE_SENTINEL;\n}\n\n/**\n * Get tier configuration from configuration.\n * Falls back to the default tier (with a warning) if the tier is unknown.\n */\nexport function getConfigTierConfig(tier: SubscriptionTier): TierConfig {\n const cfg = getConfig().tierConfigs[tier];\n if (cfg) return cfg;\n const fallback = getDefaultTier();\n console.warn(\n `[Credits Config] Unknown tier \"${tier}\". Falling back to \"${fallback}\". Valid: ${getValidTiers().join(\", \")}`\n );\n return getConfig().tierConfigs[fallback]!;\n}\n\n/**\n * Get monthly limit for a tier from configuration\n * Returns Infinity for unlimited tier\n */\nexport function getConfigMonthlyLimit(tier: SubscriptionTier): number {\n return isUnlimitedTier(tier) ? Infinity : getConfigTierConfig(tier).monthlyCredits;\n}\n\n/**\n * Runtime zod validator for tier ids. Validates against the LIVE config keys\n * at parse time, so apps that add tiers via config get correct validation.\n */\nexport const tierSchema = z\n .string()\n .refine(isValidTier, { message: \"Unknown subscription tier\" }) as unknown as z.ZodType<SubscriptionTier>;\n\n/**\n * Parse/validate a tier id against the live config keys.\n * @throws ZodError if the tier is not configured\n */\nexport function parseTier(value: unknown): SubscriptionTier {\n return tierSchema.parse(value);\n}\n\n/**\n * Check if a feature is enabled\n */\nexport function isFeatureEnabled(feature: keyof CreditSystemConfig[\"features\"]): boolean {\n return getConfig().features[feature];\n}\n\n/**\n * Convert a snake_case string to Title Case.\n * E.g., \"story_generation\" -> \"Story Generation\"\n */\nfunction snakeCaseToTitleCase(str: string): string {\n return str\n .replace(/_/g, \" \")\n .replace(/\\b\\w/g, (c) => c.toUpperCase());\n}\n\n/**\n * Get the display label for an operation type.\n * Falls back to converting snake_case to Title Case if no label is configured.\n */\nexport function getOperationLabel(operationType: string): string {\n const labels = getConfig().operationLabels;\n if (labels && operationType in labels) {\n return labels[operationType];\n }\n return snakeCaseToTitleCase(operationType);\n}\n\n/**\n * Get all operation labels as a record.\n * For any operation in operationCosts that lacks a label, generates one from the key.\n */\nexport function getOperationLabels(): Record<string, string> {\n const config = getConfig();\n const result: Record<string, string> = {};\n for (const key of Object.keys(config.operationCosts)) {\n result[key] = config.operationLabels?.[key]\n ?? snakeCaseToTitleCase(key);\n }\n return result;\n}\n\n/**\n * Reset configuration to defaults (for testing)\n */\nexport function resetConfig(): void {\n currentConfig = DEFAULT_CONFIG;\n}\n\n// Initialize configuration on module load\ninitializeConfig();\n","import type { CreditSystemConfig } from \"./index.js\";\n\n/** Interface for external config providers (e.g. Firestore-backed) */\nexport interface ICreditConfigProvider {\n getConfig(): CreditSystemConfig;\n}\n\nlet configProvider: ICreditConfigProvider | null = null;\n\n/** Register an external config provider. Called once at app startup. */\nexport function registerConfigProvider(provider: ICreditConfigProvider): void {\n configProvider = provider;\n}\n\n/** Get the registered provider, or null if none registered. */\nexport function getConfigProvider(): ICreditConfigProvider | null {\n return configProvider;\n}\n\n/** Clear registered provider (for testing). */\nexport function clearConfigProvider(): void {\n configProvider = null;\n}\n","/**\n * Core credit operations - framework agnostic\n *\n * Contains the business logic for credit operations that can be\n * used by any adapter or service implementation.\n */\n\nimport type { ICreditRepository } from \"../repository/types.js\";\nimport type { PortableReservation } from \"./types.js\";\nimport { getOperationLabel } from \"../config/index.js\";\n\n/**\n * Commit a reservation with journal entry\n *\n * @param repository - The credit repository\n * @param userId - User ID\n * @param reservationId - Reservation to commit\n */\nexport async function commitReservationWithJournal(\n repository: ICreditRepository,\n userId: string,\n reservationId: string\n): Promise<void> {\n // Get the reservation to know the amount\n const reservation = await repository.getReservation(userId, reservationId);\n if (!reservation) {\n throw new Error(`Reservation ${reservationId} not found`);\n }\n\n // Commit the reservation atomically\n await repository.commitReservationAtomic(userId, reservationId);\n\n // Create journal entry\n const credits = await repository.getUserCredits(userId);\n if (credits) {\n await repository.createJournalEntry({\n userId,\n entryType: \"debit\",\n amount: reservation.amount,\n balanceAfter: credits.balance,\n source: \"operation_commit\",\n referenceId: reservationId,\n referenceType: \"reservation\",\n description: `Committed ${reservation.amount} credits for ${getOperationLabel(reservation.operationType)}`,\n metadata: {\n operationType: reservation.operationType,\n },\n });\n }\n}\n\n/**\n * Release a reservation with journal entry\n *\n * @param repository - The credit repository\n * @param userId - User ID\n * @param reservationId - Reservation to release\n */\nexport async function releaseReservationWithJournal(\n repository: ICreditRepository,\n userId: string,\n reservationId: string\n): Promise<void> {\n // Get the reservation to check its state\n const reservation = await repository.getReservation(userId, reservationId);\n\n // Release the reservation atomically\n await repository.releaseReservationAtomic(userId, reservationId);\n\n // Create journal entry only if reservation was in reserved state\n if (reservation?.status === \"reserved\") {\n const credits = await repository.getUserCredits(userId);\n if (credits) {\n await repository.createJournalEntry({\n userId,\n entryType: \"credit\",\n amount: 0, // No actual credits returned (they were reserved, not spent)\n balanceAfter: credits.balance,\n source: \"operation_release\",\n referenceId: reservationId,\n referenceType: \"reservation\",\n description: `Released ${reservation.amount} reserved credits for ${getOperationLabel(reservation.operationType)}`,\n metadata: {\n operationType: reservation.operationType,\n amount: reservation.amount,\n },\n });\n }\n }\n}\n\n/**\n * Reserve credits for an operation\n *\n * @param repository - The credit repository\n * @param userId - User ID\n * @param amount - Credits to reserve\n * @param operationType - Type of operation\n * @param expiryMs - Reservation expiry time in milliseconds\n * @returns The reservation\n */\nexport async function reserveCreditsForOperation(\n repository: ICreditRepository,\n userId: string,\n amount: number,\n operationType: string,\n expiryMs: number = 5 * 60 * 1000\n): Promise<PortableReservation> {\n const expiresAt = new Date(Date.now() + expiryMs);\n return repository.reserveCreditsAtomic(userId, amount, operationType, expiresAt);\n}\n"],"mappings":";AAsBO,SAAS,0BACd,SACA,cACA,UACQ;AACR,SAAO,UAAU,eAAe;AAClC;AAcO,SAAS,oBAAoB,OAAwB;AAC1D,MAAI,CAAC,OAAO;AACV,YAAO,oBAAI,KAAK,GAAE,YAAY;AAAA,EAChC;AAEA,MAAI,OAAO,UAAU,UAAU;AAC7B,WAAO;AAAA,EACT;AAEA,MAAI,iBAAiB,MAAM;AACzB,WAAO,MAAM,YAAY;AAAA,EAC3B;AAEA,MACE,O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AASA,eAAsB,8BACpB,YACA,QACA,eACe;AAEf,QAAM,cAAc,MAAM,WAAW,eAAe,QAAQ,aAAa;AAGzE,QAAM,WAAW,yBAAyB,QAAQ,aAAa;AAG/D,MAAI,aAAa,WAAW,YAAY;AACtC,UAAM,UAAU,MAAM,WAAW,eAAe,MAAM;AACtD,QAAI,SAAS;AACX,YAAM,WAAW,mBAAmB;AAAA,QAClC;AAAA,QACA,WAAW;AAAA,QACX,QAAQ;AAAA;AAAA,QACR,cAAc,QAAQ;AAAA,QACtB,QAAQ;AAAA,QACR,aAAa;AAAA,QACb,eAAe;AAAA,QACf,aAAa,YAAY,YAAY,MAAM,yBAAyB,kBAAkB,YAAY,aAAa,CAAC;AAAA,QAChH,UAAU;AAAA,UACR,eAAe,YAAY;AAAA,UAC3B,QAAQ,YAAY;AAAA,QACtB;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAYA,eAAsB,2BACpB,YACA,QACA,QACA,eACA,WAAmB,IAAI,KAAK,KACE;AAC9B,QAAM,YAAY,IAAI,KAAK,KAAK,IAAI,IAAI,QAAQ;AAChD,SAAO,WAAW,qBAAqB,QAAQ,QAAQ,eAAe,SAAS;AACjF;","names":[]}
1
+ {"version":3,"sources":["../../src/core/errors.ts","../../src/core/amount.ts","../../src/core/types.ts","../../src/core/outcomes.ts","../../src/core/reservation-integrity.ts","../../src/core/payment-ref.ts","../../src/core/idempotency.ts","../../src/core/error-classify.ts","../../src/core/deferred.ts","../../src/config/index.ts","../../src/config/provider.ts","../../src/repository/types.ts","../../src/repository/flow.ts","../../src/core/operations.ts"],"sourcesContent":["import { sumAmounts } from \"./amount.js\";\n/**\n * Credit system error classes - framework agnostic\n *\n * Provides typed error handling for credit operations.\n * These errors can be used across different environments.\n */\n\n/**\n * Error codes for credit operations\n */\nexport const CreditErrorCode = {\n INSUFFICIENT_CREDITS: \"INSUFFICIENT_CREDITS\",\n RESERVATION_NOT_FOUND: \"RESERVATION_NOT_FOUND\",\n RESERVATION_EXPIRED: \"RESERVATION_EXPIRED\",\n RESERVATION_ALREADY_PROCESSED: \"RESERVATION_ALREADY_PROCESSED\",\n USER_NOT_FOUND: \"USER_NOT_FOUND\",\n INVALID_OPERATION_TYPE: \"INVALID_OPERATION_TYPE\",\n CONFIGURATION_ERROR: \"CONFIGURATION_ERROR\",\n DATABASE_ERROR: \"DATABASE_ERROR\",\n /** Caller reused an idempotency key with a different immutable payload. */\n IDEMPOTENCY_CONFLICT: \"IDEMPOTENCY_CONFLICT\",\n /**\n * Retryable infrastructure failure — serialization/deadlock, lock timeout,\n * connection loss, pool exhaustion. Distinct from `DATABASE_ERROR`, which is\n * a deterministic failure that will fail again identically on retry.\n */\n TRANSIENT_ERROR: \"TRANSIENT_ERROR\",\n /** The configured repository adapter does not implement the requested V2 method. */\n UNSUPPORTED_OPERATION: \"UNSUPPORTED_OPERATION\",\n /** Amount was not a finite positive number. */\n INVALID_AMOUNT: \"INVALID_AMOUNT\",\n /** Idempotency key was supplied but empty or whitespace-only. */\n INVALID_IDEMPOTENCY_KEY: \"INVALID_IDEMPOTENCY_KEY\",\n /**\n * A persisted reservation holds a status this library does not define, so no\n * transition can reason about it. Quarantined rather than cast; nothing moved.\n */\n CORRUPT_RESERVATION_STATUS: \"CORRUPT_RESERVATION_STATUS\",\n /**\n * A persisted reservation does not record that its hold was placed\n * atomically, so the credits it claims are not known to be reserved. Moving\n * it would spend another hold's coverage; nothing moved.\n */\n UNBACKED_RESERVATION: \"UNBACKED_RESERVATION\",\n} as const;\n\nexport type CreditErrorCodeType = (typeof CreditErrorCode)[keyof typeof CreditErrorCode];\n\n/**\n * Custom error class for credit operations\n *\n * Provides structured error information including:\n * - Error code for programmatic handling\n * - Human-readable message\n * - Optional details for debugging\n */\nexport class CreditError extends Error {\n public readonly code: CreditErrorCodeType;\n public readonly details?: Record<string, unknown>;\n\n constructor(\n message: string,\n code: CreditErrorCodeType,\n details?: Record<string, unknown>\n ) {\n super(message);\n this.name = \"CreditError\";\n this.code = code;\n this.details = details;\n\n // Maintains proper stack trace for where error was thrown\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, CreditError);\n }\n }\n\n /**\n * Convert to JSON-serializable object\n */\n toJSON(): { name: string; code: string; message: string; details?: Record<string, unknown> } {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n ...(this.details && { details: this.details }),\n };\n }\n}\n\n/**\n * Type guard to check if an error is a CreditError\n */\nexport function isCreditError(error: unknown): error is CreditError {\n return error instanceof CreditError;\n}\n\n/**\n * Check if an error represents insufficient credits\n *\n * Works with both CreditError and regular Error instances.\n * Useful for handling errors from different sources.\n */\nexport function isInsufficientCreditsError(error: unknown): boolean {\n if (isCreditError(error)) {\n return error.code === CreditErrorCode.INSUFFICIENT_CREDITS;\n }\n\n if (error instanceof Error) {\n return error.message.toLowerCase().includes(\"insufficient credits\");\n }\n\n return false;\n}\n\n/**\n * Create an insufficient credits error\n */\nexport function createInsufficientCreditsError(\n required: number,\n available: number\n): CreditError {\n return new CreditError(\n `Insufficient credits: available ${available}, required ${required}`,\n CreditErrorCode.INSUFFICIENT_CREDITS,\n { required, available, shortfall: sumAmounts(required, -available) }\n );\n}\n\n/**\n * Create a reservation not found error\n */\nexport function createReservationNotFoundError(reservationId: string): CreditError {\n return new CreditError(\n `Reservation ${reservationId} not found`,\n CreditErrorCode.RESERVATION_NOT_FOUND,\n { reservationId }\n );\n}\n\n/**\n * Create a reservation expired error\n */\nexport function createReservationExpiredError(reservationId: string): CreditError {\n return new CreditError(\n `Reservation ${reservationId} has expired`,\n CreditErrorCode.RESERVATION_EXPIRED,\n { reservationId }\n );\n}\n\n/**\n * Create a reservation already processed error\n */\nexport function createReservationAlreadyProcessedError(\n reservationId: string,\n status: string\n): CreditError {\n return new CreditError(\n `Reservation ${reservationId} has already been ${status}`,\n CreditErrorCode.RESERVATION_ALREADY_PROCESSED,\n { reservationId, status }\n );\n}\n\n/**\n * Create a user not found error\n */\nexport function createUserNotFoundError(userId: string): CreditError {\n return new CreditError(\n `User ${userId} not found`,\n CreditErrorCode.USER_NOT_FOUND,\n { userId }\n );\n}\n\n/**\n * Create an invalid operation type error\n */\nexport function createInvalidOperationTypeError(\n operationType: string,\n validTypes: string[]\n): CreditError {\n return new CreditError(\n `Invalid operation type: ${operationType}. Valid types: ${validTypes.join(\", \")}`,\n CreditErrorCode.INVALID_OPERATION_TYPE,\n { operationType, validTypes }\n );\n}\n\n/**\n * Create an idempotency conflict error\n *\n * Raised when a caller reuses an idempotency key with a different immutable\n * payload (different amount or operation type). This is a caller bug, never a\n * retryable condition — the details carry both payloads so it can be diffed.\n */\nexport function createIdempotencyConflictError(\n idempotencyKey: string,\n details?: Record<string, unknown>\n): CreditError {\n return new CreditError(\n `Idempotency key ${idempotencyKey} was reused with a different payload`,\n CreditErrorCode.IDEMPOTENCY_CONFLICT,\n { idempotencyKey, ...details }\n );\n}\n\n/**\n * Create a transient (retryable) error\n */\nexport function createTransientError(\n message: string,\n details?: Record<string, unknown>\n): CreditError {\n return new CreditError(message, CreditErrorCode.TRANSIENT_ERROR, details);\n}\n\n/**\n * Create an error for a V2 method the configured adapter does not implement\n */\nexport function createUnsupportedOperationError(\n operation: string,\n hint?: string\n): CreditError {\n return new CreditError(\n hint\n ? `Repository does not support ${operation}. ${hint}`\n : `Repository does not support ${operation}`,\n CreditErrorCode.UNSUPPORTED_OPERATION,\n { operation, ...(hint ? { hint } : {}) }\n );\n}\n\n/**\n * Create an invalid amount error\n */\nexport function createInvalidAmountError(amount: unknown): CreditError {\n return new CreditError(\n `Credit amount must be a finite positive number (got ${String(amount)})`,\n CreditErrorCode.INVALID_AMOUNT,\n { amount }\n );\n}\n\n/**\n * Check if an error is an idempotency conflict\n */\nexport function isIdempotencyConflictError(error: unknown): boolean {\n return isCreditError(error) && error.code === CreditErrorCode.IDEMPOTENCY_CONFLICT;\n}\n\n/**\n * Check if an error is safe to retry\n *\n * Only `TRANSIENT_ERROR` qualifies. Use {@link classifyDatabaseError} first to\n * turn a raw driver error into a classified `CreditError`.\n */\nexport function isTransientError(error: unknown): boolean {\n return isCreditError(error) && error.code === CreditErrorCode.TRANSIENT_ERROR;\n}\n","/**\n * Validation and exact comparison for credit amounts.\n *\n * Every amount ends up in a `numeric(12, 2)` column, so the ledger can only\n * represent values on the cent grid, with at most ten integer digits. A value\n * outside that grid is not \"close enough\" — PostgreSQL silently rounds it on\n * write, and the row that comes back no longer equals what the caller asked\n * for. Rejecting it before any row is touched is the only way the ledger and\n * the caller can agree on what happened.\n *\n * These live in core rather than in an adapter so every repository — shipped\n * or third-party — validates identically.\n */\n\nimport { CreditError, CreditErrorCode } from \"./errors.js\";\n\n/** `numeric(12, 2)`: 12 significant digits, 2 of them after the point. */\nexport const CREDIT_AMOUNT_SCALE = 2;\n/** Largest representable amount: ten integer digits plus two decimals. */\nexport const CREDIT_AMOUNT_MAX = 9_999_999_999.99;\nconst MAX_CENTS = 999_999_999_999;\n\n/**\n * Convert an amount to whole cents, or `null` if it is not exactly on the grid.\n *\n * `Math.round(value * 100) === value * 100` is the tempting check and it is\n * wrong: `1.005 * 100` is `100.49999999999999` in binary float, so a genuinely\n * invalid value can pass and a valid one can fail. Rounding first and then\n * confirming the value round-trips (`value === cents / 100`) is exact for\n * everything in range, because a cent count below 2^53 divided by 100 is the\n * nearest double to that decimal, which is what the literal parsed to.\n */\nexport function toCents(value: number): number | null {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return null;\n const cents = Math.round(value * 100);\n if (!Number.isSafeInteger(cents)) return null;\n return value === cents / 100 ? cents : null;\n}\n\n/**\n * Add amounts on the cent grid, exactly.\n *\n * Deriving a total with `+` is not safe in a ledger that validates against the\n * grid: `0.10 + 0.20` is `0.30000000000000004` and `0.30 - 0.10` is\n * `0.19999999999999998`, neither of which is a value `numeric(12, 2)` can hold.\n * Two perfectly legal columns would therefore produce a total the validator\n * rejects with `INVALID_AMOUNT`, blaming the caller for a rounding artefact.\n * Summing whole cents is exact for every value in range, and `cents / 100` is\n * the nearest double to that decimal — the same one the literal would parse to.\n *\n * Subtract by negating: `sumAmounts(total, -amount)`. Negation is exact.\n *\n * This is arithmetic, not validation. If any input is itself off the grid the\n * float sum is returned unchanged — deliberately, so a corrupt value is never\n * rounded into legitimacy here — but that is not a guarantee the result will be\n * rejected downstream: two off-grid inputs can cancel, and `sumAmounts(0.005,\n * -0.005)` is a perfectly representable `0`. Inputs read from storage must be\n * validated as inputs, with `assertValidStoredAmount` or\n * `assertValidStoredAmountRaw`, before they are summed. Checking only the\n * derived result is not enough and never was.\n */\nexport function sumAmounts(...values: number[]): number {\n let cents = 0;\n for (const value of values) {\n const valueCents = toCents(value);\n if (valueCents === null) return floatSum(values);\n cents += valueCents;\n }\n return Number.isSafeInteger(cents) ? cents / 100 : floatSum(values);\n}\n\nfunction floatSum(values: number[]): number {\n let total = 0;\n for (const value of values) total += value;\n return total;\n}\n\n/** Amounts that may be *moved*: strictly positive and on the cent grid. */\nexport function isValidCreditAmount(value: unknown): value is number {\n if (typeof value !== \"number\") return false;\n const cents = toCents(value);\n return cents !== null && cents > 0 && cents <= MAX_CENTS;\n}\n\n/**\n * Reject an unusable amount before any row is written.\n *\n * @param context - merged into the error details, e.g. `{ userId }`.\n */\nexport function assertValidCreditAmount(\n value: unknown,\n context?: Record<string, unknown>\n): asserts value is number {\n if (isValidCreditAmount(value)) return;\n throw new CreditError(\n creditAmountReason(value),\n CreditErrorCode.INVALID_AMOUNT,\n { amount: value, max: CREDIT_AMOUNT_MAX, scale: CREDIT_AMOUNT_SCALE, ...context }\n );\n}\n\n/** Say precisely which rule the value broke, so the caller can fix it. */\nfunction creditAmountReason(value: unknown): string {\n if (typeof value !== \"number\") {\n return `Credit amount must be a number (got ${typeof value})`;\n }\n if (!Number.isFinite(value)) {\n return `Credit amount must be finite (got ${String(value)})`;\n }\n if (value <= 0) {\n return `Credit amount must be greater than zero (got ${value})`;\n }\n if (value > CREDIT_AMOUNT_MAX) {\n return `Credit amount ${value} exceeds the maximum of ${CREDIT_AMOUNT_MAX}`;\n }\n return `Credit amount ${value} is not exact to ${CREDIT_AMOUNT_SCALE} decimal places`;\n}\n\n/**\n * Amounts the ledger can *record*: on the cent grid and in range, but free to\n * be zero or negative.\n *\n * Not every numeric column holds something spendable. A release journal entry\n * records `amount: 0` because no credits changed hands, and `balanceAfter` goes\n * negative for an account that was corrected or allowed to overdraw. Forcing\n * those through {@link isValidCreditAmount} would reject legitimate ledger\n * rows; skipping validation entirely would let `Infinity` or a third decimal\n * reach the column and be silently rounded or rejected by the driver.\n */\nexport function isRepresentableAmount(value: unknown): value is number {\n if (typeof value !== \"number\") return false;\n const cents = toCents(value);\n return cents !== null && Math.abs(cents) <= MAX_CENTS;\n}\n\n/**\n * Reject a ledger value the `numeric(12, 2)` column cannot hold exactly.\n *\n * @param field - the column being written, so the error names the culprit.\n */\nexport function assertRepresentableAmount(\n value: unknown,\n field: string,\n context?: Record<string, unknown>\n): asserts value is number {\n if (isRepresentableAmount(value)) return;\n throw new CreditError(\n `${field} must be a finite number exact to ${CREDIT_AMOUNT_SCALE} decimal places ` +\n `within ±${CREDIT_AMOUNT_MAX} (got ${String(value)})`,\n CreditErrorCode.INVALID_AMOUNT,\n { field, value, max: CREDIT_AMOUNT_MAX, scale: CREDIT_AMOUNT_SCALE, ...context }\n );\n}\n\n/**\n * Check a whole set of optional ledger fields at once.\n *\n * The balance writers each take a handful of independently optional numbers,\n * and validating them one `if` at a time is where one quietly gets missed.\n * Undefined entries are skipped — they mean \"leave this column alone\".\n */\nexport function assertRepresentableFields(\n fields: Record<string, unknown>,\n context?: Record<string, unknown>\n): void {\n for (const [field, value] of Object.entries(fields)) {\n if (value === undefined) continue;\n assertRepresentableAmount(value, field, context);\n }\n}\n\n/**\n * The lowest `balance` that keeps every outstanding hold committable.\n *\n * Commit's funding guard is `balance + bonusCredits >= amount`, and every live\n * hold is counted in `reserved`, so any write that lowers `balance` must keep\n * `balance + bonusCredits >= reserved` — otherwise a hold that was fully backed\n * when it was placed throws `INSUFFICIENT_CREDITS` at commit time and is\n * stranded. Monthly resets, tier downgrades and explicit tier writes all lower\n * `balance` to a configured target; this is the floor they may not cut through.\n *\n * The floor is `reserved - bonusCredits`, never below zero: bonus credits also\n * fund commits, so they count toward the backing.\n */\nexport function backedBalanceFloor(reserved: number, bonusCredits: number): number {\n const floor = Math.max(0, sumAmounts(reserved, -bonusCredits));\n // A floor beyond the representable range means the row itself is corrupt —\n // e.g. a large negative `bonusCredits` pushing `reserved - bonusCredits`\n // past the `numeric(12,2)` cap. Refuse loudly: writing it would succeed in\n // memory and be rejected by the SQL column, splitting the adapters.\n assertRepresentableAmount(floor, \"backedBalanceFloor\", { reserved, bonusCredits });\n return floor;\n}\n\n/**\n * Validate a limit derived from tier configuration.\n *\n * `Infinity` is this codebase's sentinel for an unlimited tier, so it is\n * accepted here; {@link storedMonthlyLimit} decides what actually reaches the\n * column. Every other value ends up in `numeric(12, 2)` and has to fit, so a\n * tier configured with `monthlyCredits: 1.005` is caught here rather than\n * silently rounded to `1.01` by PostgreSQL.\n */\nexport function assertRepresentableTierAmount(\n value: unknown,\n field: string,\n context?: Record<string, unknown>\n): void {\n if (value === Number.POSITIVE_INFINITY) return;\n assertRepresentableAmount(value, field, context);\n}\n\n/**\n * Validate a stored amount in the representation storage actually returned.\n *\n * Checking the mapped float is not enough, because the mapping is lossy in both\n * directions. A `numeric` column with no scale constraint can hold\n * `9999999999.9900001`; `Number()` rounds that to `9999999999.99`, which is a\n * perfectly valid amount, so a validator looking at the mapped value sees\n * nothing wrong and the transition proceeds — while PostgreSQL goes on doing\n * exact arithmetic with the digits JavaScript threw away. `NaN` and values past\n * double range are worse: the mapper turns them into `0`, which misreports what\n * the row holds.\n *\n * So this runs on the driver's own output — a string, for `numeric` — and uses\n * exact integer arithmetic. It returns the amount as a float only after\n * establishing that the float is a faithful representation of it.\n *\n * @returns the stored amount, exactly representable as a JS number.\n */\n/**\n * How an unlimited tier's monthly limit is stored.\n *\n * `getConfigMonthlyLimit` returns `Infinity` for an unlimited tier, and no\n * numeric column can hold that. Both adapters therefore store the ceiling of\n * the representable range instead: any real usage compares below it, so\n * \"unlimited\" keeps behaving like unlimited, and a reader that knows nothing\n * about the sentinel sees a very large allowance rather than a wrong one.\n *\n * This exists so the two adapters cannot drift. The SQL adapter previously\n * stored `0` here, which reads as *no* allowance — the exact opposite — while\n * the in-memory adapter kept `Infinity`.\n */\nexport function storedMonthlyLimit(limit: number): number {\n return Number.isFinite(limit) ? limit : CREDIT_AMOUNT_MAX;\n}\n\nexport function assertValidStoredAmountRaw(\n raw: unknown,\n context: Record<string, unknown>\n): number {\n const cents = numericToCents(raw);\n if (cents !== null && cents > 0n && cents <= BigInt(MAX_CENTS)) {\n return Number(cents) / 100;\n }\n throw new CreditError(\n `Stored credit amount ${String(raw)} is not a valid amount, so this ` +\n \"transition was refused before any state changed. The row must be \" +\n \"repaired before it can be committed, released or expired.\",\n CreditErrorCode.INVALID_AMOUNT,\n {\n amount: typeof raw === \"string\" ? raw : String(raw),\n reason: \"corrupt_stored_amount\",\n max: CREDIT_AMOUNT_MAX,\n scale: CREDIT_AMOUNT_SCALE,\n ...context,\n }\n );\n}\n\n/**\n * Reject a *persisted* amount that the ledger cannot honour.\n *\n * A reservation row is written once and read back on every transition, and\n * nothing stops a direct SQL write, a botched migration, or an older version of\n * this library from leaving an amount the invariants cannot reason about. A\n * negative one is the dangerous case: `reserved >= amount` is trivially true\n * for it, and `balance - (-10)` *adds* credits, so a transition that trusts the\n * stored value mints money. Every transition therefore re-validates what it\n * locked before it changes anything.\n *\n * Deliberately fails release and expire as well as commit. Returning a hold of\n * an unknown size is not obviously safer than spending one — it hands back\n * coverage that may never have been taken — so a corrupt row stops moving\n * entirely and waits for an operator, rather than being partially honoured.\n *\n * This is the float-typed form, used by the in-memory adapter where the stored\n * value *is* a JS number and no conversion has happened. A repository whose\n * storage returns some other representation must use\n * {@link assertValidStoredAmountRaw} instead, or the conversion will hide the\n * corruption from the check.\n */\nexport function assertValidStoredAmount(\n value: unknown,\n context: Record<string, unknown>\n): asserts value is number {\n if (isValidCreditAmount(value)) return;\n throw new CreditError(\n `Stored credit amount ${String(value)} is not a valid amount, so this ` +\n \"transition was refused before any state changed. The row must be \" +\n \"repaired before it can be committed, released or expired.\",\n CreditErrorCode.INVALID_AMOUNT,\n { amount: value, reason: \"corrupt_stored_amount\", max: CREDIT_AMOUNT_MAX, ...context }\n );\n}\n\n/**\n * Parse a value read back from a `numeric` column into exact cents.\n *\n * Drivers return `numeric` as a string precisely so no precision is lost in\n * transit; comparing the parsed floats would throw that away again. Returns\n * `null` for anything unparseable so callers can treat it as \"not equal\"\n * rather than crashing on malformed ledger data.\n */\nexport function numericToCents(value: unknown): bigint | null {\n if (typeof value === \"number\") {\n const cents = toCents(value);\n return cents === null ? null : BigInt(cents);\n }\n if (typeof value !== \"string\") return null;\n\n const match = /^([+-]?)(\\d+)(?:\\.(\\d*))?$/.exec(value.trim());\n if (!match) return null;\n\n const [, sign, whole, fraction = \"\"] = match;\n // More than two decimals is only acceptable when the extra digits are zeros;\n // anything else never came from a numeric(12,2) column.\n if (/[1-9]/.test(fraction.slice(CREDIT_AMOUNT_SCALE))) return null;\n\n const cents =\n BigInt(whole) * 100n + BigInt(fraction.slice(0, CREDIT_AMOUNT_SCALE).padEnd(CREDIT_AMOUNT_SCALE, \"0\"));\n return sign === \"-\" ? -cents : cents;\n}\n\n/**\n * Exact equality for two amounts that may be numbers or `numeric` strings.\n *\n * Unparseable input is *not* equal to anything, including itself — a\n * comparison against corrupt data must never come back \"matches\".\n */\nexport function sameAmount(a: unknown, b: unknown): boolean {\n const left = numericToCents(a);\n const right = numericToCents(b);\n return left !== null && right !== null && left === right;\n}\n","import { sumAmounts } from \"./amount.js\";\n/**\n * Portable credits types - framework and database agnostic\n *\n * These types use standard JavaScript types (string, Date) instead of\n * Firebase-specific types (Timestamp). This makes the credits system\n * portable to other environments without Firebase dependencies.\n *\n * Note: Firestore Timestamp is handled by the credits-firestore adapter.\n */\n\n// ==================== Utility Functions ====================\n\n/**\n * Calculate available credits from balance, bonus, and reserved amounts.\n *\n * Available = balance + bonusCredits - reserved\n *\n * @param balance - Regular monthly credits\n * @param bonusCredits - Purchased/admin credits\n * @param reserved - Credits locked for in-flight operations\n * @returns Available credits for new operations\n */\nexport function calculateAvailableCredits(\n balance: number,\n bonusCredits: number,\n reserved: number\n): number {\n return sumAmounts(balance, bonusCredits, -reserved);\n}\n\n/**\n * Convert various timestamp formats to ISO string.\n *\n * Handles:\n * - Date objects\n * - ISO string (returned as-is)\n * - Timestamp-like objects with toDate() method (Firebase)\n * - undefined/null (returns current time)\n *\n * @param value - Value to convert\n * @returns ISO 8601 string\n */\nexport function toPortableTimestamp(value: unknown): string {\n if (!value) {\n return new Date().toISOString();\n }\n\n if (typeof value === \"string\") {\n return value;\n }\n\n if (value instanceof Date) {\n return value.toISOString();\n }\n\n if (\n typeof value === \"object\" &&\n value !== null &&\n \"toDate\" in value &&\n typeof (value as { toDate: () => Date }).toDate === \"function\"\n ) {\n return (value as { toDate: () => Date }).toDate().toISOString();\n }\n\n return new Date().toISOString();\n}\n\n/**\n * Convert various timestamp formats to Date object.\n *\n * Handles:\n * - Date objects (returned as-is)\n * - ISO string\n * - Timestamp-like objects with toDate() method (Firebase)\n * - Invalid values (returns current date)\n *\n * @param value - Value to convert\n * @returns Date object\n */\nexport function toDate(value: unknown): Date {\n if (value instanceof Date) {\n return value;\n }\n\n if (typeof value === \"string\") {\n return new Date(value);\n }\n\n if (\n typeof value === \"object\" &&\n value !== null &&\n \"toDate\" in value &&\n typeof (value as { toDate: () => Date }).toDate === \"function\"\n ) {\n return (value as { toDate: () => Date }).toDate();\n }\n\n return new Date();\n}\n\n// ==================== Subscription Types ====================\n\n/**\n * Built-in tier ids (autocomplete) — apps may add more via config.\n */\nexport type BuiltinTier = \"free\" | \"basic\" | \"premium\" | \"unlimited\";\n\n/**\n * Subscription tiers for the credits system.\n *\n * Any built-in OR any config-defined tier id. The `(string & {})` keeps builtin\n * autocomplete while accepting arbitrary configured tiers.\n */\nexport type SubscriptionTier = BuiltinTier | (string & {});\n\n// ==================== Operation Types ====================\n\n/**\n * Operation types for cost tracking (provider-agnostic)\n *\n * Dynamic string type - any operation configured in the system is valid.\n */\nexport type CreditOperationType = string;\n\n/**\n * AI providers\n */\nexport type AIProviderType = \"gemini\";\n\n/**\n * Resource type for usage logging\n */\nexport type ResourceType = string;\n\n// ==================== User Credits ====================\n\n/**\n * Portable user credits balance\n *\n * Uses ISO string timestamps instead of Firebase Timestamp.\n * This type is safe for JSON serialization and works across frameworks.\n */\nexport interface PortableUserCredits {\n userId: string;\n /** Current available balance (monthly credits, reset each month) */\n balance: number;\n /** Bonus credits from purchases/admin (never reset, persist until used) */\n bonusCredits: number;\n /** Credits currently reserved for in-flight operations */\n reserved: number;\n /** User's subscription tier */\n tier: SubscriptionTier;\n /** Monthly credit limit based on tier (0 = unlimited) */\n monthlyLimit: number;\n /** Credits used this month (resets monthly) */\n monthlyUsed: number;\n /** When monthly credits reset (start of next month) - ISO 8601 */\n monthlyResetAt: string;\n /** Subscription expiry (null/undefined for free tier) - ISO 8601 or null */\n subscriptionExpiresAt?: string | null;\n /** Creation timestamp - ISO 8601 */\n createdAt: string;\n /** Last update timestamp - ISO 8601 */\n updatedAt: string;\n}\n\n// ==================== Reservation Types ====================\n\n/**\n * Credit reservation status for two-phase commit\n */\nexport type ReservationStatus = \"reserved\" | \"committed\" | \"released\" | \"expired\";\n\n/**\n * Portable credit reservation\n *\n * Used for two-phase commit to prevent double-spending.\n */\nexport interface PortableReservation {\n id: string;\n userId: string;\n /** Amount of credits reserved */\n amount: number;\n /** Operation type for tracking */\n operationType: CreditOperationType;\n /** Current status of reservation */\n status: ReservationStatus;\n /** When reservation was created - ISO 8601 */\n createdAt: string;\n /** When reservation expires (for cleanup) - ISO 8601 */\n expiresAt: string;\n /** When reservation was committed/released - ISO 8601 or undefined */\n completedAt?: string;\n /**\n * Caller-supplied idempotency key (V2). Absent on legacy reservations.\n * Unique per user; a replay with the same key returns this same reservation.\n */\n idempotencyKey?: string;\n /**\n * When the atomic reserve placed this hold - ISO 8601, or absent.\n *\n * Written by `reserveCreditsV2` inside the same transaction that increases\n * `reserved`, so its presence is proof that the hold exists. `createReservation`\n * never sets it, and the V2 transitions refuse to move a row without it.\n * See `assertHoldPlaced` in `core/reservation-integrity.ts`.\n */\n holdPlacedAt?: string;\n}\n\n// ==================== Result Types ====================\n\n/**\n * Result of a credit check operation\n */\nexport interface CreditCheckResult {\n /** Whether user has sufficient credits */\n hasCredits: boolean;\n /** Current balance (balance + bonusCredits) */\n balance: number;\n /** Required credits for operation */\n required: number;\n /** Shortfall if insufficient */\n shortfall: number;\n}\n\n/**\n * Result of a one-shot atomic credit deduction (see `CreditsService.deductCredits`).\n *\n * Discriminated on `success` so callers get exhaustive narrowing:\n * - `success: true` -> `newBalance` is populated, `available`/`shortfall` are not present.\n * - `success: false` -> `available`/`shortfall` describe the shortfall, no mutation occurred.\n */\nexport type DeductCreditsResult =\n | {\n success: true;\n /** Combined balance (balance + bonusCredits) after the deduction */\n newBalance: number;\n }\n | {\n success: false;\n reason: \"insufficient\";\n /** Combined balance (balance + bonusCredits - reserved) available before the attempt */\n available: number;\n /** Credits that were requested */\n required: number;\n /** How many more credits would have been needed */\n shortfall: number;\n };\n\n/**\n * Result of monthly reset operation\n */\nexport interface MonthlyResetResult {\n /** Whether the reset was performed */\n wasReset: boolean;\n /** The user credits after the operation */\n credits: PortableUserCredits;\n /**\n * `true` when the repository wrote the reset's journal entry inside the same\n * atomic step as the balance write. The service then skips its own journal\n * call — a separate call sits outside the reset's atomicity, and if it fails\n * after the CAS was consumed, the line is lost for good (no retry ever sees\n * the reset again). Absent/`false` means the repository did not journal and\n * the service falls back to the legacy non-atomic write.\n */\n journaled?: boolean;\n}\n\n/**\n * Result of subscription expiry check\n */\nexport interface SubscriptionExpiryResult {\n /** Whether the subscription was downgraded */\n wasDowngraded: boolean;\n /** Whether user is in grace period */\n inGracePeriod: boolean;\n /** Days remaining in grace period (0 if not in grace) */\n graceDaysRemaining: number;\n /** The user credits after the operation */\n credits: PortableUserCredits;\n /**\n * `true` when the repository wrote the downgrade's journal entry inside the\n * same atomic step as the tier write. The service then skips its own journal\n * call — a separate call sits outside the downgrade's atomicity, and if it\n * fails after the tier write committed, the account is downgraded with no\n * audit line and no retry ever fires (the row is no longer eligible).\n * Absent/`false` means the repository did not journal and the service falls\n * back to the legacy non-atomic write.\n */\n journaled?: boolean;\n}\n\n// ==================== Transaction Types ====================\n\n/**\n * Credit transaction type\n */\nexport type TransactionType = \"purchase\" | \"subscription\" | \"bonus\" | \"refund\" | \"adjustment\";\n\n/**\n * Portable credit transaction\n */\nexport interface PortableTransaction {\n id: string;\n userId: string;\n type: TransactionType;\n /** Amount of credits (positive for additions, negative for deductions) */\n amount: number;\n description: string;\n /** Reference to payment provider */\n paymentRef?: string;\n previousBalance: number;\n newBalance: number;\n createdAt: string;\n}\n\n// ==================== Journal Types ====================\n\n/**\n * Source of a credit journal entry\n */\nexport type CreditSource =\n | \"operation_commit\"\n | \"operation_release\"\n | \"purchase\"\n | \"subscription_grant\"\n | \"subscription_upgrade\"\n | \"subscription_downgrade\"\n | \"monthly_reset\"\n | \"bonus\"\n | \"refund\"\n | \"admin_adjustment\"\n | \"expiry\"\n | \"reservation_expired\";\n\n/**\n * Type of reference for a journal entry\n */\nexport type JournalReferenceType =\n | \"reservation\"\n | \"transaction\"\n | \"adjustment\"\n | \"reset\"\n | \"subscription\";\n\n/**\n * Portable credit journal entry for audit trail\n */\nexport interface PortableJournalEntry {\n id: string;\n userId: string;\n /** Type of entry - debit decreases balance, credit increases balance */\n entryType: \"debit\" | \"credit\";\n /** Amount of credits involved */\n amount: number;\n /** Balance after this entry */\n balanceAfter: number;\n /** Source of the credit change */\n source: CreditSource;\n /** Reference ID (e.g., reservationId, transactionId) */\n referenceId: string;\n /** Type of reference */\n referenceType: JournalReferenceType;\n /** Human-readable description */\n description: string;\n /** Additional metadata */\n metadata?: Record<string, unknown>;\n /**\n * Deterministic key that makes this entry unique per user (V2). Absent on\n * legacy entries; present entries cannot be written twice.\n */\n idempotencyKey?: string;\n /** When this entry was created - ISO 8601 */\n createdAt: string;\n}\n\n// ==================== Usage Types ====================\n\n/**\n * Portable usage log entry\n */\nexport interface PortableUsageLog {\n id: string;\n userId: string;\n operationType: CreditOperationType;\n provider: AIProviderType;\n creditsUsed: number;\n success: boolean;\n errorMessage?: string;\n resourceId?: string;\n resourceType?: ResourceType;\n requestId?: string;\n metadata?: Record<string, unknown>;\n createdAt: string;\n}\n\n/**\n * User-friendly usage history entry\n */\nexport interface UsageHistoryEntry {\n id: string;\n /** Type of entry for display */\n type: \"usage\" | \"purchase\" | \"bonus\" | \"reset\" | \"refund\" | \"adjustment\";\n /** Positive = earned, Negative = spent */\n creditsChange: number;\n /** Balance after this entry */\n balanceAfter: number;\n /** Human-readable description */\n description: string;\n /** When this occurred - ISO 8601 */\n createdAt: string;\n}\n\n/**\n * Paginated usage history response\n */\nexport interface UsageHistoryResponse {\n entries: UsageHistoryEntry[];\n pagination: {\n total: number;\n limit: number;\n offset: number;\n hasMore: boolean;\n };\n}\n\n// ==================== Tier Configuration ====================\n\n/**\n * Tier configuration for credit limits and pricing\n */\nexport interface TierConfig {\n tier: SubscriptionTier;\n monthlyCredits: number;\n priceUsd: number;\n features: string[];\n /** Free/default tier marker — no subscription expiry, balance untouched on tier change. Defaults to priceUsd === 0. */\n isFree?: boolean;\n /** Unlimited tier marker. Defaults to monthlyCredits === 0. */\n unlimited?: boolean;\n /** Tier assigned to brand-new users. Defaults to the tier flagged isFree. */\n isDefault?: boolean;\n}\n\n// ==================== Options Types ====================\n\n/**\n * Options for withCredits HOF\n */\nexport interface WithCreditsOptions {\n /** Operation type for cost lookup */\n operationType: CreditOperationType;\n /** AI provider (defaults to \"gemini\") */\n provider?: AIProviderType;\n /** Custom cost override (use with caution) */\n customCost?: number;\n /** Resource ID for usage logging */\n resourceId?: string;\n /** Resource type for usage logging */\n resourceType?: ResourceType;\n}\n\n// ==================== Constants ====================\n","/**\n * Typed outcomes for the V2 reservation boundary.\n *\n * The legacy `*Atomic` repository methods signal \"you lost the race\" by\n * throwing (or, worse, by silently returning). V2 makes every terminal\n * transition an explicit, serialisable value so callers can tell a winner\n * from a duplicate delivery without string-matching an error message.\n *\n * Every outcome is discriminated on `outcome` (never `status`, which is the\n * reservation's own lifecycle field and would collide).\n */\n\nimport type {\n PortableReservation,\n PortableTransaction,\n ReservationStatus,\n} from \"./types.js\";\n\n/** Statuses a reservation can no longer transition out of. */\nexport type TerminalReservationStatus = Exclude<ReservationStatus, \"reserved\">;\n\n/**\n * Result of `reserveCreditsV2`.\n *\n * - `created` — this caller minted the hold.\n * - `replayed` — same `(userId, idempotencyKey)` with an identical immutable\n * payload; the original reservation is returned and no new hold was placed.\n * - `insufficient` — the guarded hold could not be placed; nothing was written.\n * - `idempotency_conflict` — the key was reused with a different\n * amount/operation. Nothing was written; the existing reservation is\n * returned so the caller can diff it.\n */\nexport type ReserveOutcome =\n | { outcome: \"created\"; reservation: PortableReservation }\n | { outcome: \"replayed\"; reservation: PortableReservation }\n | {\n outcome: \"insufficient\";\n available: number;\n required: number;\n shortfall: number;\n }\n | {\n outcome: \"idempotency_conflict\";\n idempotencyKey: string;\n existing: PortableReservation;\n };\n\n/**\n * Result of `commitReservationV2`.\n *\n * Exactly one concurrent caller ever observes `committed`; that call — and\n * only that call — moved the balance and wrote the journal entry.\n */\nexport type CommitOutcome =\n | {\n outcome: \"committed\";\n reservation: PortableReservation;\n amount: number;\n /** `balance + bonusCredits` after the deduction, read from the same UPDATE. */\n balanceAfter: number;\n journalEntryId: string;\n }\n | {\n outcome: \"already_terminal\";\n reservation: PortableReservation;\n terminalStatus: TerminalReservationStatus;\n }\n | { outcome: \"not_found\"; reservationId: string };\n\n/** Result of `releaseReservationV2`. Mirrors {@link CommitOutcome}. */\nexport type ReleaseOutcome =\n | {\n outcome: \"released\";\n reservation: PortableReservation;\n amount: number;\n journalEntryId: string;\n }\n | {\n outcome: \"already_terminal\";\n reservation: PortableReservation;\n terminalStatus: TerminalReservationStatus;\n }\n | { outcome: \"not_found\"; reservationId: string };\n\n/**\n * Result of `expireReservationV2`.\n *\n * `not_due` means the reservation is still `reserved` but its `expiresAt` is\n * in the future relative to the sweep's `asOf` — a no-op, not a failure.\n */\nexport type ExpireOutcome =\n | {\n outcome: \"expired\";\n reservation: PortableReservation;\n amount: number;\n journalEntryId: string;\n }\n | { outcome: \"not_due\"; reservation: PortableReservation }\n | {\n outcome: \"already_terminal\";\n reservation: PortableReservation;\n terminalStatus: TerminalReservationStatus;\n }\n | { outcome: \"not_found\"; reservationId: string };\n\n/**\n * Result of crediting an account against a `paymentRef`.\n *\n * - `created` — this delivery credited the account.\n * - `replayed` — the reference was already used for the *same* credit event;\n * nothing was written and the original transaction is returned.\n * - `conflict` — the reference was already used for a *different* event\n * (another user, another amount, another source). Nothing was written;\n * `mismatch` names the first field that disagreed.\n *\n * A call with no `paymentRef` is always `created`: without a reference there is\n * nothing to deduplicate on, and every delivery is a distinct credit.\n *\n * **`created` is only a single-delivery guarantee on an adapter that implements\n * `addCreditsV2`.** Routed through a legacy adapter, `created` means \"the call\n * was made and did not throw\" — there is no global unique index behind it, so a\n * re-delivered reference credits again. `supportsIdempotentCredit` is the probe\n * that tells the two apart, and it is also why `transaction` is optional here:\n * the legacy method returns nothing, and inventing a transaction to fill the\n * field would be a fabricated audit record.\n */\nexport type AddCreditsOutcome =\n | {\n outcome: \"created\";\n /** The reference this credit was recorded under, if there was one. */\n paymentRef?: string;\n /** Absent only on the legacy fallback path; see above. */\n transaction?: PortableTransaction;\n /** Absent only on the legacy fallback path; see above. */\n journalEntryId?: string;\n }\n | {\n outcome: \"replayed\";\n paymentRef: string;\n transaction: PortableTransaction;\n }\n | {\n outcome: \"conflict\";\n paymentRef: string;\n existing: PortableTransaction;\n /** The first field of the canonical payload that disagreed. */\n mismatch: string;\n };\n\n/** True when this delivery actually moved credits. */\nexport function isCreditedOutcome(\n outcome: AddCreditsOutcome\n): outcome is Extract<AddCreditsOutcome, { outcome: \"created\" }> {\n return outcome.outcome === \"created\";\n}\n\n/** True when this caller performed the state transition. */\nexport function isWinningOutcome(\n outcome: CommitOutcome | ReleaseOutcome | ExpireOutcome\n): boolean {\n return (\n outcome.outcome === \"committed\" ||\n outcome.outcome === \"released\" ||\n outcome.outcome === \"expired\"\n );\n}\n\n/** Narrow a reserve outcome to the two cases that yield a usable reservation. */\nexport function isReservedOutcome(\n outcome: ReserveOutcome\n): outcome is Extract<ReserveOutcome, { reservation: PortableReservation }> {\n return outcome.outcome === \"created\" || outcome.outcome === \"replayed\";\n}\n","/**\n * Trust checks for a *persisted* reservation row.\n *\n * A reservation is written once and read back on every transition, and nothing\n * between those two moments belongs to this library: a direct `UPDATE`, a\n * half-finished migration, a legacy adapter or a future version can all leave a\n * row this code never wrote. Two of the fields it reads back are load-bearing.\n *\n * **`status`** decides whether a transition runs at all. It used to be cast —\n * `reservation.status as TerminalReservationStatus` — so a row holding\n * `'gremlin'` was reported as `already_terminal` with `terminalStatus:\n * 'gremlin'`: a *success* outcome, telling the caller the reservation had been\n * resolved, over a row nothing in this library can resolve. The cast is a lie\n * the type system cannot catch, so the value is checked against the closed set\n * instead and anything outside it quarantines the row.\n *\n * **`holdPlacedAt`** decides whether the hold behind the row exists. See\n * {@link assertHoldPlaced}.\n *\n * Both refusals happen before any state changes, and neither one repairs\n * anything: a corrupt row stops moving and waits for an operator. Silently\n * reconciling it would need an audit trail and a recovery procedure, and\n * guessing is how a bad row becomes a wrong balance.\n */\n\nimport { CreditError, CreditErrorCode } from \"./errors.js\";\nimport type { TerminalReservationStatus } from \"./outcomes.js\";\nimport type { PortableReservation, ReservationStatus } from \"./types.js\";\n\n/** Every status this library knows how to reason about. */\nexport const RESERVATION_STATUSES: readonly ReservationStatus[] = [\n \"reserved\",\n \"committed\",\n \"released\",\n \"expired\",\n];\n\n/** The statuses a reservation can no longer transition out of. */\nexport const TERMINAL_RESERVATION_STATUSES: readonly TerminalReservationStatus[] = [\n \"committed\",\n \"released\",\n \"expired\",\n];\n\nexport function isReservationStatus(value: unknown): value is ReservationStatus {\n return RESERVATION_STATUSES.includes(value as ReservationStatus);\n}\n\nexport function isTerminalReservationStatus(\n value: unknown\n): value is TerminalReservationStatus {\n return TERMINAL_RESERVATION_STATUSES.includes(value as TerminalReservationStatus);\n}\n\n/** The subset of a reservation these checks read, so callers can pass a row. */\nexport interface ReservationIntegrityView {\n id: string;\n userId: string;\n status: unknown;\n /** Set by the atomic reserve, in the same transaction as the hold. */\n holdPlacedAt?: string | null;\n idempotencyKey?: string | null;\n}\n\n/**\n * Refuse a transition over a status this library does not define.\n *\n * Runs ahead of every early exit, including the `already_terminal` one, for the\n * reason in the module header: `already_terminal` is a success outcome, and a\n * success outcome over an unknown status is the failure mode being prevented.\n */\nexport function assertKnownReservationStatus(\n reservation: ReservationIntegrityView,\n transition: string\n): asserts reservation is ReservationIntegrityView & { status: ReservationStatus } {\n if (isReservationStatus(reservation.status)) return;\n throw new CreditError(\n `Reservation ${reservation.id} holds the status ${JSON.stringify(reservation.status)}, ` +\n `which is not one of ${RESERVATION_STATUSES.join(\", \")}. The ${transition} was ` +\n \"refused before any state changed; the row must be repaired by an operator.\",\n CreditErrorCode.CORRUPT_RESERVATION_STATUS,\n {\n userId: reservation.userId,\n reservationId: reservation.id,\n transition,\n status: typeof reservation.status === \"string\" ? reservation.status : String(reservation.status),\n allowed: [...RESERVATION_STATUSES],\n reason: \"corrupt_reservation_status\",\n }\n );\n}\n\n/**\n * Narrow a non-`reserved` status for the `already_terminal` outcomes.\n *\n * Validates rather than casts. `assertKnownReservationStatus` has usually run\n * already; this repeats the check because the cast it replaces was the defect,\n * and a second closed-set test costs nothing next to a database round trip.\n */\nexport function terminalStatusOf(\n reservation: ReservationIntegrityView,\n transition: string\n): TerminalReservationStatus {\n assertKnownReservationStatus(reservation, transition);\n if (isTerminalReservationStatus(reservation.status)) return reservation.status;\n throw new CreditError(\n `Reservation ${reservation.id} is ${reservation.status}, which is not a terminal ` +\n `status, but the ${transition} tried to report it as one.`,\n CreditErrorCode.CORRUPT_RESERVATION_STATUS,\n {\n userId: reservation.userId,\n reservationId: reservation.id,\n transition,\n status: reservation.status,\n reason: \"not_terminal\",\n }\n );\n}\n\n/**\n * Refuse a transition over a hold that was never atomically placed.\n *\n * `holdPlacedAt` is the single invariant behind the V2 boundary: **a row is\n * only a reservation if the same atomic operation that wrote it also increased\n * `reserved` by its amount.** The atomic reserve sets the field inside that one\n * transaction, so the fact and the hold commit together or not at all.\n *\n * Without it, `createReservation` — a plain row writer that does not touch\n * `reserved` — could mint a keyed row, and a later `reserveCreditsV2` with that\n * key would adopt it as a `replayed` hold that no credits back. The caller then\n * commits it, and the commit passes its `reserved >= amount` guard by consuming\n * coverage that belongs to a *different*, real hold: two holds, one payment.\n *\n * So this is checked before adopting a replay and before every transition, and\n * `createReservation` refuses a key outright — the two halves of the same rule.\n */\nexport function assertHoldPlaced(\n reservation: ReservationIntegrityView,\n transition: string\n): void {\n if (reservation.holdPlacedAt) return;\n throw new CreditError(\n `Reservation ${reservation.id} does not record that its hold was placed atomically ` +\n \"(holdPlacedAt is absent), so the credits it claims to hold may never have been \" +\n `reserved. The ${transition} was refused before any state changed: honouring it ` +\n \"would spend coverage belonging to another reservation. Rows written by \" +\n \"createReservation are not V2 reservations; place holds with reserveCredits.\",\n CreditErrorCode.UNBACKED_RESERVATION,\n {\n userId: reservation.userId,\n reservationId: reservation.id,\n transition,\n idempotencyKey: reservation.idempotencyKey ?? undefined,\n reason: \"hold_not_placed\",\n }\n );\n}\n\n/**\n * Refuse an idempotency key on the direct, non-atomic reservation writer.\n *\n * The other half of {@link assertHoldPlaced}. `createReservation` inserts a row\n * and does not touch `reserved`, so a key registered here would name a hold\n * that does not exist. Rejecting the key at the boundary means the unbacked\n * keyed row cannot be created in the first place, rather than only being\n * refused later by every transition that tries to move it.\n *\n * The amount check that runs alongside this is about a value the ledger cannot\n * honour; this is about a *claim* the writer cannot honour.\n */\nexport function assertUnkeyedDirectReservation(input: {\n userId: string;\n idempotencyKey?: string;\n}): void {\n if (input.idempotencyKey === undefined || input.idempotencyKey === null) return;\n throw new CreditError(\n \"createReservation cannot accept an idempotencyKey: it writes the reservation \" +\n \"row without placing the hold, so the key would name credits that were never \" +\n \"reserved, and a later reserveCredits with the same key would adopt it as a \" +\n \"replay. Call reserveCredits (or reserveCreditsV2) with the key instead — it \" +\n \"claims the key and places the hold in one transaction.\",\n CreditErrorCode.UNSUPPORTED_OPERATION,\n {\n userId: input.userId,\n idempotencyKey: input.idempotencyKey,\n operation: \"createReservation\",\n reason: \"keyed_direct_reservation\",\n }\n );\n}\n\n/** True when the row records an atomically placed hold. */\nexport function hasPlacedHold(reservation: Pick<PortableReservation, \"holdPlacedAt\">): boolean {\n return Boolean(reservation.holdPlacedAt);\n}\n\n/**\n * Refuse a direct status write that would bypass the V2 state machine.\n *\n * `updateReservationStatus` assigns a status and nothing else: it does not\n * check the current status, move the balance, adjust `reserved`, or journal.\n * On a row whose hold was atomically placed, that is not an update — it is a\n * bypass. Writing `committed` onto a live hold strands `reserved` forever (the\n * real commit then reports `already_terminal` and never debits), and writing\n * `reserved` onto a terminal row re-arms a settled reservation so it can be\n * settled again.\n *\n * Two refusals, mirroring the createReservation/reserveCredits split:\n *\n * - A row bearing `holdPlacedAt` belongs to the V2 transitions. Every status it\n * will ever hold is assigned by commit/release/expire, atomically with the\n * ledger movement that status implies.\n * - No row, V2 or legacy, may be *reopened* — status can never be assigned back\n * to `reserved`, because nothing here re-places the hold that status claims.\n *\n * Rows written by `createReservation` (no hold, no key) remain freely\n * annotatable with terminal statuses: their statuses never carried ledger\n * meaning, and the V2 transitions refuse them anyway.\n */\nexport function assertDirectStatusWriteAllowed(\n reservation: ReservationIntegrityView,\n status: ReservationStatus\n): void {\n if (status === \"reserved\") {\n throw new CreditError(\n `Reservation ${reservation.id} cannot have its status set back to \"reserved\": ` +\n \"updateReservationStatus does not place a hold, so the reopened row would claim \" +\n \"credits nothing reserved. Create a new reservation with reserveCredits instead.\",\n CreditErrorCode.UNSUPPORTED_OPERATION,\n {\n userId: reservation.userId,\n reservationId: reservation.id,\n status,\n reason: \"reopen_reservation\",\n }\n );\n }\n if (!reservation.holdPlacedAt) return;\n throw new CreditError(\n `Reservation ${reservation.id} is backed by an atomically placed hold, so its ` +\n \"status may only be assigned by the transition that settles it. Writing \" +\n `\"${status}\" directly would change the status without moving the credits it ` +\n \"stands for, stranding the hold. Use commitReservation / releaseReservation / \" +\n \"expireReservation (or their V2 forms) instead.\",\n CreditErrorCode.UNSUPPORTED_OPERATION,\n {\n userId: reservation.userId,\n reservationId: reservation.id,\n status,\n reason: \"direct_status_write_on_backed_hold\",\n }\n );\n}\n","/**\n * `paymentRef` as a global, semantic idempotency boundary.\n *\n * A payment reference is the identity of a *credit event* — one webhook, one\n * invoice, one charge. It is deliberately not scoped to a user: a processor's\n * reference is unique across the processor's whole account, and the SQL adapter\n * has always enforced it with a unique index over `payment_ref` alone. Two\n * problems followed from treating it as anything less.\n *\n * **It was scoped per user in memory and globally in SQL.** The in-memory\n * adapter searched only the crediting user's own transactions, so replaying a\n * reference against a *different* user credited both accounts, while the SQL\n * adapter silently no-opped. Same call, two ledgers, opposite results — and the\n * memory one is the direction that invents money.\n *\n * **It was compared on presence, never on payload.** A reference that arrived a\n * second time carrying a different amount was accepted as a replay of the\n * first, so a corrected or spoofed webhook credited the original amount and\n * reported success. Presence is only sound when the payload is known to match;\n * otherwise the honest answer is a conflict.\n *\n * So a reference now resolves to exactly one of three outcomes — `created`,\n * `replayed`, `conflict` — in both adapters, and `conflict` mutates nothing.\n */\n\nimport { sameAmount } from \"./amount.js\";\nimport { CreditError, CreditErrorCode } from \"./errors.js\";\nimport type {\n CreditSource,\n JournalReferenceType,\n PortableTransaction,\n} from \"./types.js\";\n\n/**\n * The fields that define the credit event a reference names.\n *\n * `description` is excluded on purpose: it is human-facing copy that a retry\n * may legitimately regenerate (\"Purchase 100 credits\" versus \"Purchase of 100\n * credits\") without the event being different. Everything that decides *how\n * much lands where* is in.\n */\nexport interface PaymentEventPayload {\n userId: string;\n amount: number;\n /** The transaction row's `type` — the operation the reference names. */\n type: PortableTransaction[\"type\"];\n /** The journal entry's `source` — where the credits came from. */\n source: CreditSource;\n /** The journal entry's `referenceType`. */\n referenceType: JournalReferenceType;\n}\n\n/**\n * The stored side of the comparison, as either adapter can produce it.\n *\n * `amount` is `unknown` because SQL returns `numeric` as a string, and\n * comparing the mapped `Number` is exactly the rounding hole that let\n * `9999999999.9900001` match a request for `9999999999.99`.\n */\nexport interface StoredPaymentEvent {\n userId: string;\n amount: unknown;\n type: string;\n /** Absent when no journal entry could be located for the stored transaction. */\n source?: string;\n referenceType?: string;\n}\n\n/**\n * Normalise a payment reference to \"a reference\" or \"no reference\".\n *\n * Empty and whitespace-only strings are *not* references: they cannot identify\n * a payment, and treating them as one produced the divergence where SQL skipped\n * the duplicate check (falsy) but still stored the value, so the replay hit the\n * unique index and threw while memory quietly credited twice.\n *\n * Unlike an idempotency key, a blank reference is normalised rather than\n * rejected. A key is the caller's explicit request for exactly-once and a blank\n * one means they got it wrong; `paymentRef` is an optional annotation on a\n * credit, and an absent one is a normal, supported call.\n */\nexport function normalizePaymentRef(ref?: string | null): string | undefined {\n if (typeof ref !== \"string\") return undefined;\n const trimmed = ref.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n}\n\n/**\n * Name the first field on which a stored credit event disagrees, or `null`.\n *\n * `null` means the delivery is a genuine replay and must change nothing.\n * Anything else is a conflict: the same reference was used for a different\n * event, and crediting on it would either double-credit or credit the wrong\n * amount to the wrong account.\n *\n * `source` and `referenceType` are compared only when the stored side has them.\n * They live on the journal entry, and a transaction written before this library\n * journalled its purchases has none to compare against — treating that absence\n * as a mismatch would turn every pre-existing reference into a permanent\n * conflict, which is a refusal to credit rather than a protection against one.\n */\nexport function describePaymentMismatch(\n stored: StoredPaymentEvent,\n expected: PaymentEventPayload\n): string | null {\n if (stored.userId !== expected.userId) return \"userId\";\n if (!sameAmount(stored.amount, expected.amount)) return \"amount\";\n if (stored.type !== expected.type) return \"type\";\n if (stored.source !== undefined && stored.source !== expected.source) return \"source\";\n if (stored.referenceType !== undefined && stored.referenceType !== expected.referenceType) {\n return \"referenceType\";\n }\n return null;\n}\n\n/**\n * Refuse a payment reference on the direct, record-only transaction writer.\n *\n * `createTransaction` writes a ledger *record*: no balance moves and no journal\n * entry is created. But a `paymentRef` on that record still occupies the global\n * unique boundary, and `addCreditsV2` treats the row that holds a reference as\n * the authoritative credit event — a later delivery of the real payment with\n * the same reference then matches the record on user/amount/type, reports\n * `replayed`, and credits nothing, forever. The record would have consumed the\n * payment.\n *\n * Same shape as `assertUnkeyedDirectReservation`: the claim is refused at the\n * boundary, so the row that could impersonate a credit event cannot be written\n * in the first place. Credits that carry a reference go through\n * `addCreditsAtomic` / `addCreditsV2`, which claim the reference and move the\n * balance in one atomic step.\n */\nexport function assertUnreferencedDirectTransaction(input: {\n userId: string;\n paymentRef?: string;\n}): void {\n if (normalizePaymentRef(input.paymentRef) === undefined) return;\n throw new CreditError(\n \"createTransaction cannot accept a paymentRef: it records a transaction \" +\n \"without crediting the account, and the reference would then be treated \" +\n \"as an already-delivered payment — a later addCredits call with the same \" +\n \"reference reports `replayed` and credits nothing. Record unreferenced \" +\n \"transactions here, or deliver referenced payments through addCredits \" +\n \"(addCreditsAtomic / addCreditsV2), which claims the reference and moves \" +\n \"the balance atomically.\",\n CreditErrorCode.UNSUPPORTED_OPERATION,\n {\n userId: input.userId,\n paymentRef: input.paymentRef,\n operation: \"createTransaction\",\n reason: \"referenced_direct_transaction\",\n }\n );\n}\n\n/**\n * The conflict, as an error, for the legacy `addCreditsAtomic` signature.\n *\n * That method returns `void`, so it has nowhere to put a `conflict` outcome.\n * Swallowing one would be the original bug in a new place — the SQL adapter\n * used to no-op on a cross-user reference reuse, which reads to the caller as\n * \"credited\" — so the legacy path throws instead. Callers that want to *handle*\n * a conflict rather than catch it should use `addCreditsV2`.\n */\nexport function createPaymentRefConflictError(\n paymentRef: string,\n details: { userId: string; mismatch: string; existingUserId?: string }\n): CreditError {\n return new CreditError(\n `Payment reference ${paymentRef} has already been used for a different credit ` +\n `event (${details.mismatch} differs). Nothing was credited. A payment reference ` +\n \"identifies one credit event globally; reusing it for another user, amount or \" +\n \"source is refused rather than silently ignored.\",\n CreditErrorCode.IDEMPOTENCY_CONFLICT,\n { paymentRef, reason: \"payment_ref_conflict\", ...details }\n );\n}\n","/**\n * Validation for caller-supplied idempotency keys.\n *\n * The keys are enforced by a *partial* unique index (`WHERE idempotency_key IS\n * NOT NULL`), so \"no key\" and \"a key\" are genuinely different states and the\n * boundary between them has to be unambiguous. An empty string sat in between:\n * the SQL adapter stored it — occupying a row in the unique index — while every\n * `if (key)` check read it as absent, so the key was written but never\n * deduplicated anything, and the in-memory adapter ignored it outright. Two\n * adapters, two behaviours, neither of them the one the caller asked for.\n *\n * Rejecting is preferred over trimming. Normalising `\" job-1 \"` to `\"job-1\"`\n * would mean two callers who sent different strings silently share a hold, and\n * a caller whose key is accidentally whitespace would rather hear about it than\n * have it quietly repaired.\n */\n\nimport { CreditError, CreditErrorCode } from \"./errors.js\";\n\n/** A usable key: a string with at least one non-whitespace character. */\nexport function isValidIdempotencyKey(value: unknown): value is string {\n return typeof value === \"string\" && value.trim().length > 0;\n}\n\n/**\n * Reject an unusable idempotency key before anything is written.\n *\n * `undefined` is allowed and means \"no key\" — that is the legacy, at-least-once\n * behaviour, and it is a valid choice. Only a key that was *supplied* and\n * cannot work is an error.\n */\nexport function assertValidIdempotencyKey(\n value: unknown,\n context?: Record<string, unknown>\n): asserts value is string | undefined {\n if (value === undefined || value === null) return;\n if (isValidIdempotencyKey(value)) return;\n throw new CreditError(\n typeof value === \"string\"\n ? \"An idempotency key was supplied but is empty or whitespace-only. It \" +\n \"cannot deduplicate anything, so it was rejected rather than stored \" +\n \"as a key that never matches. Omit the key for at-least-once \" +\n \"behaviour, or send a meaningful one.\"\n : `Idempotency key must be a string (got ${typeof value})`,\n CreditErrorCode.INVALID_IDEMPOTENCY_KEY,\n { idempotencyKey: value, ...context }\n );\n}\n\n/**\n * Namespace the V2 reservation transitions own. Public writes may not use it.\n *\n * A transition that finds its deterministic key already present treats an\n * exactly-matching row as its own retry and reuses it. That is correct against\n * a row the transition itself wrote — and a hole if any caller can write one.\n * A caller who pre-seeds `reservation:<id>:commit` with a plausible-looking\n * entry would have the commit adopt it: the reservation flips to committed and\n * the balance moves, while the only journal row is the caller's, never written\n * by the transition and not necessarily describing what it did.\n *\n * Reserving the prefix removes the premise. Nothing outside the transitions can\n * create a key in it, so an existing key is either the transition's own retry\n * or corruption — and corruption is refused.\n */\nexport const RESERVED_JOURNAL_KEY_PREFIX = \"reservation:\";\n\n/** True when a key belongs to the namespace the V2 transitions own. */\nexport function isReservedJournalKey(key: unknown): boolean {\n return typeof key === \"string\" && key.startsWith(RESERVED_JOURNAL_KEY_PREFIX);\n}\n\n/**\n * Refuse a public journal write that claims a key in the reserved namespace.\n *\n * Called from the adapters' public `createJournalEntry`, never from the\n * transitions themselves — they are the ones the namespace belongs to.\n */\nexport function assertPublicJournalKey(key: unknown, userId: string): void {\n if (!isReservedJournalKey(key)) return;\n throw new CreditError(\n `Idempotency keys starting with \"${RESERVED_JOURNAL_KEY_PREFIX}\" are reserved for ` +\n 'the V2 reservation transitions and cannot be written directly. Use a key of ' +\n 'your own, or commit/release/expire the reservation through the V2 methods.',\n CreditErrorCode.INVALID_IDEMPOTENCY_KEY,\n { userId, idempotencyKey: key, reason: \"reserved_namespace\" }\n );\n}\n","/**\n * Driver-error classification.\n *\n * Consuming apps need to react differently to \"the user is out of credits\"\n * (show a paywall), \"the database blinked\" (retry), and \"our SQL is wrong\"\n * (page someone). Drivers signal that distinction through a SQLSTATE on the\n * thrown object, so this maps SQLSTATE classes onto {@link CreditErrorCode}\n * without taking a dependency on any particular driver.\n */\n\nimport {\n CreditError,\n CreditErrorCode,\n isCreditError,\n} from \"./errors.js\";\n\n/**\n * PostgreSQL SQLSTATEs whose failure is a property of the moment, not of the\n * statement — the identical call may well succeed on retry.\n *\n * - `40001` serialization_failure, `40P01` deadlock_detected, `40000` transaction_rollback\n * - `55P03` lock_not_available, `57014` query_canceled (statement timeout)\n * - `53300` too_many_connections, `53200` out_of_memory, `53400` configuration_limit_exceeded\n * - `08xxx` connection exception class\n */\nconst TRANSIENT_SQLSTATES = new Set([\n \"40000\",\n \"40001\",\n \"40P01\",\n \"55P03\",\n \"57014\",\n \"57P01\",\n \"57P02\",\n \"57P03\",\n \"53200\",\n \"53300\",\n \"53400\",\n]);\n\n/** Node driver-level codes that mean \"the socket/pool failed\", not \"the query is wrong\". */\nconst TRANSIENT_DRIVER_CODES = new Set([\n \"ECONNRESET\",\n \"ECONNREFUSED\",\n \"EPIPE\",\n \"ETIMEDOUT\",\n \"ENOTFOUND\",\n \"EHOSTUNREACH\",\n]);\n\n/**\n * `22003 numeric_value_out_of_range` — the arithmetic overflowed the column.\n *\n * Validating the operands cannot prevent this: `9999999999.99 + 0.01` is two\n * perfectly valid amounts whose *sum* the `numeric(12, 2)` column cannot hold.\n * It is a deterministic domain failure, not a broken query, so it is reported\n * as one instead of as a generic `DATABASE_ERROR`.\n */\nconst NUMERIC_OVERFLOW = \"22003\";\n\n/**\n * Read a SQLSTATE-ish `code` off an unknown thrown value.\n *\n * The chain matters. Wrapping drivers — and Drizzle itself, in places — rethrow\n * with the original error on `cause` and no `code` of their own, so looking only\n * at the outermost object reports \"no SQLSTATE\" for an error that plainly has\n * one. The walk is bounded and tracks what it has seen, since a `cause` graph\n * can be circular.\n */\nexport function getSqlState(error: unknown): string | undefined {\n const seen = new Set<unknown>();\n let current: unknown = error;\n for (let depth = 0; depth < 8; depth += 1) {\n if (typeof current !== \"object\" || current === null || seen.has(current)) return undefined;\n seen.add(current);\n const code = (current as { code?: unknown }).code;\n if (typeof code === \"string\") return code;\n current = (current as { cause?: unknown }).cause;\n }\n return undefined;\n}\n\n/**\n * True when the SQLSTATE is a unique-violation (`23505`).\n *\n * Callers that race on a partial unique index use this to tell \"someone else\n * inserted the same idempotency key\" from a genuine schema error.\n */\nexport function isUniqueViolation(error: unknown): boolean {\n return getSqlState(error) === \"23505\";\n}\n\n/** True when the error is worth retrying. */\nexport function isTransientDatabaseError(error: unknown): boolean {\n const code = getSqlState(error);\n if (!code) return false;\n if (TRANSIENT_SQLSTATES.has(code)) return true;\n if (TRANSIENT_DRIVER_CODES.has(code)) return true;\n // Whole connection-exception class (08000, 08003, 08006, 08001, 08004, 08007, 08P01).\n return code.startsWith(\"08\");\n}\n\n/**\n * Wrap an unknown thrown value in a classified {@link CreditError}.\n *\n * Already-classified `CreditError`s pass through untouched so a domain outcome\n * (insufficient credits, idempotency conflict) is never downgraded to\n * `DATABASE_ERROR` by a generic catch further up the stack.\n */\nexport function classifyDatabaseError(\n error: unknown,\n context?: Record<string, unknown>\n): CreditError {\n if (isCreditError(error)) return error;\n\n const sqlState = getSqlState(error);\n const message = error instanceof Error ? error.message : String(error);\n const details = { ...context, ...(sqlState ? { sqlState } : {}) };\n\n if (isTransientDatabaseError(error)) {\n return new CreditError(message, CreditErrorCode.TRANSIENT_ERROR, details);\n }\n\n if (sqlState === NUMERIC_OVERFLOW) {\n return new CreditError(message, CreditErrorCode.INVALID_AMOUNT, {\n ...details,\n reason: \"amount_out_of_range\",\n });\n }\n\n return new CreditError(message, CreditErrorCode.DATABASE_ERROR, details);\n}\n","/**\n * Deferred execution abstraction - framework agnostic\n *\n * Provides a way to schedule work to run after the current operation completes.\n * Different frameworks can provide their own implementations:\n * - Next.js: uses `after()` from `next/server`\n * - Generic: uses `setImmediate()` or `setTimeout()`\n * - Testing: can use synchronous execution\n */\n\n/**\n * Interface for deferred execution\n *\n * Implementations should schedule the function to run asynchronously\n * without blocking the current operation.\n */\nexport interface DeferredExecutor {\n /**\n * Schedule a function to run asynchronously\n *\n * The function should be executed after the current operation completes.\n * Errors should be caught and logged, not propagated.\n *\n * @param fn - Async function to execute\n */\n defer(fn: () => Promise<void>): void;\n}\n\n/**\n * Generic deferred executor using setImmediate/setTimeout\n *\n * Works in Node.js and browser environments.\n * Suitable for non-framework environments or testing.\n */\nexport const genericDeferred: DeferredExecutor = {\n defer(fn: () => Promise<void>): void {\n // Use setImmediate in Node.js, setTimeout as fallback\n const scheduler = typeof setImmediate !== \"undefined\" ? setImmediate : setTimeout;\n scheduler(() => {\n fn().catch((error) => {\n console.error(\"[Credits] Deferred task error:\", error);\n });\n });\n },\n};\n\n/**\n * Synchronous deferred executor\n *\n * Executes the function immediately (fire-and-forget).\n * Useful for testing or when deferred execution isn't needed.\n */\nexport const synchronousDeferred: DeferredExecutor = {\n defer(fn: () => Promise<void>): void {\n fn().catch((error) => {\n console.error(\"[Credits] Deferred task error:\", error);\n });\n },\n};\n\n/**\n * Create a custom deferred executor\n *\n * Allows frameworks to provide their own scheduling mechanism.\n *\n * @example\n * ```typescript\n * // Next.js adapter\n * import { after } from 'next/server';\n *\n * const nextJsDeferred = createDeferredExecutor((fn) => after(fn));\n * ```\n *\n * @param schedule - Function that schedules async work\n * @returns DeferredExecutor instance\n */\nexport function createDeferredExecutor(\n schedule: (fn: () => Promise<void>) => void\n): DeferredExecutor {\n return {\n defer: schedule,\n };\n}\n\n/**\n * No-op deferred executor\n *\n * Discards deferred work. Useful when you want to disable\n * background tasks (e.g., in certain test scenarios).\n */\nexport const noopDeferred: DeferredExecutor = {\n defer(_fn: () => Promise<void>): void {\n // Intentionally do nothing\n },\n};\n","import { z } from \"zod\";\nimport type { SubscriptionTier, TierConfig } from \"../core/types.js\";\nimport { getConfigProvider } from \"./provider.js\";\n\n/**\n * Schema for tier configuration\n */\nconst tierConfigSchema = z.object({\n tier: z.string().min(1),\n monthlyCredits: z.number().min(0),\n priceUsd: z.number().min(0),\n features: z.array(z.string()),\n isFree: z.boolean().optional(),\n unlimited: z.boolean().optional(),\n isDefault: z.boolean().optional(),\n});\n\n/**\n * Schema for credit system configuration\n */\nconst creditSystemConfigSchema = z.object({\n /**\n * Operation costs in credits\n * Keys are operation type names (any non-empty string)\n * Values are positive numbers representing credit cost\n */\n operationCosts: z.record(\n z.string().min(1),\n z.number().positive()\n ),\n\n /**\n * Display labels for operation types (English canonical labels).\n * Falls back to auto-generating from snake_case keys if not provided.\n */\n operationLabels: z.record(\n z.string().min(1),\n z.string().min(1)\n ).optional().default({}),\n\n /**\n * Tier configurations\n */\n tierConfigs: z.record(\n z.string().min(1),\n tierConfigSchema\n ),\n\n /**\n * Reservation expiry time in milliseconds\n */\n reservationExpiryMs: z.number().positive().default(5 * 60 * 1000),\n\n /**\n * Default credits for new users (free tier)\n */\n defaultFreeCredits: z.number().positive().default(25),\n\n /**\n * Grace period in days after subscription expires before downgrade\n */\n subscriptionGracePeriodDays: z.number().min(0).default(3),\n\n /**\n * Low balance notification threshold\n */\n lowBalanceThreshold: z.number().min(0).default(10),\n\n /**\n * Cooldown in hours between low balance notifications\n */\n lowBalanceNotificationCooldownHours: z.number().positive().default(24),\n\n /**\n * Feature flags for optional features\n */\n features: z.object({\n journalEntries: z.boolean().default(true),\n notifications: z.boolean().default(true),\n subscriptionExpiry: z.boolean().default(true),\n usageHistory: z.boolean().default(true),\n }).default({\n journalEntries: true,\n notifications: true,\n subscriptionExpiry: true,\n usageHistory: true,\n }),\n});\n\n/**\n * Credit system configuration type\n */\nexport type CreditSystemConfig = z.infer<typeof creditSystemConfigSchema>;\n\n/**\n * Default configuration\n */\nconst DEFAULT_CONFIG: CreditSystemConfig = {\n operationCosts: {\n story_generation: 5,\n conversation: 2,\n image_generation: 10,\n template_generation: 10,\n },\n operationLabels: {\n story_generation: \"Story generation\",\n conversation: \"Conversation\",\n image_generation: \"Image generation\",\n template_generation: \"Template generation\",\n },\n tierConfigs: {\n free: {\n tier: \"free\",\n monthlyCredits: 25,\n priceUsd: 0,\n isFree: true,\n isDefault: true,\n features: [\n \"25 credits per month\",\n \"Basic story generation\",\n \"Standard image quality\",\n ],\n },\n basic: {\n tier: \"basic\",\n monthlyCredits: 200,\n priceUsd: 9.99,\n features: [\n \"200 credits per month\",\n \"All story features\",\n \"High quality images\",\n \"Priority support\",\n ],\n },\n premium: {\n tier: \"premium\",\n monthlyCredits: 500,\n priceUsd: 19.99,\n features: [\n \"500 credits per month\",\n \"All features\",\n \"Highest quality images\",\n \"Early access to new features\",\n \"Priority support\",\n ],\n },\n unlimited: {\n tier: \"unlimited\",\n monthlyCredits: 0, // 0 = unlimited\n unlimited: true,\n priceUsd: 49.99,\n features: [\n \"Unlimited credits\",\n \"All features\",\n \"Highest quality images\",\n \"Early access to new features\",\n \"Dedicated support\",\n ],\n },\n },\n reservationExpiryMs: 5 * 60 * 1000, // 5 minutes\n defaultFreeCredits: 25,\n subscriptionGracePeriodDays: 3,\n lowBalanceThreshold: 10,\n lowBalanceNotificationCooldownHours: 24,\n features: {\n journalEntries: true,\n notifications: true,\n subscriptionExpiry: true,\n usageHistory: true,\n },\n};\n\n/**\n * Current configuration (can be overridden)\n */\nlet currentConfig: CreditSystemConfig = DEFAULT_CONFIG;\n\n/**\n * Load configuration from environment variables\n * Can be extended to load from other sources (file, remote config, etc.)\n *\n * Operation costs are loaded from CREDITS_OPERATION_COSTS as JSON:\n * CREDITS_OPERATION_COSTS={\"story_generation\":5,\"image_generation\":10}\n */\nexport function loadConfigFromEnv(): Partial<CreditSystemConfig> {\n const envConfig: Partial<CreditSystemConfig> = {};\n\n // Load operation costs from env as JSON\n const operationCostsEnv = process.env.CREDITS_OPERATION_COSTS;\n if (operationCostsEnv) {\n try {\n const parsed = JSON.parse(operationCostsEnv);\n if (typeof parsed === \"object\" && parsed !== null) {\n envConfig.operationCosts = {\n ...DEFAULT_CONFIG.operationCosts,\n ...parsed,\n };\n }\n } catch {\n console.warn(\"[Credits Config] Failed to parse CREDITS_OPERATION_COSTS env var as JSON\");\n }\n }\n\n // Load other settings from env\n const reservationExpiry = process.env.CREDITS_RESERVATION_EXPIRY_MS;\n if (reservationExpiry) {\n envConfig.reservationExpiryMs = parseInt(reservationExpiry, 10);\n }\n\n const defaultCredits = process.env.CREDITS_DEFAULT_FREE;\n if (defaultCredits) {\n envConfig.defaultFreeCredits = parseInt(defaultCredits, 10);\n }\n\n const gracePeriod = process.env.CREDITS_GRACE_PERIOD_DAYS;\n if (gracePeriod) {\n envConfig.subscriptionGracePeriodDays = parseInt(gracePeriod, 10);\n }\n\n const lowBalanceThreshold = process.env.CREDITS_LOW_BALANCE_THRESHOLD;\n if (lowBalanceThreshold) {\n envConfig.lowBalanceThreshold = parseInt(lowBalanceThreshold, 10);\n }\n\n // Load feature flags\n const featuresEnv = process.env.CREDITS_FEATURES;\n if (featuresEnv) {\n try {\n const features = JSON.parse(featuresEnv);\n envConfig.features = {\n ...DEFAULT_CONFIG.features,\n ...features,\n };\n } catch {\n console.warn(\"[Credits Config] Failed to parse CREDITS_FEATURES env var\");\n }\n }\n\n return envConfig;\n}\n\n/**\n * Initialize configuration\n * Merges default config with environment overrides\n */\nexport function initializeConfig(overrides?: Partial<CreditSystemConfig>): CreditSystemConfig {\n const envConfig = loadConfigFromEnv();\n\n const mergedConfig = {\n ...DEFAULT_CONFIG,\n ...envConfig,\n ...overrides,\n operationCosts: {\n ...DEFAULT_CONFIG.operationCosts,\n ...envConfig.operationCosts,\n ...overrides?.operationCosts,\n },\n operationLabels: {\n ...DEFAULT_CONFIG.operationLabels,\n ...envConfig.operationLabels,\n ...overrides?.operationLabels,\n },\n tierConfigs: {\n ...DEFAULT_CONFIG.tierConfigs,\n ...envConfig.tierConfigs,\n ...overrides?.tierConfigs,\n },\n features: {\n ...DEFAULT_CONFIG.features,\n ...envConfig.features,\n ...overrides?.features,\n },\n };\n\n // Validate configuration\n const result = creditSystemConfigSchema.safeParse(mergedConfig);\n if (!result.success) {\n console.error(\"[Credits Config] Invalid configuration:\", result.error.issues);\n throw new Error(\"Invalid credit system configuration\");\n }\n\n currentConfig = result.data;\n return currentConfig;\n}\n\n/**\n * Get the current configuration.\n * If an external provider is registered, delegates to it.\n * Otherwise falls back to the local currentConfig.\n */\nexport function getConfig(): CreditSystemConfig {\n const provider = getConfigProvider();\n if (provider) {\n return provider.getConfig();\n }\n return currentConfig;\n}\n\n/**\n * Get all valid operation types from configuration\n * Returns the keys of the operationCosts object\n */\nexport function getValidOperationTypes(): string[] {\n return Object.keys(getConfig().operationCosts);\n}\n\n/**\n * Check if an operation type is valid (configured in the system)\n * @param type - The operation type to check\n * @returns true if the operation type is configured\n */\nexport function isValidOperationType(type: string): boolean {\n return type in getConfig().operationCosts;\n}\n\n/**\n * Get operation cost from configuration\n * @throws Error if the operation type is not configured\n */\nexport function getConfigOperationCost(operationType: string): number {\n const cost = getConfig().operationCosts[operationType];\n if (cost === undefined) {\n throw new Error(\n `Unknown operation type: ${operationType}. Valid types: ${getValidOperationTypes().join(\", \")}`\n );\n }\n return cost;\n}\n\n/**\n * Get all valid tier ids from configuration\n * Returns the keys of the tierConfigs object\n */\nexport function getValidTiers(): string[] {\n return Object.keys(getConfig().tierConfigs);\n}\n\n/**\n * Check if a tier id is valid (configured in the system)\n */\nexport function isValidTier(tier: string): boolean {\n return tier in getConfig().tierConfigs;\n}\n\n/**\n * Check if a tier is the free/default tier.\n * Falls back to priceUsd === 0 when the isFree flag is not set.\n */\nexport function isFreeTier(tier: SubscriptionTier): boolean {\n const c = getConfig().tierConfigs[tier];\n if (!c) return false;\n return c.isFree ?? c.priceUsd === 0;\n}\n\n/**\n * Check if a tier is unlimited.\n * Falls back to monthlyCredits === 0 when the unlimited flag is not set.\n */\nexport function isUnlimitedTier(tier: SubscriptionTier): boolean {\n const c = getConfig().tierConfigs[tier];\n if (!c) return false;\n return c.unlimited ?? c.monthlyCredits === 0;\n}\n\n/**\n * Get the tier assigned to brand-new users.\n * Prefers the tier flagged isDefault, then the first isFree tier, then \"free\".\n */\nexport function getDefaultTier(): SubscriptionTier {\n const entries = Object.entries(getConfig().tierConfigs);\n const def =\n entries.find(([, c]) => c.isDefault)?.[0] ??\n entries.find(([, c]) => c.isFree ?? c.priceUsd === 0)?.[0];\n return def ?? \"free\";\n}\n\n/**\n * Magic balance assigned to unlimited tiers on upgrade.\n * Kept at 999999 for back-compat with stored/displayed balances.\n */\nexport const UNLIMITED_BALANCE_SENTINEL = 999999;\n\n/**\n * Get the magic balance assigned to unlimited tiers on upgrade.\n */\nexport function getUnlimitedSentinelBalance(): number {\n return UNLIMITED_BALANCE_SENTINEL;\n}\n\n/**\n * What a monthly reset must leave in `balance`, as a storable instruction.\n *\n * This is the one place the unlimited contract is defined, because it is the\n * one thing the two adapters kept disagreeing about. The canonical persisted\n * representation of an unlimited tier is:\n *\n * - `monthlyLimit` = `storedMonthlyLimit(Infinity)`, i.e. the top of the\n * representable range. Never `0`, which reads as *no* allowance.\n * - `balance` = at least {@link UNLIMITED_BALANCE_SENTINEL}, which is what\n * `updateTier` writes on upgrade.\n *\n * The reset used to leave an unlimited balance strictly alone (\"`Infinity` is\n * not storable, so change nothing\"), which is correct for a healthy account and\n * a trap for a degraded one: an unlimited user whose balance had been driven to\n * `0` — by a spend, or by the older code that stored `0` as the limit — stayed\n * at `0` through every subsequent reset and could never buy anything again. So\n * the instruction is `atLeast`, not \"leave alone\": it restores a degraded\n * balance to the sentinel and leaves a topped-up one (a purchase on top of an\n * unlimited plan) untouched. It is expressed as a floor rather than as a number\n * so the SQL adapter can apply it as `greatest(balance, n)` inside its guarded\n * UPDATE instead of writing a literal read before the lock.\n */\nexport type MonthlyResetBalance =\n /** Store exactly this value. */\n | { kind: \"absolute\"; value: number }\n /** Raise the stored balance to this value; leave anything higher alone. */\n | { kind: \"atLeast\"; value: number };\n\nexport function monthlyResetBalance(tier: SubscriptionTier): MonthlyResetBalance {\n if (isUnlimitedTier(tier)) {\n return { kind: \"atLeast\", value: UNLIMITED_BALANCE_SENTINEL };\n }\n return { kind: \"absolute\", value: getConfigMonthlyLimit(tier) };\n}\n\n/**\n * Get tier configuration from configuration.\n * Falls back to the default tier (with a warning) if the tier is unknown.\n */\nexport function getConfigTierConfig(tier: SubscriptionTier): TierConfig {\n const cfg = getConfig().tierConfigs[tier];\n if (cfg) return cfg;\n const fallback = getDefaultTier();\n console.warn(\n `[Credits Config] Unknown tier \"${tier}\". Falling back to \"${fallback}\". Valid: ${getValidTiers().join(\", \")}`\n );\n return getConfig().tierConfigs[fallback]!;\n}\n\n/**\n * Get monthly limit for a tier from configuration\n * Returns Infinity for unlimited tier\n */\nexport function getConfigMonthlyLimit(tier: SubscriptionTier): number {\n return isUnlimitedTier(tier) ? Infinity : getConfigTierConfig(tier).monthlyCredits;\n}\n\n/**\n * Runtime zod validator for tier ids. Validates against the LIVE config keys\n * at parse time, so apps that add tiers via config get correct validation.\n */\nexport const tierSchema = z\n .string()\n .refine(isValidTier, { message: \"Unknown subscription tier\" }) as unknown as z.ZodType<SubscriptionTier>;\n\n/**\n * Parse/validate a tier id against the live config keys.\n * @throws ZodError if the tier is not configured\n */\nexport function parseTier(value: unknown): SubscriptionTier {\n return tierSchema.parse(value);\n}\n\n/**\n * Check if a feature is enabled\n */\nexport function isFeatureEnabled(feature: keyof CreditSystemConfig[\"features\"]): boolean {\n return getConfig().features[feature];\n}\n\n/**\n * Convert a snake_case string to Title Case.\n * E.g., \"story_generation\" -> \"Story Generation\"\n */\nfunction snakeCaseToTitleCase(str: string): string {\n return str\n .replace(/_/g, \" \")\n .replace(/\\b\\w/g, (c) => c.toUpperCase());\n}\n\n/**\n * Get the display label for an operation type.\n * Falls back to converting snake_case to Title Case if no label is configured.\n */\nexport function getOperationLabel(operationType: string): string {\n const labels = getConfig().operationLabels;\n if (labels && operationType in labels) {\n return labels[operationType];\n }\n return snakeCaseToTitleCase(operationType);\n}\n\n/**\n * Get all operation labels as a record.\n * For any operation in operationCosts that lacks a label, generates one from the key.\n */\nexport function getOperationLabels(): Record<string, string> {\n const config = getConfig();\n const result: Record<string, string> = {};\n for (const key of Object.keys(config.operationCosts)) {\n result[key] = config.operationLabels?.[key]\n ?? snakeCaseToTitleCase(key);\n }\n return result;\n}\n\n/**\n * Reset configuration to defaults (for testing)\n */\nexport function resetConfig(): void {\n currentConfig = DEFAULT_CONFIG;\n}\n\n// Initialize configuration on module load\ninitializeConfig();\n","import type { CreditSystemConfig } from \"./index.js\";\n\n/** Interface for external config providers (e.g. Firestore-backed) */\nexport interface ICreditConfigProvider {\n getConfig(): CreditSystemConfig;\n}\n\nlet configProvider: ICreditConfigProvider | null = null;\n\n/** Register an external config provider. Called once at app startup. */\nexport function registerConfigProvider(provider: ICreditConfigProvider): void {\n configProvider = provider;\n}\n\n/** Get the registered provider, or null if none registered. */\nexport function getConfigProvider(): ICreditConfigProvider | null {\n return configProvider;\n}\n\n/** Clear registered provider (for testing). */\nexport function clearConfigProvider(): void {\n configProvider = null;\n}\n","import type {\n ICreditRepositoryCreditsV2,\n ICreditRepositoryV2,\n} from \"./v2-types.js\";\nimport type {\n PortableUserCredits,\n PortableReservation,\n PortableTransaction,\n PortableUsageLog,\n PortableJournalEntry,\n CreditOperationType,\n SubscriptionTier,\n ReservationStatus,\n AIProviderType,\n MonthlyResetResult,\n SubscriptionExpiryResult,\n CreditSource,\n JournalReferenceType,\n} from \"../core/types.js\";\n\n/**\n * Input for creating a credit reservation\n */\nexport interface CreateReservationInput {\n userId: string;\n amount: number;\n operationType: CreditOperationType;\n expiresAt: Date;\n /**\n * @deprecated Rejected — this writer does not place the hold.\n *\n * `createReservation` inserts a row and leaves `reserved` alone, so a keyed\n * row written here names a hold that does not exist, and `reserveCreditsV2`\n * would adopt it as a `replayed` reservation whose commit then spends another\n * hold's coverage. Both adapters throw `UNSUPPORTED_OPERATION` when this is\n * set. Pass the key to `reserveCredits` / `reserveCreditsV2` instead, which\n * claims the key and places the hold in one transaction.\n *\n * The field is kept rather than deleted so the refusal reaches a JavaScript\n * caller as a typed error instead of a silently ignored property.\n */\n idempotencyKey?: string;\n}\n\n/**\n * Input for creating a credit transaction\n */\nexport interface CreateTransactionInput {\n userId: string;\n type: PortableTransaction[\"type\"];\n amount: number;\n description: string;\n paymentRef?: string;\n previousBalance: number;\n newBalance: number;\n}\n\n/**\n * Input for logging usage\n */\nexport interface CreateUsageLogInput {\n userId: string;\n operationType: CreditOperationType;\n provider: AIProviderType;\n creditsUsed: number;\n success: boolean;\n errorMessage?: string;\n resourceId?: string;\n resourceType?: string;\n requestId?: string;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Query options for usage logs\n */\nexport interface UsageLogQuery {\n userId?: string;\n operationType?: CreditOperationType;\n success?: boolean;\n limit?: number;\n offset?: number;\n startDate?: Date;\n endDate?: Date;\n}\n\n/**\n * Input for creating a journal entry\n */\nexport interface CreateJournalEntryInput {\n userId: string;\n entryType: \"debit\" | \"credit\";\n amount: number;\n balanceAfter: number;\n source: CreditSource;\n referenceId: string;\n referenceType: JournalReferenceType;\n description: string;\n metadata?: Record<string, unknown>;\n /** Deterministic key making this entry unique per user (V2, optional). */\n idempotencyKey?: string;\n}\n\n/**\n * Query options for journal entries\n */\nexport interface JournalEntryQuery {\n userId: string;\n source?: CreditSource;\n referenceType?: JournalReferenceType;\n limit?: number;\n offset?: number;\n startDate?: Date;\n endDate?: Date;\n}\n\n/**\n * Partial update for user credits balance\n */\nexport interface CreditBalanceUpdate {\n balance?: number;\n bonusCredits?: number;\n reserved?: number;\n tier?: SubscriptionTier;\n monthlyLimit?: number;\n monthlyUsed?: number;\n monthlyResetAt?: Date | string;\n subscriptionExpiresAt?: Date | string | null;\n /** Increment balance by this amount (alternative to absolute value) */\n balanceIncrement?: number;\n /** Increment bonusCredits by this amount (alternative to absolute value) */\n bonusCreditsIncrement?: number;\n /** Increment reserved by this amount (alternative to absolute value) */\n reservedIncrement?: number;\n /** Increment monthlyUsed by this amount */\n monthlyUsedIncrement?: number;\n}\n\n/**\n * Input for tier update\n */\nexport interface TierUpdateInput {\n tier: SubscriptionTier;\n monthlyLimit: number;\n balance?: number;\n monthlyUsed?: number;\n subscriptionExpiresAt?: Date | string | null;\n}\n\n/**\n * Optional journal customization for `addCreditsAtomic`.\n *\n * By default a credit add records a journal entry with `source: \"purchase\"`,\n * `referenceType: \"transaction\"`, and `{ paymentRef }` metadata. These options\n * let callers override that — e.g. tag a signup grant as `source: \"bonus\"`, or\n * carry revenue-attribution fields (gross amount, credits granted) so a single\n * journal can serve as the app's revenue ledger.\n */\nexport interface AddCreditsAtomicOptions {\n /** Journal entry source (defaults to `\"purchase\"`). */\n source?: CreditSource;\n /** Journal reference type (defaults to `\"transaction\"`). */\n referenceType?: JournalReferenceType;\n /**\n * Extra metadata merged onto the journal entry. When `paymentRef` is present\n * it is merged in too (explicit keys here win on collision).\n */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Repository interface for credits database operations\n *\n * Implementations can use any database (Firestore, PostgreSQL, etc.)\n * All methods should handle their own error handling and transactions\n */\nexport interface ICreditRepository\n extends Partial<ICreditRepositoryV2>,\n Partial<ICreditRepositoryCreditsV2> {\n // ==================== User Credits ====================\n\n /**\n * Get user credits balance\n * @param userId - User ID\n * @returns User credits or null if not found\n */\n getUserCredits(userId: string): Promise<PortableUserCredits | null>;\n\n /**\n * Initialize credits for a new user\n * @param userId - User ID\n * @param tier - Initial subscription tier\n * @param initialBalance - Initial credit balance\n * @returns Initialized user credits\n */\n initializeUserCredits(\n userId: string,\n tier: SubscriptionTier,\n initialBalance: number\n ): Promise<PortableUserCredits>;\n\n /**\n * Update user credits balance\n * @param userId - User ID\n * @param updates - Partial updates to apply\n */\n updateUserCredits(userId: string, updates: CreditBalanceUpdate): Promise<void>;\n\n /**\n * Update user subscription tier\n * @param userId - User ID\n * @param input - Tier update data\n */\n updateUserTier(userId: string, input: TierUpdateInput): Promise<void>;\n\n // ==================== Reservations ====================\n\n /**\n * Create a reservation *record* — not a hold.\n *\n * Writes a row and leaves `reserved` untouched, so the row is not backed by\n * credits and no settlement path will move money for it: the commit /\n * release / expire transitions (legacy and V2 alike) refuse it with\n * `UNBACKED_RESERVATION`, and it refuses an `idempotencyKey` so it can never\n * be adopted as a V2 replay. Use it for imported or annotation-only records.\n *\n * To place a hold that can actually be committed, call `reserveCreditsAtomic`\n * or `reserveCreditsV2` — they raise `reserved` and write the row in one\n * atomic step.\n *\n * @param input - Reservation data\n * @returns Created reservation record\n */\n createReservation(input: CreateReservationInput): Promise<PortableReservation>;\n\n /**\n * Get a reservation by ID\n * @param userId - User ID\n * @param reservationId - Reservation ID\n * @returns Reservation or null\n */\n getReservation(userId: string, reservationId: string): Promise<PortableReservation | null>;\n\n /**\n * Annotate a reservation *record* with a status.\n *\n * Assigns a status and nothing else — no balance movement, no `reserved`\n * adjustment, no journal entry. It therefore refuses two writes that would\n * make the status lie about the ledger: any write to a row whose hold was\n * atomically placed (those statuses belong to commit/release/expire), and\n * any write back to `reserved` (nothing here re-places a hold). Rows written\n * by `createReservation` accept terminal statuses freely.\n *\n * @param userId - User ID\n * @param reservationId - Reservation ID\n * @param status - New status\n * @param completedAt - Completion timestamp\n */\n updateReservationStatus(\n userId: string,\n reservationId: string,\n status: ReservationStatus,\n completedAt?: Date\n ): Promise<void>;\n\n // ==================== Atomic Operations ====================\n\n /**\n * Reserve credits atomically (creates reservation + updates balance in transaction)\n * @param userId - User ID\n * @param amount - Credits to reserve\n * @param operationType - Operation type for tracking\n * @param expiresAt - Reservation expiry time\n * @returns Created reservation\n * @throws Error if insufficient credits\n */\n reserveCreditsAtomic(\n userId: string,\n amount: number,\n operationType: CreditOperationType,\n expiresAt: Date\n ): Promise<PortableReservation>;\n\n /**\n * Commit a reservation atomically (deducts credits + marks reservation committed)\n * @param userId - User ID\n * @param reservationId - Reservation ID\n * @throws Error if reservation not found or not in reserved state\n */\n commitReservationAtomic(userId: string, reservationId: string): Promise<void>;\n\n /**\n * Release a reservation atomically (releases reserved credits + marks reservation released)\n * @param userId - User ID\n * @param reservationId - Reservation ID\n */\n releaseReservationAtomic(userId: string, reservationId: string): Promise<void>;\n\n /**\n * Add credits atomically (creates transaction + updates balance)\n * @param userId - User ID\n * @param amount - Credits to add\n * @param description - Transaction description\n * @param paymentRef - Optional payment reference\n * @param options - Optional journal source / reference type / extra metadata\n * for the credit journal entry (e.g. revenue attribution fields). Lets\n * callers record a purchase's gross amount, a bonus/refund source, etc.,\n * instead of the default `source: \"purchase\"` + `{ paymentRef }` metadata.\n */\n addCreditsAtomic(\n userId: string,\n amount: number,\n description: string,\n paymentRef?: string,\n options?: AddCreditsAtomicOptions\n ): Promise<void>;\n\n /**\n * Deduct credits from a user's balance atomically.\n *\n * Splits the deduction across `balance` and `bonusCredits`, draining\n * `balance` (monthly, resets each cycle) first so persistent bonus\n * credits survive longer. Runs in a single atomic transaction so\n * concurrent deducts cannot drive either field negative.\n *\n * Callers are responsible for writing any audit record (journal /\n * transaction) — this method only moves credits.\n *\n * @param userId - User ID\n * @param amount - Credits to deduct (positive)\n * @returns Combined totals (balance + bonusCredits) before and after.\n * @throws If user has no credits doc or insufficient credits\n */\n deductCreditsAtomic(\n userId: string,\n amount: number\n ): Promise<{ previousBalance: number; newBalance: number }>;\n\n // ==================== Transactions ====================\n\n /**\n * Create a credit transaction *record* — no balance moves.\n *\n * Refuses a `paymentRef`: the reference is the global identity of a credit\n * event, and a record that carried one without crediting anyone would make a\n * later `addCredits` with the same reference report `replayed` and credit\n * nothing. Deliver referenced payments through `addCreditsAtomic` /\n * `addCreditsV2`, which claim the reference and move the balance atomically.\n *\n * @param input - Transaction data\n * @returns Created transaction\n */\n createTransaction(input: CreateTransactionInput): Promise<PortableTransaction>;\n\n /**\n * Get user's transaction history\n * @param userId - User ID\n * @param limit - Max results\n * @param offset - Skip results\n * @returns List of transactions\n */\n getTransactions(\n userId: string,\n limit?: number,\n offset?: number\n ): Promise<PortableTransaction[]>;\n\n // ==================== Usage Logs ====================\n\n /**\n * Log a usage event\n * @param input - Usage log data\n * @returns Created usage log\n */\n logUsage(input: CreateUsageLogInput): Promise<PortableUsageLog>;\n\n /**\n * Query usage logs\n * @param query - Query parameters\n * @returns List of usage logs\n */\n getUsageLogs(query: UsageLogQuery): Promise<PortableUsageLog[]>;\n\n /**\n * Get usage log count (for pagination)\n * @param query - Query parameters (without limit/offset)\n * @returns Count of matching logs\n */\n getUsageLogsCount(query: Omit<UsageLogQuery, \"limit\" | \"offset\">): Promise<number>;\n\n // ==================== Cleanup Operations ====================\n\n /**\n * Find and expire reservations past their expiration time\n * Used by cron job to clean up stale reservations\n * @param batchSize - Maximum number of reservations to process per batch (default: 100)\n * @param maxIterations - Maximum number of pagination iterations to prevent infinite loops (default: 100)\n * @returns Cleanup results with counts and errors\n */\n findAndExpireReservations(batchSize?: number, maxIterations?: number): Promise<{\n expiredCount: number;\n creditsReleased: number;\n errors: string[];\n }>;\n\n // ==================== Atomic Monthly Reset ====================\n\n /**\n * Atomically perform monthly reset if needed\n * Uses optimistic locking to prevent race conditions\n *\n * @param userId - User ID\n * @param tier - User's current subscription tier (for determining new balance)\n * @param expectedResetAt - The expected monthlyResetAt value (for optimistic locking)\n * @returns Result indicating whether reset was performed and updated credits\n */\n atomicMonthlyReset(\n userId: string,\n tier: SubscriptionTier,\n expectedResetAt: Date | string\n ): Promise<MonthlyResetResult>;\n\n // ==================== Subscription Expiry ====================\n\n /**\n * Check and handle subscription expiry with grace period\n * Auto-downgrades expired subscriptions after grace period\n *\n * @param userId - User ID\n * @param gracePeriodDays - Days to allow after expiry before downgrade (default: 3)\n * @returns Result indicating whether downgrade occurred\n */\n checkAndHandleSubscriptionExpiry(\n userId: string,\n gracePeriodDays?: number\n ): Promise<SubscriptionExpiryResult>;\n\n // ==================== Journal Entries ====================\n\n /**\n * Create a journal entry for audit trail\n * @param input - Journal entry data\n * @returns Created journal entry\n */\n createJournalEntry(input: CreateJournalEntryInput): Promise<PortableJournalEntry>;\n\n /**\n * Get journal entries for a user\n * @param query - Query parameters\n * @returns List of journal entries\n */\n getJournalEntries(query: JournalEntryQuery): Promise<PortableJournalEntry[]>;\n\n /**\n * Get journal entry count for pagination\n * @param query - Query parameters (without limit/offset)\n * @returns Count of matching entries\n */\n getJournalEntriesCount(query: Omit<JournalEntryQuery, \"limit\" | \"offset\">): Promise<number>;\n}\n\n/**\n * Factory type for creating repository instances\n */\nexport type CreditRepositoryFactory = () => ICreditRepository;\n\n/**\n * Narrow a repository to one that implements the full V2 boundary.\n *\n * V2 methods are optional on {@link ICreditRepository}, so callers that need\n * the idempotent/race-safe path must probe rather than assume. A repository\n * only counts as V2 when it implements *all four* transitions — a partial\n * implementation would leave one path silently unsafe.\n */\nexport function supportsCreditsV2(\n repository: ICreditRepository\n): repository is ICreditRepository & ICreditRepositoryV2 {\n return (\n typeof repository.reserveCreditsV2 === \"function\" &&\n typeof repository.commitReservationV2 === \"function\" &&\n typeof repository.releaseReservationV2 === \"function\" &&\n typeof repository.expireReservationV2 === \"function\"\n );\n}\n\n/**\n * Narrow a repository to one that credits idempotently against a `paymentRef`.\n *\n * Deliberately a separate probe from {@link supportsCreditsV2}: serialising\n * reservations and enforcing a global payment reference are different\n * guarantees resting on different database objects, and an adapter may have one\n * without the other.\n */\nexport function supportsIdempotentCredit(\n repository: ICreditRepository\n): repository is ICreditRepository & ICreditRepositoryCreditsV2 {\n return typeof repository.addCreditsV2 === \"function\";\n}\n\n/**\n * Convert PortableUserCredits to client-safe format\n * Utility function that implementations can use\n */\nexport function toClientUserCredits(credits: PortableUserCredits): PortableUserCredits {\n // Already in portable format, just ensure all timestamps are ISO strings\n return {\n userId: credits.userId,\n balance: credits.balance,\n bonusCredits: credits.bonusCredits ?? 0,\n reserved: credits.reserved,\n tier: credits.tier,\n monthlyLimit: credits.monthlyLimit,\n monthlyUsed: credits.monthlyUsed,\n monthlyResetAt: toISOString(credits.monthlyResetAt),\n subscriptionExpiresAt: credits.subscriptionExpiresAt\n ? toISOString(credits.subscriptionExpiresAt)\n : null,\n createdAt: toISOString(credits.createdAt),\n updatedAt: toISOString(credits.updatedAt),\n };\n}\n\n/**\n * Convert any timestamp-like value to ISO string\n */\nfunction toISOString(value: unknown): string {\n if (!value) return new Date().toISOString();\n if (typeof value === \"string\") return value;\n if (value instanceof Date) return value.toISOString();\n // Handle Firestore Timestamp-like objects\n if (typeof value === \"object\" && \"toDate\" in value && typeof (value as { toDate: () => Date }).toDate === \"function\") {\n return (value as { toDate: () => Date }).toDate().toISOString();\n }\n return new Date().toISOString();\n}\n","/**\n * One reservation flow for both repository generations.\n *\n * Adapters that implement the V2 boundary get the idempotent, race-safe path\n * and own their journal entry. Adapters that do not (Firestore, custom\n * implementations) keep the legacy read-then-write path, with the service\n * writing the journal exactly as it always did — so upgrading this package\n * does not change their behaviour, and does not double-write anyone's ledger.\n */\n\nimport { getOperationLabel } from \"../config/index.js\";\nimport { assertValidCreditAmount, sumAmounts } from \"../core/amount.js\";\nimport {\n createUnsupportedOperationError,\n isInsufficientCreditsError,\n} from \"../core/errors.js\";\nimport type {\n AddCreditsOutcome,\n CommitOutcome,\n ReleaseOutcome,\n ReserveOutcome,\n} from \"../core/outcomes.js\";\nimport { normalizePaymentRef } from \"../core/payment-ref.js\";\nimport type { ICreditRepository } from \"./types.js\";\nimport { supportsCreditsV2, supportsIdempotentCredit } from \"./types.js\";\nimport type {\n AddCreditsV2Input,\n ReservationTransitionOptions,\n ReserveCreditsV2Input,\n} from \"./v2-types.js\";\n\n/**\n * Reserve credits through V2 when available.\n *\n * A legacy adapter cannot honour an idempotency key — it has no unique index\n * to enforce it — so asking for one there is a caller error rather than a\n * silently ignored option.\n */\nexport async function reserveThroughRepository(\n repository: ICreditRepository,\n input: ReserveCreditsV2Input\n): Promise<ReserveOutcome> {\n const v2 = supportsCreditsV2(repository);\n\n // The capability check comes first, so a caller who asked for a guarantee\n // this repository cannot give always hears *that*, rather than whichever\n // other complaint the arguments happen to trigger. A legacy adapter has no\n // unique index to enforce the key, so it cannot deduplicate a replay, and\n // reporting `created` for the second delivery would be a lie that costs the\n // user real credits.\n if (!v2 && input.idempotencyKey !== undefined) {\n throw createUnsupportedOperationError(\n \"reserveCredits with an idempotencyKey\",\n \"This repository does not implement the V2 boundary, so it cannot \" +\n \"enforce idempotency keys. Use a V2 repository (check with \" +\n \"supportsCreditsV2) or omit the key and accept at-least-once holds.\"\n );\n }\n\n assertValidCreditAmount(input.amount, { userId: input.userId });\n\n if (v2) {\n return repository.reserveCreditsV2(input);\n }\n\n try {\n const reservation = await repository.reserveCreditsAtomic(\n input.userId,\n input.amount,\n input.operationType,\n input.expiresAt\n );\n return { outcome: \"created\", reservation };\n } catch (error) {\n // Only a genuine funds shortfall becomes the `insufficient` outcome. The\n // previous version asked the repository for the balance and called any\n // failure `insufficient` whenever that balance happened to be low — which\n // silently rebranded connection drops and driver faults as \"the user is\n // out of credits\", and hid real outages behind an upsell.\n if (!isInsufficientCreditsError(error)) throw error;\n\n const credits = await repository.getUserCredits(input.userId);\n const available = credits\n ? sumAmounts(credits.balance, credits.bonusCredits, -credits.reserved)\n : 0;\n return {\n outcome: \"insufficient\",\n available,\n required: input.amount,\n shortfall: Math.max(sumAmounts(input.amount, -available), 0),\n };\n }\n}\n\n/**\n * Commit through V2 when available, else the legacy read-then-write path.\n *\n * **The legacy path cannot promise a single winner.** It reads the status and\n * then writes, with no lock and no compare-and-set between the two, so two\n * concurrent commits of the same reservation can both observe `reserved` and\n * both proceed. The typed outcome still describes what *this* call saw, but on\n * a legacy adapter `committed` means \"this call did the work\", not \"this call\n * was the only one that did\". Callers needing exactly-once must use a\n * repository for which `supportsCreditsV2` returns `true`.\n */\nexport async function commitThroughRepository(\n repository: ICreditRepository,\n userId: string,\n reservationId: string,\n options?: ReservationTransitionOptions\n): Promise<CommitOutcome> {\n if (supportsCreditsV2(repository)) {\n return repository.commitReservationV2(userId, reservationId, options);\n }\n\n const reservation = await repository.getReservation(userId, reservationId);\n if (!reservation) return { outcome: \"not_found\", reservationId };\n if (reservation.status !== \"reserved\") {\n return {\n outcome: \"already_terminal\",\n reservation,\n terminalStatus: reservation.status,\n };\n }\n\n await repository.commitReservationAtomic(userId, reservationId);\n\n const credits = await repository.getUserCredits(userId);\n // The ledger balance, not the `balance` column alone: every other journal\n // writer — the V2 transitions, add and deduct — records\n // `balance + bonusCredits`, and recording less here made the same account's\n // audit trail disagree with itself whenever it held bonus credits.\n const balanceAfter = credits ? sumAmounts(credits.balance, credits.bonusCredits) : 0;\n const entry = await repository.createJournalEntry({\n userId,\n entryType: \"debit\",\n amount: reservation.amount,\n balanceAfter,\n source: \"operation_commit\",\n referenceId: reservationId,\n referenceType: \"reservation\",\n description:\n options?.description ??\n `Committed ${reservation.amount} credits for ${getOperationLabel(reservation.operationType)}`,\n // Deterministic fields last: they carry the identity of the event, and a\n // caller who happens to send an `operationType` or an `amount` must not\n // relabel what actually moved.\n metadata: {\n ...options?.metadata,\n operationType: reservation.operationType,\n amount: reservation.amount,\n },\n });\n\n return {\n outcome: \"committed\",\n reservation: { ...reservation, status: \"committed\" },\n amount: reservation.amount,\n balanceAfter,\n journalEntryId: entry.id,\n };\n}\n\n/**\n * Release through V2 when available, else the legacy read-then-write path.\n *\n * Same caveat as {@link commitThroughRepository}: on a legacy adapter the\n * read-then-write sequence is unguarded, so `released` does not exclude a\n * concurrent commit having also run. Only V2 repositories serialise the two.\n */\nexport async function releaseThroughRepository(\n repository: ICreditRepository,\n userId: string,\n reservationId: string,\n options?: ReservationTransitionOptions\n): Promise<ReleaseOutcome> {\n if (supportsCreditsV2(repository)) {\n return repository.releaseReservationV2(userId, reservationId, options);\n }\n\n const reservation = await repository.getReservation(userId, reservationId);\n if (!reservation) {\n // Legacy adapters vary on whether releasing an unknown reservation throws;\n // ask them anyway so that behaviour is preserved, then report not_found.\n await repository.releaseReservationAtomic(userId, reservationId);\n return { outcome: \"not_found\", reservationId };\n }\n if (reservation.status !== \"reserved\") {\n // The hold is already resolved, so there is nothing to hand back. Legacy\n // adapters disagree about whether releasing a processed reservation is an\n // error, and `releaseCredits` is specified to be a silent no-op here — so\n // the call is still made for adapters that use it to reconcile, and a\n // refusal is swallowed rather than propagated. The conflict is not hidden:\n // it is what `already_terminal` reports, and `releaseCreditsDetailed`\n // surfaces it to callers that ask.\n await repository.releaseReservationAtomic(userId, reservationId).catch(() => undefined);\n return {\n outcome: \"already_terminal\",\n reservation,\n terminalStatus: reservation.status,\n };\n }\n\n await repository.releaseReservationAtomic(userId, reservationId);\n\n const credits = await repository.getUserCredits(userId);\n const entry = await repository.createJournalEntry({\n userId,\n entryType: \"credit\",\n // No credits changed hands — the hold just moved back into \"available\".\n amount: 0,\n balanceAfter: credits ? sumAmounts(credits.balance, credits.bonusCredits) : 0,\n source: \"operation_release\",\n referenceId: reservationId,\n referenceType: \"reservation\",\n description:\n options?.description ??\n `Released ${reservation.amount} reserved credits for ${getOperationLabel(reservation.operationType)}`,\n metadata: {\n ...options?.metadata,\n operationType: reservation.operationType,\n amount: reservation.amount,\n },\n });\n\n return {\n outcome: \"released\",\n reservation: { ...reservation, status: \"released\" },\n amount: reservation.amount,\n journalEntryId: entry.id,\n };\n}\n\n/**\n * Credit an account through the idempotent path when the adapter has one.\n *\n * A legacy adapter cannot resolve `created` / `replayed` / `conflict`: it has\n * no global unique index over `payment_ref`, so it cannot tell a re-delivered\n * webhook from a second, genuinely different payment that reuses a reference.\n * Rather than invent an outcome, this reports `created` — which is what the\n * legacy method actually did — and the ambiguity is documented on the return\n * type instead of hidden inside it.\n *\n * The reference is normalised here as well as in the adapters, so a legacy\n * adapter that stores the raw string does not persist a whitespace-only\n * reference that would then deduplicate nothing.\n */\nexport async function addCreditsThroughRepository(\n repository: ICreditRepository,\n input: AddCreditsV2Input\n): Promise<AddCreditsOutcome> {\n assertValidCreditAmount(input.amount, { userId: input.userId, operation: \"addCredits\" });\n const paymentRef = normalizePaymentRef(input.paymentRef);\n\n if (supportsIdempotentCredit(repository)) {\n return repository.addCreditsV2({ ...input, paymentRef });\n }\n\n await repository.addCreditsAtomic(\n input.userId,\n input.amount,\n input.description,\n paymentRef,\n input.options\n );\n\n // The legacy method returns nothing, so there is no transaction to hand back\n // and no way to know whether it deduplicated. Report the one thing that is\n // true — a call was made and did not throw — rather than fabricate a record.\n return paymentRef ? { outcome: \"created\", paymentRef } : { outcome: \"created\" };\n}\n","/**\n * Core credit operations - framework agnostic\n *\n * Contains the business logic for credit operations that can be\n * used by any adapter or service implementation.\n */\n\nimport type { ICreditRepository } from \"../repository/types.js\";\nimport type { PortableReservation } from \"./types.js\";\nimport {\n commitThroughRepository,\n releaseThroughRepository,\n reserveThroughRepository,\n} from \"../repository/flow.js\";\nimport {\n createReservationAlreadyProcessedError,\n createReservationNotFoundError,\n createInsufficientCreditsError,\n} from \"./errors.js\";\n\n/**\n * Commit a reservation with journal entry\n *\n * On a V2 repository the balance move and the journal entry happen in one\n * transaction and this function adds nothing of its own — the duplicate entry\n * the previous implementation wrote is gone. Legacy adapters keep the old\n * read-then-write path, journal included.\n *\n * @param repository - The credit repository\n * @param userId - User ID\n * @param reservationId - Reservation to commit\n */\nexport async function commitReservationWithJournal(\n repository: ICreditRepository,\n userId: string,\n reservationId: string\n): Promise<void> {\n const outcome = await commitThroughRepository(repository, userId, reservationId);\n if (outcome.outcome === \"not_found\") {\n throw createReservationNotFoundError(reservationId);\n }\n if (outcome.outcome === \"already_terminal\" && outcome.terminalStatus !== \"committed\") {\n throw createReservationAlreadyProcessedError(reservationId, outcome.terminalStatus);\n }\n}\n\n/**\n * Release a reservation with journal entry\n *\n * @param repository - The credit repository\n * @param userId - User ID\n * @param reservationId - Reservation to release\n */\nexport async function releaseReservationWithJournal(\n repository: ICreditRepository,\n userId: string,\n reservationId: string\n): Promise<void> {\n await releaseThroughRepository(repository, userId, reservationId);\n}\n\n/**\n * Reserve credits for an operation\n *\n * @param repository - The credit repository\n * @param userId - User ID\n * @param amount - Credits to reserve\n * @param operationType - Type of operation\n * @param expiryMs - Reservation expiry time in milliseconds\n * @param idempotencyKey - Optional caller key; a replay with the same\n * amount/operation returns the original reservation instead of a second hold\n * @returns The reservation\n */\nexport async function reserveCreditsForOperation(\n repository: ICreditRepository,\n userId: string,\n amount: number,\n operationType: string,\n expiryMs: number = 5 * 60 * 1000,\n idempotencyKey?: string\n): Promise<PortableReservation> {\n const expiresAt = new Date(Date.now() + expiryMs);\n const outcome = await reserveThroughRepository(repository, {\n userId,\n amount,\n operationType,\n expiresAt,\n idempotencyKey,\n });\n\n if (outcome.outcome === \"created\" || outcome.outcome === \"replayed\") {\n return outcome.reservation;\n }\n if (outcome.outcome === \"insufficient\") {\n throw createInsufficientCreditsError(outcome.required, outcome.available);\n }\n throw createReservationAlreadyProcessedError(\n outcome.existing.id,\n outcome.existing.status\n );\n}\n"],"mappings":";AAWO,IAAM,kBAAkB;AAAA,EAC7B,sBAAsB;AAAA,EACtB,uBAAuB;AAAA,EACvB,qBAAqB;AAAA,EACrB,+BAA+B;AAAA,EAC/B,gBAAgB;AAAA,EAChB,wBAAwB;AAAA,EACxB,qBAAqB;AAAA,EACrB,gBAAgB;AAAA;AAAA,EAEhB,sBAAsB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMtB,iBAAiB;AAAA;AAAA,EAEjB,uBAAuB;AAAA;AAAA,EAEvB,gBAAgB;AAAA;AAAA,EAEhB,yBAAyB;AAAA;AAAA;AAAA;AAAA;AAAA,EAKzB,4BAA4B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAM5B,sBAAsB;AACxB;AAYO,IAAM,cAAN,MAAM,qBAAoB,MAAM;AAAA,EACrB;AAAA,EACA;AAAA,EAEhB,YACE,SACA,MACA,SACA;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,UAAU;AAGf,QAAI,MAAM,mBAAmB;AAC3B,YAAM,kBAAkB,MAAM,YAAW;AAAA,IAC3C;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,SAA6F;AAC3F,WAAO;AAAA,MACL,MAAM,KAAK;AAAA,MACX,MAAM,KAAK;AAAA,MACX,SAAS,KAAK;AAAA,MACd,GAAI,KAAK,WAAW,EAAE,SAAS,KAAK,QAAQ;AAAA,IAC9C;AAAA,EACF;AACF;AAKO,SA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