@nehorai/credits 2.0.0 → 2.2.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 (43) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +384 -377
  3. package/dist/adapters/index.cjs +12 -8
  4. package/dist/adapters/index.cjs.map +1 -1
  5. package/dist/adapters/index.d.cts +3 -2
  6. package/dist/adapters/index.d.ts +3 -2
  7. package/dist/adapters/index.js +12 -8
  8. package/dist/adapters/index.js.map +1 -1
  9. package/dist/auth/index.cjs.map +1 -1
  10. package/dist/auth/index.js.map +1 -1
  11. package/dist/core/index.cjs +106 -4
  12. package/dist/core/index.cjs.map +1 -1
  13. package/dist/core/index.d.cts +92 -5
  14. package/dist/core/index.d.ts +92 -5
  15. package/dist/core/index.js +96 -4
  16. package/dist/core/index.js.map +1 -1
  17. package/dist/index.cjs +282 -45
  18. package/dist/index.cjs.map +1 -1
  19. package/dist/index.d.cts +9 -7
  20. package/dist/index.d.ts +9 -7
  21. package/dist/index.js +270 -45
  22. package/dist/index.js.map +1 -1
  23. package/dist/repository/index.cjs +251 -41
  24. package/dist/repository/index.cjs.map +1 -1
  25. package/dist/repository/index.d.cts +34 -6
  26. package/dist/repository/index.d.ts +34 -6
  27. package/dist/repository/index.js +248 -40
  28. package/dist/repository/index.js.map +1 -1
  29. package/dist/sdk/index.cjs.map +1 -1
  30. package/dist/sdk/index.d.cts +2 -2
  31. package/dist/sdk/index.d.ts +2 -2
  32. package/dist/sdk/index.js.map +1 -1
  33. package/dist/service/index.cjs +12 -6
  34. package/dist/service/index.cjs.map +1 -1
  35. package/dist/service/index.d.cts +2 -2
  36. package/dist/service/index.d.ts +2 -2
  37. package/dist/service/index.js +12 -6
  38. package/dist/service/index.js.map +1 -1
  39. package/dist/{types-BmG5Omzj.d.ts → types-3c-IAwZI.d.ts} +38 -3
  40. package/dist/{types-DJ8yqaVr.d.cts → types-MaViK5tD.d.cts} +23 -1
  41. package/dist/{types-DJ8yqaVr.d.ts → types-MaViK5tD.d.ts} +23 -1
  42. package/dist/{types-C8hZMe8a.d.cts → types-XSjNXO5l.d.cts} +38 -3
  43. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/repository/index.ts","../../src/repository/types.ts","../../src/core/amount.ts","../../src/core/errors.ts","../../src/core/idempotency.ts","../../src/repository/v2-types.ts","../../src/config/index.ts","../../src/config/provider.ts","../../src/core/payment-ref.ts","../../src/repository/flow.ts","../../src/repository/utils.ts","../../src/repository/memory/snapshot.ts","../../src/core/reservation-integrity.ts","../../src/repository/memory/mutex.ts","../../src/repository/memory/store.ts","../../src/repository/memory/transition-journal.ts","../../src/repository/memory/v2.ts","../../src/repository/memory/index.ts"],"sourcesContent":["/**\n * Credits repository - barrel exports\n *\n * Provides database-agnostic interface for credits storage\n */\n\n// Types and interfaces\nexport type {\n ICreditRepository,\n CreditRepositoryFactory,\n CreateReservationInput,\n CreateTransactionInput,\n CreateUsageLogInput,\n CreateJournalEntryInput,\n UsageLogQuery,\n JournalEntryQuery,\n CreditBalanceUpdate,\n TierUpdateInput,\n AddCreditsAtomicOptions,\n} from \"./types.js\";\n\nexport {\n toClientUserCredits,\n supportsCreditsV2,\n supportsIdempotentCredit,\n} from \"./types.js\";\n\n// V2 boundary (idempotent, race-safe reservations)\nexport type {\n ICreditRepositoryV2,\n ICreditRepositoryCreditsV2,\n AddCreditsV2Input,\n ReserveCreditsV2Input,\n ReservationTransitionOptions,\n ExpireReservationV2Options,\n} from \"./v2-types.js\";\nexport { reservationJournalKey } from \"./v2-types.js\";\nexport {\n reserveThroughRepository,\n commitThroughRepository,\n releaseThroughRepository,\n addCreditsThroughRepository,\n} from \"./flow.js\";\n\n// Shared utilities\nexport { generateId, toDate, getNextMonthlyReset } from \"./utils.js\";\n\n// In-memory implementation (for testing and prototyping)\nexport {\n InMemoryCreditRepository,\n createInMemoryCreditRepository,\n} from \"./memory/index.js\";\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 * 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 * 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 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 * Inputs for the V2 reservation boundary.\n *\n * V2 is additive: every method is optional on {@link ICreditRepository} so\n * existing adapters keep compiling and keep working through the legacy\n * `*Atomic` methods. Adapters that implement V2 must satisfy the contract\n * documented on {@link ICreditRepositoryV2}.\n */\n\nimport type { CreditOperationType } from \"../core/types.js\";\nimport type {\n AddCreditsOutcome,\n CommitOutcome,\n ExpireOutcome,\n ReleaseOutcome,\n ReserveOutcome,\n} from \"../core/outcomes.js\";\nimport { RESERVED_JOURNAL_KEY_PREFIX } from \"../core/idempotency.js\";\nimport type { AddCreditsAtomicOptions } from \"./types.js\";\n\n/**\n * Input for `reserveCreditsV2`.\n *\n * `userId`, `amount` and `operationType` form the immutable payload bound to\n * `idempotencyKey`: replaying the same key with the same payload returns the\n * original reservation, replaying it with a different one is a conflict.\n * `expiresAt` is deliberately *not* part of the payload — a retry naturally\n * computes a later deadline and that must not be treated as a conflict.\n */\nexport interface ReserveCreditsV2Input {\n userId: string;\n amount: number;\n operationType: CreditOperationType;\n expiresAt: Date;\n /**\n * Caller-supplied key, unique per user. Omit it to get legacy\n * (non-idempotent) reserve semantics — every call mints a new hold.\n */\n idempotencyKey?: string;\n}\n\n/** Optional journal customisation for a V2 state transition. */\nexport interface ReservationTransitionOptions {\n /** Overrides the generated journal description. */\n description?: string;\n /** Merged onto the journal entry's metadata. */\n metadata?: Record<string, unknown>;\n}\n\n/** Options for `expireReservationV2`. */\nexport interface ExpireReservationV2Options extends ReservationTransitionOptions {\n /**\n * Sweep timestamp. A reservation only expires when `expiresAt <= asOf`;\n * otherwise the outcome is `not_due`. Defaults to now.\n */\n asOf?: Date;\n}\n\n/**\n * The V2 surface. Every method must:\n *\n * 1. run in a single database transaction;\n * 2. take row locks in a consistent order — reservation first, then balance —\n * so concurrent transitions cannot deadlock;\n * 3. transition status with a compare-and-set (`WHERE status = 'reserved'`)\n * and report the loser truthfully instead of silently succeeding;\n * 4. mutate balances with column expressions, never with values read earlier\n * in the transaction;\n * 5. write at most one journal entry, inside the same transaction, keyed so a\n * retry cannot duplicate it;\n * 6. perform no callbacks and no network I/O inside the transaction.\n */\nexport interface ICreditRepositoryV2 {\n reserveCreditsV2(input: ReserveCreditsV2Input): Promise<ReserveOutcome>;\n\n commitReservationV2(\n userId: string,\n reservationId: string,\n options?: ReservationTransitionOptions\n ): Promise<CommitOutcome>;\n\n releaseReservationV2(\n userId: string,\n reservationId: string,\n options?: ReservationTransitionOptions\n ): Promise<ReleaseOutcome>;\n\n expireReservationV2(\n userId: string,\n reservationId: string,\n options?: ExpireReservationV2Options\n ): Promise<ExpireOutcome>;\n}\n\n/** Input for `addCreditsV2`. */\nexport interface AddCreditsV2Input {\n userId: string;\n amount: number;\n description: string;\n /**\n * Global idempotency key for the credit event. Empty and whitespace-only\n * strings normalise to \"no reference\" — see `normalizePaymentRef`.\n */\n paymentRef?: string;\n options?: AddCreditsAtomicOptions;\n}\n\n/**\n * The idempotent credit surface, separate from {@link ICreditRepositoryV2}.\n *\n * It is its own interface with its own probe because the two capabilities are\n * genuinely independent: an adapter can serialise reservations without having a\n * unique index over `payment_ref`, and folding this into the reservation probe\n * would make `supportsCreditsV2` narrow third-party adapters to a method they\n * never wrote.\n *\n * An implementation must:\n *\n * 1. run in a single transaction;\n * 2. resolve a non-empty reference to exactly one of `created` / `replayed` /\n * `conflict`, comparing the canonical payload — not merely the reference's\n * presence — before reporting a replay;\n * 3. write nothing at all on `replayed` or `conflict`;\n * 4. enforce the reference *globally*, so the same reference cannot credit two\n * different users;\n * 5. fail closed if the uniqueness it relies on is not actually in place.\n */\nexport interface ICreditRepositoryCreditsV2 {\n addCreditsV2(input: AddCreditsV2Input): Promise<AddCreditsOutcome>;\n}\n\n/**\n * Deterministic journal key for a reservation transition.\n *\n * Derived purely from the reservation id and the transition, so a retried\n * commit computes the same key and collides with the first entry on the\n * journal's partial unique index instead of writing a second row.\n */\nexport function reservationJournalKey(\n reservationId: string,\n transition: \"commit\" | \"release\" | \"expire\"\n): string {\n return `${RESERVED_JOURNAL_KEY_PREFIX}${reservationId}:${transition}`;\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","/**\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 * 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 * Shared utilities for credit repository implementations\n *\n * These are pure functions with no server-only dependencies,\n * making them safe to use in any repository implementation.\n */\n\n/**\n * Generate a unique ID\n * Uses timestamp + random string for uniqueness\n */\nexport function generateId(): string {\n return `${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;\n}\n\n/**\n * Convert date-like value to Date object\n * Handles: Date, string, Firestore Timestamp\n */\nexport function toDate(value: Date | string | unknown): Date {\n if (value instanceof Date) return value;\n if (typeof value === \"string\") return new Date(value);\n // Handle Firestore Timestamp\n if (typeof value === \"object\" && value !== null && \"toDate\" in value) {\n return (value as { toDate: () => Date }).toDate();\n }\n return new Date();\n}\n\n/**\n * Get the first day of next month\n * Used for calculating monthly reset dates\n */\nexport function getNextMonthlyReset(from: Date = new Date()): Date {\n const next = new Date(from);\n next.setMonth(next.getMonth() + 1);\n next.setDate(1);\n next.setHours(0, 0, 0, 0);\n return next;\n}\n","/**\n * Copies at the boundary, so nothing stored is ever handed to a caller.\n *\n * A real adapter maps a database row into a fresh object every time. This one\n * used to return the object it had stored, which made it behave in ways no\n * production adapter does: a caller's earlier read mutated under them when a\n * later write landed, and a caller that adjusted a returned record corrupted\n * the store without going through any write path at all.\n *\n * That is not a theoretical difference. The service's monthly reset compared\n * the post-reset balance against the balance it had read moments earlier, got\n * zero because both were the same object, and silently skipped the reset's\n * journal entry — a bug that could not reproduce against the SQL adapter.\n *\n * `metadata` is copied one level deeper because it is the one field callers\n * routinely pass in and then keep a reference to.\n */\n\ninterface WithMetadata {\n metadata?: Record<string, unknown> | null;\n}\n\n/** A detached copy of one stored record. */\nexport function copyRecord<T extends object>(record: T): T;\nexport function copyRecord<T extends object>(record: T | undefined): T | undefined;\nexport function copyRecord<T extends object>(record: T | undefined): T | undefined {\n if (!record) return undefined;\n const copy = { ...record };\n const metadata = (record as WithMetadata).metadata;\n if (metadata && typeof metadata === \"object\") {\n (copy as WithMetadata).metadata = { ...metadata };\n }\n return copy;\n}\n\n/** A detached copy of a list of stored records, and of the list itself. */\nexport function copyRecords<T extends object>(records: readonly T[]): T[] {\n return records.map((record) => copyRecord(record));\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 * Promise-chaining mutex keyed by an arbitrary string.\n *\n * The in-memory repository has no database to serialise it, but its critical\n * sections still span `await` points — and every `await` is a scheduling point\n * where another caller can interleave. Without a lock, \"read balance, then\n * write balance\" in one method is exactly the lost update the SQL adapter uses\n * row locks to prevent, so contract tests would pass in memory and fail in\n * production. This models those row locks.\n */\nexport class KeyedMutex {\n private readonly tails = new Map<string, Promise<unknown>>();\n\n /**\n * Run `fn` with exclusive access to `key`.\n *\n * Callers queue in arrival order. The stored tail settles either way, so one\n * caller throwing does not wedge the queue behind it.\n */\n async run<T>(key: string, fn: () => Promise<T>): Promise<T> {\n const previous = this.tails.get(key) ?? Promise.resolve();\n const result = previous.then(fn, fn);\n const tail = result.then(\n () => undefined,\n () => undefined\n );\n this.tails.set(key, tail);\n\n try {\n return await result;\n } finally {\n // Drop the entry once we are the last waiter, so the map does not grow\n // one permanent entry per user id ever seen.\n if (this.tails.get(key) === tail) {\n this.tails.delete(key);\n }\n }\n }\n}\n","import type {\n PortableJournalEntry,\n PortableReservation,\n PortableTransaction,\n PortableUsageLog,\n PortableUserCredits,\n} from \"../../core/types.js\";\nimport { KeyedMutex } from \"./mutex.js\";\n\n/**\n * Backing state for {@link InMemoryCreditRepository}.\n *\n * Split out so the V2 transition logic can operate on the same state without\n * the repository class having to expose its internals publicly.\n */\nexport class MemoryStore {\n readonly users = new Map<string, PortableUserCredits>();\n readonly reservations = new Map<string, Map<string, PortableReservation>>();\n readonly transactions = new Map<string, PortableTransaction[]>();\n usageLogs: PortableUsageLog[] = [];\n readonly journalEntries = new Map<string, PortableJournalEntry[]>();\n\n /** Stands in for the reservations table's partial unique index. */\n readonly reservationKeys = new Map<string, string>();\n /** Stands in for the journal table's partial unique index. */\n readonly journalKeys = new Map<string, string>();\n\n /** Stands in for the database's per-user row locks. */\n readonly locks = new KeyedMutex();\n\n /**\n * Test-only yield point, awaited between reading state and mutating it.\n *\n * Unset in production, so the critical sections stay synchronous and this\n * costs nothing. Tests set it to a real macrotask yield, which forces\n * concurrent callers to interleave at exactly the spot a database would have\n * them contend — turning the lock above from decoration into the thing the\n * concurrency tests actually depend on.\n */\n schedulingHook?: () => Promise<void>;\n\n clear(): void {\n this.users.clear();\n this.reservations.clear();\n this.transactions.clear();\n this.usageLogs = [];\n this.journalEntries.clear();\n this.reservationKeys.clear();\n this.journalKeys.clear();\n }\n}\n\n/**\n * Composite map key standing in for a two-column unique index.\n *\n * The separator is a newline because it cannot appear in a user id and is\n * vanishingly unlikely in a caller-supplied idempotency key, so two distinct\n * pairs cannot collide into one entry.\n */\nexport function scopedKey(userId: string, key: string): string {\n return `${userId}\\n${key}`;\n}\n","/**\n * Deterministic journal writes for the in-memory V2 transitions.\n *\n * The SQL adapter gets this from a partial unique index plus an\n * `ON CONFLICT DO NOTHING` that re-reads and compares the losing row. There is\n * no index here, so the same contract has to be built by hand — and it has to\n * be the *same* contract, or the shared reservation tests prove nothing about\n * the adapter anyone actually ships.\n *\n * Two properties matter. A key that already exists must be accepted only when\n * the stored row describes the identical event, so a wrong row pre-seeded\n * through the public `createJournalEntry` cannot make a transition report a\n * charge the ledger does not record. And the check has to happen *before* the\n * balances move: this store has no transaction to roll back, so a throw after\n * mutation would leave the ledger half-transitioned.\n */\n\nimport { assertRepresentableFields, sameAmount } from \"../../core/amount.js\";\nimport { CreditError, CreditErrorCode } from \"../../core/errors.js\";\nimport type { CreditSource, PortableJournalEntry } from \"../../core/types.js\";\nimport { generateId } from \"../utils.js\";\nimport { MemoryStore, scopedKey } from \"./store.js\";\n\nexport interface JournalWriteInput {\n userId: string;\n /** The transition writing this entry, so a refusal names what was refused. */\n operation: string;\n entryType: \"debit\" | \"credit\";\n amount: number;\n balanceAfter: number;\n source: CreditSource;\n reservationId: string;\n description: string;\n metadata?: Record<string, unknown>;\n idempotencyKey: string;\n}\n\n/** Name the first field an existing entry disagrees on, or `null` if it matches. */\nfunction describeJournalMismatch(\n row: PortableJournalEntry,\n input: JournalWriteInput\n): string | null {\n if (row.userId !== input.userId) return \"user_id\";\n if (row.entryType !== input.entryType) return \"entry_type\";\n if (!sameAmount(row.amount, input.amount)) return \"amount\";\n if (!sameAmount(row.balanceAfter, input.balanceAfter)) return \"balance_after\";\n if (row.source !== input.source) return \"source\";\n if (row.referenceId !== input.reservationId) return \"reference_id\";\n if (row.referenceType !== \"reservation\") return \"reference_type\";\n\n // Only the fields this adapter sets deterministically. Caller-supplied extras\n // are free-form and may legitimately differ between a request and its retry,\n // so they are not part of the identity of the event.\n const existingMeta = (row.metadata ?? {}) as Record<string, unknown>;\n const expectedMeta = (input.metadata ?? {}) as Record<string, unknown>;\n if (existingMeta.operationType !== expectedMeta.operationType) {\n return \"metadata.operationType\";\n }\n const hadAmount = existingMeta.amount !== undefined;\n const wantsAmount = expectedMeta.amount !== undefined;\n if (hadAmount !== wantsAmount) return \"metadata.amount\";\n if (wantsAmount && !sameAmount(existingMeta.amount, expectedMeta.amount)) {\n return \"metadata.amount\";\n }\n return null;\n}\n\nfunction findEntry(\n store: MemoryStore,\n userId: string,\n entryId: string\n): PortableJournalEntry | undefined {\n return store.journalEntries.get(userId)?.find((entry) => entry.id === entryId);\n}\n\n/**\n * Decide what the journal write will do — without doing it.\n *\n * Returns the id of an existing, exactly matching entry to reuse, or\n * `undefined` when a fresh row is needed. Throws when the key is taken by a\n * different event, and it throws *here*, before the caller has touched a single\n * balance.\n */\nexport function planTransitionJournal(\n store: MemoryStore,\n input: JournalWriteInput\n): string | undefined {\n // `balanceAfter` is a derived total, and every transition journal write\n // passes through this preflight before the ledger moves. Validating it here\n // rather than at each call site means a transition added later cannot forget\n // it, and a total the numeric column could not hold refuses while the\n // balances are still untouched.\n assertRepresentableFields(\n { amount: input.amount, \"journal balanceAfter\": input.balanceAfter },\n { userId: input.userId, reservationId: input.reservationId, operation: input.operation }\n );\n\n const existingId = store.journalKeys.get(scopedKey(input.userId, input.idempotencyKey));\n if (!existingId) return undefined;\n\n const row = findEntry(store, input.userId, existingId);\n const mismatch = row\n ? describeJournalMismatch(row, input)\n : \"the key is registered but its entry is missing\";\n if (mismatch) {\n throw new CreditError(\n `Journal key ${input.idempotencyKey} is already used by a different entry ` +\n `(${mismatch}). The transition was refused rather than reported as applied.`,\n CreditErrorCode.DATABASE_ERROR,\n {\n idempotencyKey: input.idempotencyKey,\n reservationId: input.reservationId,\n mismatch,\n }\n );\n }\n return existingId;\n}\n\n/**\n * Perform the write the preflight authorised.\n *\n * `existingId` is whatever {@link planTransitionJournal} returned for this same\n * input; passing it through keeps the decision and the write from drifting\n * apart, which is the whole point of splitting them.\n */\nexport function commitTransitionJournal(\n store: MemoryStore,\n input: JournalWriteInput,\n existingId: string | undefined\n): string {\n if (existingId) return existingId;\n\n const entry: PortableJournalEntry = {\n id: generateId(),\n userId: input.userId,\n entryType: input.entryType,\n amount: input.amount,\n balanceAfter: input.balanceAfter,\n source: input.source,\n referenceId: input.reservationId,\n referenceType: \"reservation\",\n description: input.description,\n metadata: input.metadata,\n idempotencyKey: input.idempotencyKey,\n createdAt: new Date().toISOString(),\n };\n\n if (!store.journalEntries.has(input.userId)) {\n store.journalEntries.set(input.userId, []);\n }\n store.journalEntries.get(input.userId)!.push(entry);\n store.journalKeys.set(scopedKey(input.userId, input.idempotencyKey), entry.id);\n return entry.id;\n}\n","/**\n * V2 reservation transitions for the in-memory repository.\n *\n * These mirror the SQL adapter's guarantees rather than its mechanics: every\n * transition runs inside the user's lock (standing in for the row locks),\n * re-reads state *after* acquiring it, compares-and-sets the status, and\n * writes at most one journal entry keyed so a retry cannot duplicate it.\n *\n * Modelling that here is what makes the shared contract tests meaningful — a\n * naive implementation would pass them by accident because nothing interleaves.\n */\n\nimport {\n assertValidCreditAmount,\n assertValidStoredAmount,\n sumAmounts,\n} from \"../../core/amount.js\";\nimport { assertValidIdempotencyKey } from \"../../core/idempotency.js\";\nimport {\n assertHoldPlaced,\n assertKnownReservationStatus,\n terminalStatusOf as narrowTerminalStatus,\n} from \"../../core/reservation-integrity.js\";\nimport { copyRecord } from \"./snapshot.js\";\nimport { assertRepresentableFields } from \"../../core/amount.js\";\nimport { CreditError, CreditErrorCode } from \"../../core/errors.js\";\nimport type {\n CommitOutcome,\n ExpireOutcome,\n ReleaseOutcome,\n ReserveOutcome,\n TerminalReservationStatus,\n} from \"../../core/outcomes.js\";\nimport type {\n CreditSource,\n PortableReservation,\n PortableUserCredits,\n} from \"../../core/types.js\";\nimport { getOperationLabel } from \"../../config/index.js\";\nimport { generateId } from \"../utils.js\";\nimport {\n commitTransitionJournal,\n planTransitionJournal,\n type JournalWriteInput,\n} from \"./transition-journal.js\";\nimport type {\n ExpireReservationV2Options,\n ReservationTransitionOptions,\n ReserveCreditsV2Input,\n} from \"../v2-types.js\";\nimport { reservationJournalKey } from \"../v2-types.js\";\nimport { MemoryStore, scopedKey } from \"./store.js\";\n\n/** Yield at the read/write seam so tests can force real interleaving. */\nasync function yieldPoint(store: MemoryStore): Promise<void> {\n if (store.schedulingHook) await store.schedulingHook();\n}\n\n/**\n * Refuse a transition whose hold is no longer covered by `reserved`.\n *\n * The SQL adapter enforces this as `reserved >= amount` in the UPDATE's WHERE.\n * Clamping with `Math.max(reserved - amount, 0)` instead would look harmless\n * and quietly consume the coverage of *other* live holds, so those commits\n * would later fail or overdraw. Failing here keeps the damage contained and\n * visible, and — because the caller sees `DATABASE_ERROR` rather than\n * `INSUFFICIENT_CREDITS` — correctly reads as corruption, not as a user who\n * ran out of money.\n */\nfunction assertReservedCoversHold(\n credits: PortableUserCredits,\n userId: string,\n reservationId: string,\n amount: number\n): void {\n if (credits.reserved >= amount) return;\n throw new CreditError(\n `Credit balance invariant violated for user ${userId} while processing ` +\n `reservation ${reservationId}: reserved (${credits.reserved}) is less ` +\n `than the hold (${amount}). The transition was rolled back.`,\n CreditErrorCode.DATABASE_ERROR,\n { userId, reservationId, amount, reserved: credits.reserved }\n );\n}\n\n/**\n * Re-validate a persisted amount before the transition touches anything.\n *\n * Mirrors the SQL adapter: the reservation row was written once and is read\n * back on every transition, and a value that is negative, non-finite or off the\n * cent grid makes every downstream invariant meaningless — `reserved >= -10` is\n * trivially true, and subtracting a negative *adds* credits.\n */\nfunction assertLockedAmount(reservation: PortableReservation, transition: string): void {\n assertValidStoredAmount(reservation.amount, {\n userId: reservation.userId,\n reservationId: reservation.id,\n transition,\n });\n}\n\n/**\n * Narrow a non-`reserved` status, validating instead of casting.\n *\n * The cast this replaces reported `already_terminal` — a *success* outcome —\n * over a row holding any string at all, so a corrupt status read to the caller\n * as \"this reservation is resolved\". See `core/reservation-integrity.ts`.\n */\nfunction terminalStatusOf(\n reservation: PortableReservation,\n transition: string\n): TerminalReservationStatus {\n return narrowTerminalStatus(reservation, transition);\n}\n\n/**\n * Every check a persisted reservation must pass before a transition touches it.\n *\n * Ordered ahead of the `already_terminal` and `not_due` early exits on purpose:\n * both are success outcomes, and reporting one over a row that is corrupt or\n * unbacked tells the caller the reservation is fine.\n */\nfunction assertTrustworthy(reservation: PortableReservation, transition: string): void {\n assertKnownReservationStatus(reservation, transition);\n assertLockedAmount(reservation, transition);\n assertHoldPlaced(reservation, transition);\n}\n\nfunction getReservation(\n store: MemoryStore,\n userId: string,\n reservationId: string\n): PortableReservation | undefined {\n return store.reservations.get(userId)?.get(reservationId);\n}\n\n/**\n * The *live* stored record, deliberately — the transitions in this module write\n * through it. Everything that crosses the repository's public surface goes\n * through `copyRecord` instead; see `./snapshot.js`.\n */\nfunction requireUser(store: MemoryStore, userId: string): PortableUserCredits {\n const credits = store.users.get(userId);\n if (!credits) {\n throw new CreditError(\n `User credits not found for user ${userId}`,\n CreditErrorCode.USER_NOT_FOUND,\n { userId }\n );\n }\n return credits;\n}\n\nexport async function reserveCreditsV2(\n store: MemoryStore,\n input: ReserveCreditsV2Input\n): Promise<ReserveOutcome> {\n assertValidCreditAmount(input.amount, { userId: input.userId });\n assertValidIdempotencyKey(input.idempotencyKey, { userId: input.userId });\n\n return store.locks.run(input.userId, async () => {\n if (input.idempotencyKey) {\n const existingId = store.reservationKeys.get(\n scopedKey(input.userId, input.idempotencyKey)\n );\n if (existingId) {\n const existing = getReservation(store, input.userId, existingId);\n if (existing) {\n // Before the payload comparison, and before any outcome is chosen: a\n // row is only adoptable as a replay if *its own* reserve placed the\n // hold. Adopting an unbacked row would report `replayed` over credits\n // nothing ever held. Mirrors the SQL adapter.\n assertHoldPlaced(existing, \"reserve replay\");\n // `expiresAt` is excluded on purpose: a retry legitimately computes a\n // later deadline and that must not read as a conflict.\n const samePayload =\n existing.amount === input.amount &&\n existing.operationType === input.operationType;\n return samePayload\n ? { outcome: \"replayed\", reservation: copyRecord(existing) }\n : {\n outcome: \"idempotency_conflict\",\n idempotencyKey: input.idempotencyKey,\n existing: copyRecord(existing),\n };\n }\n }\n }\n\n const credits = requireUser(store, input.userId);\n const available = sumAmounts(credits.balance, credits.bonusCredits, -credits.reserved);\n await yieldPoint(store);\n if (available < input.amount) {\n return {\n outcome: \"insufficient\",\n available,\n required: input.amount,\n shortfall: sumAmounts(input.amount, -available),\n };\n }\n\n const now = new Date().toISOString();\n const reservation: PortableReservation = {\n id: generateId(),\n userId: input.userId,\n amount: input.amount,\n operationType: input.operationType,\n status: \"reserved\",\n createdAt: now,\n expiresAt: input.expiresAt.toISOString(),\n idempotencyKey: input.idempotencyKey,\n // The hold-origin fact. Written here and nowhere else, in the same\n // critical section that raises `reserved` below, so the row and the hold\n // become visible together. `createReservation` cannot set it.\n holdPlacedAt: now,\n };\n\n if (!store.reservations.has(input.userId)) {\n store.reservations.set(input.userId, new Map());\n }\n // The derived hold is checked before the reservation row exists, not after:\n // a refusal here must leave no reservation, no key registration and no\n // counter change behind.\n const nextReserved = sumAmounts(credits.reserved, input.amount);\n assertRepresentableFields(\n { reserved: nextReserved },\n { userId: input.userId, operation: \"reserveCredits\" }\n );\n\n store.reservations.get(input.userId)!.set(reservation.id, reservation);\n if (input.idempotencyKey) {\n store.reservationKeys.set(\n scopedKey(input.userId, input.idempotencyKey),\n reservation.id\n );\n }\n\n credits.reserved = nextReserved;\n credits.updatedAt = now;\n\n return { outcome: \"created\", reservation: copyRecord(reservation) };\n });\n}\n\nexport async function commitReservationV2(\n store: MemoryStore,\n userId: string,\n reservationId: string,\n options?: ReservationTransitionOptions\n): Promise<CommitOutcome> {\n return store.locks.run(userId, async () => {\n const reservation = getReservation(store, userId, reservationId);\n if (!reservation) return { outcome: \"not_found\", reservationId };\n // Ahead of the early exits: `already_terminal` and `not_due` are success\n // outcomes, and reporting one over a row that is unusable tells the caller\n // the reservation is fine. Mirrors the SQL adapter.\n assertTrustworthy(reservation, \"commit\");\n\n if (reservation.status !== \"reserved\") {\n return {\n outcome: \"already_terminal\",\n reservation: copyRecord(reservation),\n terminalStatus: terminalStatusOf(reservation, \"commit\"),\n };\n }\n\n const credits = requireUser(store, userId);\n const amount = reservation.amount;\n await yieldPoint(store);\n assertReservedCoversHold(credits, userId, reservationId, amount);\n if (sumAmounts(credits.balance, credits.bonusCredits) < amount) {\n throw new CreditError(\n `Insufficient credits to commit reservation ${reservationId}`,\n CreditErrorCode.INSUFFICIENT_CREDITS,\n { userId, reservationId, required: amount }\n );\n }\n\n // Project the post-transition balances before applying them. The store has\n // no transaction to roll back, so everything that can refuse — the journal\n // key check below — has to refuse while the ledger is still untouched. The\n // projected values are then assigned verbatim, so the number the journal\n // records and the number the balance ends up holding cannot drift apart.\n const fromBalance = Math.min(credits.balance, amount);\n const nextBalance = sumAmounts(credits.balance, -fromBalance);\n const nextBonusCredits = sumAmounts(credits.bonusCredits, -sumAmounts(amount, -fromBalance));\n const balanceAfter = sumAmounts(nextBalance, nextBonusCredits);\n\n const journal: JournalWriteInput = {\n userId,\n operation: \"commitReservation\",\n entryType: \"debit\",\n amount,\n balanceAfter,\n source: \"operation_commit\",\n reservationId,\n description:\n options?.description ??\n `Committed ${amount} credits for ${getOperationLabel(reservation.operationType)}`,\n // Caller metadata first: the deterministic fields carry the identity of\n // the event that the collision check compares on.\n metadata: { ...options?.metadata, operationType: reservation.operationType, amount },\n idempotencyKey: reservationJournalKey(reservationId, \"commit\"),\n };\n const nextReserved = sumAmounts(credits.reserved, -amount);\n const nextMonthlyUsed = sumAmounts(credits.monthlyUsed, amount);\n assertRepresentableFields(\n {\n balance: nextBalance,\n bonusCredits: nextBonusCredits,\n reserved: nextReserved,\n monthlyUsed: nextMonthlyUsed,\n },\n { userId, operation: \"commitReservation\" }\n );\n\n const existingEntryId = planTransitionJournal(store, journal);\n\n reservation.status = \"committed\";\n reservation.completedAt = new Date().toISOString();\n\n // Drain `balance` before `bonusCredits`, matching the SQL adapter.\n credits.balance = nextBalance;\n credits.bonusCredits = nextBonusCredits;\n credits.reserved = nextReserved;\n credits.monthlyUsed = nextMonthlyUsed;\n credits.updatedAt = new Date().toISOString();\n\n const journalEntryId = commitTransitionJournal(store, journal, existingEntryId);\n\n return {\n outcome: \"committed\",\n reservation: copyRecord(reservation),\n amount,\n balanceAfter,\n journalEntryId,\n };\n });\n}\n\nexport async function releaseReservationV2(\n store: MemoryStore,\n userId: string,\n reservationId: string,\n options?: ReservationTransitionOptions\n): Promise<ReleaseOutcome> {\n return store.locks.run(userId, async () => {\n const reservation = getReservation(store, userId, reservationId);\n if (!reservation) return { outcome: \"not_found\", reservationId };\n // Ahead of the early exits: `already_terminal` and `not_due` are success\n // outcomes, and reporting one over a row that is unusable tells the caller\n // the reservation is fine. Mirrors the SQL adapter.\n assertTrustworthy(reservation, \"release\");\n\n if (reservation.status !== \"reserved\") {\n return {\n outcome: \"already_terminal\",\n reservation: copyRecord(reservation),\n terminalStatus: terminalStatusOf(reservation, \"release\"),\n };\n }\n\n await yieldPoint(store);\n const journalEntryId = finishUnspent(store, reservation, {\n status: \"released\",\n source: \"operation_release\",\n transition: \"release\",\n verb: \"Released\",\n options,\n });\n\n return {\n outcome: \"released\",\n reservation: copyRecord(reservation),\n amount: reservation.amount,\n journalEntryId,\n };\n });\n}\n\nexport async function expireReservationV2(\n store: MemoryStore,\n userId: string,\n reservationId: string,\n options?: ExpireReservationV2Options\n): Promise<ExpireOutcome> {\n const asOf = options?.asOf ?? new Date();\n return store.locks.run(userId, async () => {\n const reservation = getReservation(store, userId, reservationId);\n if (!reservation) return { outcome: \"not_found\", reservationId };\n // Ahead of the early exits: `already_terminal` and `not_due` are success\n // outcomes, and reporting one over a row that is unusable tells the caller\n // the reservation is fine. Mirrors the SQL adapter.\n assertTrustworthy(reservation, \"expire\");\n\n if (reservation.status !== \"reserved\") {\n return {\n outcome: \"already_terminal\",\n reservation: copyRecord(reservation),\n terminalStatus: terminalStatusOf(reservation, \"expire\"),\n };\n }\n if (new Date(reservation.expiresAt).getTime() > asOf.getTime()) {\n return { outcome: \"not_due\", reservation: copyRecord(reservation) };\n }\n\n await yieldPoint(store);\n const journalEntryId = finishUnspent(store, reservation, {\n status: \"expired\",\n source: \"reservation_expired\",\n transition: \"expire\",\n verb: \"Expired\",\n options,\n });\n\n return {\n outcome: \"expired\",\n reservation: copyRecord(reservation),\n amount: reservation.amount,\n journalEntryId,\n };\n });\n}\n\ninterface UnspentTransition {\n status: \"released\" | \"expired\";\n source: CreditSource;\n transition: \"release\" | \"expire\";\n verb: string;\n options?: ReservationTransitionOptions;\n}\n\n/**\n * Hand a hold back unspent and journal it.\n *\n * `amount` is 0 because no credits changed hands — the hold only moves back\n * into \"available\". The hold size stays in metadata, matching the SQL adapter.\n */\nfunction finishUnspent(\n store: MemoryStore,\n reservation: PortableReservation,\n transition: UnspentTransition\n): string {\n const credits = requireUser(store, reservation.userId);\n assertReservedCoversHold(\n credits,\n reservation.userId,\n reservation.id,\n reservation.amount\n );\n\n // Handing a hold back does not move balance or bonus, so the recorded\n // `balanceAfter` is the current total either way — but the journal check\n // still runs before the mutation, so a key collision leaves `reserved`, the\n // status and `completedAt` untouched.\n const journal: JournalWriteInput = {\n userId: reservation.userId,\n operation: `${transition.transition}Reservation`,\n entryType: \"credit\",\n amount: 0,\n balanceAfter: sumAmounts(credits.balance, credits.bonusCredits),\n source: transition.source,\n reservationId: reservation.id,\n description:\n transition.options?.description ??\n `${transition.verb} ${reservation.amount} reserved credits for ${getOperationLabel(reservation.operationType)}`,\n metadata: {\n ...transition.options?.metadata,\n operationType: reservation.operationType,\n amount: reservation.amount,\n },\n idempotencyKey: reservationJournalKey(reservation.id, transition.transition),\n };\n const nextReserved = sumAmounts(credits.reserved, -reservation.amount);\n assertRepresentableFields(\n { reserved: nextReserved },\n { userId: reservation.userId, operation: `${transition.transition}Reservation` }\n );\n\n const existingEntryId = planTransitionJournal(store, journal);\n\n reservation.status = transition.status;\n reservation.completedAt = new Date().toISOString();\n credits.reserved = nextReserved;\n credits.updatedAt = new Date().toISOString();\n\n return commitTransitionJournal(store, journal, existingEntryId);\n}\n","/**\n * In-Memory Credit Repository Implementation\n *\n * A database-agnostic implementation of ICreditRepository for testing and prototyping.\n * All data is stored in memory and lost when the process restarts.\n *\n * Usage:\n * - Unit tests without database dependency\n * - Local development and prototyping\n * - Reference implementation for custom repositories\n */\n\nimport type {\n PortableUserCredits,\n PortableReservation,\n PortableTransaction,\n PortableJournalEntry,\n PortableUsageLog,\n SubscriptionTier,\n ReservationStatus,\n MonthlyResetResult,\n SubscriptionExpiryResult,\n} from \"../../core/types.js\";\nimport type {\n ICreditRepository,\n CreateReservationInput,\n CreateTransactionInput,\n CreateUsageLogInput,\n CreateJournalEntryInput,\n UsageLogQuery,\n JournalEntryQuery,\n CreditBalanceUpdate,\n TierUpdateInput,\n AddCreditsAtomicOptions,\n} from \"../types.js\";\nimport type {\n AddCreditsOutcome,\n CommitOutcome,\n ExpireOutcome,\n ReleaseOutcome,\n ReserveOutcome,\n} from \"../../core/outcomes.js\";\nimport type {\n AddCreditsV2Input,\n ExpireReservationV2Options,\n ReservationTransitionOptions,\n ReserveCreditsV2Input,\n} from \"../v2-types.js\";\nimport {\n assertUnreferencedDirectTransaction,\n createPaymentRefConflictError,\n describePaymentMismatch,\n normalizePaymentRef,\n type PaymentEventPayload,\n} from \"../../core/payment-ref.js\";\nimport {\n createInsufficientCreditsError,\n createReservationAlreadyProcessedError,\n createReservationNotFoundError,\n} from \"../../core/errors.js\";\nimport { generateId, toDate, getNextMonthlyReset } from \"../utils.js\";\nimport { copyRecord, copyRecords } from \"./snapshot.js\";\nimport {\n assertRepresentableAmount,\n assertRepresentableFields,\n assertRepresentableTierAmount,\n backedBalanceFloor,\n storedMonthlyLimit,\n assertValidCreditAmount,\n sumAmounts,\n} from \"../../core/amount.js\";\nimport {\n assertPublicJournalKey,\n assertValidIdempotencyKey,\n} from \"../../core/idempotency.js\";\nimport {\n assertDirectStatusWriteAllowed,\n assertUnkeyedDirectReservation,\n} from \"../../core/reservation-integrity.js\";\nimport { CreditError, CreditErrorCode } from \"../../core/errors.js\";\nimport { MemoryStore, scopedKey } from \"./store.js\";\nimport {\n commitReservationV2,\n expireReservationV2,\n releaseReservationV2,\n reserveCreditsV2,\n} from \"./v2.js\";\nimport {\n getConfigMonthlyLimit,\n getConfigTierConfig,\n getDefaultTier,\n isFreeTier,\n monthlyResetBalance,\n} from \"../../config/index.js\";\n\n/**\n * In-Memory implementation of ICreditRepository\n *\n * Implements all repository methods using Map-based storage.\n * Useful for testing and as a reference implementation.\n */\n/** Apply an increment, or report `undefined` when the caller sent none. */\n/** Accept either half of the `Date | string` timestamp inputs the API takes. */\nfunction isoOf(value: Date | string): string {\n return value instanceof Date ? value.toISOString() : value;\n}\n\nexport class InMemoryCreditRepository implements ICreditRepository {\n private readonly store = new MemoryStore();\n\n // ==================== User Credits ====================\n\n /**\n * A copy, never the live record.\n *\n * Handing out the stored object made this adapter behave unlike any real\n * one: a caller holding a \"before\" snapshot saw it mutate under them. The\n * service's monthly reset compared `resetResult.credits.balance` against the\n * balance it had read moments earlier, got zero because both were the same\n * object, and silently skipped the reset's journal entry — while the SQL\n * adapter, which maps each row into a fresh object, wrote it.\n */\n async getUserCredits(userId: string): Promise<PortableUserCredits | null> {\n const credits = this.store.users.get(userId);\n return copyRecord(credits) ?? null;\n }\n\n async initializeUserCredits(\n userId: string,\n tier: SubscriptionTier,\n initialBalance: number\n ): Promise<PortableUserCredits> {\n return copyRecord(this.seedUser(userId, tier, initialBalance));\n }\n\n /**\n * The synchronous body of `initializeUserCredits`.\n *\n * Kept `await`-free on purpose: `addCreditsV2` seeds a missing user *inside*\n * its critical section, and an `await` between the payment-reference check\n * and the transaction write opens a gap another caller can run through — two\n * simultaneous first deliveries of the same reference would then both credit.\n */\n private seedUser(\n userId: string,\n tier: SubscriptionTier,\n initialBalance: number\n ): PortableUserCredits {\n assertRepresentableAmount(initialBalance, \"initialBalance\", { userId });\n // Derived from tier configuration rather than supplied by the caller, and\n // therefore just as capable of being unrepresentable: a tier configured\n // with `monthlyCredits: 1.005` writes a number the column cannot hold.\n const configured = getConfigMonthlyLimit(tier);\n assertRepresentableTierAmount(configured, \"monthlyLimit\", { userId, tier });\n // Stored through the shared contract so both adapters hold the same number\n // for an unlimited tier. See `storedMonthlyLimit`.\n const monthlyLimit = storedMonthlyLimit(configured);\n\n const now = new Date().toISOString();\n const credits: PortableUserCredits = {\n userId,\n balance: initialBalance,\n bonusCredits: 0,\n reserved: 0,\n tier,\n monthlyLimit,\n monthlyUsed: 0,\n monthlyResetAt: getNextMonthlyReset().toISOString(),\n subscriptionExpiresAt: null,\n createdAt: now,\n updatedAt: now,\n };\n this.store.users.set(userId, credits);\n return credits;\n }\n\n async updateUserCredits(userId: string, updates: CreditBalanceUpdate): Promise<void> {\n assertRepresentableFields(\n {\n balance: updates.balance,\n bonusCredits: updates.bonusCredits,\n reserved: updates.reserved,\n monthlyLimit: updates.monthlyLimit,\n monthlyUsed: updates.monthlyUsed,\n balanceIncrement: updates.balanceIncrement,\n bonusCreditsIncrement: updates.bonusCreditsIncrement,\n reservedIncrement: updates.reservedIncrement,\n monthlyUsedIncrement: updates.monthlyUsedIncrement,\n },\n { userId, operation: \"updateUserCredits\" }\n );\n\n const credits = this.store.users.get(userId);\n if (!credits) {\n throw new Error(`User ${userId} not found`);\n }\n\n // The entire record is projected onto a candidate before anything is\n // written back. Assigning the absolute fields first and validating the\n // increments afterwards would leave a refused update half-applied — an\n // explicit `monthlyUsed: 5` would stick even though the derived `balance`\n // it was sent with was rejected — and this store has no transaction to\n // undo it. Every numeric field is checked on the candidate, so the record\n // either takes the whole update or none of it.\n const next: PortableUserCredits = { ...credits };\n\n if (updates.balance !== undefined) next.balance = updates.balance;\n if (updates.bonusCredits !== undefined) next.bonusCredits = updates.bonusCredits;\n if (updates.reserved !== undefined) next.reserved = updates.reserved;\n if (updates.tier !== undefined) next.tier = updates.tier;\n if (updates.monthlyLimit !== undefined) next.monthlyLimit = updates.monthlyLimit;\n if (updates.monthlyUsed !== undefined) next.monthlyUsed = updates.monthlyUsed;\n if (updates.monthlyResetAt !== undefined) {\n next.monthlyResetAt = isoOf(updates.monthlyResetAt);\n }\n if (updates.subscriptionExpiresAt !== undefined) {\n next.subscriptionExpiresAt =\n updates.subscriptionExpiresAt === null\n ? null\n : isoOf(updates.subscriptionExpiresAt);\n }\n\n // Increments are checked as *results*, not just as arguments: adding a\n // legal 0.01 to a legal 9999999999.99 produces a number the column cannot\n // hold. They apply on top of whatever the absolute fields just set; the SQL\n // adapter is built to match, and the SQL package's\n // `__tests__/integration/adapter-parity.test.ts` pins the two together.\n //\n // `sumAmounts`, not `+`: a float sum can land off the cent grid the ledger\n // validates against, and rejecting a legal increment as `INVALID_AMOUNT` is\n // a worse failure than the overflow this check exists for.\n if (updates.balanceIncrement !== undefined) {\n next.balance = sumAmounts(next.balance, updates.balanceIncrement);\n }\n if (updates.bonusCreditsIncrement !== undefined) {\n next.bonusCredits = sumAmounts(next.bonusCredits, updates.bonusCreditsIncrement);\n }\n if (updates.reservedIncrement !== undefined) {\n next.reserved = sumAmounts(next.reserved, updates.reservedIncrement);\n }\n if (updates.monthlyUsedIncrement !== undefined) {\n next.monthlyUsed = sumAmounts(next.monthlyUsed, updates.monthlyUsedIncrement);\n }\n\n assertRepresentableFields(\n {\n balance: next.balance,\n bonusCredits: next.bonusCredits,\n reserved: next.reserved,\n monthlyUsed: next.monthlyUsed,\n },\n { userId, operation: \"updateUserCredits\" }\n );\n assertRepresentableTierAmount(next.monthlyLimit, \"monthlyLimit\", {\n userId,\n operation: \"updateUserCredits\",\n });\n\n next.updatedAt = new Date().toISOString();\n this.store.users.set(userId, next);\n }\n\n async updateUserTier(userId: string, input: TierUpdateInput): Promise<void> {\n assertRepresentableFields(\n { monthlyLimit: input.monthlyLimit, balance: input.balance, monthlyUsed: input.monthlyUsed },\n { userId, operation: \"updateUserTier\" }\n );\n\n const credits = this.store.users.get(userId);\n if (!credits) {\n throw new Error(`User ${userId} not found`);\n }\n\n credits.tier = input.tier;\n credits.monthlyLimit = input.monthlyLimit;\n // A tier write may lower the balance, but never below what still backs the\n // outstanding holds — see `backedBalanceFloor`. Same clamp as the SQL\n // adapter, so a downgrade cannot strand a live reservation.\n if (input.balance !== undefined) {\n credits.balance = Math.max(\n input.balance,\n backedBalanceFloor(credits.reserved, credits.bonusCredits)\n );\n }\n if (input.monthlyUsed !== undefined) credits.monthlyUsed = input.monthlyUsed;\n if (input.subscriptionExpiresAt !== undefined) {\n if (input.subscriptionExpiresAt === null) {\n credits.subscriptionExpiresAt = null;\n } else {\n credits.subscriptionExpiresAt = input.subscriptionExpiresAt instanceof Date\n ? input.subscriptionExpiresAt.toISOString()\n : input.subscriptionExpiresAt;\n }\n }\n credits.updatedAt = new Date().toISOString();\n\n this.store.users.set(userId, credits);\n }\n\n // ==================== Reservations ====================\n\n async createReservation(input: CreateReservationInput): Promise<PortableReservation> {\n // Same refusal as the SQL adapter: a row written with an amount the ledger\n // cannot honour has no repair path once it exists, and every transition\n // that later locks it would have to refuse anyway.\n assertValidCreditAmount(input.amount, { userId: input.userId, operation: \"createReservation\" });\n assertUnkeyedDirectReservation(input);\n\n const now = new Date().toISOString();\n const reservation: PortableReservation = {\n id: generateId(),\n userId: input.userId,\n amount: input.amount,\n operationType: input.operationType,\n status: \"reserved\",\n createdAt: now,\n expiresAt: input.expiresAt.toISOString(),\n };\n\n if (!this.store.reservations.has(input.userId)) {\n this.store.reservations.set(input.userId, new Map());\n }\n this.store.reservations.get(input.userId)!.set(reservation.id, reservation);\n\n return copyRecord(reservation);\n }\n\n async getReservation(\n userId: string,\n reservationId: string\n ): Promise<PortableReservation | null> {\n const userReservations = this.store.reservations.get(userId);\n if (!userReservations) return null;\n return copyRecord(userReservations.get(reservationId)) ?? null;\n }\n\n async updateReservationStatus(\n userId: string,\n reservationId: string,\n status: ReservationStatus,\n completedAt?: Date\n ): Promise<void> {\n const userReservations = this.store.reservations.get(userId);\n if (!userReservations) {\n throw new Error(`No reservations found for user ${userId}`);\n }\n\n const reservation = userReservations.get(reservationId);\n if (!reservation) {\n throw new Error(`Reservation ${reservationId} not found`);\n }\n\n // A backed hold's status is owned by the transition that settles it, and no\n // row may be reopened: this method assigns a status and nothing else, so on\n // a V2 row it would change the status without the ledger movement the\n // status stands for. See `assertDirectStatusWriteAllowed`.\n assertDirectStatusWriteAllowed(reservation, status);\n\n reservation.status = status;\n if (completedAt) reservation.completedAt = completedAt.toISOString();\n\n userReservations.set(reservationId, reservation);\n }\n\n // ==================== Atomic Operations ====================\n\n // ==================== V2 boundary ====================\n //\n // As in the Drizzle adapter, V2 is the real implementation and the legacy\n // `*Atomic` methods are adapters over it, so both APIs share one set of\n // guarantees.\n\n async reserveCreditsV2(input: ReserveCreditsV2Input): Promise<ReserveOutcome> {\n return reserveCreditsV2(this.store, input);\n }\n\n async commitReservationV2(\n userId: string,\n reservationId: string,\n options?: ReservationTransitionOptions\n ): Promise<CommitOutcome> {\n return commitReservationV2(this.store, userId, reservationId, options);\n }\n\n async releaseReservationV2(\n userId: string,\n reservationId: string,\n options?: ReservationTransitionOptions\n ): Promise<ReleaseOutcome> {\n return releaseReservationV2(this.store, userId, reservationId, options);\n }\n\n async expireReservationV2(\n userId: string,\n reservationId: string,\n options?: ExpireReservationV2Options\n ): Promise<ExpireOutcome> {\n return expireReservationV2(this.store, userId, reservationId, options);\n }\n\n // ==================== Legacy atomic operations ====================\n\n async reserveCreditsAtomic(\n userId: string,\n amount: number,\n operationType: string,\n expiresAt: Date\n ): Promise<PortableReservation> {\n const outcome = await this.reserveCreditsV2({ userId, amount, operationType, expiresAt });\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(outcome.existing.id, outcome.existing.status);\n }\n\n async commitReservationAtomic(userId: string, reservationId: string): Promise<void> {\n const outcome = await this.commitReservationV2(userId, reservationId);\n if (outcome.outcome === \"committed\") return;\n if (outcome.outcome === \"not_found\") throw createReservationNotFoundError(reservationId);\n // Re-delivering a commit for an already-committed reservation stays a no-op.\n if (outcome.terminalStatus === \"committed\") return;\n throw createReservationAlreadyProcessedError(reservationId, outcome.terminalStatus);\n }\n\n async releaseReservationAtomic(userId: string, reservationId: string): Promise<void> {\n const outcome = await this.releaseReservationV2(userId, reservationId);\n if (outcome.outcome === \"not_found\") throw createReservationNotFoundError(reservationId);\n // Releasing an already-terminal reservation is a no-op, as before.\n }\n\n /**\n * The stored transaction carrying this reference, in *any* user's ledger.\n *\n * Deliberately not scoped to one user. The SQL adapter's unique index covers\n * `payment_ref` alone, so searching only the crediting user's own history made\n * the same reference credit two different accounts here while the SQL adapter\n * treated the second delivery as a duplicate. See `core/payment-ref.ts`.\n */\n private findByPaymentRef(paymentRef: string): PortableTransaction | undefined {\n for (const recorded of this.store.transactions.values()) {\n const hit = recorded.find((transaction) => transaction.paymentRef === paymentRef);\n if (hit) return hit;\n }\n return undefined;\n }\n\n /** The journal entry written alongside a stored purchase, if there is one. */\n private journalForTransaction(\n transaction: PortableTransaction\n ): PortableJournalEntry | undefined {\n return this.store.journalEntries\n .get(transaction.userId)\n ?.find((entry) => entry.referenceId === transaction.id);\n }\n\n /**\n * Credit an account, resolving `paymentRef` to created / replayed / conflict.\n *\n * The reference is checked and the transaction is recorded with no `await`\n * between them. `createTransaction` is `async` but its body is synchronous, so\n * under JavaScript's run-to-completion semantics no other caller can observe\n * the gap — which is what stands in for the SQL adapter's unique index.\n *\n * A `replayed` or `conflict` outcome writes nothing at all: the check runs\n * before the balance moves, not after.\n */\n async addCreditsV2(input: AddCreditsV2Input): Promise<AddCreditsOutcome> {\n const { userId, amount, description, options } = input;\n assertValidCreditAmount(amount, { userId, operation: \"addCredits\" });\n\n // Empty and whitespace-only strings are not references. Normalised in one\n // place so this adapter and the SQL one agree on which calls carry one.\n const paymentRef = normalizePaymentRef(input.paymentRef);\n const payload: PaymentEventPayload = {\n userId,\n amount,\n type: \"purchase\",\n source: options?.source ?? \"purchase\",\n referenceType: options?.referenceType ?? \"transaction\",\n };\n\n if (paymentRef) {\n const existing = this.findByPaymentRef(paymentRef);\n if (existing) {\n const journal = this.journalForTransaction(existing);\n // Presence is not enough. A reference that arrives again with a\n // different user, amount or source is a *different* credit event, and\n // reporting it as a replay would credit the first amount and call the\n // second one done.\n const mismatch = describePaymentMismatch(\n {\n userId: existing.userId,\n amount: existing.amount,\n type: existing.type,\n source: journal?.source,\n referenceType: journal?.referenceType,\n },\n payload\n );\n return mismatch === null\n ? { outcome: \"replayed\", paymentRef, transaction: copyRecord(existing) }\n : { outcome: \"conflict\", paymentRef, existing: copyRecord(existing), mismatch };\n }\n }\n\n // After the reference check, never before it: a replay or a conflict must\n // write nothing, including the account row this creates. An absent user is\n // created at tier defaults, matching the SQL adapter's `ensureUserCredits`\n // — the first credit for a not-yet-seeded user (a webhook that outran\n // provisioning) lands instead of throwing in one adapter and landing in the\n // other.\n if (!this.store.users.has(userId)) {\n const tier = getDefaultTier();\n // `seedUser`, not `await initializeUserCredits(...)`: an `await` here sat\n // between the reference check above and the transaction write below, and\n // two simultaneous first deliveries of one reference both ran through\n // that gap and both credited. The seed is synchronous so the critical\n // section stays unbroken under run-to-completion.\n this.seedUser(userId, tier, storedMonthlyLimit(getConfigMonthlyLimit(tier)));\n }\n const credits = this.store.users.get(userId)!;\n\n // Project first, mutate second. The transaction write below validates the\n // derived `newBalance`, and if that throws after the balance has already\n // moved the store is left holding half of an operation that reported\n // failure. There is no rollback here, so nothing may change until every\n // derived value is known to be storable.\n const previousTotal = sumAmounts(credits.balance, credits.bonusCredits);\n const nextBonusCredits = sumAmounts(credits.bonusCredits, amount);\n const newTotal = sumAmounts(credits.balance, nextBonusCredits);\n assertRepresentableFields(\n { previousBalance: previousTotal, bonusCredits: nextBonusCredits, newBalance: newTotal },\n { userId, operation: \"addCredits\" }\n );\n\n credits.bonusCredits = nextBonusCredits;\n credits.updatedAt = new Date().toISOString();\n this.store.users.set(userId, credits);\n\n // Recorded through the internal writer: the public `createTransaction`\n // refuses a `paymentRef` precisely so that only this path — which moved the\n // balance above — can claim one.\n const transaction = this.recordTransaction({\n userId,\n type: \"purchase\",\n amount,\n description,\n paymentRef,\n previousBalance: previousTotal,\n newBalance: newTotal,\n });\n\n // Journal entry (parity with the Drizzle adapter): a single journal can then\n // serve as the app's credit ledger, including revenue-attribution metadata.\n const journalMetadata = {\n ...(paymentRef ? { paymentRef } : {}),\n ...(options?.metadata ?? {}),\n };\n const entry = await this.createJournalEntry({\n userId,\n entryType: \"credit\",\n amount,\n balanceAfter: newTotal,\n source: payload.source,\n referenceId: transaction.id ?? paymentRef ?? \"unknown\",\n referenceType: payload.referenceType,\n description,\n metadata: Object.keys(journalMetadata).length > 0 ? journalMetadata : undefined,\n });\n\n return paymentRef\n ? { outcome: \"created\", paymentRef, transaction, journalEntryId: entry.id }\n : { outcome: \"created\", transaction, journalEntryId: entry.id };\n }\n\n /**\n * The legacy signature, on top of {@link addCreditsV2}.\n *\n * `Promise<void>` has nowhere to report a conflict, and silently returning is\n * indistinguishable from \"credited\" — the exact failure this round is closing\n * — so a conflict throws. A genuine replay still returns quietly, because\n * that *is* the idempotent no-op the caller asked for.\n */\n async addCreditsAtomic(\n userId: string,\n amount: number,\n description: string,\n paymentRef?: string,\n options?: AddCreditsAtomicOptions\n ): Promise<void> {\n const outcome = await this.addCreditsV2({\n userId,\n amount,\n description,\n paymentRef,\n options,\n });\n if (outcome.outcome === \"conflict\") {\n throw createPaymentRefConflictError(outcome.paymentRef, {\n userId,\n mismatch: outcome.mismatch,\n existingUserId: outcome.existing.userId,\n });\n }\n }\n\n async deductCreditsAtomic(\n userId: string,\n amount: number\n ): Promise<{ previousBalance: number; newBalance: number }> {\n // `amount > 0` alone let 1.005, Infinity and out-of-range values through to\n // arithmetic the `numeric(12, 2)` adapter could never have stored.\n assertValidCreditAmount(amount, { userId, operation: \"deductCredits\" });\n\n const credits = this.store.users.get(userId);\n if (!credits) {\n throw new Error(`User credits not found for userId: ${userId}`);\n }\n\n const available = sumAmounts(credits.balance, credits.bonusCredits, -credits.reserved);\n if (available < amount) {\n throw new Error(\n `Insufficient credits. Available: ${available}, requested: ${amount}`\n );\n }\n\n // Drain balance first, then bonusCredits — same policy as commit.\n const balanceDeduction = Math.min(credits.balance, amount);\n const bonusDeduction = sumAmounts(amount, -balanceDeduction);\n\n // Projected and checked before anything moves, for the same reason as\n // `addCreditsAtomic`: there is no rollback in this store.\n const previousBalance = sumAmounts(credits.balance, credits.bonusCredits);\n const nextBalance = sumAmounts(credits.balance, -balanceDeduction);\n const nextBonusCredits = sumAmounts(credits.bonusCredits, -bonusDeduction);\n const newBalance = sumAmounts(previousBalance, -amount);\n assertRepresentableFields(\n { previousBalance, balance: nextBalance, bonusCredits: nextBonusCredits, newBalance },\n { userId, operation: \"deductCredits\" }\n );\n\n credits.balance = nextBalance;\n credits.bonusCredits = nextBonusCredits;\n credits.updatedAt = new Date().toISOString();\n this.store.users.set(userId, credits);\n\n return { previousBalance, newBalance };\n }\n\n // ==================== Transactions ====================\n\n async createTransaction(input: CreateTransactionInput): Promise<PortableTransaction> {\n // A record with a `paymentRef` would occupy the global payment boundary\n // without crediting anyone — a later addCredits with the same reference\n // then reports `replayed` and credits nothing. Referenced payments go\n // through addCredits; see `assertUnreferencedDirectTransaction`.\n assertUnreferencedDirectTransaction(input);\n // Always absent after the guard; spelled as the normalised value so a blank\n // string is stored as \"no reference\", matching the SQL adapter.\n return this.recordTransaction({\n ...input,\n paymentRef: normalizePaymentRef(input.paymentRef),\n });\n }\n\n /** The unguarded writer, for `addCreditsV2` — which has moved the balance. */\n private recordTransaction(input: CreateTransactionInput): PortableTransaction {\n // Ledger records, not movements: a correction may be negative and a balance\n // may be below zero, so these check what `numeric(12, 2)` can hold.\n assertRepresentableAmount(input.amount, \"transaction amount\", { userId: input.userId });\n assertRepresentableAmount(input.previousBalance, \"transaction previousBalance\", {\n userId: input.userId,\n });\n assertRepresentableAmount(input.newBalance, \"transaction newBalance\", {\n userId: input.userId,\n });\n\n const transaction: PortableTransaction = {\n id: generateId(),\n userId: input.userId,\n type: input.type,\n amount: input.amount,\n description: input.description,\n paymentRef: input.paymentRef,\n previousBalance: input.previousBalance,\n newBalance: input.newBalance,\n createdAt: new Date().toISOString(),\n };\n\n if (!this.store.transactions.has(input.userId)) {\n this.store.transactions.set(input.userId, []);\n }\n this.store.transactions.get(input.userId)!.push(transaction);\n\n return copyRecord(transaction);\n }\n\n async getTransactions(\n userId: string,\n limit = 50,\n offset = 0\n ): Promise<PortableTransaction[]> {\n const userTransactions = this.store.transactions.get(userId) ?? [];\n // Sort by createdAt descending (most recent first)\n const sorted = [...userTransactions].sort((a, b) => {\n const aDate = toDate(a.createdAt).getTime();\n const bDate = toDate(b.createdAt).getTime();\n return bDate - aDate;\n });\n return copyRecords(sorted.slice(offset, offset + limit));\n }\n\n // ==================== Usage Logs ====================\n\n async logUsage(input: CreateUsageLogInput): Promise<PortableUsageLog> {\n assertRepresentableAmount(input.creditsUsed, \"creditsUsed\", { userId: input.userId });\n\n const log: PortableUsageLog = {\n id: generateId(),\n userId: input.userId,\n operationType: input.operationType,\n provider: input.provider,\n creditsUsed: input.creditsUsed,\n success: input.success,\n errorMessage: input.errorMessage,\n resourceId: input.resourceId,\n resourceType: input.resourceType,\n requestId: input.requestId,\n metadata: input.metadata ? { ...input.metadata } : input.metadata,\n createdAt: new Date().toISOString(),\n };\n\n this.store.usageLogs.push(log);\n return copyRecord(log);\n }\n\n async getUsageLogs(query: UsageLogQuery): Promise<PortableUsageLog[]> {\n let results = [...this.store.usageLogs];\n\n // Apply filters\n if (query.userId) {\n results = results.filter((log) => log.userId === query.userId);\n }\n if (query.operationType) {\n results = results.filter((log) => log.operationType === query.operationType);\n }\n if (query.success !== undefined) {\n results = results.filter((log) => log.success === query.success);\n }\n if (query.startDate) {\n const startTime = query.startDate.getTime();\n results = results.filter(\n (log) => toDate(log.createdAt).getTime() >= startTime\n );\n }\n if (query.endDate) {\n const endTime = query.endDate.getTime();\n results = results.filter(\n (log) => toDate(log.createdAt).getTime() <= endTime\n );\n }\n\n // Sort by createdAt descending\n results.sort((a, b) => {\n return toDate(b.createdAt).getTime() - toDate(a.createdAt).getTime();\n });\n\n // Apply pagination\n const offset = query.offset ?? 0;\n const limit = query.limit ?? 50;\n return copyRecords(results.slice(offset, offset + limit));\n }\n\n async getUsageLogsCount(\n query: Omit<UsageLogQuery, \"limit\" | \"offset\">\n ): Promise<number> {\n const results = await this.getUsageLogs({ ...query, limit: Infinity, offset: 0 });\n return results.length;\n }\n\n // ==================== Journal Entries ====================\n\n async createJournalEntry(input: CreateJournalEntryInput): Promise<PortableJournalEntry> {\n return this.recordJournalEntry(input);\n }\n\n /**\n * The synchronous body of `createJournalEntry`, so `atomicMonthlyReset` can\n * write its journal line inside the same run-to-completion step as the\n * balance write — an `await` between the two is exactly the gap that loses\n * the line when the second half fails.\n */\n private recordJournalEntry(input: CreateJournalEntryInput): PortableJournalEntry {\n assertRepresentableAmount(input.amount, \"journal amount\", { userId: input.userId });\n assertRepresentableAmount(input.balanceAfter, \"journal balanceAfter\", {\n userId: input.userId,\n });\n assertValidIdempotencyKey(input.idempotencyKey, { userId: input.userId });\n assertPublicJournalKey(input.idempotencyKey, input.userId);\n\n // The SQL adapter has a partial unique index on `(user_id, idempotency_key)`.\n // Without the equivalent here, a key written through this public method was\n // invisible to the V2 transitions, which would then happily write a *second*\n // row under the same deterministic key — the ledger would record one event\n // twice and the two adapters would disagree about what happened.\n const key =\n input.idempotencyKey !== undefined\n ? scopedKey(input.userId, input.idempotencyKey)\n : undefined;\n if (key !== undefined && this.store.journalKeys.has(key)) {\n throw new CreditError(\n `Journal idempotency key ${input.idempotencyKey} is already used for user ` +\n `${input.userId}. The unique constraint refuses a second entry.`,\n CreditErrorCode.DATABASE_ERROR,\n { userId: input.userId, idempotencyKey: input.idempotencyKey }\n );\n }\n\n const entry: PortableJournalEntry = {\n id: generateId(),\n userId: input.userId,\n entryType: input.entryType,\n amount: input.amount,\n balanceAfter: input.balanceAfter,\n source: input.source,\n referenceId: input.referenceId,\n referenceType: input.referenceType,\n description: input.description,\n metadata: input.metadata ? { ...input.metadata } : input.metadata,\n idempotencyKey: input.idempotencyKey,\n createdAt: new Date().toISOString(),\n };\n\n if (!this.store.journalEntries.has(input.userId)) {\n this.store.journalEntries.set(input.userId, []);\n }\n this.store.journalEntries.get(input.userId)!.push(entry);\n if (key !== undefined) this.store.journalKeys.set(key, entry.id);\n\n return copyRecord(entry);\n }\n\n async getJournalEntries(query: JournalEntryQuery): Promise<PortableJournalEntry[]> {\n let results = this.store.journalEntries.get(query.userId) ?? [];\n\n // Apply filters\n if (query.source) {\n results = results.filter((entry) => entry.source === query.source);\n }\n if (query.referenceType) {\n results = results.filter((entry) => entry.referenceType === query.referenceType);\n }\n if (query.startDate) {\n const startTime = query.startDate.getTime();\n results = results.filter(\n (entry) => toDate(entry.createdAt).getTime() >= startTime\n );\n }\n if (query.endDate) {\n const endTime = query.endDate.getTime();\n results = results.filter(\n (entry) => toDate(entry.createdAt).getTime() <= endTime\n );\n }\n\n // Sort by createdAt descending\n results = [...results].sort((a, b) => {\n return toDate(b.createdAt).getTime() - toDate(a.createdAt).getTime();\n });\n\n // Apply pagination\n const offset = query.offset ?? 0;\n const limit = query.limit ?? 50;\n return copyRecords(results.slice(offset, offset + limit));\n }\n\n async getJournalEntriesCount(\n query: Omit<JournalEntryQuery, \"limit\" | \"offset\">\n ): Promise<number> {\n const results = await this.getJournalEntries({\n ...query,\n limit: Infinity,\n offset: 0,\n });\n return results.length;\n }\n\n // ==================== Cleanup Operations ====================\n\n /**\n * Expire every hold whose deadline has passed.\n *\n * Each candidate goes through the guarded {@link expireReservationV2}, which\n * re-checks the status and the deadline under the user's lock. The previous\n * implementation released the hold and then overwrote the status to\n * `expired`, so a commit landing in between got its credits handed back and\n * was then relabelled.\n */\n async findAndExpireReservations(\n _batchSize = 100,\n _maxIterations = 100\n ): Promise<{\n expiredCount: number;\n creditsReleased: number;\n errors: string[];\n }> {\n const asOf = new Date();\n let expiredCount = 0;\n let creditsReleased = 0;\n const errors: string[] = [];\n\n // Snapshot the candidates first: expiring mutates the maps being iterated.\n const candidates: Array<{ userId: string; reservationId: string }> = [];\n for (const [userId, userReservations] of this.store.reservations) {\n for (const [reservationId, reservation] of userReservations) {\n if (\n reservation.status === \"reserved\" &&\n toDate(reservation.expiresAt).getTime() < asOf.getTime()\n ) {\n candidates.push({ userId, reservationId });\n }\n }\n }\n\n for (const candidate of candidates) {\n try {\n const outcome = await this.expireReservationV2(\n candidate.userId,\n candidate.reservationId,\n { asOf }\n );\n if (outcome.outcome === \"expired\") {\n expiredCount++;\n creditsReleased = sumAmounts(creditsReleased, outcome.amount);\n }\n } catch (error) {\n errors.push(\n `Failed to expire reservation ${candidate.reservationId}: ${error}`\n );\n }\n }\n\n return { expiredCount, creditsReleased, errors };\n }\n\n // ==================== Atomic Monthly Reset ====================\n\n async atomicMonthlyReset(\n userId: string,\n tier: SubscriptionTier,\n expectedResetAt: Date | string\n ): Promise<MonthlyResetResult> {\n const credits = this.store.users.get(userId);\n if (!credits) {\n throw new Error(`User ${userId} not found`);\n }\n\n // Optimistic locking: check if expectedResetAt matches current value\n const currentResetAt = toDate(credits.monthlyResetAt).getTime();\n const expected = toDate(expectedResetAt).getTime();\n\n if (currentResetAt !== expected) {\n // Another request already performed the reset\n return { wasReset: false, credits: { ...credits } };\n }\n\n // Perform the reset\n assertRepresentableTierAmount(getConfigMonthlyLimit(tier), \"monthlyLimit\", { userId, tier });\n const nextReset = getNextMonthlyReset();\n\n // The unlimited contract, from the one place that defines it. This used to\n // read `newBalance === Infinity ? credits.balance : newBalance` — \"leave an\n // unlimited balance alone\" — which never restored an unlimited account whose\n // balance had been driven to zero. See `monthlyResetBalance`.\n // Floored at what still backs the outstanding holds: a reset that cut\n // `balance + bonusCredits` below `reserved` would strand every live\n // reservation at commit time with INSUFFICIENT_CREDITS. See\n // `backedBalanceFloor`.\n const target = monthlyResetBalance(tier);\n const floor = backedBalanceFloor(credits.reserved, credits.bonusCredits);\n const previousBalance = credits.balance;\n const newBalance =\n target.kind === \"atLeast\"\n ? Math.max(credits.balance, target.value, floor)\n : Math.max(target.value, floor);\n\n // The journal line is part of the reset, not a follow-up. It is validated\n // before anything mutates and written synchronously after, so no failure or\n // interleaving can consume the CAS and lose the line — which is exactly\n // what happened when the service wrote it as a separate call: the retry saw\n // `wasReset: false` and the reset entry was gone for good.\n const change = sumAmounts(newBalance, -previousBalance);\n const balanceAfter = sumAmounts(newBalance, credits.bonusCredits);\n assertRepresentableAmount(Math.abs(change), \"journal amount\", { userId });\n assertRepresentableAmount(balanceAfter, \"journal balanceAfter\", { userId });\n\n credits.balance = newBalance;\n credits.monthlyUsed = 0;\n credits.monthlyResetAt = nextReset.toISOString();\n credits.updatedAt = new Date().toISOString();\n this.store.users.set(userId, credits);\n\n if (change !== 0) {\n this.recordJournalEntry({\n userId,\n entryType: change > 0 ? \"credit\" : \"debit\",\n amount: Math.abs(change),\n balanceAfter,\n source: \"monthly_reset\",\n referenceId: `reset-${Date.now()}`,\n referenceType: \"reset\",\n description: `Monthly credit reset for ${tier} tier.`,\n metadata: { tier, previousBalance, newBalance },\n });\n }\n\n return { wasReset: true, credits: { ...credits }, journaled: true };\n }\n\n // ==================== Subscription Expiry ====================\n\n async checkAndHandleSubscriptionExpiry(\n userId: string,\n gracePeriodDays = 3\n ): Promise<SubscriptionExpiryResult> {\n const credits = this.store.users.get(userId);\n if (!credits) {\n throw new Error(`User ${userId} not found`);\n }\n\n // Free tier doesn't expire\n if (isFreeTier(credits.tier) || !credits.subscriptionExpiresAt) {\n return {\n wasDowngraded: false,\n inGracePeriod: false,\n graceDaysRemaining: 0,\n credits: { ...credits },\n };\n }\n\n const now = new Date();\n const expiresAt = toDate(credits.subscriptionExpiresAt);\n const daysSinceExpiry =\n (now.getTime() - expiresAt.getTime()) / (1000 * 60 * 60 * 24);\n\n if (daysSinceExpiry <= 0) {\n // Not expired yet\n return {\n wasDowngraded: false,\n inGracePeriod: false,\n graceDaysRemaining: 0,\n credits: { ...credits },\n };\n }\n\n if (daysSinceExpiry <= gracePeriodDays) {\n // In grace period\n return {\n wasDowngraded: false,\n inGracePeriod: true,\n graceDaysRemaining: Math.ceil(gracePeriodDays - daysSinceExpiry),\n credits: { ...credits },\n };\n }\n\n // Grace period expired - downgrade to the configured default tier\n const defaultTier = getDefaultTier();\n // `getConfigMonthlyLimit`, not the raw `monthlyCredits`: in tier *config*\n // zero means unlimited, so reading the field directly would downgrade onto\n // an unlimited default tier with a limit and a balance of zero.\n const configured = getConfigMonthlyLimit(defaultTier);\n assertRepresentableTierAmount(configured, \"monthlyLimit\", {\n userId,\n tier: defaultTier,\n });\n const limit = storedMonthlyLimit(configured);\n\n // The downgrade may cut the balance to the new tier's limit, but never\n // below what still backs the outstanding holds — see `backedBalanceFloor`.\n const previousTier = credits.tier;\n const previousBalance = credits.balance;\n const newBalance = Math.max(\n Math.min(credits.balance, limit),\n backedBalanceFloor(credits.reserved, credits.bonusCredits)\n );\n\n // The journal line is part of the downgrade, not a follow-up: validated\n // before anything mutates, written synchronously after. Written separately\n // by the service, a failure landed after the tier write, and no retry ever\n // fired again — the row was no longer eligible, the audit line gone.\n const balanceAfter = sumAmounts(newBalance, credits.bonusCredits);\n assertRepresentableAmount(balanceAfter, \"journal balanceAfter\", { userId });\n\n credits.tier = defaultTier;\n credits.monthlyLimit = limit;\n credits.balance = newBalance;\n credits.subscriptionExpiresAt = null;\n credits.updatedAt = new Date().toISOString();\n this.store.users.set(userId, credits);\n\n this.recordJournalEntry({\n userId,\n entryType: \"debit\",\n amount: 0, // No credits deducted, just tier change\n balanceAfter,\n source: \"subscription_downgrade\",\n referenceId: `downgrade-${Date.now()}`,\n referenceType: \"subscription\",\n description: `Subscription expired. Downgraded from ${previousTier} to ${defaultTier} tier.`,\n metadata: { previousTier, previousBalance, newBalance },\n });\n\n return {\n wasDowngraded: true,\n inGracePeriod: false,\n graceDaysRemaining: 0,\n credits: { ...credits },\n journaled: true,\n };\n }\n\n // ==================== Testing Utilities ====================\n\n /**\n * Clear all data (useful for testing)\n */\n clear(): void {\n this.store.clear();\n }\n\n /**\n * Install a yield point inside every V2 critical section (testing only).\n *\n * Unset, the critical sections run start-to-finish synchronously, so\n * concurrent callers never interleave and a concurrency test would pass even\n * with the locking removed. Setting this to a real yield (a macrotask or a\n * barrier) makes callers genuinely overlap, so the tests exercise the lock\n * instead of the event loop. Never call this in production code.\n */\n setSchedulingHook(hook: (() => Promise<void>) | undefined): void {\n this.store.schedulingHook = hook;\n }\n\n /**\n * Get all users (useful for testing/debugging)\n */\n getAllUsers(): PortableUserCredits[] {\n return copyRecords(Array.from(this.store.users.values()));\n }\n\n /**\n * Get all reservations for a user (useful for testing)\n */\n getAllReservations(userId: string): PortableReservation[] {\n const userReservations = this.store.reservations.get(userId);\n if (!userReservations) return [];\n return copyRecords(Array.from(userReservations.values()));\n }\n}\n\n/**\n * Create a new in-memory repository instance\n * Each call creates a fresh, isolated instance\n */\nexport function createInMemoryCreditRepository(): InMemoryCreditRepository {\n return new InMemoryCreditRepository();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC0dO,SAAS,kBACd,YACuD;AACvD,SACE,OAAO,WAAW,qBAAqB,cACvC,OAAO,WAAW,wBAAwB,cAC1C,OAAO,WAAW,yBAAyB,cAC3C,OAAO,WAAW,wBAAwB;AAE9C;AAUO,SAAS,yBACd,YAC8D;AAC9D,SAAO,OA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B;AAAA,MACpB,SAAS,EAAE,GAAG,QAAQ;AAAA,MACtB,WAAW;AAAA,IACb;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,QAAc;AACZ,SAAK,MAAM,MAAM;AAAA,EACnB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,kBAAkB,MAA+C;AAC/D,SAAK,MAAM,iBAAiB;AAAA,EAC9B;AAAA;AAAA;AAAA;AAAA,EAKA,cAAqC;AACnC,WAAO,YAAY,MAAM,KAAK,KAAK,MAAM,MAAM,OAAO,CAAC,CAAC;AAAA,EAC1D;AAAA;AAAA;AAAA;AAAA,EAKA,mBAAmB,QAAuC;AACxD,UAAM,mBAAmB,KAAK,MAAM,aAAa,IAAI,MAAM;AAC3D,QAAI,CAAC,iBAAkB,QAAO,CAAC;AAC/B,WAAO,YAAY,MAAM,KAAK,iBAAiB,OAAO,CAAC,CAAC;AAAA,EAC1D;AACF;AAMO,SAAS,iCAA2D;AACzE,SAAO,IAAI,yBAAyB;AACtC;","names":["cents","terminalStatusOf"]}
1
+ {"version":3,"sources":["../../src/repository/index.ts","../../src/repository/types.ts","../../src/core/amount.ts","../../src/core/errors.ts","../../src/core/idempotency.ts","../../src/repository/v2-types.ts","../../src/config/index.ts","../../src/config/provider.ts","../../src/core/payment-ref.ts","../../src/repository/flow.ts","../../src/repository/utils.ts","../../src/repository/memory/snapshot.ts","../../src/core/reservation-integrity.ts","../../src/repository/memory/mutex.ts","../../src/repository/memory/store.ts","../../src/repository/memory/transition-journal.ts","../../src/repository/memory/v2.ts","../../src/repository/memory/index.ts"],"sourcesContent":["/**\r\n * Credits repository - barrel exports\r\n *\r\n * Provides database-agnostic interface for credits storage\r\n */\r\n\r\n// Types and interfaces\r\nexport type {\r\n ICreditRepository,\r\n CreditRepositoryFactory,\r\n CreateReservationInput,\r\n CreateTransactionInput,\r\n CreateUsageLogInput,\r\n CreateJournalEntryInput,\r\n UsageLogQuery,\r\n JournalEntryQuery,\r\n CreditBalanceUpdate,\r\n TierUpdateInput,\r\n AddCreditsAtomicOptions,\r\n} from \"./types.js\";\r\n\r\nexport {\r\n toClientUserCredits,\r\n supportsCreditsV2,\r\n supportsIdempotentCredit,\r\n} from \"./types.js\";\r\n\r\n// V2 boundary (idempotent, race-safe reservations)\r\nexport type {\r\n ICreditRepositoryV2,\r\n ICreditRepositoryCreditsV2,\r\n AddCreditsV2Input,\r\n ReserveCreditsV2Input,\r\n ReservationTransitionOptions,\r\n ExpireReservationV2Options,\r\n} from \"./v2-types.js\";\r\nexport { reservationJournalKey } from \"./v2-types.js\";\r\nexport {\r\n reserveThroughRepository,\r\n commitThroughRepository,\r\n releaseThroughRepository,\r\n addCreditsThroughRepository,\r\n} from \"./flow.js\";\r\n\r\n// Shared utilities\r\nexport {\r\n assertValidBalanceUpdate,\r\n generateId,\r\n toDate,\r\n getNextMonthlyReset,\r\n validateBalanceUpdate,\r\n type BalanceValidationResult,\r\n} from \"./utils.js\";\r\n\r\n// In-memory implementation (for testing and prototyping)\r\nexport {\r\n InMemoryCreditRepository,\r\n createInMemoryCreditRepository,\r\n} from \"./memory/index.js\";\r\n","import type {\r\n ICreditRepositoryCreditsV2,\r\n ICreditRepositoryV2,\r\n} from \"./v2-types.js\";\r\nimport type {\r\n PortableUserCredits,\r\n PortableReservation,\r\n PortableTransaction,\r\n PortableUsageLog,\r\n PortableJournalEntry,\r\n CreditOperationType,\r\n SubscriptionTier,\r\n ReservationStatus,\r\n AIProviderType,\r\n MonthlyResetResult,\r\n SubscriptionExpiryResult,\r\n CreditSource,\r\n JournalReferenceType,\r\n} from \"../core/types.js\";\r\n\r\n/**\r\n * Input for creating a credit reservation\r\n */\r\nexport interface CreateReservationInput {\r\n userId: string;\r\n amount: number;\r\n operationType: CreditOperationType;\r\n expiresAt: Date;\r\n /**\r\n * @deprecated Rejected — this writer does not place the hold.\r\n *\r\n * `createReservation` inserts a row and leaves `reserved` alone, so a keyed\r\n * row written here names a hold that does not exist, and `reserveCreditsV2`\r\n * would adopt it as a `replayed` reservation whose commit then spends another\r\n * hold's coverage. Both adapters throw `UNSUPPORTED_OPERATION` when this is\r\n * set. Pass the key to `reserveCredits` / `reserveCreditsV2` instead, which\r\n * claims the key and places the hold in one transaction.\r\n *\r\n * The field is kept rather than deleted so the refusal reaches a JavaScript\r\n * caller as a typed error instead of a silently ignored property.\r\n */\r\n idempotencyKey?: string;\r\n}\r\n\r\n/**\r\n * Input for creating a credit transaction\r\n */\r\nexport interface CreateTransactionInput {\r\n userId: string;\r\n type: PortableTransaction[\"type\"];\r\n amount: number;\r\n description: string;\r\n paymentRef?: string;\r\n previousBalance: number;\r\n newBalance: number;\r\n}\r\n\r\n/**\r\n * Input for logging usage\r\n */\r\nexport interface CreateUsageLogInput {\r\n userId: string;\r\n operationType: CreditOperationType;\r\n provider: AIProviderType;\r\n creditsUsed: number;\r\n success: boolean;\r\n errorMessage?: string;\r\n resourceId?: string;\r\n resourceType?: string;\r\n requestId?: string;\r\n metadata?: Record<string, unknown>;\r\n}\r\n\r\n/**\r\n * Query options for usage logs\r\n */\r\nexport interface UsageLogQuery {\r\n userId?: string;\r\n operationType?: CreditOperationType;\r\n success?: boolean;\r\n limit?: number;\r\n offset?: number;\r\n startDate?: Date;\r\n endDate?: Date;\r\n}\r\n\r\n/**\r\n * Input for creating a journal entry\r\n */\r\nexport interface CreateJournalEntryInput {\r\n userId: string;\r\n entryType: \"debit\" | \"credit\";\r\n amount: number;\r\n balanceAfter: number;\r\n source: CreditSource;\r\n referenceId: string;\r\n referenceType: JournalReferenceType;\r\n description: string;\r\n metadata?: Record<string, unknown>;\r\n /** Deterministic key making this entry unique per user (V2, optional). */\r\n idempotencyKey?: string;\r\n}\r\n\r\n/**\r\n * Query options for journal entries\r\n */\r\nexport interface JournalEntryQuery {\r\n userId: string;\r\n source?: CreditSource;\r\n referenceType?: JournalReferenceType;\r\n limit?: number;\r\n offset?: number;\r\n startDate?: Date;\r\n endDate?: Date;\r\n}\r\n\r\n/**\r\n * Partial update for user credits balance\r\n */\r\nexport interface CreditBalanceUpdate {\r\n balance?: number;\r\n bonusCredits?: number;\r\n reserved?: number;\r\n tier?: SubscriptionTier;\r\n monthlyLimit?: number;\r\n monthlyUsed?: number;\r\n monthlyResetAt?: Date | string;\r\n subscriptionExpiresAt?: Date | string | null;\r\n /** Increment balance by this amount (alternative to absolute value) */\r\n balanceIncrement?: number;\r\n /** Increment bonusCredits by this amount (alternative to absolute value) */\r\n bonusCreditsIncrement?: number;\r\n /** Increment reserved by this amount (alternative to absolute value) */\r\n reservedIncrement?: number;\r\n /** Increment monthlyUsed by this amount */\r\n monthlyUsedIncrement?: number;\r\n}\r\n\r\n/**\r\n * Input for tier update\r\n */\r\nexport interface TierUpdateInput {\r\n tier: SubscriptionTier;\r\n monthlyLimit: number;\r\n balance?: number;\r\n /**\r\n * Atomically lowers balance to at most this, only when the account's current tier is not free.\r\n * Ignored for an account already free. Cannot be combined with `balance`.\r\n * Like every balance reduction, it stops at the credits backing outstanding holds.\r\n */\r\n balanceCap?: number;\r\n monthlyUsed?: number;\r\n subscriptionExpiresAt?: Date | string | null;\r\n}\r\n\r\n/**\r\n * Free-tier policy an application hands to a repository, for the decisions that\r\n * have to be made inside the write, from the account's current state.\r\n */\r\nexport interface CreditPolicyOptions {\r\n /**\r\n * Decides a due monthly reset, inside the reset transaction, from the account's current state.\r\n * null: no reset and no write (wasReset false, monthlyResetAt unchanged).\r\n * Takes precedence over getMonthlyLimit. monthlyLimit is written only when returned.\r\n * A throw aborts the transaction.\r\n *\r\n * Must be synchronous and free of side effects: a contended transaction runs it again.\r\n * The balance is validated, and floored at the credits backing outstanding holds.\r\n */\r\n resolveMonthlyReset?: (credits: { tier: SubscriptionTier; balance: number }) =>\r\n { balance: number; monthlyLimit?: number } | null;\r\n /**\r\n * Balance cap and monthlyLimit on a subscription-expiry downgrade.\r\n * Default: DEFAULT_FREE_CREDITS in the Firestore adapter, the default tier's\r\n * configured limit in the in-memory adapter.\r\n */\r\n getDowngradeBalanceCap?: () => number;\r\n}\r\n\r\n/**\r\n * Optional journal customization for `addCreditsAtomic`.\r\n *\r\n * By default a credit add records a journal entry with `source: \"purchase\"`,\r\n * `referenceType: \"transaction\"`, and `{ paymentRef }` metadata. These options\r\n * let callers override that — e.g. tag a signup grant as `source: \"bonus\"`, or\r\n * carry revenue-attribution fields (gross amount, credits granted) so a single\r\n * journal can serve as the app's revenue ledger.\r\n */\r\nexport interface AddCreditsAtomicOptions {\r\n /** Journal entry source (defaults to `\"purchase\"`). */\r\n source?: CreditSource;\r\n /** Journal reference type (defaults to `\"transaction\"`). */\r\n referenceType?: JournalReferenceType;\r\n /**\r\n * Extra metadata merged onto the journal entry. When `paymentRef` is present\r\n * it is merged in too (explicit keys here win on collision).\r\n */\r\n metadata?: Record<string, unknown>;\r\n}\r\n\r\n/**\r\n * Repository interface for credits database operations\r\n *\r\n * Implementations can use any database (Firestore, PostgreSQL, etc.)\r\n * All methods should handle their own error handling and transactions\r\n */\r\nexport interface ICreditRepository\r\n extends Partial<ICreditRepositoryV2>,\r\n Partial<ICreditRepositoryCreditsV2> {\r\n // ==================== User Credits ====================\r\n\r\n /**\r\n * Get user credits balance\r\n * @param userId - User ID\r\n * @returns User credits or null if not found\r\n */\r\n getUserCredits(userId: string): Promise<PortableUserCredits | null>;\r\n\r\n /**\r\n * Initialize credits for a new user\r\n * @param userId - User ID\r\n * @param tier - Initial subscription tier\r\n * @param initialBalance - Initial credit balance\r\n * @returns Initialized user credits\r\n */\r\n initializeUserCredits(\r\n userId: string,\r\n tier: SubscriptionTier,\r\n initialBalance: number\r\n ): Promise<PortableUserCredits>;\r\n\r\n /**\r\n * Update user credits balance\r\n * @param userId - User ID\r\n * @param updates - Partial updates to apply\r\n */\r\n updateUserCredits(userId: string, updates: CreditBalanceUpdate): Promise<void>;\r\n\r\n /**\r\n * Update user subscription tier\r\n * @param userId - User ID\r\n * @param input - Tier update data\r\n */\r\n updateUserTier(userId: string, input: TierUpdateInput): Promise<void>;\r\n\r\n // ==================== Reservations ====================\r\n\r\n /**\r\n * Create a reservation *record* — not a hold.\r\n *\r\n * Writes a row and leaves `reserved` untouched, so the row is not backed by\r\n * credits and no settlement path will move money for it: the commit /\r\n * release / expire transitions (legacy and V2 alike) refuse it with\r\n * `UNBACKED_RESERVATION`, and it refuses an `idempotencyKey` so it can never\r\n * be adopted as a V2 replay. Use it for imported or annotation-only records.\r\n *\r\n * To place a hold that can actually be committed, call `reserveCreditsAtomic`\r\n * or `reserveCreditsV2` — they raise `reserved` and write the row in one\r\n * atomic step.\r\n *\r\n * @param input - Reservation data\r\n * @returns Created reservation record\r\n */\r\n createReservation(input: CreateReservationInput): Promise<PortableReservation>;\r\n\r\n /**\r\n * Get a reservation by ID\r\n * @param userId - User ID\r\n * @param reservationId - Reservation ID\r\n * @returns Reservation or null\r\n */\r\n getReservation(userId: string, reservationId: string): Promise<PortableReservation | null>;\r\n\r\n /**\r\n * Annotate a reservation *record* with a status.\r\n *\r\n * Assigns a status and nothing else — no balance movement, no `reserved`\r\n * adjustment, no journal entry. It therefore refuses two writes that would\r\n * make the status lie about the ledger: any write to a row whose hold was\r\n * atomically placed (those statuses belong to commit/release/expire), and\r\n * any write back to `reserved` (nothing here re-places a hold). Rows written\r\n * by `createReservation` accept terminal statuses freely.\r\n *\r\n * @param userId - User ID\r\n * @param reservationId - Reservation ID\r\n * @param status - New status\r\n * @param completedAt - Completion timestamp\r\n */\r\n updateReservationStatus(\r\n userId: string,\r\n reservationId: string,\r\n status: ReservationStatus,\r\n completedAt?: Date\r\n ): Promise<void>;\r\n\r\n // ==================== Atomic Operations ====================\r\n\r\n /**\r\n * Reserve credits atomically (creates reservation + updates balance in transaction)\r\n * @param userId - User ID\r\n * @param amount - Credits to reserve\r\n * @param operationType - Operation type for tracking\r\n * @param expiresAt - Reservation expiry time\r\n * @returns Created reservation\r\n * @throws Error if insufficient credits\r\n */\r\n reserveCreditsAtomic(\r\n userId: string,\r\n amount: number,\r\n operationType: CreditOperationType,\r\n expiresAt: Date\r\n ): Promise<PortableReservation>;\r\n\r\n /**\r\n * Commit a reservation atomically (deducts credits + marks reservation committed)\r\n * @param userId - User ID\r\n * @param reservationId - Reservation ID\r\n * @throws Error if reservation not found or not in reserved state\r\n */\r\n commitReservationAtomic(userId: string, reservationId: string): Promise<void>;\r\n\r\n /**\r\n * Release a reservation atomically (releases reserved credits + marks reservation released)\r\n * @param userId - User ID\r\n * @param reservationId - Reservation ID\r\n */\r\n releaseReservationAtomic(userId: string, reservationId: string): Promise<void>;\r\n\r\n /**\r\n * Add credits atomically (creates transaction + updates balance)\r\n * @param userId - User ID\r\n * @param amount - Credits to add\r\n * @param description - Transaction description\r\n * @param paymentRef - Optional payment reference\r\n * @param options - Optional journal source / reference type / extra metadata\r\n * for the credit journal entry (e.g. revenue attribution fields). Lets\r\n * callers record a purchase's gross amount, a bonus/refund source, etc.,\r\n * instead of the default `source: \"purchase\"` + `{ paymentRef }` metadata.\r\n */\r\n addCreditsAtomic(\r\n userId: string,\r\n amount: number,\r\n description: string,\r\n paymentRef?: string,\r\n options?: AddCreditsAtomicOptions\r\n ): Promise<void>;\r\n\r\n /**\r\n * Deduct credits from a user's balance atomically.\r\n *\r\n * Splits the deduction across `balance` and `bonusCredits`, draining\r\n * `balance` (monthly, resets each cycle) first so persistent bonus\r\n * credits survive longer. Runs in a single atomic transaction so\r\n * concurrent deducts cannot drive either field negative.\r\n *\r\n * Callers are responsible for writing any audit record (journal /\r\n * transaction) — this method only moves credits.\r\n *\r\n * @param userId - User ID\r\n * @param amount - Credits to deduct (positive)\r\n * @returns Combined totals (balance + bonusCredits) before and after.\r\n * @throws If user has no credits doc or insufficient credits\r\n */\r\n deductCreditsAtomic(\r\n userId: string,\r\n amount: number\r\n ): Promise<{ previousBalance: number; newBalance: number }>;\r\n\r\n // ==================== Transactions ====================\r\n\r\n /**\r\n * Create a credit transaction *record* — no balance moves.\r\n *\r\n * Refuses a `paymentRef`: the reference is the global identity of a credit\r\n * event, and a record that carried one without crediting anyone would make a\r\n * later `addCredits` with the same reference report `replayed` and credit\r\n * nothing. Deliver referenced payments through `addCreditsAtomic` /\r\n * `addCreditsV2`, which claim the reference and move the balance atomically.\r\n *\r\n * @param input - Transaction data\r\n * @returns Created transaction\r\n */\r\n createTransaction(input: CreateTransactionInput): Promise<PortableTransaction>;\r\n\r\n /**\r\n * Get user's transaction history\r\n * @param userId - User ID\r\n * @param limit - Max results\r\n * @param offset - Skip results\r\n * @returns List of transactions\r\n */\r\n getTransactions(\r\n userId: string,\r\n limit?: number,\r\n offset?: number\r\n ): Promise<PortableTransaction[]>;\r\n\r\n // ==================== Usage Logs ====================\r\n\r\n /**\r\n * Log a usage event\r\n * @param input - Usage log data\r\n * @returns Created usage log\r\n */\r\n logUsage(input: CreateUsageLogInput): Promise<PortableUsageLog>;\r\n\r\n /**\r\n * Query usage logs\r\n * @param query - Query parameters\r\n * @returns List of usage logs\r\n */\r\n getUsageLogs(query: UsageLogQuery): Promise<PortableUsageLog[]>;\r\n\r\n /**\r\n * Get usage log count (for pagination)\r\n * @param query - Query parameters (without limit/offset)\r\n * @returns Count of matching logs\r\n */\r\n getUsageLogsCount(query: Omit<UsageLogQuery, \"limit\" | \"offset\">): Promise<number>;\r\n\r\n // ==================== Cleanup Operations ====================\r\n\r\n /**\r\n * Find and expire reservations past their expiration time\r\n * Used by cron job to clean up stale reservations\r\n * @param batchSize - Maximum number of reservations to process per batch (default: 100)\r\n * @param maxIterations - Maximum number of pagination iterations to prevent infinite loops (default: 100)\r\n * @returns Cleanup results with counts and errors\r\n */\r\n findAndExpireReservations(batchSize?: number, maxIterations?: number): Promise<{\r\n expiredCount: number;\r\n creditsReleased: number;\r\n errors: string[];\r\n }>;\r\n\r\n // ==================== Atomic Monthly Reset ====================\r\n\r\n /**\r\n * Atomically perform monthly reset if needed\r\n * Uses optimistic locking to prevent race conditions\r\n *\r\n * @param userId - User ID\r\n * @param tier - The tier the caller last read. Not trusted: it may be stale by the\r\n * time the write runs, so implementations must use the tier stored on the account.\r\n * @param expectedResetAt - The expected monthlyResetAt value (for optimistic locking)\r\n * @returns Result indicating whether reset was performed and updated credits\r\n */\r\n atomicMonthlyReset(\r\n userId: string,\r\n tier: SubscriptionTier,\r\n expectedResetAt: Date | string\r\n ): Promise<MonthlyResetResult>;\r\n\r\n // ==================== Subscription Expiry ====================\r\n\r\n /**\r\n * Check and handle subscription expiry with grace period\r\n * Auto-downgrades expired subscriptions after grace period\r\n *\r\n * @param userId - User ID\r\n * @param gracePeriodDays - Days to allow after expiry before downgrade (default: 3)\r\n * @returns Result indicating whether downgrade occurred\r\n */\r\n checkAndHandleSubscriptionExpiry(\r\n userId: string,\r\n gracePeriodDays?: number\r\n ): Promise<SubscriptionExpiryResult>;\r\n\r\n // ==================== Journal Entries ====================\r\n\r\n /**\r\n * Create a journal entry for audit trail\r\n * @param input - Journal entry data\r\n * @returns Created journal entry\r\n */\r\n createJournalEntry(input: CreateJournalEntryInput): Promise<PortableJournalEntry>;\r\n\r\n /**\r\n * Get journal entries for a user\r\n * @param query - Query parameters\r\n * @returns List of journal entries\r\n */\r\n getJournalEntries(query: JournalEntryQuery): Promise<PortableJournalEntry[]>;\r\n\r\n /**\r\n * Get journal entry count for pagination\r\n * @param query - Query parameters (without limit/offset)\r\n * @returns Count of matching entries\r\n */\r\n getJournalEntriesCount(query: Omit<JournalEntryQuery, \"limit\" | \"offset\">): Promise<number>;\r\n}\r\n\r\n/**\r\n * Factory type for creating repository instances\r\n */\r\nexport type CreditRepositoryFactory = () => ICreditRepository;\r\n\r\n/**\r\n * Narrow a repository to one that implements the full V2 boundary.\r\n *\r\n * V2 methods are optional on {@link ICreditRepository}, so callers that need\r\n * the idempotent/race-safe path must probe rather than assume. A repository\r\n * only counts as V2 when it implements *all four* transitions — a partial\r\n * implementation would leave one path silently unsafe.\r\n */\r\nexport function supportsCreditsV2(\r\n repository: ICreditRepository\r\n): repository is ICreditRepository & ICreditRepositoryV2 {\r\n return (\r\n typeof repository.reserveCreditsV2 === \"function\" &&\r\n typeof repository.commitReservationV2 === \"function\" &&\r\n typeof repository.releaseReservationV2 === \"function\" &&\r\n typeof repository.expireReservationV2 === \"function\"\r\n );\r\n}\r\n\r\n/**\r\n * Narrow a repository to one that credits idempotently against a `paymentRef`.\r\n *\r\n * Deliberately a separate probe from {@link supportsCreditsV2}: serialising\r\n * reservations and enforcing a global payment reference are different\r\n * guarantees resting on different database objects, and an adapter may have one\r\n * without the other.\r\n */\r\nexport function supportsIdempotentCredit(\r\n repository: ICreditRepository\r\n): repository is ICreditRepository & ICreditRepositoryCreditsV2 {\r\n return typeof repository.addCreditsV2 === \"function\";\r\n}\r\n\r\n/**\r\n * Convert PortableUserCredits to client-safe format\r\n * Utility function that implementations can use\r\n */\r\nexport function toClientUserCredits(credits: PortableUserCredits): PortableUserCredits {\r\n // Already in portable format, just ensure all timestamps are ISO strings\r\n return {\r\n userId: credits.userId,\r\n balance: credits.balance,\r\n bonusCredits: credits.bonusCredits ?? 0,\r\n reserved: credits.reserved,\r\n tier: credits.tier,\r\n monthlyLimit: credits.monthlyLimit,\r\n monthlyUsed: credits.monthlyUsed,\r\n monthlyResetAt: toISOString(credits.monthlyResetAt),\r\n subscriptionExpiresAt: credits.subscriptionExpiresAt\r\n ? toISOString(credits.subscriptionExpiresAt)\r\n : null,\r\n ...(credits.expiredHoldBacking !== undefined\r\n ? { expiredHoldBacking: credits.expiredHoldBacking }\r\n : {}),\r\n ...(credits.signupGrant !== undefined ? { signupGrant: credits.signupGrant } : {}),\r\n createdAt: toISOString(credits.createdAt),\r\n updatedAt: toISOString(credits.updatedAt),\r\n };\r\n}\r\n\r\n/**\r\n * Convert any timestamp-like value to ISO string\r\n */\r\nfunction toISOString(value: unknown): string {\r\n if (!value) return new Date().toISOString();\r\n if (typeof value === \"string\") return value;\r\n if (value instanceof Date) return value.toISOString();\r\n // Handle Firestore Timestamp-like objects\r\n if (typeof value === \"object\" && \"toDate\" in value && typeof (value as { toDate: () => Date }).toDate === \"function\") {\r\n return (value as { toDate: () => Date }).toDate().toISOString();\r\n }\r\n return new Date().toISOString();\r\n}\r\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\";\nimport type { PortableReservation } from \"./types.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 * The balance left by a cap: lowered to `cap` at most, never raised, and never\n * cut through the credits backing outstanding holds (see\n * {@link backedBalanceFloor}). A balance already under `cap` is left alone,\n * which is the point of computing this from the stored row inside a transaction\n * rather than writing a value the caller read earlier.\n */\nexport function cappedBalance(\n balance: number,\n cap: number,\n reserved: number,\n bonusCredits: number\n): number {\n return Math.min(balance, Math.max(cap, backedBalanceFloor(reserved, bonusCredits)));\n}\n\n/** A balance a lowering write lands on, and how much of it only backs holds. */\nexport interface PlannedBalance {\n balance: number;\n expiredHoldBacking: number;\n}\n\n/** The part of a balance not kept only for holds. A missing field reads as 0. */\nexport function spendableBalance(balance: number, expiredHoldBacking = 0): number {\n return sumAmounts(balance, -Math.min(expiredHoldBacking, balance));\n}\n\n/**\n * An absolute balance write: `target`, floored at what backs outstanding holds.\n * Whatever the floor kept above `target` is not the account's to spend.\n */\nexport function planBalanceTarget(\n target: number,\n reserved: number,\n bonusCredits: number\n): PlannedBalance {\n const balance = Math.max(target, backedBalanceFloor(reserved, bonusCredits));\n return { balance, expiredHoldBacking: sumAmounts(balance, -target) };\n}\n\n/**\n * A cap on the spendable part of a balance. Like {@link cappedBalance} it never\n * raises the balance and never cuts through what backs holds, and it records the\n * part kept above the cap so a later release cannot hand it back. Credits already\n * marked stay marked, so applying a cap twice changes nothing.\n */\nexport function planBalanceCap(\n balance: number,\n cap: number,\n reserved: number,\n bonusCredits: number,\n expiredHoldBacking = 0\n): PlannedBalance {\n const spendable = spendableBalance(balance, expiredHoldBacking);\n const target = Math.min(spendable, cap);\n // Marked credits belong to the holds they back. A cap adds to them when the floor\n // needs it and never takes them away, even if later bonus credits lowered the floor.\n const kept = Math.max(\n sumAmounts(balance, -spendable),\n sumAmounts(backedBalanceFloor(reserved, bonusCredits), -target)\n );\n const next = Math.min(balance, sumAmounts(target, kept));\n return { balance: next, expiredHoldBacking: Math.max(0, sumAmounts(next, -target)) };\n}\n\n/**\n * What a closing hold takes out of the credits kept only for holds: its own share\n * and nothing of another hold's. `holdBacking` comes from\n * {@link attributeExpiredBacking}.\n */\nexport function settleExpiredHoldBacking(\n balance: number,\n expiredHoldBacking: number,\n holdBacking: number\n): { used: number; remaining: number } {\n const held = Math.min(expiredHoldBacking, balance);\n const used = Math.min(held, holdBacking);\n return { used, remaining: sumAmounts(held, -used) };\n}\n\n/** The balances a commit lands on, and whether the account could pay it. */\nexport interface PlannedHoldCommit {\n covered: boolean;\n balance: number;\n bonusCredits: number;\n expiredHoldBacking: number;\n}\n\n/**\n * Pay a hold: first its own share of the marked credits, then spendable balance,\n * then bonus. Marked credits backing other holds are never touched, so what this\n * commit costs does not depend on which holds closed before it.\n */\nexport function planHoldCommit(\n balance: number,\n bonusCredits: number,\n expiredHoldBacking: number,\n holdBacking: number,\n amount: number\n): PlannedHoldCommit {\n const backing = settleExpiredHoldBacking(balance, expiredHoldBacking, holdBacking);\n const rest = sumAmounts(amount, -backing.used);\n const fromSpendable = Math.min(spendableBalance(balance, expiredHoldBacking), rest);\n const fromBonus = sumAmounts(rest, -fromSpendable);\n return {\n covered: fromBonus <= bonusCredits,\n balance: sumAmounts(balance, -backing.used, -fromSpendable),\n bonusCredits: sumAmounts(bonusCredits, -fromBonus),\n expiredHoldBacking: backing.remaining,\n };\n}\n\n/** The fields of an open hold that decide its share of the marked credits. */\nexport type ExpiredBackingHold = Pick<\n PortableReservation,\n \"id\" | \"amount\" | \"expiredBacking\" | \"holdPlacedAt\"\n>;\n\n/**\n * Split `total` marked credits across open holds, returning each hold's share.\n *\n * Shares a hold already has are kept first, oldest hold first, so lowering `total`\n * trims the newest and raising it never moves credits off a hold. Only what is left\n * goes to holds with room, again oldest first, which makes the split a function of\n * the holds and not of the order they later close in. A hold never carries more than\n * its amount. A row without `holdPlacedAt` is a record, not a hold, and gets nothing.\n *\n * The account's `expiredHoldBacking` is written as the sum of these shares, in the\n * same write, so what `total` could not attribute is not marked. Such credits stay out\n * of reach anyway, because the `reserved` that kept them still counts against them.\n */\nexport function attributeExpiredBacking(\n holds: readonly ExpiredBackingHold[],\n total: number\n): Map<string, number> {\n const placed = holds\n .filter((hold) => hold.holdPlacedAt)\n .sort((a, b) =>\n a.holdPlacedAt === b.holdPlacedAt\n ? a.id < b.id ? -1 : 1\n : (a.holdPlacedAt as string) < (b.holdPlacedAt as string) ? -1 : 1\n );\n const shares = new Map<string, number>();\n let left = total;\n for (const hold of placed) {\n const kept = Math.min(hold.expiredBacking ?? 0, hold.amount, left);\n shares.set(hold.id, kept);\n left = sumAmounts(left, -kept);\n }\n for (const hold of placed) {\n const share = shares.get(hold.id) as number;\n const added = Math.min(sumAmounts(hold.amount, -share), left);\n shares.set(hold.id, sumAmounts(share, added));\n left = sumAmounts(left, -added);\n }\n return shares;\n}\n\n/**\n * The field to write for a new backing value: nothing when it was and stays 0, so\n * an account that never had any keeps a document without the field.\n */\nexport function expiredHoldBackingPatch(\n next: number,\n stored = 0\n): { expiredHoldBacking?: number } {\n return next > 0 || stored > 0 ? { expiredHoldBacking: next } : {};\n}\n\n/**\n * Validate a balance target supplied by the application: a cap or the result of\n * a monthly-reset decision. It must be storable and cannot be negative.\n */\nexport function assertValidBalanceTarget(\n value: unknown,\n field: string,\n context?: Record<string, unknown>\n): asserts value is number {\n assertRepresentableAmount(value, field, context);\n if (value < 0) {\n throw new CreditError(\n `${field} cannot be negative (got ${value})`,\n CreditErrorCode.INVALID_AMOUNT,\n { field, value, ...context }\n );\n }\n}\n\n/**\n * Validate how a tier write changes the balance. `balance` sets a value the\n * caller computed and `balanceCap` lowers the stored value, so naming both has\n * no single meaning and is refused.\n */\nexport function assertValidTierBalanceInput(\n input: { balance?: number; balanceCap?: number },\n context?: Record<string, unknown>\n): void {\n if (input.balanceCap === undefined) return;\n if (input.balance !== undefined) {\n throw new CreditError(\n \"A tier update cannot set both balance and balanceCap\",\n CreditErrorCode.INVALID_AMOUNT,\n { balance: input.balance, balanceCap: input.balanceCap, ...context }\n );\n }\n assertValidBalanceTarget(input.balanceCap, \"balanceCap\", context);\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\";\r\n/**\r\n * Credit system error classes - framework agnostic\r\n *\r\n * Provides typed error handling for credit operations.\r\n * These errors can be used across different environments.\r\n */\r\n\r\n/**\r\n * Error codes for credit operations\r\n */\r\nexport const CreditErrorCode = {\r\n INSUFFICIENT_CREDITS: \"INSUFFICIENT_CREDITS\",\r\n RESERVATION_NOT_FOUND: \"RESERVATION_NOT_FOUND\",\r\n RESERVATION_EXPIRED: \"RESERVATION_EXPIRED\",\r\n RESERVATION_ALREADY_PROCESSED: \"RESERVATION_ALREADY_PROCESSED\",\r\n USER_NOT_FOUND: \"USER_NOT_FOUND\",\r\n INVALID_OPERATION_TYPE: \"INVALID_OPERATION_TYPE\",\r\n CONFIGURATION_ERROR: \"CONFIGURATION_ERROR\",\r\n DATABASE_ERROR: \"DATABASE_ERROR\",\r\n /** Caller reused an idempotency key with a different immutable payload. */\r\n IDEMPOTENCY_CONFLICT: \"IDEMPOTENCY_CONFLICT\",\r\n /**\r\n * Retryable infrastructure failure — serialization/deadlock, lock timeout,\r\n * connection loss, pool exhaustion. Distinct from `DATABASE_ERROR`, which is\r\n * a deterministic failure that will fail again identically on retry.\r\n */\r\n TRANSIENT_ERROR: \"TRANSIENT_ERROR\",\r\n /** The configured repository adapter does not implement the requested V2 method. */\r\n UNSUPPORTED_OPERATION: \"UNSUPPORTED_OPERATION\",\r\n /** Amount was not a finite positive number. */\r\n INVALID_AMOUNT: \"INVALID_AMOUNT\",\r\n /** Idempotency key was supplied but empty or whitespace-only. */\r\n INVALID_IDEMPOTENCY_KEY: \"INVALID_IDEMPOTENCY_KEY\",\r\n /**\r\n * A persisted reservation holds a status this library does not define, so no\r\n * transition can reason about it. Quarantined rather than cast; nothing moved.\r\n */\r\n CORRUPT_RESERVATION_STATUS: \"CORRUPT_RESERVATION_STATUS\",\r\n /**\r\n * A persisted reservation does not record that its hold was placed\r\n * atomically, so the credits it claims are not known to be reserved. Moving\r\n * it would spend another hold's coverage; nothing moved.\r\n */\r\n UNBACKED_RESERVATION: \"UNBACKED_RESERVATION\",\r\n} as const;\r\n\r\nexport type CreditErrorCodeType = (typeof CreditErrorCode)[keyof typeof CreditErrorCode];\r\n\r\n/**\r\n * Custom error class for credit operations\r\n *\r\n * Provides structured error information including:\r\n * - Error code for programmatic handling\r\n * - Human-readable message\r\n * - Optional details for debugging\r\n */\r\nexport class CreditError extends Error {\r\n public readonly code: CreditErrorCodeType;\r\n public readonly details?: Record<string, unknown>;\r\n\r\n constructor(\r\n message: string,\r\n code: CreditErrorCodeType,\r\n details?: Record<string, unknown>\r\n ) {\r\n super(message);\r\n this.name = \"CreditError\";\r\n this.code = code;\r\n this.details = details;\r\n\r\n // Maintains proper stack trace for where error was thrown\r\n if (Error.captureStackTrace) {\r\n Error.captureStackTrace(this, CreditError);\r\n }\r\n }\r\n\r\n /**\r\n * Convert to JSON-serializable object\r\n */\r\n toJSON(): { name: string; code: string; message: string; details?: Record<string, unknown> } {\r\n return {\r\n name: this.name,\r\n code: this.code,\r\n message: this.message,\r\n ...(this.details && { details: this.details }),\r\n };\r\n }\r\n}\r\n\r\n/**\r\n * Type guard to check if an error is a CreditError\r\n */\r\nexport function isCreditError(error: unknown): error is CreditError {\r\n return error instanceof CreditError;\r\n}\r\n\r\n/**\r\n * Check if an error represents insufficient credits\r\n *\r\n * Works with both CreditError and regular Error instances.\r\n * Useful for handling errors from different sources.\r\n */\r\nexport function isInsufficientCreditsError(error: unknown): boolean {\r\n if (isCreditError(error)) {\r\n return error.code === CreditErrorCode.INSUFFICIENT_CREDITS;\r\n }\r\n\r\n if (error instanceof Error) {\r\n return error.message.toLowerCase().includes(\"insufficient credits\");\r\n }\r\n\r\n return false;\r\n}\r\n\r\n/**\r\n * Create an insufficient credits error\r\n */\r\nexport function createInsufficientCreditsError(\r\n required: number,\r\n available: number\r\n): CreditError {\r\n return new CreditError(\r\n `Insufficient credits: available ${available}, required ${required}`,\r\n CreditErrorCode.INSUFFICIENT_CREDITS,\r\n { required, available, shortfall: sumAmounts(required, -available) }\r\n );\r\n}\r\n\r\n/**\r\n * Create a reservation not found error\r\n */\r\nexport function createReservationNotFoundError(reservationId: string): CreditError {\r\n return new CreditError(\r\n `Reservation ${reservationId} not found`,\r\n CreditErrorCode.RESERVATION_NOT_FOUND,\r\n { reservationId }\r\n );\r\n}\r\n\r\n/**\r\n * Create a reservation expired error\r\n */\r\nexport function createReservationExpiredError(reservationId: string): CreditError {\r\n return new CreditError(\r\n `Reservation ${reservationId} has expired`,\r\n CreditErrorCode.RESERVATION_EXPIRED,\r\n { reservationId }\r\n );\r\n}\r\n\r\n/**\r\n * Create a reservation already processed error\r\n */\r\nexport function createReservationAlreadyProcessedError(\r\n reservationId: string,\r\n status: string\r\n): CreditError {\r\n return new CreditError(\r\n `Reservation ${reservationId} has already been ${status}`,\r\n CreditErrorCode.RESERVATION_ALREADY_PROCESSED,\r\n { reservationId, status }\r\n );\r\n}\r\n\r\n/**\r\n * Create a user not found error\r\n */\r\nexport function createUserNotFoundError(userId: string): CreditError {\r\n return new CreditError(\r\n `User ${userId} not found`,\r\n CreditErrorCode.USER_NOT_FOUND,\r\n { userId }\r\n );\r\n}\r\n\r\n/**\r\n * Create an invalid operation type error\r\n */\r\nexport function createInvalidOperationTypeError(\r\n operationType: string,\r\n validTypes: string[]\r\n): CreditError {\r\n return new CreditError(\r\n `Invalid operation type: ${operationType}. Valid types: ${validTypes.join(\", \")}`,\r\n CreditErrorCode.INVALID_OPERATION_TYPE,\r\n { operationType, validTypes }\r\n );\r\n}\r\n\r\n/**\r\n * Create an idempotency conflict error\r\n *\r\n * Raised when a caller reuses an idempotency key with a different immutable\r\n * payload (different amount or operation type). This is a caller bug, never a\r\n * retryable condition — the details carry both payloads so it can be diffed.\r\n */\r\nexport function createIdempotencyConflictError(\r\n idempotencyKey: string,\r\n details?: Record<string, unknown>\r\n): CreditError {\r\n return new CreditError(\r\n `Idempotency key ${idempotencyKey} was reused with a different payload`,\r\n CreditErrorCode.IDEMPOTENCY_CONFLICT,\r\n { idempotencyKey, ...details }\r\n );\r\n}\r\n\r\n/**\r\n * Create a transient (retryable) error\r\n */\r\nexport function createTransientError(\r\n message: string,\r\n details?: Record<string, unknown>\r\n): CreditError {\r\n return new CreditError(message, CreditErrorCode.TRANSIENT_ERROR, details);\r\n}\r\n\r\n/**\r\n * Create an error for a V2 method the configured adapter does not implement\r\n */\r\nexport function createUnsupportedOperationError(\r\n operation: string,\r\n hint?: string\r\n): CreditError {\r\n return new CreditError(\r\n hint\r\n ? `Repository does not support ${operation}. ${hint}`\r\n : `Repository does not support ${operation}`,\r\n CreditErrorCode.UNSUPPORTED_OPERATION,\r\n { operation, ...(hint ? { hint } : {}) }\r\n );\r\n}\r\n\r\n/**\r\n * Create an invalid amount error\r\n */\r\nexport function createInvalidAmountError(amount: unknown): CreditError {\r\n return new CreditError(\r\n `Credit amount must be a finite positive number (got ${String(amount)})`,\r\n CreditErrorCode.INVALID_AMOUNT,\r\n { amount }\r\n );\r\n}\r\n\r\n/**\r\n * Check if an error is an idempotency conflict\r\n */\r\nexport function isIdempotencyConflictError(error: unknown): boolean {\r\n return isCreditError(error) && error.code === CreditErrorCode.IDEMPOTENCY_CONFLICT;\r\n}\r\n\r\n/**\r\n * Check if an error is safe to retry\r\n *\r\n * Only `TRANSIENT_ERROR` qualifies. Use {@link classifyDatabaseError} first to\r\n * turn a raw driver error into a classified `CreditError`.\r\n */\r\nexport function isTransientError(error: unknown): boolean {\r\n return isCreditError(error) && error.code === CreditErrorCode.TRANSIENT_ERROR;\r\n}\r\n","/**\r\n * Validation for caller-supplied idempotency keys.\r\n *\r\n * The keys are enforced by a *partial* unique index (`WHERE idempotency_key IS\r\n * NOT NULL`), so \"no key\" and \"a key\" are genuinely different states and the\r\n * boundary between them has to be unambiguous. An empty string sat in between:\r\n * the SQL adapter stored it — occupying a row in the unique index — while every\r\n * `if (key)` check read it as absent, so the key was written but never\r\n * deduplicated anything, and the in-memory adapter ignored it outright. Two\r\n * adapters, two behaviours, neither of them the one the caller asked for.\r\n *\r\n * Rejecting is preferred over trimming. Normalising `\" job-1 \"` to `\"job-1\"`\r\n * would mean two callers who sent different strings silently share a hold, and\r\n * a caller whose key is accidentally whitespace would rather hear about it than\r\n * have it quietly repaired.\r\n */\r\n\r\nimport { CreditError, CreditErrorCode } from \"./errors.js\";\r\n\r\n/** A usable key: a string with at least one non-whitespace character. */\r\nexport function isValidIdempotencyKey(value: unknown): value is string {\r\n return typeof value === \"string\" && value.trim().length > 0;\r\n}\r\n\r\n/**\r\n * Reject an unusable idempotency key before anything is written.\r\n *\r\n * `undefined` is allowed and means \"no key\" — that is the legacy, at-least-once\r\n * behaviour, and it is a valid choice. Only a key that was *supplied* and\r\n * cannot work is an error.\r\n */\r\nexport function assertValidIdempotencyKey(\r\n value: unknown,\r\n context?: Record<string, unknown>\r\n): asserts value is string | undefined {\r\n if (value === undefined || value === null) return;\r\n if (isValidIdempotencyKey(value)) return;\r\n throw new CreditError(\r\n typeof value === \"string\"\r\n ? \"An idempotency key was supplied but is empty or whitespace-only. It \" +\r\n \"cannot deduplicate anything, so it was rejected rather than stored \" +\r\n \"as a key that never matches. Omit the key for at-least-once \" +\r\n \"behaviour, or send a meaningful one.\"\r\n : `Idempotency key must be a string (got ${typeof value})`,\r\n CreditErrorCode.INVALID_IDEMPOTENCY_KEY,\r\n { idempotencyKey: value, ...context }\r\n );\r\n}\r\n\r\n/**\r\n * Namespace the V2 reservation transitions own. Public writes may not use it.\r\n *\r\n * A transition that finds its deterministic key already present treats an\r\n * exactly-matching row as its own retry and reuses it. That is correct against\r\n * a row the transition itself wrote — and a hole if any caller can write one.\r\n * A caller who pre-seeds `reservation:<id>:commit` with a plausible-looking\r\n * entry would have the commit adopt it: the reservation flips to committed and\r\n * the balance moves, while the only journal row is the caller's, never written\r\n * by the transition and not necessarily describing what it did.\r\n *\r\n * Reserving the prefix removes the premise. Nothing outside the transitions can\r\n * create a key in it, so an existing key is either the transition's own retry\r\n * or corruption — and corruption is refused.\r\n */\r\nexport const RESERVED_JOURNAL_KEY_PREFIX = \"reservation:\";\r\n\r\n/** True when a key belongs to the namespace the V2 transitions own. */\r\nexport function isReservedJournalKey(key: unknown): boolean {\r\n return typeof key === \"string\" && key.startsWith(RESERVED_JOURNAL_KEY_PREFIX);\r\n}\r\n\r\n/**\r\n * Refuse a public journal write that claims a key in the reserved namespace.\r\n *\r\n * Called from the adapters' public `createJournalEntry`, never from the\r\n * transitions themselves — they are the ones the namespace belongs to.\r\n */\r\nexport function assertPublicJournalKey(key: unknown, userId: string): void {\r\n if (!isReservedJournalKey(key)) return;\r\n throw new CreditError(\r\n `Idempotency keys starting with \"${RESERVED_JOURNAL_KEY_PREFIX}\" are reserved for ` +\r\n 'the V2 reservation transitions and cannot be written directly. Use a key of ' +\r\n 'your own, or commit/release/expire the reservation through the V2 methods.',\r\n CreditErrorCode.INVALID_IDEMPOTENCY_KEY,\r\n { userId, idempotencyKey: key, reason: \"reserved_namespace\" }\r\n );\r\n}\r\n","/**\r\n * Inputs for the V2 reservation boundary.\r\n *\r\n * V2 is additive: every method is optional on {@link ICreditRepository} so\r\n * existing adapters keep compiling and keep working through the legacy\r\n * `*Atomic` methods. Adapters that implement V2 must satisfy the contract\r\n * documented on {@link ICreditRepositoryV2}.\r\n */\r\n\r\nimport type { CreditOperationType } from \"../core/types.js\";\r\nimport type {\r\n AddCreditsOutcome,\r\n CommitOutcome,\r\n ExpireOutcome,\r\n ReleaseOutcome,\r\n ReserveOutcome,\r\n} from \"../core/outcomes.js\";\r\nimport { RESERVED_JOURNAL_KEY_PREFIX } from \"../core/idempotency.js\";\r\nimport type { AddCreditsAtomicOptions } from \"./types.js\";\r\n\r\n/**\r\n * Input for `reserveCreditsV2`.\r\n *\r\n * `userId`, `amount` and `operationType` form the immutable payload bound to\r\n * `idempotencyKey`: replaying the same key with the same payload returns the\r\n * original reservation, replaying it with a different one is a conflict.\r\n * `expiresAt` is deliberately *not* part of the payload — a retry naturally\r\n * computes a later deadline and that must not be treated as a conflict.\r\n */\r\nexport interface ReserveCreditsV2Input {\r\n userId: string;\r\n amount: number;\r\n operationType: CreditOperationType;\r\n expiresAt: Date;\r\n /**\r\n * Caller-supplied key, unique per user. Omit it to get legacy\r\n * (non-idempotent) reserve semantics — every call mints a new hold.\r\n */\r\n idempotencyKey?: string;\r\n}\r\n\r\n/** Optional journal customisation for a V2 state transition. */\r\nexport interface ReservationTransitionOptions {\r\n /** Overrides the generated journal description. */\r\n description?: string;\r\n /** Merged onto the journal entry's metadata. */\r\n metadata?: Record<string, unknown>;\r\n}\r\n\r\n/** Options for `expireReservationV2`. */\r\nexport interface ExpireReservationV2Options extends ReservationTransitionOptions {\r\n /**\r\n * Sweep timestamp. A reservation only expires when `expiresAt <= asOf`;\r\n * otherwise the outcome is `not_due`. Defaults to now.\r\n */\r\n asOf?: Date;\r\n}\r\n\r\n/**\r\n * The V2 surface. Every method must:\r\n *\r\n * 1. run in a single database transaction;\r\n * 2. take row locks in a consistent order — reservation first, then balance —\r\n * so concurrent transitions cannot deadlock;\r\n * 3. transition status with a compare-and-set (`WHERE status = 'reserved'`)\r\n * and report the loser truthfully instead of silently succeeding;\r\n * 4. mutate balances with column expressions, never with values read earlier\r\n * in the transaction;\r\n * 5. write at most one journal entry, inside the same transaction, keyed so a\r\n * retry cannot duplicate it;\r\n * 6. perform no callbacks and no network I/O inside the transaction.\r\n */\r\nexport interface ICreditRepositoryV2 {\r\n reserveCreditsV2(input: ReserveCreditsV2Input): Promise<ReserveOutcome>;\r\n\r\n commitReservationV2(\r\n userId: string,\r\n reservationId: string,\r\n options?: ReservationTransitionOptions\r\n ): Promise<CommitOutcome>;\r\n\r\n releaseReservationV2(\r\n userId: string,\r\n reservationId: string,\r\n options?: ReservationTransitionOptions\r\n ): Promise<ReleaseOutcome>;\r\n\r\n expireReservationV2(\r\n userId: string,\r\n reservationId: string,\r\n options?: ExpireReservationV2Options\r\n ): Promise<ExpireOutcome>;\r\n}\r\n\r\n/** Input for `addCreditsV2`. */\r\nexport interface AddCreditsV2Input {\r\n userId: string;\r\n amount: number;\r\n description: string;\r\n /**\r\n * Global idempotency key for the credit event. Empty and whitespace-only\r\n * strings normalise to \"no reference\" — see `normalizePaymentRef`.\r\n */\r\n paymentRef?: string;\r\n options?: AddCreditsAtomicOptions;\r\n}\r\n\r\n/**\r\n * The idempotent credit surface, separate from {@link ICreditRepositoryV2}.\r\n *\r\n * It is its own interface with its own probe because the two capabilities are\r\n * genuinely independent: an adapter can serialise reservations without having a\r\n * unique index over `payment_ref`, and folding this into the reservation probe\r\n * would make `supportsCreditsV2` narrow third-party adapters to a method they\r\n * never wrote.\r\n *\r\n * An implementation must:\r\n *\r\n * 1. run in a single transaction;\r\n * 2. resolve a non-empty reference to exactly one of `created` / `replayed` /\r\n * `conflict`, comparing the canonical payload — not merely the reference's\r\n * presence — before reporting a replay;\r\n * 3. write nothing at all on `replayed` or `conflict`;\r\n * 4. enforce the reference *globally*, so the same reference cannot credit two\r\n * different users;\r\n * 5. fail closed if the uniqueness it relies on is not actually in place.\r\n */\r\nexport interface ICreditRepositoryCreditsV2 {\r\n addCreditsV2(input: AddCreditsV2Input): Promise<AddCreditsOutcome>;\r\n}\r\n\r\n/**\r\n * Deterministic journal key for a reservation transition.\r\n *\r\n * Derived purely from the reservation id and the transition, so a retried\r\n * commit computes the same key and collides with the first entry on the\r\n * journal's partial unique index instead of writing a second row.\r\n */\r\nexport function reservationJournalKey(\r\n reservationId: string,\r\n transition: \"commit\" | \"release\" | \"expire\"\r\n): string {\r\n return `${RESERVED_JOURNAL_KEY_PREFIX}${reservationId}:${transition}`;\r\n}\r\n","import { z } from \"zod\";\r\nimport type { SubscriptionTier, TierConfig } from \"../core/types.js\";\r\nimport { getConfigProvider } from \"./provider.js\";\r\n\r\n/**\r\n * Schema for tier configuration\r\n */\r\nconst tierConfigSchema = z.object({\r\n tier: z.string().min(1),\r\n monthlyCredits: z.number().min(0),\r\n priceUsd: z.number().min(0),\r\n features: z.array(z.string()),\r\n isFree: z.boolean().optional(),\r\n unlimited: z.boolean().optional(),\r\n isDefault: z.boolean().optional(),\r\n});\r\n\r\n/**\r\n * Schema for credit system configuration\r\n */\r\nconst creditSystemConfigSchema = z.object({\r\n /**\r\n * Operation costs in credits\r\n * Keys are operation type names (any non-empty string)\r\n * Values are non-negative numbers representing credit cost. 0 marks a free\r\n * operation: `withCredits` runs it without touching the ledger. Amounts that\r\n * move credits stay strictly positive, so `reserveCredits` refuses a 0.\r\n */\r\n operationCosts: z.record(\r\n z.string().min(1),\r\n z.number().nonnegative()\r\n ),\r\n\r\n /**\r\n * Display labels for operation types (English canonical labels).\r\n * Falls back to auto-generating from snake_case keys if not provided.\r\n */\r\n operationLabels: z.record(\r\n z.string().min(1),\r\n z.string().min(1)\r\n ).optional().default({}),\r\n\r\n /**\r\n * Tier configurations\r\n */\r\n tierConfigs: z.record(\r\n z.string().min(1),\r\n tierConfigSchema\r\n ),\r\n\r\n /**\r\n * Reservation expiry time in milliseconds\r\n */\r\n reservationExpiryMs: z.number().positive().default(5 * 60 * 1000),\r\n\r\n /**\r\n * Default credits for new users (free tier). 0 means no signup grant.\r\n */\r\n defaultFreeCredits: z.number().min(0).default(25),\r\n\r\n /**\r\n * Grace period in days after subscription expires before downgrade\r\n */\r\n subscriptionGracePeriodDays: z.number().min(0).default(3),\r\n\r\n /**\r\n * Low balance notification threshold\r\n */\r\n lowBalanceThreshold: z.number().min(0).default(10),\r\n\r\n /**\r\n * Cooldown in hours between low balance notifications\r\n */\r\n lowBalanceNotificationCooldownHours: z.number().positive().default(24),\r\n\r\n /**\r\n * Feature flags for optional features\r\n */\r\n features: z.object({\r\n journalEntries: z.boolean().default(true),\r\n notifications: z.boolean().default(true),\r\n subscriptionExpiry: z.boolean().default(true),\r\n usageHistory: z.boolean().default(true),\r\n }).default({\r\n journalEntries: true,\r\n notifications: true,\r\n subscriptionExpiry: true,\r\n usageHistory: true,\r\n }),\r\n});\r\n\r\n/**\r\n * Credit system configuration type\r\n */\r\nexport type CreditSystemConfig = z.infer<typeof creditSystemConfigSchema>;\r\n\r\n/**\r\n * Default configuration\r\n */\r\nconst DEFAULT_CONFIG: CreditSystemConfig = {\r\n operationCosts: {\r\n story_generation: 5,\r\n conversation: 2,\r\n image_generation: 10,\r\n template_generation: 10,\r\n },\r\n operationLabels: {\r\n story_generation: \"Story generation\",\r\n conversation: \"Conversation\",\r\n image_generation: \"Image generation\",\r\n template_generation: \"Template generation\",\r\n },\r\n tierConfigs: {\r\n free: {\r\n tier: \"free\",\r\n monthlyCredits: 25,\r\n priceUsd: 0,\r\n isFree: true,\r\n isDefault: true,\r\n features: [\r\n \"25 credits per month\",\r\n \"Basic story generation\",\r\n \"Standard image quality\",\r\n ],\r\n },\r\n basic: {\r\n tier: \"basic\",\r\n monthlyCredits: 200,\r\n priceUsd: 9.99,\r\n features: [\r\n \"200 credits per month\",\r\n \"All story features\",\r\n \"High quality images\",\r\n \"Priority support\",\r\n ],\r\n },\r\n premium: {\r\n tier: \"premium\",\r\n monthlyCredits: 500,\r\n priceUsd: 19.99,\r\n features: [\r\n \"500 credits per month\",\r\n \"All features\",\r\n \"Highest quality images\",\r\n \"Early access to new features\",\r\n \"Priority support\",\r\n ],\r\n },\r\n unlimited: {\r\n tier: \"unlimited\",\r\n monthlyCredits: 0, // 0 = unlimited\r\n unlimited: true,\r\n priceUsd: 49.99,\r\n features: [\r\n \"Unlimited credits\",\r\n \"All features\",\r\n \"Highest quality images\",\r\n \"Early access to new features\",\r\n \"Dedicated support\",\r\n ],\r\n },\r\n },\r\n reservationExpiryMs: 5 * 60 * 1000, // 5 minutes\r\n defaultFreeCredits: 25,\r\n subscriptionGracePeriodDays: 3,\r\n lowBalanceThreshold: 10,\r\n lowBalanceNotificationCooldownHours: 24,\r\n features: {\r\n journalEntries: true,\r\n notifications: true,\r\n subscriptionExpiry: true,\r\n usageHistory: true,\r\n },\r\n};\r\n\r\n/**\r\n * Current configuration (can be overridden)\r\n */\r\nlet currentConfig: CreditSystemConfig = DEFAULT_CONFIG;\r\n\r\n/**\r\n * Load configuration from environment variables\r\n * Can be extended to load from other sources (file, remote config, etc.)\r\n *\r\n * Operation costs are loaded from CREDITS_OPERATION_COSTS as JSON:\r\n * CREDITS_OPERATION_COSTS={\"story_generation\":5,\"image_generation\":10}\r\n */\r\nexport function loadConfigFromEnv(): Partial<CreditSystemConfig> {\r\n const envConfig: Partial<CreditSystemConfig> = {};\r\n\r\n // Load operation costs from env as JSON\r\n const operationCostsEnv = process.env.CREDITS_OPERATION_COSTS;\r\n if (operationCostsEnv) {\r\n try {\r\n const parsed = JSON.parse(operationCostsEnv);\r\n if (typeof parsed === \"object\" && parsed !== null) {\r\n envConfig.operationCosts = {\r\n ...DEFAULT_CONFIG.operationCosts,\r\n ...parsed,\r\n };\r\n }\r\n } catch {\r\n console.warn(\"[Credits Config] Failed to parse CREDITS_OPERATION_COSTS env var as JSON\");\r\n }\r\n }\r\n\r\n // Load other settings from env\r\n const reservationExpiry = process.env.CREDITS_RESERVATION_EXPIRY_MS;\r\n if (reservationExpiry) {\r\n envConfig.reservationExpiryMs = parseInt(reservationExpiry, 10);\r\n }\r\n\r\n const defaultCredits = process.env.CREDITS_DEFAULT_FREE;\r\n if (defaultCredits) {\r\n envConfig.defaultFreeCredits = parseInt(defaultCredits, 10);\r\n }\r\n\r\n const gracePeriod = process.env.CREDITS_GRACE_PERIOD_DAYS;\r\n if (gracePeriod) {\r\n envConfig.subscriptionGracePeriodDays = parseInt(gracePeriod, 10);\r\n }\r\n\r\n const lowBalanceThreshold = process.env.CREDITS_LOW_BALANCE_THRESHOLD;\r\n if (lowBalanceThreshold) {\r\n envConfig.lowBalanceThreshold = parseInt(lowBalanceThreshold, 10);\r\n }\r\n\r\n // Load feature flags\r\n const featuresEnv = process.env.CREDITS_FEATURES;\r\n if (featuresEnv) {\r\n try {\r\n const features = JSON.parse(featuresEnv);\r\n envConfig.features = {\r\n ...DEFAULT_CONFIG.features,\r\n ...features,\r\n };\r\n } catch {\r\n console.warn(\"[Credits Config] Failed to parse CREDITS_FEATURES env var\");\r\n }\r\n }\r\n\r\n return envConfig;\r\n}\r\n\r\n/**\r\n * Initialize configuration\r\n * Merges default config with environment overrides\r\n */\r\nexport function initializeConfig(overrides?: Partial<CreditSystemConfig>): CreditSystemConfig {\r\n const envConfig = loadConfigFromEnv();\r\n\r\n const mergedConfig = {\r\n ...DEFAULT_CONFIG,\r\n ...envConfig,\r\n ...overrides,\r\n operationCosts: {\r\n ...DEFAULT_CONFIG.operationCosts,\r\n ...envConfig.operationCosts,\r\n ...overrides?.operationCosts,\r\n },\r\n operationLabels: {\r\n ...DEFAULT_CONFIG.operationLabels,\r\n ...envConfig.operationLabels,\r\n ...overrides?.operationLabels,\r\n },\r\n tierConfigs: {\r\n ...DEFAULT_CONFIG.tierConfigs,\r\n ...envConfig.tierConfigs,\r\n ...overrides?.tierConfigs,\r\n },\r\n features: {\r\n ...DEFAULT_CONFIG.features,\r\n ...envConfig.features,\r\n ...overrides?.features,\r\n },\r\n };\r\n\r\n // Validate configuration\r\n const result = creditSystemConfigSchema.safeParse(mergedConfig);\r\n if (!result.success) {\r\n console.error(\"[Credits Config] Invalid configuration:\", result.error.issues);\r\n throw new Error(\"Invalid credit system configuration\");\r\n }\r\n\r\n currentConfig = result.data;\r\n return currentConfig;\r\n}\r\n\r\n/**\r\n * Get the current configuration.\r\n * If an external provider is registered, delegates to it.\r\n * Otherwise falls back to the local currentConfig.\r\n */\r\nexport function getConfig(): CreditSystemConfig {\r\n const provider = getConfigProvider();\r\n if (provider) {\r\n return provider.getConfig();\r\n }\r\n return currentConfig;\r\n}\r\n\r\n/**\r\n * Get all valid operation types from configuration\r\n * Returns the keys of the operationCosts object\r\n */\r\nexport function getValidOperationTypes(): string[] {\r\n return Object.keys(getConfig().operationCosts);\r\n}\r\n\r\n/**\r\n * Check if an operation type is valid (configured in the system)\r\n * @param type - The operation type to check\r\n * @returns true if the operation type is configured\r\n */\r\nexport function isValidOperationType(type: string): boolean {\r\n return type in getConfig().operationCosts;\r\n}\r\n\r\n/**\r\n * Get operation cost from configuration\r\n * @throws Error if the operation type is not configured\r\n */\r\nexport function getConfigOperationCost(operationType: string): number {\r\n const cost = getConfig().operationCosts[operationType];\r\n if (cost === undefined) {\r\n throw new Error(\r\n `Unknown operation type: ${operationType}. Valid types: ${getValidOperationTypes().join(\", \")}`\r\n );\r\n }\r\n return cost;\r\n}\r\n\r\n/**\r\n * Get all valid tier ids from configuration\r\n * Returns the keys of the tierConfigs object\r\n */\r\nexport function getValidTiers(): string[] {\r\n return Object.keys(getConfig().tierConfigs);\r\n}\r\n\r\n/**\r\n * Check if a tier id is valid (configured in the system)\r\n */\r\nexport function isValidTier(tier: string): boolean {\r\n return tier in getConfig().tierConfigs;\r\n}\r\n\r\n/**\r\n * Check if a tier is the free/default tier.\r\n * Falls back to priceUsd === 0 when the isFree flag is not set.\r\n */\r\nexport function isFreeTier(tier: SubscriptionTier): boolean {\r\n const c = getConfig().tierConfigs[tier];\r\n if (!c) return false;\r\n return c.isFree ?? c.priceUsd === 0;\r\n}\r\n\r\n/**\r\n * Check if a tier is unlimited.\r\n * Falls back to monthlyCredits === 0 when the unlimited flag is not set.\r\n */\r\nexport function isUnlimitedTier(tier: SubscriptionTier): boolean {\r\n const c = getConfig().tierConfigs[tier];\r\n if (!c) return false;\r\n return c.unlimited ?? c.monthlyCredits === 0;\r\n}\r\n\r\n/**\r\n * Get the tier assigned to brand-new users.\r\n * Prefers the tier flagged isDefault, then the first isFree tier, then \"free\".\r\n */\r\nexport function getDefaultTier(): SubscriptionTier {\r\n const entries = Object.entries(getConfig().tierConfigs);\r\n const def =\r\n entries.find(([, c]) => c.isDefault)?.[0] ??\r\n entries.find(([, c]) => c.isFree ?? c.priceUsd === 0)?.[0];\r\n return def ?? \"free\";\r\n}\r\n\r\n/**\r\n * Magic balance assigned to unlimited tiers on upgrade.\r\n * Kept at 999999 for back-compat with stored/displayed balances.\r\n */\r\nexport const UNLIMITED_BALANCE_SENTINEL = 999999;\r\n\r\n/**\r\n * Get the magic balance assigned to unlimited tiers on upgrade.\r\n */\r\nexport function getUnlimitedSentinelBalance(): number {\r\n return UNLIMITED_BALANCE_SENTINEL;\r\n}\r\n\r\n/**\r\n * What a monthly reset must leave in `balance`, as a storable instruction.\r\n *\r\n * This is the one place the unlimited contract is defined, because it is the\r\n * one thing the two adapters kept disagreeing about. The canonical persisted\r\n * representation of an unlimited tier is:\r\n *\r\n * - `monthlyLimit` = `storedMonthlyLimit(Infinity)`, i.e. the top of the\r\n * representable range. Never `0`, which reads as *no* allowance.\r\n * - `balance` = at least {@link UNLIMITED_BALANCE_SENTINEL}, which is what\r\n * `updateTier` writes on upgrade.\r\n *\r\n * The reset used to leave an unlimited balance strictly alone (\"`Infinity` is\r\n * not storable, so change nothing\"), which is correct for a healthy account and\r\n * a trap for a degraded one: an unlimited user whose balance had been driven to\r\n * `0` — by a spend, or by the older code that stored `0` as the limit — stayed\r\n * at `0` through every subsequent reset and could never buy anything again. So\r\n * the instruction is `atLeast`, not \"leave alone\": it restores a degraded\r\n * balance to the sentinel and leaves a topped-up one (a purchase on top of an\r\n * unlimited plan) untouched. It is expressed as a floor rather than as a number\r\n * so the SQL adapter can apply it as `greatest(balance, n)` inside its guarded\r\n * UPDATE instead of writing a literal read before the lock.\r\n */\r\nexport type MonthlyResetBalance =\r\n /** Store exactly this value. */\r\n | { kind: \"absolute\"; value: number }\r\n /** Raise the stored balance to this value; leave anything higher alone. */\r\n | { kind: \"atLeast\"; value: number };\r\n\r\nexport function monthlyResetBalance(tier: SubscriptionTier): MonthlyResetBalance {\r\n if (isUnlimitedTier(tier)) {\r\n return { kind: \"atLeast\", value: UNLIMITED_BALANCE_SENTINEL };\r\n }\r\n return { kind: \"absolute\", value: getConfigMonthlyLimit(tier) };\r\n}\r\n\r\n/**\r\n * Get tier configuration from configuration.\r\n * Falls back to the default tier (with a warning) if the tier is unknown.\r\n */\r\nexport function getConfigTierConfig(tier: SubscriptionTier): TierConfig {\r\n const cfg = getConfig().tierConfigs[tier];\r\n if (cfg) return cfg;\r\n const fallback = getDefaultTier();\r\n console.warn(\r\n `[Credits Config] Unknown tier \"${tier}\". Falling back to \"${fallback}\". Valid: ${getValidTiers().join(\", \")}`\r\n );\r\n return getConfig().tierConfigs[fallback]!;\r\n}\r\n\r\n/**\r\n * Get monthly limit for a tier from configuration\r\n * Returns Infinity for unlimited tier\r\n */\r\nexport function getConfigMonthlyLimit(tier: SubscriptionTier): number {\r\n return isUnlimitedTier(tier) ? Infinity : getConfigTierConfig(tier).monthlyCredits;\r\n}\r\n\r\n/**\r\n * Runtime zod validator for tier ids. Validates against the LIVE config keys\r\n * at parse time, so apps that add tiers via config get correct validation.\r\n */\r\nexport const tierSchema = z\r\n .string()\r\n .refine(isValidTier, { message: \"Unknown subscription tier\" }) as unknown as z.ZodType<SubscriptionTier>;\r\n\r\n/**\r\n * Parse/validate a tier id against the live config keys.\r\n * @throws ZodError if the tier is not configured\r\n */\r\nexport function parseTier(value: unknown): SubscriptionTier {\r\n return tierSchema.parse(value);\r\n}\r\n\r\n/**\r\n * Check if a feature is enabled\r\n */\r\nexport function isFeatureEnabled(feature: keyof CreditSystemConfig[\"features\"]): boolean {\r\n return getConfig().features[feature];\r\n}\r\n\r\n/**\r\n * Convert a snake_case string to Title Case.\r\n * E.g., \"story_generation\" -> \"Story Generation\"\r\n */\r\nfunction snakeCaseToTitleCase(str: string): string {\r\n return str\r\n .replace(/_/g, \" \")\r\n .replace(/\\b\\w/g, (c) => c.toUpperCase());\r\n}\r\n\r\n/**\r\n * Get the display label for an operation type.\r\n * Falls back to converting snake_case to Title Case if no label is configured.\r\n */\r\nexport function getOperationLabel(operationType: string): string {\r\n const labels = getConfig().operationLabels;\r\n if (labels && operationType in labels) {\r\n return labels[operationType];\r\n }\r\n return snakeCaseToTitleCase(operationType);\r\n}\r\n\r\n/**\r\n * Get all operation labels as a record.\r\n * For any operation in operationCosts that lacks a label, generates one from the key.\r\n */\r\nexport function getOperationLabels(): Record<string, string> {\r\n const config = getConfig();\r\n const result: Record<string, string> = {};\r\n for (const key of Object.keys(config.operationCosts)) {\r\n result[key] = config.operationLabels?.[key]\r\n ?? snakeCaseToTitleCase(key);\r\n }\r\n return result;\r\n}\r\n\r\n/**\r\n * Reset configuration to defaults (for testing)\r\n */\r\nexport function resetConfig(): void {\r\n currentConfig = DEFAULT_CONFIG;\r\n}\r\n\r\n// Initialize configuration on module load\r\ninitializeConfig();\r\n","import type { CreditSystemConfig } from \"./index.js\";\r\n\r\n/** Interface for external config providers (e.g. Firestore-backed) */\r\nexport interface ICreditConfigProvider {\r\n getConfig(): CreditSystemConfig;\r\n}\r\n\r\nlet configProvider: ICreditConfigProvider | null = null;\r\n\r\n/** Register an external config provider. Called once at app startup. */\r\nexport function registerConfigProvider(provider: ICreditConfigProvider): void {\r\n configProvider = provider;\r\n}\r\n\r\n/** Get the registered provider, or null if none registered. */\r\nexport function getConfigProvider(): ICreditConfigProvider | null {\r\n return configProvider;\r\n}\r\n\r\n/** Clear registered provider (for testing). */\r\nexport function clearConfigProvider(): void {\r\n configProvider = null;\r\n}\r\n","/**\r\n * `paymentRef` as a global, semantic idempotency boundary.\r\n *\r\n * A payment reference is the identity of a *credit event* — one webhook, one\r\n * invoice, one charge. It is deliberately not scoped to a user: a processor's\r\n * reference is unique across the processor's whole account, and the SQL adapter\r\n * has always enforced it with a unique index over `payment_ref` alone. Two\r\n * problems followed from treating it as anything less.\r\n *\r\n * **It was scoped per user in memory and globally in SQL.** The in-memory\r\n * adapter searched only the crediting user's own transactions, so replaying a\r\n * reference against a *different* user credited both accounts, while the SQL\r\n * adapter silently no-opped. Same call, two ledgers, opposite results — and the\r\n * memory one is the direction that invents money.\r\n *\r\n * **It was compared on presence, never on payload.** A reference that arrived a\r\n * second time carrying a different amount was accepted as a replay of the\r\n * first, so a corrected or spoofed webhook credited the original amount and\r\n * reported success. Presence is only sound when the payload is known to match;\r\n * otherwise the honest answer is a conflict.\r\n *\r\n * So a reference now resolves to exactly one of three outcomes — `created`,\r\n * `replayed`, `conflict` — in both adapters, and `conflict` mutates nothing.\r\n */\r\n\r\nimport { sameAmount } from \"./amount.js\";\r\nimport { CreditError, CreditErrorCode } from \"./errors.js\";\r\nimport type {\r\n CreditSource,\r\n JournalReferenceType,\r\n PortableTransaction,\r\n} from \"./types.js\";\r\n\r\n/**\r\n * The fields that define the credit event a reference names.\r\n *\r\n * `description` is excluded on purpose: it is human-facing copy that a retry\r\n * may legitimately regenerate (\"Purchase 100 credits\" versus \"Purchase of 100\r\n * credits\") without the event being different. Everything that decides *how\r\n * much lands where* is in.\r\n */\r\nexport interface PaymentEventPayload {\r\n userId: string;\r\n amount: number;\r\n /** The transaction row's `type` — the operation the reference names. */\r\n type: PortableTransaction[\"type\"];\r\n /** The journal entry's `source` — where the credits came from. */\r\n source: CreditSource;\r\n /** The journal entry's `referenceType`. */\r\n referenceType: JournalReferenceType;\r\n}\r\n\r\n/**\r\n * The stored side of the comparison, as either adapter can produce it.\r\n *\r\n * `amount` is `unknown` because SQL returns `numeric` as a string, and\r\n * comparing the mapped `Number` is exactly the rounding hole that let\r\n * `9999999999.9900001` match a request for `9999999999.99`.\r\n */\r\nexport interface StoredPaymentEvent {\r\n userId: string;\r\n amount: unknown;\r\n type: string;\r\n /** Absent when no journal entry could be located for the stored transaction. */\r\n source?: string;\r\n referenceType?: string;\r\n}\r\n\r\n/**\r\n * Normalise a payment reference to \"a reference\" or \"no reference\".\r\n *\r\n * Empty and whitespace-only strings are *not* references: they cannot identify\r\n * a payment, and treating them as one produced the divergence where SQL skipped\r\n * the duplicate check (falsy) but still stored the value, so the replay hit the\r\n * unique index and threw while memory quietly credited twice.\r\n *\r\n * Unlike an idempotency key, a blank reference is normalised rather than\r\n * rejected. A key is the caller's explicit request for exactly-once and a blank\r\n * one means they got it wrong; `paymentRef` is an optional annotation on a\r\n * credit, and an absent one is a normal, supported call.\r\n */\r\nexport function normalizePaymentRef(ref?: string | null): string | undefined {\r\n if (typeof ref !== \"string\") return undefined;\r\n const trimmed = ref.trim();\r\n return trimmed.length > 0 ? trimmed : undefined;\r\n}\r\n\r\n/**\r\n * Name the first field on which a stored credit event disagrees, or `null`.\r\n *\r\n * `null` means the delivery is a genuine replay and must change nothing.\r\n * Anything else is a conflict: the same reference was used for a different\r\n * event, and crediting on it would either double-credit or credit the wrong\r\n * amount to the wrong account.\r\n *\r\n * `source` and `referenceType` are compared only when the stored side has them.\r\n * They live on the journal entry, and a transaction written before this library\r\n * journalled its purchases has none to compare against — treating that absence\r\n * as a mismatch would turn every pre-existing reference into a permanent\r\n * conflict, which is a refusal to credit rather than a protection against one.\r\n */\r\nexport function describePaymentMismatch(\r\n stored: StoredPaymentEvent,\r\n expected: PaymentEventPayload\r\n): string | null {\r\n if (stored.userId !== expected.userId) return \"userId\";\r\n if (!sameAmount(stored.amount, expected.amount)) return \"amount\";\r\n if (stored.type !== expected.type) return \"type\";\r\n if (stored.source !== undefined && stored.source !== expected.source) return \"source\";\r\n if (stored.referenceType !== undefined && stored.referenceType !== expected.referenceType) {\r\n return \"referenceType\";\r\n }\r\n return null;\r\n}\r\n\r\n/**\r\n * Refuse a payment reference on the direct, record-only transaction writer.\r\n *\r\n * `createTransaction` writes a ledger *record*: no balance moves and no journal\r\n * entry is created. But a `paymentRef` on that record still occupies the global\r\n * unique boundary, and `addCreditsV2` treats the row that holds a reference as\r\n * the authoritative credit event — a later delivery of the real payment with\r\n * the same reference then matches the record on user/amount/type, reports\r\n * `replayed`, and credits nothing, forever. The record would have consumed the\r\n * payment.\r\n *\r\n * Same shape as `assertUnkeyedDirectReservation`: the claim is refused at the\r\n * boundary, so the row that could impersonate a credit event cannot be written\r\n * in the first place. Credits that carry a reference go through\r\n * `addCreditsAtomic` / `addCreditsV2`, which claim the reference and move the\r\n * balance in one atomic step.\r\n */\r\nexport function assertUnreferencedDirectTransaction(input: {\r\n userId: string;\r\n paymentRef?: string;\r\n}): void {\r\n if (normalizePaymentRef(input.paymentRef) === undefined) return;\r\n throw new CreditError(\r\n \"createTransaction cannot accept a paymentRef: it records a transaction \" +\r\n \"without crediting the account, and the reference would then be treated \" +\r\n \"as an already-delivered payment — a later addCredits call with the same \" +\r\n \"reference reports `replayed` and credits nothing. Record unreferenced \" +\r\n \"transactions here, or deliver referenced payments through addCredits \" +\r\n \"(addCreditsAtomic / addCreditsV2), which claims the reference and moves \" +\r\n \"the balance atomically.\",\r\n CreditErrorCode.UNSUPPORTED_OPERATION,\r\n {\r\n userId: input.userId,\r\n paymentRef: input.paymentRef,\r\n operation: \"createTransaction\",\r\n reason: \"referenced_direct_transaction\",\r\n }\r\n );\r\n}\r\n\r\n/**\r\n * The conflict, as an error, for the legacy `addCreditsAtomic` signature.\r\n *\r\n * That method returns `void`, so it has nowhere to put a `conflict` outcome.\r\n * Swallowing one would be the original bug in a new place — the SQL adapter\r\n * used to no-op on a cross-user reference reuse, which reads to the caller as\r\n * \"credited\" — so the legacy path throws instead. Callers that want to *handle*\r\n * a conflict rather than catch it should use `addCreditsV2`.\r\n */\r\nexport function createPaymentRefConflictError(\r\n paymentRef: string,\r\n details: { userId: string; mismatch: string; existingUserId?: string }\r\n): CreditError {\r\n return new CreditError(\r\n `Payment reference ${paymentRef} has already been used for a different credit ` +\r\n `event (${details.mismatch} differs). Nothing was credited. A payment reference ` +\r\n \"identifies one credit event globally; reusing it for another user, amount or \" +\r\n \"source is refused rather than silently ignored.\",\r\n CreditErrorCode.IDEMPOTENCY_CONFLICT,\r\n { paymentRef, reason: \"payment_ref_conflict\", ...details }\r\n );\r\n}\r\n","/**\r\n * One reservation flow for both repository generations.\r\n *\r\n * Adapters that implement the V2 boundary get the idempotent, race-safe path\r\n * and own their journal entry. Adapters that do not (Firestore, custom\r\n * implementations) keep the legacy read-then-write path, with the service\r\n * writing the journal exactly as it always did — so upgrading this package\r\n * does not change their behaviour, and does not double-write anyone's ledger.\r\n */\r\n\r\nimport { getOperationLabel } from \"../config/index.js\";\r\nimport { assertValidCreditAmount, sumAmounts } from \"../core/amount.js\";\r\nimport {\r\n createUnsupportedOperationError,\r\n isInsufficientCreditsError,\r\n} from \"../core/errors.js\";\r\nimport type {\r\n AddCreditsOutcome,\r\n CommitOutcome,\r\n ReleaseOutcome,\r\n ReserveOutcome,\r\n} from \"../core/outcomes.js\";\r\nimport { normalizePaymentRef } from \"../core/payment-ref.js\";\r\nimport type { ICreditRepository } from \"./types.js\";\r\nimport { supportsCreditsV2, supportsIdempotentCredit } from \"./types.js\";\r\nimport type {\r\n AddCreditsV2Input,\r\n ReservationTransitionOptions,\r\n ReserveCreditsV2Input,\r\n} from \"./v2-types.js\";\r\n\r\n/**\r\n * Reserve credits through V2 when available.\r\n *\r\n * A legacy adapter cannot honour an idempotency key — it has no unique index\r\n * to enforce it — so asking for one there is a caller error rather than a\r\n * silently ignored option.\r\n */\r\nexport async function reserveThroughRepository(\r\n repository: ICreditRepository,\r\n input: ReserveCreditsV2Input\r\n): Promise<ReserveOutcome> {\r\n const v2 = supportsCreditsV2(repository);\r\n\r\n // The capability check comes first, so a caller who asked for a guarantee\r\n // this repository cannot give always hears *that*, rather than whichever\r\n // other complaint the arguments happen to trigger. A legacy adapter has no\r\n // unique index to enforce the key, so it cannot deduplicate a replay, and\r\n // reporting `created` for the second delivery would be a lie that costs the\r\n // user real credits.\r\n if (!v2 && input.idempotencyKey !== undefined) {\r\n throw createUnsupportedOperationError(\r\n \"reserveCredits with an idempotencyKey\",\r\n \"This repository does not implement the V2 boundary, so it cannot \" +\r\n \"enforce idempotency keys. Use a V2 repository (check with \" +\r\n \"supportsCreditsV2) or omit the key and accept at-least-once holds.\"\r\n );\r\n }\r\n\r\n assertValidCreditAmount(input.amount, { userId: input.userId });\r\n\r\n if (v2) {\r\n return repository.reserveCreditsV2(input);\r\n }\r\n\r\n try {\r\n const reservation = await repository.reserveCreditsAtomic(\r\n input.userId,\r\n input.amount,\r\n input.operationType,\r\n input.expiresAt\r\n );\r\n return { outcome: \"created\", reservation };\r\n } catch (error) {\r\n // Only a genuine funds shortfall becomes the `insufficient` outcome. The\r\n // previous version asked the repository for the balance and called any\r\n // failure `insufficient` whenever that balance happened to be low — which\r\n // silently rebranded connection drops and driver faults as \"the user is\r\n // out of credits\", and hid real outages behind an upsell.\r\n if (!isInsufficientCreditsError(error)) throw error;\r\n\r\n const credits = await repository.getUserCredits(input.userId);\r\n const available = credits\r\n ? sumAmounts(credits.balance, credits.bonusCredits, -credits.reserved)\r\n : 0;\r\n return {\r\n outcome: \"insufficient\",\r\n available,\r\n required: input.amount,\r\n shortfall: Math.max(sumAmounts(input.amount, -available), 0),\r\n };\r\n }\r\n}\r\n\r\n/**\r\n * Commit through V2 when available, else the legacy read-then-write path.\r\n *\r\n * **The legacy path cannot promise a single winner.** It reads the status and\r\n * then writes, with no lock and no compare-and-set between the two, so two\r\n * concurrent commits of the same reservation can both observe `reserved` and\r\n * both proceed. The typed outcome still describes what *this* call saw, but on\r\n * a legacy adapter `committed` means \"this call did the work\", not \"this call\r\n * was the only one that did\". Callers needing exactly-once must use a\r\n * repository for which `supportsCreditsV2` returns `true`.\r\n */\r\nexport async function commitThroughRepository(\r\n repository: ICreditRepository,\r\n userId: string,\r\n reservationId: string,\r\n options?: ReservationTransitionOptions\r\n): Promise<CommitOutcome> {\r\n if (supportsCreditsV2(repository)) {\r\n return repository.commitReservationV2(userId, reservationId, options);\r\n }\r\n\r\n const reservation = await repository.getReservation(userId, reservationId);\r\n if (!reservation) return { outcome: \"not_found\", reservationId };\r\n if (reservation.status !== \"reserved\") {\r\n return {\r\n outcome: \"already_terminal\",\r\n reservation,\r\n terminalStatus: reservation.status,\r\n };\r\n }\r\n\r\n await repository.commitReservationAtomic(userId, reservationId);\r\n\r\n const credits = await repository.getUserCredits(userId);\r\n // The ledger balance, not the `balance` column alone: every other journal\r\n // writer — the V2 transitions, add and deduct — records\r\n // `balance + bonusCredits`, and recording less here made the same account's\r\n // audit trail disagree with itself whenever it held bonus credits.\r\n const balanceAfter = credits ? sumAmounts(credits.balance, credits.bonusCredits) : 0;\r\n const entry = await repository.createJournalEntry({\r\n userId,\r\n entryType: \"debit\",\r\n amount: reservation.amount,\r\n balanceAfter,\r\n source: \"operation_commit\",\r\n referenceId: reservationId,\r\n referenceType: \"reservation\",\r\n description:\r\n options?.description ??\r\n `Committed ${reservation.amount} credits for ${getOperationLabel(reservation.operationType)}`,\r\n // Deterministic fields last: they carry the identity of the event, and a\r\n // caller who happens to send an `operationType` or an `amount` must not\r\n // relabel what actually moved.\r\n metadata: {\r\n ...options?.metadata,\r\n operationType: reservation.operationType,\r\n amount: reservation.amount,\r\n },\r\n });\r\n\r\n return {\r\n outcome: \"committed\",\r\n reservation: { ...reservation, status: \"committed\" },\r\n amount: reservation.amount,\r\n balanceAfter,\r\n journalEntryId: entry.id,\r\n };\r\n}\r\n\r\n/**\r\n * Release through V2 when available, else the legacy read-then-write path.\r\n *\r\n * Same caveat as {@link commitThroughRepository}: on a legacy adapter the\r\n * read-then-write sequence is unguarded, so `released` does not exclude a\r\n * concurrent commit having also run. Only V2 repositories serialise the two.\r\n */\r\nexport async function releaseThroughRepository(\r\n repository: ICreditRepository,\r\n userId: string,\r\n reservationId: string,\r\n options?: ReservationTransitionOptions\r\n): Promise<ReleaseOutcome> {\r\n if (supportsCreditsV2(repository)) {\r\n return repository.releaseReservationV2(userId, reservationId, options);\r\n }\r\n\r\n const reservation = await repository.getReservation(userId, reservationId);\r\n if (!reservation) {\r\n // Legacy adapters vary on whether releasing an unknown reservation throws;\r\n // ask them anyway so that behaviour is preserved, then report not_found.\r\n await repository.releaseReservationAtomic(userId, reservationId);\r\n return { outcome: \"not_found\", reservationId };\r\n }\r\n if (reservation.status !== \"reserved\") {\r\n // The hold is already resolved, so there is nothing to hand back. Legacy\r\n // adapters disagree about whether releasing a processed reservation is an\r\n // error, and `releaseCredits` is specified to be a silent no-op here — so\r\n // the call is still made for adapters that use it to reconcile, and a\r\n // refusal is swallowed rather than propagated. The conflict is not hidden:\r\n // it is what `already_terminal` reports, and `releaseCreditsDetailed`\r\n // surfaces it to callers that ask.\r\n await repository.releaseReservationAtomic(userId, reservationId).catch(() => undefined);\r\n return {\r\n outcome: \"already_terminal\",\r\n reservation,\r\n terminalStatus: reservation.status,\r\n };\r\n }\r\n\r\n await repository.releaseReservationAtomic(userId, reservationId);\r\n\r\n const credits = await repository.getUserCredits(userId);\r\n const entry = await repository.createJournalEntry({\r\n userId,\r\n entryType: \"credit\",\r\n // No credits changed hands — the hold just moved back into \"available\".\r\n amount: 0,\r\n balanceAfter: credits ? sumAmounts(credits.balance, credits.bonusCredits) : 0,\r\n source: \"operation_release\",\r\n referenceId: reservationId,\r\n referenceType: \"reservation\",\r\n description:\r\n options?.description ??\r\n `Released ${reservation.amount} reserved credits for ${getOperationLabel(reservation.operationType)}`,\r\n metadata: {\r\n ...options?.metadata,\r\n operationType: reservation.operationType,\r\n amount: reservation.amount,\r\n },\r\n });\r\n\r\n return {\r\n outcome: \"released\",\r\n reservation: { ...reservation, status: \"released\" },\r\n amount: reservation.amount,\r\n journalEntryId: entry.id,\r\n };\r\n}\r\n\r\n/**\r\n * Credit an account through the idempotent path when the adapter has one.\r\n *\r\n * A legacy adapter cannot resolve `created` / `replayed` / `conflict`: it has\r\n * no global unique index over `payment_ref`, so it cannot tell a re-delivered\r\n * webhook from a second, genuinely different payment that reuses a reference.\r\n * Rather than invent an outcome, this reports `created` — which is what the\r\n * legacy method actually did — and the ambiguity is documented on the return\r\n * type instead of hidden inside it.\r\n *\r\n * The reference is normalised here as well as in the adapters, so a legacy\r\n * adapter that stores the raw string does not persist a whitespace-only\r\n * reference that would then deduplicate nothing.\r\n */\r\nexport async function addCreditsThroughRepository(\r\n repository: ICreditRepository,\r\n input: AddCreditsV2Input\r\n): Promise<AddCreditsOutcome> {\r\n assertValidCreditAmount(input.amount, { userId: input.userId, operation: \"addCredits\" });\r\n const paymentRef = normalizePaymentRef(input.paymentRef);\r\n\r\n if (supportsIdempotentCredit(repository)) {\r\n return repository.addCreditsV2({ ...input, paymentRef });\r\n }\r\n\r\n await repository.addCreditsAtomic(\r\n input.userId,\r\n input.amount,\r\n input.description,\r\n paymentRef,\r\n input.options\r\n );\r\n\r\n // The legacy method returns nothing, so there is no transaction to hand back\r\n // and no way to know whether it deduplicated. Report the one thing that is\r\n // true — a call was made and did not throw — rather than fabricate a record.\r\n return paymentRef ? { outcome: \"created\", paymentRef } : { outcome: \"created\" };\r\n}\r\n","/**\r\n * Shared utilities for credit repository implementations\r\n *\r\n * These are pure functions with no server-only dependencies,\r\n * making them safe to use in any repository implementation.\r\n */\r\n\r\nimport { sumAmounts } from \"../core/amount.js\";\r\nimport type { PortableUserCredits } from \"../core/types.js\";\r\nimport type { CreditBalanceUpdate } from \"./types.js\";\r\n\r\n/**\r\n * Generate a unique ID\r\n * Uses timestamp + random string for uniqueness\r\n */\r\nexport function generateId(): string {\r\n return `${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;\r\n}\r\n\r\n/**\r\n * Convert date-like value to Date object\r\n * Handles: Date, string, Firestore Timestamp\r\n */\r\nexport function toDate(value: Date | string | unknown): Date {\r\n if (value instanceof Date) return value;\r\n if (typeof value === \"string\") return new Date(value);\r\n // Handle Firestore Timestamp\r\n if (typeof value === \"object\" && value !== null && \"toDate\" in value) {\r\n return (value as { toDate: () => Date }).toDate();\r\n }\r\n return new Date();\r\n}\r\n\r\n/**\r\n * Get the first day of next month\r\n * Used for calculating monthly reset dates\r\n */\r\nexport function getNextMonthlyReset(from: Date = new Date()): Date {\r\n // From components: `setMonth` on the 31st overflows (31 Jan became 3 March, then\r\n // 1 March after `setDate(1)`), which skipped a whole month.\r\n return new Date(from.getFullYear(), from.getMonth() + 1, 1);\r\n}\r\n\r\n/** Result of validating a balance update. */\r\nexport interface BalanceValidationResult {\r\n valid: boolean;\r\n errors: string[];\r\n}\r\n\r\n/**\r\n * Whether an update leaves a valid account: no negative field, and `reserved` covered\r\n * by `balance + bonusCredits`, which is the floor outstanding holds put under the\r\n * balance. An increment is applied on top of the absolute value when a call names both.\r\n *\r\n * An update is a delta the caller asked for, so one that cannot be honoured is refused,\r\n * as a deduct is. Only tier writes and resets stop at the floor: they state a target.\r\n *\r\n * A negative balance increment is a charge, so it draws only on the balance above\r\n * `expiredHoldBacking`: those credits are expired and leave when their hold closes, so\r\n * charging them would hand the charge back. An absolute balance replaces the field and\r\n * the marks with it, so only an increment on the stored balance meets this limit.\r\n */\r\nexport function validateBalanceUpdate(\r\n current: Pick<PortableUserCredits, \"balance\" | \"bonusCredits\" | \"reserved\" | \"expiredHoldBacking\">,\r\n updates: CreditBalanceUpdate\r\n): BalanceValidationResult {\r\n const next = (base: number, absolute?: number, increment?: number) =>\r\n sumAmounts(absolute ?? base, increment ?? 0);\r\n const balance = next(current.balance, updates.balance, updates.balanceIncrement);\r\n const bonusCredits = next(\r\n current.bonusCredits ?? 0,\r\n updates.bonusCredits,\r\n updates.bonusCreditsIncrement\r\n );\r\n const reserved = next(current.reserved ?? 0, updates.reserved, updates.reservedIncrement);\r\n\r\n const errors: string[] = [];\r\n if (balance < 0) errors.push(`Balance cannot be negative: ${balance}`);\r\n const marked = updates.balance === undefined ? (current.expiredHoldBacking ?? 0) : 0;\r\n if ((updates.balanceIncrement ?? 0) < 0 && balance >= 0 && balance < marked) {\r\n errors.push(`Balance (${balance}) cannot go below expired hold backing (${marked})`);\r\n }\r\n if (bonusCredits < 0) errors.push(`BonusCredits cannot be negative: ${bonusCredits}`);\r\n if (reserved < 0) errors.push(`Reserved cannot be negative: ${reserved}`);\r\n\r\n const covering = sumAmounts(balance, bonusCredits);\r\n if (reserved > covering) {\r\n errors.push(`Reserved (${reserved}) exceeds balance + bonusCredits (${covering})`);\r\n }\r\n return { valid: errors.length === 0, errors };\r\n}\r\n\r\n/** Refuse an update {@link validateBalanceUpdate} finds invalid. */\r\nexport function assertValidBalanceUpdate(\r\n current: Pick<PortableUserCredits, \"balance\" | \"bonusCredits\" | \"reserved\" | \"expiredHoldBacking\">,\r\n updates: CreditBalanceUpdate\r\n): void {\r\n const result = validateBalanceUpdate(current, updates);\r\n if (!result.valid) {\r\n throw new Error(`Invalid balance update: ${result.errors.join(\"; \")}`);\r\n }\r\n}\r\n","/**\r\n * Copies at the boundary, so nothing stored is ever handed to a caller.\r\n *\r\n * A real adapter maps a database row into a fresh object every time. This one\r\n * used to return the object it had stored, which made it behave in ways no\r\n * production adapter does: a caller's earlier read mutated under them when a\r\n * later write landed, and a caller that adjusted a returned record corrupted\r\n * the store without going through any write path at all.\r\n *\r\n * That is not a theoretical difference. The service's monthly reset compared\r\n * the post-reset balance against the balance it had read moments earlier, got\r\n * zero because both were the same object, and silently skipped the reset's\r\n * journal entry — a bug that could not reproduce against the SQL adapter.\r\n *\r\n * `metadata` is copied one level deeper because it is the one field callers\r\n * routinely pass in and then keep a reference to.\r\n */\r\n\r\ninterface WithMetadata {\r\n metadata?: Record<string, unknown> | null;\r\n}\r\n\r\n/** A detached copy of one stored record. */\r\nexport function copyRecord<T extends object>(record: T): T;\r\nexport function copyRecord<T extends object>(record: T | undefined): T | undefined;\r\nexport function copyRecord<T extends object>(record: T | undefined): T | undefined {\r\n if (!record) return undefined;\r\n const copy = { ...record };\r\n const metadata = (record as WithMetadata).metadata;\r\n if (metadata && typeof metadata === \"object\") {\r\n (copy as WithMetadata).metadata = { ...metadata };\r\n }\r\n return copy;\r\n}\r\n\r\n/** A detached copy of a list of stored records, and of the list itself. */\r\nexport function copyRecords<T extends object>(records: readonly T[]): T[] {\r\n return records.map((record) => copyRecord(record));\r\n}\r\n","/**\r\n * Trust checks for a *persisted* reservation row.\r\n *\r\n * A reservation is written once and read back on every transition, and nothing\r\n * between those two moments belongs to this library: a direct `UPDATE`, a\r\n * half-finished migration, a legacy adapter or a future version can all leave a\r\n * row this code never wrote. Two of the fields it reads back are load-bearing.\r\n *\r\n * **`status`** decides whether a transition runs at all. It used to be cast —\r\n * `reservation.status as TerminalReservationStatus` — so a row holding\r\n * `'gremlin'` was reported as `already_terminal` with `terminalStatus:\r\n * 'gremlin'`: a *success* outcome, telling the caller the reservation had been\r\n * resolved, over a row nothing in this library can resolve. The cast is a lie\r\n * the type system cannot catch, so the value is checked against the closed set\r\n * instead and anything outside it quarantines the row.\r\n *\r\n * **`holdPlacedAt`** decides whether the hold behind the row exists. See\r\n * {@link assertHoldPlaced}.\r\n *\r\n * Both refusals happen before any state changes, and neither one repairs\r\n * anything: a corrupt row stops moving and waits for an operator. Silently\r\n * reconciling it would need an audit trail and a recovery procedure, and\r\n * guessing is how a bad row becomes a wrong balance.\r\n */\r\n\r\nimport { CreditError, CreditErrorCode } from \"./errors.js\";\r\nimport type { TerminalReservationStatus } from \"./outcomes.js\";\r\nimport type { PortableReservation, ReservationStatus } from \"./types.js\";\r\n\r\n/** Every status this library knows how to reason about. */\r\nexport const RESERVATION_STATUSES: readonly ReservationStatus[] = [\r\n \"reserved\",\r\n \"committed\",\r\n \"released\",\r\n \"expired\",\r\n];\r\n\r\n/** The statuses a reservation can no longer transition out of. */\r\nexport const TERMINAL_RESERVATION_STATUSES: readonly TerminalReservationStatus[] = [\r\n \"committed\",\r\n \"released\",\r\n \"expired\",\r\n];\r\n\r\nexport function isReservationStatus(value: unknown): value is ReservationStatus {\r\n return RESERVATION_STATUSES.includes(value as ReservationStatus);\r\n}\r\n\r\nexport function isTerminalReservationStatus(\r\n value: unknown\r\n): value is TerminalReservationStatus {\r\n return TERMINAL_RESERVATION_STATUSES.includes(value as TerminalReservationStatus);\r\n}\r\n\r\n/** The subset of a reservation these checks read, so callers can pass a row. */\r\nexport interface ReservationIntegrityView {\r\n id: string;\r\n userId: string;\r\n status: unknown;\r\n /** Set by the atomic reserve, in the same transaction as the hold. */\r\n holdPlacedAt?: string | null;\r\n idempotencyKey?: string | null;\r\n}\r\n\r\n/**\r\n * Refuse a transition over a status this library does not define.\r\n *\r\n * Runs ahead of every early exit, including the `already_terminal` one, for the\r\n * reason in the module header: `already_terminal` is a success outcome, and a\r\n * success outcome over an unknown status is the failure mode being prevented.\r\n */\r\nexport function assertKnownReservationStatus(\r\n reservation: ReservationIntegrityView,\r\n transition: string\r\n): asserts reservation is ReservationIntegrityView & { status: ReservationStatus } {\r\n if (isReservationStatus(reservation.status)) return;\r\n throw new CreditError(\r\n `Reservation ${reservation.id} holds the status ${JSON.stringify(reservation.status)}, ` +\r\n `which is not one of ${RESERVATION_STATUSES.join(\", \")}. The ${transition} was ` +\r\n \"refused before any state changed; the row must be repaired by an operator.\",\r\n CreditErrorCode.CORRUPT_RESERVATION_STATUS,\r\n {\r\n userId: reservation.userId,\r\n reservationId: reservation.id,\r\n transition,\r\n status: typeof reservation.status === \"string\" ? reservation.status : String(reservation.status),\r\n allowed: [...RESERVATION_STATUSES],\r\n reason: \"corrupt_reservation_status\",\r\n }\r\n );\r\n}\r\n\r\n/**\r\n * Narrow a non-`reserved` status for the `already_terminal` outcomes.\r\n *\r\n * Validates rather than casts. `assertKnownReservationStatus` has usually run\r\n * already; this repeats the check because the cast it replaces was the defect,\r\n * and a second closed-set test costs nothing next to a database round trip.\r\n */\r\nexport function terminalStatusOf(\r\n reservation: ReservationIntegrityView,\r\n transition: string\r\n): TerminalReservationStatus {\r\n assertKnownReservationStatus(reservation, transition);\r\n if (isTerminalReservationStatus(reservation.status)) return reservation.status;\r\n throw new CreditError(\r\n `Reservation ${reservation.id} is ${reservation.status}, which is not a terminal ` +\r\n `status, but the ${transition} tried to report it as one.`,\r\n CreditErrorCode.CORRUPT_RESERVATION_STATUS,\r\n {\r\n userId: reservation.userId,\r\n reservationId: reservation.id,\r\n transition,\r\n status: reservation.status,\r\n reason: \"not_terminal\",\r\n }\r\n );\r\n}\r\n\r\n/**\r\n * Refuse a transition over a hold that was never atomically placed.\r\n *\r\n * `holdPlacedAt` is the single invariant behind the V2 boundary: **a row is\r\n * only a reservation if the same atomic operation that wrote it also increased\r\n * `reserved` by its amount.** The atomic reserve sets the field inside that one\r\n * transaction, so the fact and the hold commit together or not at all.\r\n *\r\n * Without it, `createReservation` — a plain row writer that does not touch\r\n * `reserved` — could mint a keyed row, and a later `reserveCreditsV2` with that\r\n * key would adopt it as a `replayed` hold that no credits back. The caller then\r\n * commits it, and the commit passes its `reserved >= amount` guard by consuming\r\n * coverage that belongs to a *different*, real hold: two holds, one payment.\r\n *\r\n * So this is checked before adopting a replay and before every transition, and\r\n * `createReservation` refuses a key outright — the two halves of the same rule.\r\n */\r\nexport function assertHoldPlaced(\r\n reservation: ReservationIntegrityView,\r\n transition: string\r\n): void {\r\n if (reservation.holdPlacedAt) return;\r\n throw new CreditError(\r\n `Reservation ${reservation.id} does not record that its hold was placed atomically ` +\r\n \"(holdPlacedAt is absent), so the credits it claims to hold may never have been \" +\r\n `reserved. The ${transition} was refused before any state changed: honouring it ` +\r\n \"would spend coverage belonging to another reservation. Rows written by \" +\r\n \"createReservation are not V2 reservations; place holds with reserveCredits.\",\r\n CreditErrorCode.UNBACKED_RESERVATION,\r\n {\r\n userId: reservation.userId,\r\n reservationId: reservation.id,\r\n transition,\r\n idempotencyKey: reservation.idempotencyKey ?? undefined,\r\n reason: \"hold_not_placed\",\r\n }\r\n );\r\n}\r\n\r\n/**\r\n * Refuse an idempotency key on the direct, non-atomic reservation writer.\r\n *\r\n * The other half of {@link assertHoldPlaced}. `createReservation` inserts a row\r\n * and does not touch `reserved`, so a key registered here would name a hold\r\n * that does not exist. Rejecting the key at the boundary means the unbacked\r\n * keyed row cannot be created in the first place, rather than only being\r\n * refused later by every transition that tries to move it.\r\n *\r\n * The amount check that runs alongside this is about a value the ledger cannot\r\n * honour; this is about a *claim* the writer cannot honour.\r\n */\r\nexport function assertUnkeyedDirectReservation(input: {\r\n userId: string;\r\n idempotencyKey?: string;\r\n}): void {\r\n if (input.idempotencyKey === undefined || input.idempotencyKey === null) return;\r\n throw new CreditError(\r\n \"createReservation cannot accept an idempotencyKey: it writes the reservation \" +\r\n \"row without placing the hold, so the key would name credits that were never \" +\r\n \"reserved, and a later reserveCredits with the same key would adopt it as a \" +\r\n \"replay. Call reserveCredits (or reserveCreditsV2) with the key instead — it \" +\r\n \"claims the key and places the hold in one transaction.\",\r\n CreditErrorCode.UNSUPPORTED_OPERATION,\r\n {\r\n userId: input.userId,\r\n idempotencyKey: input.idempotencyKey,\r\n operation: \"createReservation\",\r\n reason: \"keyed_direct_reservation\",\r\n }\r\n );\r\n}\r\n\r\n/** True when the row records an atomically placed hold. */\r\nexport function hasPlacedHold(reservation: Pick<PortableReservation, \"holdPlacedAt\">): boolean {\r\n return Boolean(reservation.holdPlacedAt);\r\n}\r\n\r\n/**\r\n * Refuse a direct status write that would bypass the V2 state machine.\r\n *\r\n * `updateReservationStatus` assigns a status and nothing else: it does not\r\n * check the current status, move the balance, adjust `reserved`, or journal.\r\n * On a row whose hold was atomically placed, that is not an update — it is a\r\n * bypass. Writing `committed` onto a live hold strands `reserved` forever (the\r\n * real commit then reports `already_terminal` and never debits), and writing\r\n * `reserved` onto a terminal row re-arms a settled reservation so it can be\r\n * settled again.\r\n *\r\n * Two refusals, mirroring the createReservation/reserveCredits split:\r\n *\r\n * - A row bearing `holdPlacedAt` belongs to the V2 transitions. Every status it\r\n * will ever hold is assigned by commit/release/expire, atomically with the\r\n * ledger movement that status implies.\r\n * - No row, V2 or legacy, may be *reopened* — status can never be assigned back\r\n * to `reserved`, because nothing here re-places the hold that status claims.\r\n *\r\n * Rows written by `createReservation` (no hold, no key) remain freely\r\n * annotatable with terminal statuses: their statuses never carried ledger\r\n * meaning, and the V2 transitions refuse them anyway.\r\n */\r\nexport function assertDirectStatusWriteAllowed(\r\n reservation: ReservationIntegrityView,\r\n status: ReservationStatus\r\n): void {\r\n if (status === \"reserved\") {\r\n throw new CreditError(\r\n `Reservation ${reservation.id} cannot have its status set back to \"reserved\": ` +\r\n \"updateReservationStatus does not place a hold, so the reopened row would claim \" +\r\n \"credits nothing reserved. Create a new reservation with reserveCredits instead.\",\r\n CreditErrorCode.UNSUPPORTED_OPERATION,\r\n {\r\n userId: reservation.userId,\r\n reservationId: reservation.id,\r\n status,\r\n reason: \"reopen_reservation\",\r\n }\r\n );\r\n }\r\n if (!reservation.holdPlacedAt) return;\r\n throw new CreditError(\r\n `Reservation ${reservation.id} is backed by an atomically placed hold, so its ` +\r\n \"status may only be assigned by the transition that settles it. Writing \" +\r\n `\"${status}\" directly would change the status without moving the credits it ` +\r\n \"stands for, stranding the hold. Use commitReservation / releaseReservation / \" +\r\n \"expireReservation (or their V2 forms) instead.\",\r\n CreditErrorCode.UNSUPPORTED_OPERATION,\r\n {\r\n userId: reservation.userId,\r\n reservationId: reservation.id,\r\n status,\r\n reason: \"direct_status_write_on_backed_hold\",\r\n }\r\n );\r\n}\r\n","/**\r\n * Promise-chaining mutex keyed by an arbitrary string.\r\n *\r\n * The in-memory repository has no database to serialise it, but its critical\r\n * sections still span `await` points — and every `await` is a scheduling point\r\n * where another caller can interleave. Without a lock, \"read balance, then\r\n * write balance\" in one method is exactly the lost update the SQL adapter uses\r\n * row locks to prevent, so contract tests would pass in memory and fail in\r\n * production. This models those row locks.\r\n */\r\nexport class KeyedMutex {\r\n private readonly tails = new Map<string, Promise<unknown>>();\r\n\r\n /**\r\n * Run `fn` with exclusive access to `key`.\r\n *\r\n * Callers queue in arrival order. The stored tail settles either way, so one\r\n * caller throwing does not wedge the queue behind it.\r\n */\r\n async run<T>(key: string, fn: () => Promise<T>): Promise<T> {\r\n const previous = this.tails.get(key) ?? Promise.resolve();\r\n const result = previous.then(fn, fn);\r\n const tail = result.then(\r\n () => undefined,\r\n () => undefined\r\n );\r\n this.tails.set(key, tail);\r\n\r\n try {\r\n return await result;\r\n } finally {\r\n // Drop the entry once we are the last waiter, so the map does not grow\r\n // one permanent entry per user id ever seen.\r\n if (this.tails.get(key) === tail) {\r\n this.tails.delete(key);\r\n }\r\n }\r\n }\r\n}\r\n","import type {\r\n PortableJournalEntry,\r\n PortableReservation,\r\n PortableTransaction,\r\n PortableUsageLog,\r\n PortableUserCredits,\r\n} from \"../../core/types.js\";\r\nimport { KeyedMutex } from \"./mutex.js\";\r\n\r\n/**\r\n * Backing state for {@link InMemoryCreditRepository}.\r\n *\r\n * Split out so the V2 transition logic can operate on the same state without\r\n * the repository class having to expose its internals publicly.\r\n */\r\nexport class MemoryStore {\r\n readonly users = new Map<string, PortableUserCredits>();\r\n readonly reservations = new Map<string, Map<string, PortableReservation>>();\r\n readonly transactions = new Map<string, PortableTransaction[]>();\r\n usageLogs: PortableUsageLog[] = [];\r\n readonly journalEntries = new Map<string, PortableJournalEntry[]>();\r\n\r\n /** Stands in for the reservations table's partial unique index. */\r\n readonly reservationKeys = new Map<string, string>();\r\n /** Stands in for the journal table's partial unique index. */\r\n readonly journalKeys = new Map<string, string>();\r\n\r\n /** Stands in for the database's per-user row locks. */\r\n readonly locks = new KeyedMutex();\r\n\r\n /**\r\n * Test-only yield point, awaited between reading state and mutating it.\r\n *\r\n * Unset in production, so the critical sections stay synchronous and this\r\n * costs nothing. Tests set it to a real macrotask yield, which forces\r\n * concurrent callers to interleave at exactly the spot a database would have\r\n * them contend — turning the lock above from decoration into the thing the\r\n * concurrency tests actually depend on.\r\n */\r\n schedulingHook?: () => Promise<void>;\r\n\r\n clear(): void {\r\n this.users.clear();\r\n this.reservations.clear();\r\n this.transactions.clear();\r\n this.usageLogs = [];\r\n this.journalEntries.clear();\r\n this.reservationKeys.clear();\r\n this.journalKeys.clear();\r\n }\r\n}\r\n\r\n/**\r\n * Composite map key standing in for a two-column unique index.\r\n *\r\n * The separator is a newline because it cannot appear in a user id and is\r\n * vanishingly unlikely in a caller-supplied idempotency key, so two distinct\r\n * pairs cannot collide into one entry.\r\n */\r\nexport function scopedKey(userId: string, key: string): string {\r\n return `${userId}\\n${key}`;\r\n}\r\n","/**\r\n * Deterministic journal writes for the in-memory V2 transitions.\r\n *\r\n * The SQL adapter gets this from a partial unique index plus an\r\n * `ON CONFLICT DO NOTHING` that re-reads and compares the losing row. There is\r\n * no index here, so the same contract has to be built by hand — and it has to\r\n * be the *same* contract, or the shared reservation tests prove nothing about\r\n * the adapter anyone actually ships.\r\n *\r\n * Two properties matter. A key that already exists must be accepted only when\r\n * the stored row describes the identical event, so a wrong row pre-seeded\r\n * through the public `createJournalEntry` cannot make a transition report a\r\n * charge the ledger does not record. And the check has to happen *before* the\r\n * balances move: this store has no transaction to roll back, so a throw after\r\n * mutation would leave the ledger half-transitioned.\r\n */\r\n\r\nimport { assertRepresentableFields, sameAmount } from \"../../core/amount.js\";\r\nimport { CreditError, CreditErrorCode } from \"../../core/errors.js\";\r\nimport type { CreditSource, PortableJournalEntry } from \"../../core/types.js\";\r\nimport { generateId } from \"../utils.js\";\r\nimport { MemoryStore, scopedKey } from \"./store.js\";\r\n\r\nexport interface JournalWriteInput {\r\n userId: string;\r\n /** The transition writing this entry, so a refusal names what was refused. */\r\n operation: string;\r\n entryType: \"debit\" | \"credit\";\r\n amount: number;\r\n balanceAfter: number;\r\n source: CreditSource;\r\n reservationId: string;\r\n description: string;\r\n metadata?: Record<string, unknown>;\r\n idempotencyKey: string;\r\n}\r\n\r\n/** Name the first field an existing entry disagrees on, or `null` if it matches. */\r\nfunction describeJournalMismatch(\r\n row: PortableJournalEntry,\r\n input: JournalWriteInput\r\n): string | null {\r\n if (row.userId !== input.userId) return \"user_id\";\r\n if (row.entryType !== input.entryType) return \"entry_type\";\r\n if (!sameAmount(row.amount, input.amount)) return \"amount\";\r\n if (!sameAmount(row.balanceAfter, input.balanceAfter)) return \"balance_after\";\r\n if (row.source !== input.source) return \"source\";\r\n if (row.referenceId !== input.reservationId) return \"reference_id\";\r\n if (row.referenceType !== \"reservation\") return \"reference_type\";\r\n\r\n // Only the fields this adapter sets deterministically. Caller-supplied extras\r\n // are free-form and may legitimately differ between a request and its retry,\r\n // so they are not part of the identity of the event.\r\n const existingMeta = (row.metadata ?? {}) as Record<string, unknown>;\r\n const expectedMeta = (input.metadata ?? {}) as Record<string, unknown>;\r\n if (existingMeta.operationType !== expectedMeta.operationType) {\r\n return \"metadata.operationType\";\r\n }\r\n const hadAmount = existingMeta.amount !== undefined;\r\n const wantsAmount = expectedMeta.amount !== undefined;\r\n if (hadAmount !== wantsAmount) return \"metadata.amount\";\r\n if (wantsAmount && !sameAmount(existingMeta.amount, expectedMeta.amount)) {\r\n return \"metadata.amount\";\r\n }\r\n return null;\r\n}\r\n\r\nfunction findEntry(\r\n store: MemoryStore,\r\n userId: string,\r\n entryId: string\r\n): PortableJournalEntry | undefined {\r\n return store.journalEntries.get(userId)?.find((entry) => entry.id === entryId);\r\n}\r\n\r\n/**\r\n * Decide what the journal write will do — without doing it.\r\n *\r\n * Returns the id of an existing, exactly matching entry to reuse, or\r\n * `undefined` when a fresh row is needed. Throws when the key is taken by a\r\n * different event, and it throws *here*, before the caller has touched a single\r\n * balance.\r\n */\r\nexport function planTransitionJournal(\r\n store: MemoryStore,\r\n input: JournalWriteInput\r\n): string | undefined {\r\n // `balanceAfter` is a derived total, and every transition journal write\r\n // passes through this preflight before the ledger moves. Validating it here\r\n // rather than at each call site means a transition added later cannot forget\r\n // it, and a total the numeric column could not hold refuses while the\r\n // balances are still untouched.\r\n assertRepresentableFields(\r\n { amount: input.amount, \"journal balanceAfter\": input.balanceAfter },\r\n { userId: input.userId, reservationId: input.reservationId, operation: input.operation }\r\n );\r\n\r\n const existingId = store.journalKeys.get(scopedKey(input.userId, input.idempotencyKey));\r\n if (!existingId) return undefined;\r\n\r\n const row = findEntry(store, input.userId, existingId);\r\n const mismatch = row\r\n ? describeJournalMismatch(row, input)\r\n : \"the key is registered but its entry is missing\";\r\n if (mismatch) {\r\n throw new CreditError(\r\n `Journal key ${input.idempotencyKey} is already used by a different entry ` +\r\n `(${mismatch}). The transition was refused rather than reported as applied.`,\r\n CreditErrorCode.DATABASE_ERROR,\r\n {\r\n idempotencyKey: input.idempotencyKey,\r\n reservationId: input.reservationId,\r\n mismatch,\r\n }\r\n );\r\n }\r\n return existingId;\r\n}\r\n\r\n/**\r\n * Perform the write the preflight authorised.\r\n *\r\n * `existingId` is whatever {@link planTransitionJournal} returned for this same\r\n * input; passing it through keeps the decision and the write from drifting\r\n * apart, which is the whole point of splitting them.\r\n */\r\nexport function commitTransitionJournal(\r\n store: MemoryStore,\r\n input: JournalWriteInput,\r\n existingId: string | undefined\r\n): string {\r\n if (existingId) return existingId;\r\n\r\n const entry: PortableJournalEntry = {\r\n id: generateId(),\r\n userId: input.userId,\r\n entryType: input.entryType,\r\n amount: input.amount,\r\n balanceAfter: input.balanceAfter,\r\n source: input.source,\r\n referenceId: input.reservationId,\r\n referenceType: \"reservation\",\r\n description: input.description,\r\n metadata: input.metadata,\r\n idempotencyKey: input.idempotencyKey,\r\n createdAt: new Date().toISOString(),\r\n };\r\n\r\n if (!store.journalEntries.has(input.userId)) {\r\n store.journalEntries.set(input.userId, []);\r\n }\r\n store.journalEntries.get(input.userId)!.push(entry);\r\n store.journalKeys.set(scopedKey(input.userId, input.idempotencyKey), entry.id);\r\n return entry.id;\r\n}\r\n","/**\r\n * V2 reservation transitions for the in-memory repository.\r\n *\r\n * These mirror the SQL adapter's guarantees rather than its mechanics: every\r\n * transition runs inside the user's lock (standing in for the row locks),\r\n * re-reads state *after* acquiring it, compares-and-sets the status, and\r\n * writes at most one journal entry keyed so a retry cannot duplicate it.\r\n *\r\n * Modelling that here is what makes the shared contract tests meaningful — a\r\n * naive implementation would pass them by accident because nothing interleaves.\r\n */\r\n\r\nimport {\r\n assertValidCreditAmount,\r\n assertValidStoredAmount,\r\n attributeExpiredBacking,\r\n expiredHoldBackingPatch,\r\n planHoldCommit,\r\n settleExpiredHoldBacking,\r\n sumAmounts,\r\n} from \"../../core/amount.js\";\r\nimport { assertValidIdempotencyKey } from \"../../core/idempotency.js\";\r\nimport {\r\n assertHoldPlaced,\r\n assertKnownReservationStatus,\r\n terminalStatusOf as narrowTerminalStatus,\r\n} from \"../../core/reservation-integrity.js\";\r\nimport { copyRecord } from \"./snapshot.js\";\r\nimport { assertRepresentableFields } from \"../../core/amount.js\";\r\nimport { CreditError, CreditErrorCode } from \"../../core/errors.js\";\r\nimport type {\r\n CommitOutcome,\r\n ExpireOutcome,\r\n ReleaseOutcome,\r\n ReserveOutcome,\r\n TerminalReservationStatus,\r\n} from \"../../core/outcomes.js\";\r\nimport type {\r\n CreditSource,\r\n PortableReservation,\r\n PortableUserCredits,\r\n} from \"../../core/types.js\";\r\nimport { getOperationLabel } from \"../../config/index.js\";\r\nimport { generateId } from \"../utils.js\";\r\nimport {\r\n commitTransitionJournal,\r\n planTransitionJournal,\r\n type JournalWriteInput,\r\n} from \"./transition-journal.js\";\r\nimport type {\r\n ExpireReservationV2Options,\r\n ReservationTransitionOptions,\r\n ReserveCreditsV2Input,\r\n} from \"../v2-types.js\";\r\nimport { reservationJournalKey } from \"../v2-types.js\";\r\nimport { MemoryStore, scopedKey } from \"./store.js\";\r\n\r\n/** Yield at the read/write seam so tests can force real interleaving. */\r\nasync function yieldPoint(store: MemoryStore): Promise<void> {\r\n if (store.schedulingHook) await store.schedulingHook();\r\n}\r\n\r\n/**\r\n * Refuse a transition whose hold is no longer covered by `reserved`.\r\n *\r\n * The SQL adapter enforces this as `reserved >= amount` in the UPDATE's WHERE.\r\n * Clamping with `Math.max(reserved - amount, 0)` instead would look harmless\r\n * and quietly consume the coverage of *other* live holds, so those commits\r\n * would later fail or overdraw. Failing here keeps the damage contained and\r\n * visible, and — because the caller sees `DATABASE_ERROR` rather than\r\n * `INSUFFICIENT_CREDITS` — correctly reads as corruption, not as a user who\r\n * ran out of money.\r\n */\r\nfunction assertReservedCoversHold(\r\n credits: PortableUserCredits,\r\n userId: string,\r\n reservationId: string,\r\n amount: number\r\n): void {\r\n if (credits.reserved >= amount) return;\r\n throw new CreditError(\r\n `Credit balance invariant violated for user ${userId} while processing ` +\r\n `reservation ${reservationId}: reserved (${credits.reserved}) is less ` +\r\n `than the hold (${amount}). The transition was rolled back.`,\r\n CreditErrorCode.DATABASE_ERROR,\r\n { userId, reservationId, amount, reserved: credits.reserved }\r\n );\r\n}\r\n\r\n/**\r\n * Re-validate a persisted amount before the transition touches anything.\r\n *\r\n * Mirrors the SQL adapter: the reservation row was written once and is read\r\n * back on every transition, and a value that is negative, non-finite or off the\r\n * cent grid makes every downstream invariant meaningless — `reserved >= -10` is\r\n * trivially true, and subtracting a negative *adds* credits.\r\n */\r\nfunction assertLockedAmount(reservation: PortableReservation, transition: string): void {\r\n assertValidStoredAmount(reservation.amount, {\r\n userId: reservation.userId,\r\n reservationId: reservation.id,\r\n transition,\r\n });\r\n}\r\n\r\n/**\r\n * Narrow a non-`reserved` status, validating instead of casting.\r\n *\r\n * The cast this replaces reported `already_terminal` — a *success* outcome —\r\n * over a row holding any string at all, so a corrupt status read to the caller\r\n * as \"this reservation is resolved\". See `core/reservation-integrity.ts`.\r\n */\r\nfunction terminalStatusOf(\r\n reservation: PortableReservation,\r\n transition: string\r\n): TerminalReservationStatus {\r\n return narrowTerminalStatus(reservation, transition);\r\n}\r\n\r\n/**\r\n * Every check a persisted reservation must pass before a transition touches it.\r\n *\r\n * Ordered ahead of the `already_terminal` and `not_due` early exits on purpose:\r\n * both are success outcomes, and reporting one over a row that is corrupt or\r\n * unbacked tells the caller the reservation is fine.\r\n */\r\nfunction assertTrustworthy(reservation: PortableReservation, transition: string): void {\r\n assertKnownReservationStatus(reservation, transition);\r\n assertLockedAmount(reservation, transition);\r\n assertHoldPlaced(reservation, transition);\r\n}\r\n\r\nfunction openHolds(store: MemoryStore, userId: string): PortableReservation[] {\r\n return [...(store.reservations.get(userId)?.values() ?? [])].filter(\r\n (reservation) => reservation.status === \"reserved\"\r\n );\r\n}\r\n\r\n/**\r\n * Set the marked credits on an account and attribute them to its open holds: the total\r\n * stored is always the sum of the shares stored. An account that never had any reads\r\n * no holds and gains no fields.\r\n */\r\nexport function writeExpiredHoldBacking(\r\n store: MemoryStore,\r\n credits: PortableUserCredits,\r\n next: number\r\n): void {\r\n const stored = credits.expiredHoldBacking;\r\n if (next <= 0 && !stored) return;\r\n const holds = openHolds(store, credits.userId);\r\n const shares = attributeExpiredBacking(holds, next);\r\n for (const hold of holds) {\r\n const share = shares.get(hold.id) ?? 0;\r\n if (share !== (hold.expiredBacking ?? 0)) hold.expiredBacking = share;\r\n }\r\n Object.assign(credits, expiredHoldBackingPatch(sumAmounts(...shares.values()), stored));\r\n}\r\n\r\nfunction getReservation(\r\n store: MemoryStore,\r\n userId: string,\r\n reservationId: string\r\n): PortableReservation | undefined {\r\n return store.reservations.get(userId)?.get(reservationId);\r\n}\r\n\r\n/**\r\n * The *live* stored record, deliberately — the transitions in this module write\r\n * through it. Everything that crosses the repository's public surface goes\r\n * through `copyRecord` instead; see `./snapshot.js`.\r\n */\r\nfunction requireUser(store: MemoryStore, userId: string): PortableUserCredits {\r\n const credits = store.users.get(userId);\r\n if (!credits) {\r\n throw new CreditError(\r\n `User credits not found for user ${userId}`,\r\n CreditErrorCode.USER_NOT_FOUND,\r\n { userId }\r\n );\r\n }\r\n return credits;\r\n}\r\n\r\nexport async function reserveCreditsV2(\r\n store: MemoryStore,\r\n input: ReserveCreditsV2Input\r\n): Promise<ReserveOutcome> {\r\n assertValidCreditAmount(input.amount, { userId: input.userId });\r\n assertValidIdempotencyKey(input.idempotencyKey, { userId: input.userId });\r\n\r\n return store.locks.run(input.userId, async () => {\r\n if (input.idempotencyKey) {\r\n const existingId = store.reservationKeys.get(\r\n scopedKey(input.userId, input.idempotencyKey)\r\n );\r\n if (existingId) {\r\n const existing = getReservation(store, input.userId, existingId);\r\n if (existing) {\r\n // Before the payload comparison, and before any outcome is chosen: a\r\n // row is only adoptable as a replay if *its own* reserve placed the\r\n // hold. Adopting an unbacked row would report `replayed` over credits\r\n // nothing ever held. Mirrors the SQL adapter.\r\n assertHoldPlaced(existing, \"reserve replay\");\r\n // `expiresAt` is excluded on purpose: a retry legitimately computes a\r\n // later deadline and that must not read as a conflict.\r\n const samePayload =\r\n existing.amount === input.amount &&\r\n existing.operationType === input.operationType;\r\n return samePayload\r\n ? { outcome: \"replayed\", reservation: copyRecord(existing) }\r\n : {\r\n outcome: \"idempotency_conflict\",\r\n idempotencyKey: input.idempotencyKey,\r\n existing: copyRecord(existing),\r\n };\r\n }\r\n }\r\n }\r\n\r\n const credits = requireUser(store, input.userId);\r\n const available = sumAmounts(credits.balance, credits.bonusCredits, -credits.reserved);\r\n await yieldPoint(store);\r\n if (available < input.amount) {\r\n return {\r\n outcome: \"insufficient\",\r\n available,\r\n required: input.amount,\r\n shortfall: sumAmounts(input.amount, -available),\r\n };\r\n }\r\n\r\n const now = new Date().toISOString();\r\n const reservation: PortableReservation = {\r\n id: generateId(),\r\n userId: input.userId,\r\n amount: input.amount,\r\n operationType: input.operationType,\r\n status: \"reserved\",\r\n createdAt: now,\r\n expiresAt: input.expiresAt.toISOString(),\r\n idempotencyKey: input.idempotencyKey,\r\n // The hold-origin fact. Written here and nowhere else, in the same\r\n // critical section that raises `reserved` below, so the row and the hold\r\n // become visible together. `createReservation` cannot set it.\r\n holdPlacedAt: now,\r\n };\r\n\r\n if (!store.reservations.has(input.userId)) {\r\n store.reservations.set(input.userId, new Map());\r\n }\r\n // The derived hold is checked before the reservation row exists, not after:\r\n // a refusal here must leave no reservation, no key registration and no\r\n // counter change behind.\r\n const nextReserved = sumAmounts(credits.reserved, input.amount);\r\n assertRepresentableFields(\r\n { reserved: nextReserved },\r\n { userId: input.userId, operation: \"reserveCredits\" }\r\n );\r\n\r\n store.reservations.get(input.userId)!.set(reservation.id, reservation);\r\n if (input.idempotencyKey) {\r\n store.reservationKeys.set(\r\n scopedKey(input.userId, input.idempotencyKey),\r\n reservation.id\r\n );\r\n }\r\n\r\n credits.reserved = nextReserved;\r\n credits.updatedAt = now;\r\n\r\n return { outcome: \"created\", reservation: copyRecord(reservation) };\r\n });\r\n}\r\n\r\nexport async function commitReservationV2(\r\n store: MemoryStore,\r\n userId: string,\r\n reservationId: string,\r\n options?: ReservationTransitionOptions\r\n): Promise<CommitOutcome> {\r\n return store.locks.run(userId, async () => {\r\n const reservation = getReservation(store, userId, reservationId);\r\n if (!reservation) return { outcome: \"not_found\", reservationId };\r\n // Ahead of the early exits: `already_terminal` and `not_due` are success\r\n // outcomes, and reporting one over a row that is unusable tells the caller\r\n // the reservation is fine. Mirrors the SQL adapter.\r\n assertTrustworthy(reservation, \"commit\");\r\n\r\n if (reservation.status !== \"reserved\") {\r\n return {\r\n outcome: \"already_terminal\",\r\n reservation: copyRecord(reservation),\r\n terminalStatus: terminalStatusOf(reservation, \"commit\"),\r\n };\r\n }\r\n\r\n const credits = requireUser(store, userId);\r\n const amount = reservation.amount;\r\n await yieldPoint(store);\r\n assertReservedCoversHold(credits, userId, reservationId, amount);\r\n const paid = planHoldCommit(\r\n credits.balance,\r\n credits.bonusCredits,\r\n credits.expiredHoldBacking ?? 0,\r\n reservation.expiredBacking ?? 0,\r\n amount\r\n );\r\n if (!paid.covered) {\r\n throw new CreditError(\r\n `Insufficient credits to commit reservation ${reservationId}`,\r\n CreditErrorCode.INSUFFICIENT_CREDITS,\r\n { userId, reservationId, required: amount }\r\n );\r\n }\r\n\r\n // Project the post-transition balances before applying them. The store has\r\n // no transaction to roll back, so everything that can refuse — the journal\r\n // key check below — has to refuse while the ledger is still untouched. The\r\n // projected values are then assigned verbatim, so the number the journal\r\n // records and the number the balance ends up holding cannot drift apart.\r\n const nextBalance = paid.balance;\r\n const nextBonusCredits = paid.bonusCredits;\r\n const balanceAfter = sumAmounts(nextBalance, nextBonusCredits);\r\n\r\n const journal: JournalWriteInput = {\r\n userId,\r\n operation: \"commitReservation\",\r\n entryType: \"debit\",\r\n amount,\r\n balanceAfter,\r\n source: \"operation_commit\",\r\n reservationId,\r\n description:\r\n options?.description ??\r\n `Committed ${amount} credits for ${getOperationLabel(reservation.operationType)}`,\r\n // Caller metadata first: the deterministic fields carry the identity of\r\n // the event that the collision check compares on.\r\n metadata: { ...options?.metadata, operationType: reservation.operationType, amount },\r\n idempotencyKey: reservationJournalKey(reservationId, \"commit\"),\r\n };\r\n const nextReserved = sumAmounts(credits.reserved, -amount);\r\n const nextMonthlyUsed = sumAmounts(credits.monthlyUsed, amount);\r\n assertRepresentableFields(\r\n {\r\n balance: nextBalance,\r\n bonusCredits: nextBonusCredits,\r\n reserved: nextReserved,\r\n monthlyUsed: nextMonthlyUsed,\r\n },\r\n { userId, operation: \"commitReservation\" }\r\n );\r\n\r\n const existingEntryId = planTransitionJournal(store, journal);\r\n\r\n reservation.status = \"committed\";\r\n reservation.completedAt = new Date().toISOString();\r\n\r\n // Drain `balance` before `bonusCredits`, matching the SQL adapter.\r\n credits.balance = nextBalance;\r\n credits.bonusCredits = nextBonusCredits;\r\n credits.reserved = nextReserved;\r\n credits.monthlyUsed = nextMonthlyUsed;\r\n Object.assign(\r\n credits,\r\n expiredHoldBackingPatch(paid.expiredHoldBacking, credits.expiredHoldBacking)\r\n );\r\n credits.updatedAt = new Date().toISOString();\r\n\r\n const journalEntryId = commitTransitionJournal(store, journal, existingEntryId);\r\n\r\n return {\r\n outcome: \"committed\",\r\n reservation: copyRecord(reservation),\r\n amount,\r\n balanceAfter,\r\n journalEntryId,\r\n };\r\n });\r\n}\r\n\r\nexport async function releaseReservationV2(\r\n store: MemoryStore,\r\n userId: string,\r\n reservationId: string,\r\n options?: ReservationTransitionOptions\r\n): Promise<ReleaseOutcome> {\r\n return store.locks.run(userId, async () => {\r\n const reservation = getReservation(store, userId, reservationId);\r\n if (!reservation) return { outcome: \"not_found\", reservationId };\r\n // Ahead of the early exits: `already_terminal` and `not_due` are success\r\n // outcomes, and reporting one over a row that is unusable tells the caller\r\n // the reservation is fine. Mirrors the SQL adapter.\r\n assertTrustworthy(reservation, \"release\");\r\n\r\n if (reservation.status !== \"reserved\") {\r\n return {\r\n outcome: \"already_terminal\",\r\n reservation: copyRecord(reservation),\r\n terminalStatus: terminalStatusOf(reservation, \"release\"),\r\n };\r\n }\r\n\r\n await yieldPoint(store);\r\n const journalEntryId = finishUnspent(store, reservation, {\r\n status: \"released\",\r\n source: \"operation_release\",\r\n transition: \"release\",\r\n verb: \"Released\",\r\n options,\r\n });\r\n\r\n return {\r\n outcome: \"released\",\r\n reservation: copyRecord(reservation),\r\n amount: reservation.amount,\r\n journalEntryId,\r\n };\r\n });\r\n}\r\n\r\nexport async function expireReservationV2(\r\n store: MemoryStore,\r\n userId: string,\r\n reservationId: string,\r\n options?: ExpireReservationV2Options\r\n): Promise<ExpireOutcome> {\r\n const asOf = options?.asOf ?? new Date();\r\n return store.locks.run(userId, async () => {\r\n const reservation = getReservation(store, userId, reservationId);\r\n if (!reservation) return { outcome: \"not_found\", reservationId };\r\n // Ahead of the early exits: `already_terminal` and `not_due` are success\r\n // outcomes, and reporting one over a row that is unusable tells the caller\r\n // the reservation is fine. Mirrors the SQL adapter.\r\n assertTrustworthy(reservation, \"expire\");\r\n\r\n if (reservation.status !== \"reserved\") {\r\n return {\r\n outcome: \"already_terminal\",\r\n reservation: copyRecord(reservation),\r\n terminalStatus: terminalStatusOf(reservation, \"expire\"),\r\n };\r\n }\r\n if (new Date(reservation.expiresAt).getTime() > asOf.getTime()) {\r\n return { outcome: \"not_due\", reservation: copyRecord(reservation) };\r\n }\r\n\r\n await yieldPoint(store);\r\n const journalEntryId = finishUnspent(store, reservation, {\r\n status: \"expired\",\r\n source: \"reservation_expired\",\r\n transition: \"expire\",\r\n verb: \"Expired\",\r\n options,\r\n });\r\n\r\n return {\r\n outcome: \"expired\",\r\n reservation: copyRecord(reservation),\r\n amount: reservation.amount,\r\n journalEntryId,\r\n };\r\n });\r\n}\r\n\r\ninterface UnspentTransition {\r\n status: \"released\" | \"expired\";\r\n source: CreditSource;\r\n transition: \"release\" | \"expire\";\r\n verb: string;\r\n options?: ReservationTransitionOptions;\r\n}\r\n\r\n/**\r\n * Hand a hold back unspent and journal it.\r\n *\r\n * `amount` is 0 because no credits changed hands — the hold only moves back\r\n * into \"available\". The hold size stays in metadata, matching the SQL adapter.\r\n */\r\nfunction finishUnspent(\r\n store: MemoryStore,\r\n reservation: PortableReservation,\r\n transition: UnspentTransition\r\n): string {\r\n const credits = requireUser(store, reservation.userId);\r\n assertReservedCoversHold(\r\n credits,\r\n reservation.userId,\r\n reservation.id,\r\n reservation.amount\r\n );\r\n\r\n // Handing a hold back removes only this hold's share of the credits kept solely to\r\n // back holds. The journal check still runs before the mutation, so a key collision\r\n // leaves `reserved`, the balance, the status and `completedAt` untouched.\r\n const backing = settleExpiredHoldBacking(\r\n credits.balance,\r\n credits.expiredHoldBacking ?? 0,\r\n reservation.expiredBacking ?? 0\r\n );\r\n const nextBalance = sumAmounts(credits.balance, -backing.used);\r\n const journal: JournalWriteInput = {\r\n userId: reservation.userId,\r\n operation: `${transition.transition}Reservation`,\r\n entryType: \"credit\",\r\n amount: 0,\r\n balanceAfter: sumAmounts(nextBalance, credits.bonusCredits),\r\n source: transition.source,\r\n reservationId: reservation.id,\r\n description:\r\n transition.options?.description ??\r\n `${transition.verb} ${reservation.amount} reserved credits for ${getOperationLabel(reservation.operationType)}`,\r\n metadata: {\r\n ...transition.options?.metadata,\r\n operationType: reservation.operationType,\r\n amount: reservation.amount,\r\n ...(backing.used > 0 ? { expiredCreditsRemoved: backing.used } : {}),\r\n },\r\n idempotencyKey: reservationJournalKey(reservation.id, transition.transition),\r\n };\r\n const nextReserved = sumAmounts(credits.reserved, -reservation.amount);\r\n assertRepresentableFields(\r\n { reserved: nextReserved },\r\n { userId: reservation.userId, operation: `${transition.transition}Reservation` }\r\n );\r\n\r\n const existingEntryId = planTransitionJournal(store, journal);\r\n\r\n reservation.status = transition.status;\r\n reservation.completedAt = new Date().toISOString();\r\n credits.reserved = nextReserved;\r\n credits.balance = nextBalance;\r\n Object.assign(credits, expiredHoldBackingPatch(backing.remaining, credits.expiredHoldBacking));\r\n credits.updatedAt = new Date().toISOString();\r\n\r\n return commitTransitionJournal(store, journal, existingEntryId);\r\n}\r\n","/**\n * In-Memory Credit Repository Implementation\n *\n * A database-agnostic implementation of ICreditRepository for testing and prototyping.\n * All data is stored in memory and lost when the process restarts.\n *\n * Usage:\n * - Unit tests without database dependency\n * - Local development and prototyping\n * - Reference implementation for custom repositories\n */\n\nimport type {\n PortableUserCredits,\n PortableReservation,\n PortableTransaction,\n PortableJournalEntry,\n PortableUsageLog,\n SubscriptionTier,\n ReservationStatus,\n MonthlyResetResult,\n SubscriptionExpiryResult,\n} from \"../../core/types.js\";\nimport type {\n ICreditRepository,\n CreateReservationInput,\n CreateTransactionInput,\n CreateUsageLogInput,\n CreateJournalEntryInput,\n UsageLogQuery,\n JournalEntryQuery,\n CreditBalanceUpdate,\n TierUpdateInput,\n AddCreditsAtomicOptions,\n CreditPolicyOptions,\n} from \"../types.js\";\nimport type {\n AddCreditsOutcome,\n CommitOutcome,\n ExpireOutcome,\n ReleaseOutcome,\n ReserveOutcome,\n} from \"../../core/outcomes.js\";\nimport type {\n AddCreditsV2Input,\n ExpireReservationV2Options,\n ReservationTransitionOptions,\n ReserveCreditsV2Input,\n} from \"../v2-types.js\";\nimport {\n assertUnreferencedDirectTransaction,\n createPaymentRefConflictError,\n describePaymentMismatch,\n normalizePaymentRef,\n type PaymentEventPayload,\n} from \"../../core/payment-ref.js\";\nimport {\n createInsufficientCreditsError,\n createReservationAlreadyProcessedError,\n createReservationNotFoundError,\n} from \"../../core/errors.js\";\nimport { assertValidBalanceUpdate, generateId, toDate, getNextMonthlyReset } from \"../utils.js\";\nimport { copyRecord, copyRecords } from \"./snapshot.js\";\nimport {\n assertRepresentableAmount,\n assertRepresentableFields,\n assertRepresentableTierAmount,\n assertValidBalanceTarget,\n assertValidTierBalanceInput,\n planBalanceCap,\n planBalanceTarget,\n spendableBalance,\n storedMonthlyLimit,\n assertValidCreditAmount,\n sumAmounts,\n} from \"../../core/amount.js\";\nimport {\n assertPublicJournalKey,\n assertValidIdempotencyKey,\n} from \"../../core/idempotency.js\";\nimport {\n assertDirectStatusWriteAllowed,\n assertUnkeyedDirectReservation,\n} from \"../../core/reservation-integrity.js\";\nimport { CreditError, CreditErrorCode } from \"../../core/errors.js\";\nimport { MemoryStore, scopedKey } from \"./store.js\";\nimport {\n commitReservationV2,\n expireReservationV2,\n releaseReservationV2,\n reserveCreditsV2,\n writeExpiredHoldBacking,\n} from \"./v2.js\";\nimport {\n getConfigMonthlyLimit,\n getConfigTierConfig,\n getDefaultTier,\n isFreeTier,\n monthlyResetBalance,\n} from \"../../config/index.js\";\n\n/**\n * In-Memory implementation of ICreditRepository\n *\n * Implements all repository methods using Map-based storage.\n * Useful for testing and as a reference implementation.\n */\n/** Apply an increment, or report `undefined` when the caller sent none. */\n/** Accept either half of the `Date | string` timestamp inputs the API takes. */\nfunction isoOf(value: Date | string): string {\n return value instanceof Date ? value.toISOString() : value;\n}\n\nexport class InMemoryCreditRepository implements ICreditRepository {\n private readonly store = new MemoryStore();\n private readonly options: CreditPolicyOptions;\n\n constructor(options: CreditPolicyOptions = {}) {\n this.options = options;\n }\n\n // ==================== User Credits ====================\n\n /**\n * A copy, never the live record.\n *\n * Handing out the stored object made this adapter behave unlike any real\n * one: a caller holding a \"before\" snapshot saw it mutate under them. The\n * service's monthly reset compared `resetResult.credits.balance` against the\n * balance it had read moments earlier, got zero because both were the same\n * object, and silently skipped the reset's journal entry — while the SQL\n * adapter, which maps each row into a fresh object, wrote it.\n */\n async getUserCredits(userId: string): Promise<PortableUserCredits | null> {\n const credits = this.store.users.get(userId);\n return copyRecord(credits) ?? null;\n }\n\n async initializeUserCredits(\n userId: string,\n tier: SubscriptionTier,\n initialBalance: number\n ): Promise<PortableUserCredits> {\n // Create only: a late second call must not wipe an account already in use.\n const existing = this.store.users.get(userId);\n return copyRecord(existing ?? this.seedUser(userId, tier, initialBalance));\n }\n\n /**\n * The synchronous body of `initializeUserCredits`.\n *\n * Kept `await`-free on purpose: `addCreditsV2` seeds a missing user *inside*\n * its critical section, and an `await` between the payment-reference check\n * and the transaction write opens a gap another caller can run through — two\n * simultaneous first deliveries of the same reference would then both credit.\n */\n private seedUser(\n userId: string,\n tier: SubscriptionTier,\n initialBalance: number\n ): PortableUserCredits {\n assertRepresentableAmount(initialBalance, \"initialBalance\", { userId });\n // Derived from tier configuration rather than supplied by the caller, and\n // therefore just as capable of being unrepresentable: a tier configured\n // with `monthlyCredits: 1.005` writes a number the column cannot hold.\n const configured = getConfigMonthlyLimit(tier);\n assertRepresentableTierAmount(configured, \"monthlyLimit\", { userId, tier });\n // Stored through the shared contract so both adapters hold the same number\n // for an unlimited tier. See `storedMonthlyLimit`.\n const monthlyLimit = storedMonthlyLimit(configured);\n\n const now = new Date().toISOString();\n const credits: PortableUserCredits = {\n userId,\n balance: initialBalance,\n bonusCredits: 0,\n reserved: 0,\n tier,\n monthlyLimit,\n monthlyUsed: 0,\n monthlyResetAt: getNextMonthlyReset().toISOString(),\n subscriptionExpiresAt: null,\n createdAt: now,\n updatedAt: now,\n };\n this.store.users.set(userId, credits);\n return credits;\n }\n\n async updateUserCredits(userId: string, updates: CreditBalanceUpdate): Promise<void> {\n assertRepresentableFields(\n {\n balance: updates.balance,\n bonusCredits: updates.bonusCredits,\n reserved: updates.reserved,\n monthlyLimit: updates.monthlyLimit,\n monthlyUsed: updates.monthlyUsed,\n balanceIncrement: updates.balanceIncrement,\n bonusCreditsIncrement: updates.bonusCreditsIncrement,\n reservedIncrement: updates.reservedIncrement,\n monthlyUsedIncrement: updates.monthlyUsedIncrement,\n },\n { userId, operation: \"updateUserCredits\" }\n );\n\n const credits = this.store.users.get(userId);\n if (!credits) {\n throw new Error(`User ${userId} not found`);\n }\n assertValidBalanceUpdate(credits, updates);\n\n // The entire record is projected onto a candidate before anything is\n // written back. Assigning the absolute fields first and validating the\n // increments afterwards would leave a refused update half-applied — an\n // explicit `monthlyUsed: 5` would stick even though the derived `balance`\n // it was sent with was rejected — and this store has no transaction to\n // undo it. Every numeric field is checked on the candidate, so the record\n // either takes the whole update or none of it.\n const next: PortableUserCredits = { ...credits };\n\n if (updates.balance !== undefined) {\n next.balance = updates.balance;\n }\n if (updates.bonusCredits !== undefined) next.bonusCredits = updates.bonusCredits;\n if (updates.reserved !== undefined) next.reserved = updates.reserved;\n if (updates.tier !== undefined) next.tier = updates.tier;\n if (updates.monthlyLimit !== undefined) next.monthlyLimit = updates.monthlyLimit;\n if (updates.monthlyUsed !== undefined) next.monthlyUsed = updates.monthlyUsed;\n if (updates.monthlyResetAt !== undefined) {\n next.monthlyResetAt = isoOf(updates.monthlyResetAt);\n }\n if (updates.subscriptionExpiresAt !== undefined) {\n next.subscriptionExpiresAt =\n updates.subscriptionExpiresAt === null\n ? null\n : isoOf(updates.subscriptionExpiresAt);\n }\n\n // Increments are checked as *results*, not just as arguments: adding a\n // legal 0.01 to a legal 9999999999.99 produces a number the column cannot\n // hold. They apply on top of whatever the absolute fields just set; the SQL\n // adapter is built to match, and the SQL package's\n // `__tests__/integration/adapter-parity.test.ts` pins the two together.\n //\n // `sumAmounts`, not `+`: a float sum can land off the cent grid the ledger\n // validates against, and rejecting a legal increment as `INVALID_AMOUNT` is\n // a worse failure than the overflow this check exists for.\n if (updates.balanceIncrement !== undefined) {\n next.balance = sumAmounts(next.balance, updates.balanceIncrement);\n }\n if (updates.bonusCreditsIncrement !== undefined) {\n next.bonusCredits = sumAmounts(next.bonusCredits, updates.bonusCreditsIncrement);\n }\n if (updates.reservedIncrement !== undefined) {\n next.reserved = sumAmounts(next.reserved, updates.reservedIncrement);\n }\n if (updates.monthlyUsedIncrement !== undefined) {\n next.monthlyUsed = sumAmounts(next.monthlyUsed, updates.monthlyUsedIncrement);\n }\n\n assertRepresentableFields(\n {\n balance: next.balance,\n bonusCredits: next.bonusCredits,\n reserved: next.reserved,\n monthlyUsed: next.monthlyUsed,\n },\n { userId, operation: \"updateUserCredits\" }\n );\n assertRepresentableTierAmount(next.monthlyLimit, \"monthlyLimit\", {\n userId,\n operation: \"updateUserCredits\",\n });\n\n // An absolute balance replaces what the marked credits were part of. An increment\n // cannot reach them: the validator refused it.\n if ((credits.expiredHoldBacking ?? 0) > 0 && updates.balance !== undefined) {\n writeExpiredHoldBacking(this.store, next, 0);\n }\n\n next.updatedAt = new Date().toISOString();\n this.store.users.set(userId, next);\n }\n\n async updateUserTier(userId: string, input: TierUpdateInput): Promise<void> {\n assertRepresentableFields(\n { monthlyLimit: input.monthlyLimit, balance: input.balance, monthlyUsed: input.monthlyUsed },\n { userId, operation: \"updateUserTier\" }\n );\n assertValidTierBalanceInput(input, { userId, operation: \"updateUserTier\" });\n\n const credits = this.store.users.get(userId);\n if (!credits) {\n throw new Error(`User ${userId} not found`);\n }\n\n // Decided from the tier the account holds now, before this write replaces it.\n if (input.balanceCap !== undefined && !isFreeTier(credits.tier)) {\n const capped = planBalanceCap(\n credits.balance,\n input.balanceCap,\n credits.reserved,\n credits.bonusCredits,\n credits.expiredHoldBacking\n );\n credits.balance = capped.balance;\n writeExpiredHoldBacking(this.store, credits, capped.expiredHoldBacking);\n }\n\n credits.tier = input.tier;\n credits.monthlyLimit = input.monthlyLimit;\n // A tier write may lower the balance, but never below what still backs the\n // outstanding holds — see `backedBalanceFloor`. Same clamp as the SQL\n // adapter, so a downgrade cannot strand a live reservation.\n if (input.balance !== undefined) {\n const planned = planBalanceTarget(input.balance, credits.reserved, credits.bonusCredits);\n credits.balance = planned.balance;\n writeExpiredHoldBacking(this.store, credits, planned.expiredHoldBacking);\n }\n if (input.monthlyUsed !== undefined) credits.monthlyUsed = input.monthlyUsed;\n if (input.subscriptionExpiresAt !== undefined) {\n if (input.subscriptionExpiresAt === null) {\n credits.subscriptionExpiresAt = null;\n } else {\n credits.subscriptionExpiresAt = input.subscriptionExpiresAt instanceof Date\n ? input.subscriptionExpiresAt.toISOString()\n : input.subscriptionExpiresAt;\n }\n }\n credits.updatedAt = new Date().toISOString();\n\n this.store.users.set(userId, credits);\n }\n\n // ==================== Reservations ====================\n\n async createReservation(input: CreateReservationInput): Promise<PortableReservation> {\n // Same refusal as the SQL adapter: a row written with an amount the ledger\n // cannot honour has no repair path once it exists, and every transition\n // that later locks it would have to refuse anyway.\n assertValidCreditAmount(input.amount, { userId: input.userId, operation: \"createReservation\" });\n assertUnkeyedDirectReservation(input);\n\n const now = new Date().toISOString();\n const reservation: PortableReservation = {\n id: generateId(),\n userId: input.userId,\n amount: input.amount,\n operationType: input.operationType,\n status: \"reserved\",\n createdAt: now,\n expiresAt: input.expiresAt.toISOString(),\n };\n\n if (!this.store.reservations.has(input.userId)) {\n this.store.reservations.set(input.userId, new Map());\n }\n this.store.reservations.get(input.userId)!.set(reservation.id, reservation);\n\n return copyRecord(reservation);\n }\n\n async getReservation(\n userId: string,\n reservationId: string\n ): Promise<PortableReservation | null> {\n const userReservations = this.store.reservations.get(userId);\n if (!userReservations) return null;\n return copyRecord(userReservations.get(reservationId)) ?? null;\n }\n\n async updateReservationStatus(\n userId: string,\n reservationId: string,\n status: ReservationStatus,\n completedAt?: Date\n ): Promise<void> {\n const userReservations = this.store.reservations.get(userId);\n if (!userReservations) {\n throw new Error(`No reservations found for user ${userId}`);\n }\n\n const reservation = userReservations.get(reservationId);\n if (!reservation) {\n throw new Error(`Reservation ${reservationId} not found`);\n }\n\n // A backed hold's status is owned by the transition that settles it, and no\n // row may be reopened: this method assigns a status and nothing else, so on\n // a V2 row it would change the status without the ledger movement the\n // status stands for. See `assertDirectStatusWriteAllowed`.\n assertDirectStatusWriteAllowed(reservation, status);\n\n reservation.status = status;\n if (completedAt) reservation.completedAt = completedAt.toISOString();\n\n userReservations.set(reservationId, reservation);\n }\n\n // ==================== Atomic Operations ====================\n\n // ==================== V2 boundary ====================\n //\n // As in the Drizzle adapter, V2 is the real implementation and the legacy\n // `*Atomic` methods are adapters over it, so both APIs share one set of\n // guarantees.\n\n async reserveCreditsV2(input: ReserveCreditsV2Input): Promise<ReserveOutcome> {\n return reserveCreditsV2(this.store, input);\n }\n\n async commitReservationV2(\n userId: string,\n reservationId: string,\n options?: ReservationTransitionOptions\n ): Promise<CommitOutcome> {\n return commitReservationV2(this.store, userId, reservationId, options);\n }\n\n async releaseReservationV2(\n userId: string,\n reservationId: string,\n options?: ReservationTransitionOptions\n ): Promise<ReleaseOutcome> {\n return releaseReservationV2(this.store, userId, reservationId, options);\n }\n\n async expireReservationV2(\n userId: string,\n reservationId: string,\n options?: ExpireReservationV2Options\n ): Promise<ExpireOutcome> {\n return expireReservationV2(this.store, userId, reservationId, options);\n }\n\n // ==================== Legacy atomic operations ====================\n\n async reserveCreditsAtomic(\n userId: string,\n amount: number,\n operationType: string,\n expiresAt: Date\n ): Promise<PortableReservation> {\n const outcome = await this.reserveCreditsV2({ userId, amount, operationType, expiresAt });\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(outcome.existing.id, outcome.existing.status);\n }\n\n async commitReservationAtomic(userId: string, reservationId: string): Promise<void> {\n const outcome = await this.commitReservationV2(userId, reservationId);\n if (outcome.outcome === \"committed\") return;\n if (outcome.outcome === \"not_found\") throw createReservationNotFoundError(reservationId);\n // Re-delivering a commit for an already-committed reservation stays a no-op.\n if (outcome.terminalStatus === \"committed\") return;\n throw createReservationAlreadyProcessedError(reservationId, outcome.terminalStatus);\n }\n\n async releaseReservationAtomic(userId: string, reservationId: string): Promise<void> {\n const outcome = await this.releaseReservationV2(userId, reservationId);\n if (outcome.outcome === \"not_found\") throw createReservationNotFoundError(reservationId);\n // Releasing an already-terminal reservation is a no-op, as before.\n }\n\n /**\n * The stored transaction carrying this reference, in *any* user's ledger.\n *\n * Deliberately not scoped to one user. The SQL adapter's unique index covers\n * `payment_ref` alone, so searching only the crediting user's own history made\n * the same reference credit two different accounts here while the SQL adapter\n * treated the second delivery as a duplicate. See `core/payment-ref.ts`.\n */\n private findByPaymentRef(paymentRef: string): PortableTransaction | undefined {\n for (const recorded of this.store.transactions.values()) {\n const hit = recorded.find((transaction) => transaction.paymentRef === paymentRef);\n if (hit) return hit;\n }\n return undefined;\n }\n\n /** The journal entry written alongside a stored purchase, if there is one. */\n private journalForTransaction(\n transaction: PortableTransaction\n ): PortableJournalEntry | undefined {\n return this.store.journalEntries\n .get(transaction.userId)\n ?.find((entry) => entry.referenceId === transaction.id);\n }\n\n /**\n * Credit an account, resolving `paymentRef` to created / replayed / conflict.\n *\n * The reference is checked and the transaction is recorded with no `await`\n * between them. `createTransaction` is `async` but its body is synchronous, so\n * under JavaScript's run-to-completion semantics no other caller can observe\n * the gap — which is what stands in for the SQL adapter's unique index.\n *\n * A `replayed` or `conflict` outcome writes nothing at all: the check runs\n * before the balance moves, not after.\n */\n async addCreditsV2(input: AddCreditsV2Input): Promise<AddCreditsOutcome> {\n const { userId, amount, description, options } = input;\n assertValidCreditAmount(amount, { userId, operation: \"addCredits\" });\n\n // Empty and whitespace-only strings are not references. Normalised in one\n // place so this adapter and the SQL one agree on which calls carry one.\n const paymentRef = normalizePaymentRef(input.paymentRef);\n const payload: PaymentEventPayload = {\n userId,\n amount,\n type: \"purchase\",\n source: options?.source ?? \"purchase\",\n referenceType: options?.referenceType ?? \"transaction\",\n };\n\n if (paymentRef) {\n const existing = this.findByPaymentRef(paymentRef);\n if (existing) {\n const journal = this.journalForTransaction(existing);\n // Presence is not enough. A reference that arrives again with a\n // different user, amount or source is a *different* credit event, and\n // reporting it as a replay would credit the first amount and call the\n // second one done.\n const mismatch = describePaymentMismatch(\n {\n userId: existing.userId,\n amount: existing.amount,\n type: existing.type,\n source: journal?.source,\n referenceType: journal?.referenceType,\n },\n payload\n );\n return mismatch === null\n ? { outcome: \"replayed\", paymentRef, transaction: copyRecord(existing) }\n : { outcome: \"conflict\", paymentRef, existing: copyRecord(existing), mismatch };\n }\n }\n\n // After the reference check, never before it: a replay or a conflict must\n // write nothing, including the account row this creates. An absent user is\n // created at tier defaults, matching the SQL adapter's `ensureUserCredits`\n // — the first credit for a not-yet-seeded user (a webhook that outran\n // provisioning) lands instead of throwing in one adapter and landing in the\n // other.\n if (!this.store.users.has(userId)) {\n const tier = getDefaultTier();\n // `seedUser`, not `await initializeUserCredits(...)`: an `await` here sat\n // between the reference check above and the transaction write below, and\n // two simultaneous first deliveries of one reference both ran through\n // that gap and both credited. The seed is synchronous so the critical\n // section stays unbroken under run-to-completion.\n this.seedUser(userId, tier, storedMonthlyLimit(getConfigMonthlyLimit(tier)));\n }\n const credits = this.store.users.get(userId)!;\n\n // Project first, mutate second. The transaction write below validates the\n // derived `newBalance`, and if that throws after the balance has already\n // moved the store is left holding half of an operation that reported\n // failure. There is no rollback here, so nothing may change until every\n // derived value is known to be storable.\n const previousTotal = sumAmounts(credits.balance, credits.bonusCredits);\n const nextBonusCredits = sumAmounts(credits.bonusCredits, amount);\n const newTotal = sumAmounts(credits.balance, nextBonusCredits);\n assertRepresentableFields(\n { previousBalance: previousTotal, bonusCredits: nextBonusCredits, newBalance: newTotal },\n { userId, operation: \"addCredits\" }\n );\n\n credits.bonusCredits = nextBonusCredits;\n credits.updatedAt = new Date().toISOString();\n this.store.users.set(userId, credits);\n\n // Recorded through the internal writer: the public `createTransaction`\n // refuses a `paymentRef` precisely so that only this path — which moved the\n // balance above — can claim one.\n const transaction = this.recordTransaction({\n userId,\n type: \"purchase\",\n amount,\n description,\n paymentRef,\n previousBalance: previousTotal,\n newBalance: newTotal,\n });\n\n // Journal entry (parity with the Drizzle adapter): a single journal can then\n // serve as the app's credit ledger, including revenue-attribution metadata.\n const journalMetadata = {\n ...(paymentRef ? { paymentRef } : {}),\n ...(options?.metadata ?? {}),\n };\n const entry = await this.createJournalEntry({\n userId,\n entryType: \"credit\",\n amount,\n balanceAfter: newTotal,\n source: payload.source,\n referenceId: transaction.id ?? paymentRef ?? \"unknown\",\n referenceType: payload.referenceType,\n description,\n metadata: Object.keys(journalMetadata).length > 0 ? journalMetadata : undefined,\n });\n\n return paymentRef\n ? { outcome: \"created\", paymentRef, transaction, journalEntryId: entry.id }\n : { outcome: \"created\", transaction, journalEntryId: entry.id };\n }\n\n /**\n * The legacy signature, on top of {@link addCreditsV2}.\n *\n * `Promise<void>` has nowhere to report a conflict, and silently returning is\n * indistinguishable from \"credited\" — the exact failure this round is closing\n * — so a conflict throws. A genuine replay still returns quietly, because\n * that *is* the idempotent no-op the caller asked for.\n */\n async addCreditsAtomic(\n userId: string,\n amount: number,\n description: string,\n paymentRef?: string,\n options?: AddCreditsAtomicOptions\n ): Promise<void> {\n const outcome = await this.addCreditsV2({\n userId,\n amount,\n description,\n paymentRef,\n options,\n });\n if (outcome.outcome === \"conflict\") {\n throw createPaymentRefConflictError(outcome.paymentRef, {\n userId,\n mismatch: outcome.mismatch,\n existingUserId: outcome.existing.userId,\n });\n }\n }\n\n async deductCreditsAtomic(\n userId: string,\n amount: number\n ): Promise<{ previousBalance: number; newBalance: number }> {\n // `amount > 0` alone let 1.005, Infinity and out-of-range values through to\n // arithmetic the `numeric(12, 2)` adapter could never have stored.\n assertValidCreditAmount(amount, { userId, operation: \"deductCredits\" });\n\n const credits = this.store.users.get(userId);\n if (!credits) {\n throw new Error(`User credits not found for userId: ${userId}`);\n }\n\n const spendable = spendableBalance(credits.balance, credits.expiredHoldBacking);\n const available = Math.min(\n sumAmounts(credits.balance, credits.bonusCredits, -credits.reserved),\n sumAmounts(spendable, credits.bonusCredits)\n );\n if (available < amount) {\n throw new Error(\n `Insufficient credits. Available: ${available}, requested: ${amount}`\n );\n }\n\n // Drain balance first, then bonusCredits — same policy as commit. Credits kept\n // only for holds have expired: a deduct cannot land on them.\n const balanceDeduction = Math.min(spendable, amount);\n const bonusDeduction = sumAmounts(amount, -balanceDeduction);\n\n // Projected and checked before anything moves, for the same reason as\n // `addCreditsAtomic`: there is no rollback in this store.\n const previousBalance = sumAmounts(credits.balance, credits.bonusCredits);\n const nextBalance = sumAmounts(credits.balance, -balanceDeduction);\n const nextBonusCredits = sumAmounts(credits.bonusCredits, -bonusDeduction);\n const newBalance = sumAmounts(previousBalance, -amount);\n assertRepresentableFields(\n { previousBalance, balance: nextBalance, bonusCredits: nextBonusCredits, newBalance },\n { userId, operation: \"deductCredits\" }\n );\n\n credits.balance = nextBalance;\n credits.bonusCredits = nextBonusCredits;\n credits.updatedAt = new Date().toISOString();\n this.store.users.set(userId, credits);\n\n return { previousBalance, newBalance };\n }\n\n // ==================== Transactions ====================\n\n async createTransaction(input: CreateTransactionInput): Promise<PortableTransaction> {\n // A record with a `paymentRef` would occupy the global payment boundary\n // without crediting anyone — a later addCredits with the same reference\n // then reports `replayed` and credits nothing. Referenced payments go\n // through addCredits; see `assertUnreferencedDirectTransaction`.\n assertUnreferencedDirectTransaction(input);\n // Always absent after the guard; spelled as the normalised value so a blank\n // string is stored as \"no reference\", matching the SQL adapter.\n return this.recordTransaction({\n ...input,\n paymentRef: normalizePaymentRef(input.paymentRef),\n });\n }\n\n /** The unguarded writer, for `addCreditsV2` — which has moved the balance. */\n private recordTransaction(input: CreateTransactionInput): PortableTransaction {\n // Ledger records, not movements: a correction may be negative and a balance\n // may be below zero, so these check what `numeric(12, 2)` can hold.\n assertRepresentableAmount(input.amount, \"transaction amount\", { userId: input.userId });\n assertRepresentableAmount(input.previousBalance, \"transaction previousBalance\", {\n userId: input.userId,\n });\n assertRepresentableAmount(input.newBalance, \"transaction newBalance\", {\n userId: input.userId,\n });\n\n const transaction: PortableTransaction = {\n id: generateId(),\n userId: input.userId,\n type: input.type,\n amount: input.amount,\n description: input.description,\n paymentRef: input.paymentRef,\n previousBalance: input.previousBalance,\n newBalance: input.newBalance,\n createdAt: new Date().toISOString(),\n };\n\n if (!this.store.transactions.has(input.userId)) {\n this.store.transactions.set(input.userId, []);\n }\n this.store.transactions.get(input.userId)!.push(transaction);\n\n return copyRecord(transaction);\n }\n\n async getTransactions(\n userId: string,\n limit = 50,\n offset = 0\n ): Promise<PortableTransaction[]> {\n const userTransactions = this.store.transactions.get(userId) ?? [];\n // Sort by createdAt descending (most recent first)\n const sorted = [...userTransactions].sort((a, b) => {\n const aDate = toDate(a.createdAt).getTime();\n const bDate = toDate(b.createdAt).getTime();\n return bDate - aDate;\n });\n return copyRecords(sorted.slice(offset, offset + limit));\n }\n\n // ==================== Usage Logs ====================\n\n async logUsage(input: CreateUsageLogInput): Promise<PortableUsageLog> {\n assertRepresentableAmount(input.creditsUsed, \"creditsUsed\", { userId: input.userId });\n\n const log: PortableUsageLog = {\n id: generateId(),\n userId: input.userId,\n operationType: input.operationType,\n provider: input.provider,\n creditsUsed: input.creditsUsed,\n success: input.success,\n errorMessage: input.errorMessage,\n resourceId: input.resourceId,\n resourceType: input.resourceType,\n requestId: input.requestId,\n metadata: input.metadata ? { ...input.metadata } : input.metadata,\n createdAt: new Date().toISOString(),\n };\n\n this.store.usageLogs.push(log);\n return copyRecord(log);\n }\n\n async getUsageLogs(query: UsageLogQuery): Promise<PortableUsageLog[]> {\n let results = [...this.store.usageLogs];\n\n // Apply filters\n if (query.userId) {\n results = results.filter((log) => log.userId === query.userId);\n }\n if (query.operationType) {\n results = results.filter((log) => log.operationType === query.operationType);\n }\n if (query.success !== undefined) {\n results = results.filter((log) => log.success === query.success);\n }\n if (query.startDate) {\n const startTime = query.startDate.getTime();\n results = results.filter(\n (log) => toDate(log.createdAt).getTime() >= startTime\n );\n }\n if (query.endDate) {\n const endTime = query.endDate.getTime();\n results = results.filter(\n (log) => toDate(log.createdAt).getTime() <= endTime\n );\n }\n\n // Sort by createdAt descending\n results.sort((a, b) => {\n return toDate(b.createdAt).getTime() - toDate(a.createdAt).getTime();\n });\n\n // Apply pagination\n const offset = query.offset ?? 0;\n const limit = query.limit ?? 50;\n return copyRecords(results.slice(offset, offset + limit));\n }\n\n async getUsageLogsCount(\n query: Omit<UsageLogQuery, \"limit\" | \"offset\">\n ): Promise<number> {\n const results = await this.getUsageLogs({ ...query, limit: Infinity, offset: 0 });\n return results.length;\n }\n\n // ==================== Journal Entries ====================\n\n async createJournalEntry(input: CreateJournalEntryInput): Promise<PortableJournalEntry> {\n return this.recordJournalEntry(input);\n }\n\n /**\n * The synchronous body of `createJournalEntry`, so `atomicMonthlyReset` can\n * write its journal line inside the same run-to-completion step as the\n * balance write — an `await` between the two is exactly the gap that loses\n * the line when the second half fails.\n */\n private recordJournalEntry(input: CreateJournalEntryInput): PortableJournalEntry {\n assertRepresentableAmount(input.amount, \"journal amount\", { userId: input.userId });\n assertRepresentableAmount(input.balanceAfter, \"journal balanceAfter\", {\n userId: input.userId,\n });\n assertValidIdempotencyKey(input.idempotencyKey, { userId: input.userId });\n assertPublicJournalKey(input.idempotencyKey, input.userId);\n\n // The SQL adapter has a partial unique index on `(user_id, idempotency_key)`.\n // Without the equivalent here, a key written through this public method was\n // invisible to the V2 transitions, which would then happily write a *second*\n // row under the same deterministic key — the ledger would record one event\n // twice and the two adapters would disagree about what happened.\n const key =\n input.idempotencyKey !== undefined\n ? scopedKey(input.userId, input.idempotencyKey)\n : undefined;\n if (key !== undefined && this.store.journalKeys.has(key)) {\n throw new CreditError(\n `Journal idempotency key ${input.idempotencyKey} is already used for user ` +\n `${input.userId}. The unique constraint refuses a second entry.`,\n CreditErrorCode.DATABASE_ERROR,\n { userId: input.userId, idempotencyKey: input.idempotencyKey }\n );\n }\n\n const entry: PortableJournalEntry = {\n id: generateId(),\n userId: input.userId,\n entryType: input.entryType,\n amount: input.amount,\n balanceAfter: input.balanceAfter,\n source: input.source,\n referenceId: input.referenceId,\n referenceType: input.referenceType,\n description: input.description,\n metadata: input.metadata ? { ...input.metadata } : input.metadata,\n idempotencyKey: input.idempotencyKey,\n createdAt: new Date().toISOString(),\n };\n\n if (!this.store.journalEntries.has(input.userId)) {\n this.store.journalEntries.set(input.userId, []);\n }\n this.store.journalEntries.get(input.userId)!.push(entry);\n if (key !== undefined) this.store.journalKeys.set(key, entry.id);\n\n return copyRecord(entry);\n }\n\n async getJournalEntries(query: JournalEntryQuery): Promise<PortableJournalEntry[]> {\n let results = this.store.journalEntries.get(query.userId) ?? [];\n\n // Apply filters\n if (query.source) {\n results = results.filter((entry) => entry.source === query.source);\n }\n if (query.referenceType) {\n results = results.filter((entry) => entry.referenceType === query.referenceType);\n }\n if (query.startDate) {\n const startTime = query.startDate.getTime();\n results = results.filter(\n (entry) => toDate(entry.createdAt).getTime() >= startTime\n );\n }\n if (query.endDate) {\n const endTime = query.endDate.getTime();\n results = results.filter(\n (entry) => toDate(entry.createdAt).getTime() <= endTime\n );\n }\n\n // Sort by createdAt descending\n results = [...results].sort((a, b) => {\n return toDate(b.createdAt).getTime() - toDate(a.createdAt).getTime();\n });\n\n // Apply pagination\n const offset = query.offset ?? 0;\n const limit = query.limit ?? 50;\n return copyRecords(results.slice(offset, offset + limit));\n }\n\n async getJournalEntriesCount(\n query: Omit<JournalEntryQuery, \"limit\" | \"offset\">\n ): Promise<number> {\n const results = await this.getJournalEntries({\n ...query,\n limit: Infinity,\n offset: 0,\n });\n return results.length;\n }\n\n // ==================== Cleanup Operations ====================\n\n /**\n * Expire every hold whose deadline has passed.\n *\n * Each candidate goes through the guarded {@link expireReservationV2}, which\n * re-checks the status and the deadline under the user's lock. The previous\n * implementation released the hold and then overwrote the status to\n * `expired`, so a commit landing in between got its credits handed back and\n * was then relabelled.\n */\n async findAndExpireReservations(\n _batchSize = 100,\n _maxIterations = 100\n ): Promise<{\n expiredCount: number;\n creditsReleased: number;\n errors: string[];\n }> {\n const asOf = new Date();\n let expiredCount = 0;\n let creditsReleased = 0;\n const errors: string[] = [];\n\n // Snapshot the candidates first: expiring mutates the maps being iterated.\n const candidates: Array<{ userId: string; reservationId: string }> = [];\n for (const [userId, userReservations] of this.store.reservations) {\n for (const [reservationId, reservation] of userReservations) {\n if (\n reservation.status === \"reserved\" &&\n toDate(reservation.expiresAt).getTime() < asOf.getTime()\n ) {\n candidates.push({ userId, reservationId });\n }\n }\n }\n\n for (const candidate of candidates) {\n try {\n const outcome = await this.expireReservationV2(\n candidate.userId,\n candidate.reservationId,\n { asOf }\n );\n if (outcome.outcome === \"expired\") {\n expiredCount++;\n creditsReleased = sumAmounts(creditsReleased, outcome.amount);\n }\n } catch (error) {\n errors.push(\n `Failed to expire reservation ${candidate.reservationId}: ${error}`\n );\n }\n }\n\n return { expiredCount, creditsReleased, errors };\n }\n\n // ==================== Atomic Monthly Reset ====================\n\n /**\n * @param _tier - Not trusted. The caller read it earlier and the account may\n * have changed tier since, so the reset uses the tier stored on the account.\n */\n async atomicMonthlyReset(\n userId: string,\n _tier: SubscriptionTier,\n expectedResetAt: Date | string\n ): Promise<MonthlyResetResult> {\n const credits = this.store.users.get(userId);\n if (!credits) {\n throw new Error(`User ${userId} not found`);\n }\n\n // Optimistic locking: check if expectedResetAt matches current value\n const currentResetAt = toDate(credits.monthlyResetAt).getTime();\n const expected = toDate(expectedResetAt).getTime();\n\n if (currentResetAt !== expected) {\n // Another request already performed the reset\n return { wasReset: false, credits: { ...credits } };\n }\n\n const tier = credits.tier;\n // The resolver decides on credits the account may spend, not on those kept\n // only for holds; otherwise \"keep the balance\" would unmark them.\n const spendable = spendableBalance(credits.balance, credits.expiredHoldBacking);\n const decision = this.options.resolveMonthlyReset?.({ tier, balance: spendable });\n if (decision === null) {\n return { wasReset: false, credits: { ...credits } };\n }\n if (decision) {\n assertValidBalanceTarget(decision.balance, \"resolveMonthlyReset balance\", { userId, tier });\n if (decision.monthlyLimit !== undefined) {\n assertValidBalanceTarget(decision.monthlyLimit, \"resolveMonthlyReset monthlyLimit\", {\n userId,\n tier,\n });\n }\n } else {\n assertRepresentableTierAmount(getConfigMonthlyLimit(tier), \"monthlyLimit\", { userId, tier });\n }\n\n // Perform the reset\n const nextReset = getNextMonthlyReset();\n\n // The unlimited contract, from the one place that defines it. This used to\n // read `newBalance === Infinity ? credits.balance : newBalance` — \"leave an\n // unlimited balance alone\" — which never restored an unlimited account whose\n // balance had been driven to zero. See `monthlyResetBalance`.\n // Floored at what still backs the outstanding holds: a reset that cut\n // `balance + bonusCredits` below `reserved` would strand every live\n // reservation at commit time with INSUFFICIENT_CREDITS. See\n // `backedBalanceFloor`.\n const previousBalance = credits.balance;\n let target: number;\n if (decision) {\n target = decision.balance;\n } else {\n const configured = monthlyResetBalance(tier);\n target =\n configured.kind === \"atLeast\" ? Math.max(spendable, configured.value) : configured.value;\n }\n const planned = planBalanceTarget(target, credits.reserved, credits.bonusCredits);\n const newBalance = planned.balance;\n\n // The journal line is part of the reset, not a follow-up. It is validated\n // before anything mutates and written synchronously after, so no failure or\n // interleaving can consume the CAS and lose the line — which is exactly\n // what happened when the service wrote it as a separate call: the retry saw\n // `wasReset: false` and the reset entry was gone for good.\n const change = sumAmounts(newBalance, -previousBalance);\n const balanceAfter = sumAmounts(newBalance, credits.bonusCredits);\n assertRepresentableAmount(Math.abs(change), \"journal amount\", { userId });\n assertRepresentableAmount(balanceAfter, \"journal balanceAfter\", { userId });\n\n credits.balance = newBalance;\n writeExpiredHoldBacking(this.store, credits, planned.expiredHoldBacking);\n if (decision?.monthlyLimit !== undefined) credits.monthlyLimit = decision.monthlyLimit;\n credits.monthlyUsed = 0;\n credits.monthlyResetAt = nextReset.toISOString();\n credits.updatedAt = new Date().toISOString();\n this.store.users.set(userId, credits);\n\n if (change !== 0) {\n this.recordJournalEntry({\n userId,\n entryType: change > 0 ? \"credit\" : \"debit\",\n amount: Math.abs(change),\n balanceAfter,\n source: \"monthly_reset\",\n referenceId: `reset-${Date.now()}`,\n referenceType: \"reset\",\n description: `Monthly credit reset for ${tier} tier.`,\n metadata: { tier, previousBalance, newBalance },\n });\n }\n\n return { wasReset: true, credits: { ...credits }, journaled: true };\n }\n\n // ==================== Subscription Expiry ====================\n\n async checkAndHandleSubscriptionExpiry(\n userId: string,\n gracePeriodDays = 3\n ): Promise<SubscriptionExpiryResult> {\n const credits = this.store.users.get(userId);\n if (!credits) {\n throw new Error(`User ${userId} not found`);\n }\n\n // Free tier doesn't expire\n if (isFreeTier(credits.tier) || !credits.subscriptionExpiresAt) {\n return {\n wasDowngraded: false,\n inGracePeriod: false,\n graceDaysRemaining: 0,\n credits: { ...credits },\n };\n }\n\n const now = new Date();\n const expiresAt = toDate(credits.subscriptionExpiresAt);\n const daysSinceExpiry =\n (now.getTime() - expiresAt.getTime()) / (1000 * 60 * 60 * 24);\n\n if (daysSinceExpiry <= 0) {\n // Not expired yet\n return {\n wasDowngraded: false,\n inGracePeriod: false,\n graceDaysRemaining: 0,\n credits: { ...credits },\n };\n }\n\n if (daysSinceExpiry <= gracePeriodDays) {\n // In grace period\n return {\n wasDowngraded: false,\n inGracePeriod: true,\n graceDaysRemaining: Math.ceil(gracePeriodDays - daysSinceExpiry),\n credits: { ...credits },\n };\n }\n\n // Grace period expired - downgrade to the configured default tier\n const defaultTier = getDefaultTier();\n let limit: number;\n if (this.options.getDowngradeBalanceCap) {\n limit = this.options.getDowngradeBalanceCap();\n assertValidBalanceTarget(limit, \"getDowngradeBalanceCap\", { userId, tier: defaultTier });\n } else {\n // `getConfigMonthlyLimit`, not the raw `monthlyCredits`: in tier *config*\n // zero means unlimited, so reading the field directly would downgrade onto\n // an unlimited default tier with a limit and a balance of zero.\n const configured = getConfigMonthlyLimit(defaultTier);\n assertRepresentableTierAmount(configured, \"monthlyLimit\", {\n userId,\n tier: defaultTier,\n });\n limit = storedMonthlyLimit(configured);\n }\n\n // The downgrade may cut the balance to the new tier's limit, but never\n // below what still backs the outstanding holds — see `backedBalanceFloor`.\n const previousTier = credits.tier;\n const previousBalance = credits.balance;\n const planned = planBalanceCap(\n credits.balance,\n limit,\n credits.reserved,\n credits.bonusCredits,\n credits.expiredHoldBacking\n );\n const newBalance = planned.balance;\n\n // The journal line is part of the downgrade, not a follow-up: validated\n // before anything mutates, written synchronously after. Written separately\n // by the service, a failure landed after the tier write, and no retry ever\n // fired again — the row was no longer eligible, the audit line gone.\n const balanceAfter = sumAmounts(newBalance, credits.bonusCredits);\n assertRepresentableAmount(balanceAfter, \"journal balanceAfter\", { userId });\n\n credits.tier = defaultTier;\n credits.monthlyLimit = limit;\n credits.balance = newBalance;\n writeExpiredHoldBacking(this.store, credits, planned.expiredHoldBacking);\n credits.subscriptionExpiresAt = null;\n credits.updatedAt = new Date().toISOString();\n this.store.users.set(userId, credits);\n\n this.recordJournalEntry({\n userId,\n entryType: \"debit\",\n amount: 0, // No credits deducted, just tier change\n balanceAfter,\n source: \"subscription_downgrade\",\n referenceId: `downgrade-${Date.now()}`,\n referenceType: \"subscription\",\n description: `Subscription expired. Downgraded from ${previousTier} to ${defaultTier} tier.`,\n metadata: { previousTier, previousBalance, newBalance },\n });\n\n return {\n wasDowngraded: true,\n inGracePeriod: false,\n graceDaysRemaining: 0,\n credits: { ...credits },\n journaled: true,\n };\n }\n\n // ==================== Testing Utilities ====================\n\n /**\n * Clear all data (useful for testing)\n */\n clear(): void {\n this.store.clear();\n }\n\n /**\n * Install a yield point inside every V2 critical section (testing only).\n *\n * Unset, the critical sections run start-to-finish synchronously, so\n * concurrent callers never interleave and a concurrency test would pass even\n * with the locking removed. Setting this to a real yield (a macrotask or a\n * barrier) makes callers genuinely overlap, so the tests exercise the lock\n * instead of the event loop. Never call this in production code.\n */\n setSchedulingHook(hook: (() => Promise<void>) | undefined): void {\n this.store.schedulingHook = hook;\n }\n\n /**\n * Get all users (useful for testing/debugging)\n */\n getAllUsers(): PortableUserCredits[] {\n return copyRecords(Array.from(this.store.users.values()));\n }\n\n /**\n * Get all reservations for a user (useful for testing)\n */\n getAllReservations(userId: string): PortableReservation[] {\n const userReservations = this.store.reservations.get(userId);\n if (!userReservations) return [];\n return copyRecords(Array.from(userReservations.values()));\n }\n}\n\n/**\n * Create a new in-memory repository instance\n * Each call creates a fresh, isolated instance\n */\nexport function createInMemoryCreditRepository(\n options: CreditPolicyOptions = {}\n): InMemoryCreditRepository {\n return new InMemoryCreditRepository(options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACyfO,SAAS,kBACd,YACuD;AACvD,SACE,OAAO,WAAW,qBAAqB,cACvC,OAAO,WAAW,wBAAwB,cAC1C,OAAO,WAAW,yBAAyB,cAC3C,OAAO,WAAW,wBAAwB;AAE9C;AAUO,SAAS,yBACd,YAC8D;AAC9D,SAAO,OAAO,WAAW,iBAAiB;AAC5C;AAMO,SAAS,oBAAoB,SAAmD;AAErF,SAAO;AAAA,IACL,QAAQ,QAAQ;AAAA,IAChB,SAAS,QAAQ;AAAA,IACjB,cAAc,QAAQ,gBAAgB;AAAA,IAC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