@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/service/index.ts","../../src/core/errors.ts","../../src/core/amount.ts","../../src/core/types.ts","../../src/config/index.ts","../../src/config/provider.ts","../../src/core/payment-ref.ts","../../src/repository/types.ts","../../src/repository/flow.ts","../../src/service/credits-service.ts"],"sourcesContent":["export {\n CreditsService,\n createCreditsService,\n} from \"./credits-service.js\";\n\nexport type {\n LowBalanceNotificationCallback,\n SubscriptionExpiredNotificationCallback,\n ReserveCreditsOptions,\n DeductCreditsOptions,\n} from \"./credits-service.js\";\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 and exact comparison for credit amounts.\n *\n * Every amount ends up in a `numeric(12, 2)` column, so the ledger can only\n * represent values on the cent grid, with at most ten integer digits. A value\n * outside that grid is not \"close enough\" — PostgreSQL silently rounds it on\n * write, and the row that comes back no longer equals what the caller asked\n * for. Rejecting it before any row is touched is the only way the ledger and\n * the caller can agree on what happened.\n *\n * These live in core rather than in an adapter so every repository — shipped\n * or third-party — validates identically.\n */\n\nimport { CreditError, CreditErrorCode } from \"./errors.js\";\n\n/** `numeric(12, 2)`: 12 significant digits, 2 of them after the point. */\nexport const CREDIT_AMOUNT_SCALE = 2;\n/** Largest representable amount: ten integer digits plus two decimals. */\nexport const CREDIT_AMOUNT_MAX = 9_999_999_999.99;\nconst MAX_CENTS = 999_999_999_999;\n\n/**\n * Convert an amount to whole cents, or `null` if it is not exactly on the grid.\n *\n * `Math.round(value * 100) === value * 100` is the tempting check and it is\n * wrong: `1.005 * 100` is `100.49999999999999` in binary float, so a genuinely\n * invalid value can pass and a valid one can fail. Rounding first and then\n * confirming the value round-trips (`value === cents / 100`) is exact for\n * everything in range, because a cent count below 2^53 divided by 100 is the\n * nearest double to that decimal, which is what the literal parsed to.\n */\nexport function toCents(value: number): number | null {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return null;\n const cents = Math.round(value * 100);\n if (!Number.isSafeInteger(cents)) return null;\n return value === cents / 100 ? cents : null;\n}\n\n/**\n * Add amounts on the cent grid, exactly.\n *\n * Deriving a total with `+` is not safe in a ledger that validates against the\n * grid: `0.10 + 0.20` is `0.30000000000000004` and `0.30 - 0.10` is\n * `0.19999999999999998`, neither of which is a value `numeric(12, 2)` can hold.\n * Two perfectly legal columns would therefore produce a total the validator\n * rejects with `INVALID_AMOUNT`, blaming the caller for a rounding artefact.\n * Summing whole cents is exact for every value in range, and `cents / 100` is\n * the nearest double to that decimal — the same one the literal would parse to.\n *\n * Subtract by negating: `sumAmounts(total, -amount)`. Negation is exact.\n *\n * This is arithmetic, not validation. If any input is itself off the grid the\n * float sum is returned unchanged — deliberately, so a corrupt value is never\n * rounded into legitimacy here — but that is not a guarantee the result will be\n * rejected downstream: two off-grid inputs can cancel, and `sumAmounts(0.005,\n * -0.005)` is a perfectly representable `0`. Inputs read from storage must be\n * validated as inputs, with `assertValidStoredAmount` or\n * `assertValidStoredAmountRaw`, before they are summed. Checking only the\n * derived result is not enough and never was.\n */\nexport function sumAmounts(...values: number[]): number {\n let cents = 0;\n for (const value of values) {\n const valueCents = toCents(value);\n if (valueCents === null) return floatSum(values);\n cents += valueCents;\n }\n return Number.isSafeInteger(cents) ? cents / 100 : floatSum(values);\n}\n\nfunction floatSum(values: number[]): number {\n let total = 0;\n for (const value of values) total += value;\n return total;\n}\n\n/** Amounts that may be *moved*: strictly positive and on the cent grid. */\nexport function isValidCreditAmount(value: unknown): value is number {\n if (typeof value !== \"number\") return false;\n const cents = toCents(value);\n return cents !== null && cents > 0 && cents <= MAX_CENTS;\n}\n\n/**\n * Reject an unusable amount before any row is written.\n *\n * @param context - merged into the error details, e.g. `{ userId }`.\n */\nexport function assertValidCreditAmount(\n value: unknown,\n context?: Record<string, unknown>\n): asserts value is number {\n if (isValidCreditAmount(value)) return;\n throw new CreditError(\n creditAmountReason(value),\n CreditErrorCode.INVALID_AMOUNT,\n { amount: value, max: CREDIT_AMOUNT_MAX, scale: CREDIT_AMOUNT_SCALE, ...context }\n );\n}\n\n/** Say precisely which rule the value broke, so the caller can fix it. */\nfunction creditAmountReason(value: unknown): string {\n if (typeof value !== \"number\") {\n return `Credit amount must be a number (got ${typeof value})`;\n }\n if (!Number.isFinite(value)) {\n return `Credit amount must be finite (got ${String(value)})`;\n }\n if (value <= 0) {\n return `Credit amount must be greater than zero (got ${value})`;\n }\n if (value > CREDIT_AMOUNT_MAX) {\n return `Credit amount ${value} exceeds the maximum of ${CREDIT_AMOUNT_MAX}`;\n }\n return `Credit amount ${value} is not exact to ${CREDIT_AMOUNT_SCALE} decimal places`;\n}\n\n/**\n * Amounts the ledger can *record*: on the cent grid and in range, but free to\n * be zero or negative.\n *\n * Not every numeric column holds something spendable. A release journal entry\n * records `amount: 0` because no credits changed hands, and `balanceAfter` goes\n * negative for an account that was corrected or allowed to overdraw. Forcing\n * those through {@link isValidCreditAmount} would reject legitimate ledger\n * rows; skipping validation entirely would let `Infinity` or a third decimal\n * reach the column and be silently rounded or rejected by the driver.\n */\nexport function isRepresentableAmount(value: unknown): value is number {\n if (typeof value !== \"number\") return false;\n const cents = toCents(value);\n return cents !== null && Math.abs(cents) <= MAX_CENTS;\n}\n\n/**\n * Reject a ledger value the `numeric(12, 2)` column cannot hold exactly.\n *\n * @param field - the column being written, so the error names the culprit.\n */\nexport function assertRepresentableAmount(\n value: unknown,\n field: string,\n context?: Record<string, unknown>\n): asserts value is number {\n if (isRepresentableAmount(value)) return;\n throw new CreditError(\n `${field} must be a finite number exact to ${CREDIT_AMOUNT_SCALE} decimal places ` +\n `within ±${CREDIT_AMOUNT_MAX} (got ${String(value)})`,\n CreditErrorCode.INVALID_AMOUNT,\n { field, value, max: CREDIT_AMOUNT_MAX, scale: CREDIT_AMOUNT_SCALE, ...context }\n );\n}\n\n/**\n * Check a whole set of optional ledger fields at once.\n *\n * The balance writers each take a handful of independently optional numbers,\n * and validating them one `if` at a time is where one quietly gets missed.\n * Undefined entries are skipped — they mean \"leave this column alone\".\n */\nexport function assertRepresentableFields(\n fields: Record<string, unknown>,\n context?: Record<string, unknown>\n): void {\n for (const [field, value] of Object.entries(fields)) {\n if (value === undefined) continue;\n assertRepresentableAmount(value, field, context);\n }\n}\n\n/**\n * The lowest `balance` that keeps every outstanding hold committable.\n *\n * Commit's funding guard is `balance + bonusCredits >= amount`, and every live\n * hold is counted in `reserved`, so any write that lowers `balance` must keep\n * `balance + bonusCredits >= reserved` — otherwise a hold that was fully backed\n * when it was placed throws `INSUFFICIENT_CREDITS` at commit time and is\n * stranded. Monthly resets, tier downgrades and explicit tier writes all lower\n * `balance` to a configured target; this is the floor they may not cut through.\n *\n * The floor is `reserved - bonusCredits`, never below zero: bonus credits also\n * fund commits, so they count toward the backing.\n */\nexport function backedBalanceFloor(reserved: number, bonusCredits: number): number {\n const floor = Math.max(0, sumAmounts(reserved, -bonusCredits));\n // A floor beyond the representable range means the row itself is corrupt —\n // e.g. a large negative `bonusCredits` pushing `reserved - bonusCredits`\n // past the `numeric(12,2)` cap. Refuse loudly: writing it would succeed in\n // memory and be rejected by the SQL column, splitting the adapters.\n assertRepresentableAmount(floor, \"backedBalanceFloor\", { reserved, bonusCredits });\n return floor;\n}\n\n/**\n * Validate a limit derived from tier configuration.\n *\n * `Infinity` is this codebase's sentinel for an unlimited tier, so it is\n * accepted here; {@link storedMonthlyLimit} decides what actually reaches the\n * column. Every other value ends up in `numeric(12, 2)` and has to fit, so a\n * tier configured with `monthlyCredits: 1.005` is caught here rather than\n * silently rounded to `1.01` by PostgreSQL.\n */\nexport function assertRepresentableTierAmount(\n value: unknown,\n field: string,\n context?: Record<string, unknown>\n): void {\n if (value === Number.POSITIVE_INFINITY) return;\n assertRepresentableAmount(value, field, context);\n}\n\n/**\n * Validate a stored amount in the representation storage actually returned.\n *\n * Checking the mapped float is not enough, because the mapping is lossy in both\n * directions. A `numeric` column with no scale constraint can hold\n * `9999999999.9900001`; `Number()` rounds that to `9999999999.99`, which is a\n * perfectly valid amount, so a validator looking at the mapped value sees\n * nothing wrong and the transition proceeds — while PostgreSQL goes on doing\n * exact arithmetic with the digits JavaScript threw away. `NaN` and values past\n * double range are worse: the mapper turns them into `0`, which misreports what\n * the row holds.\n *\n * So this runs on the driver's own output — a string, for `numeric` — and uses\n * exact integer arithmetic. It returns the amount as a float only after\n * establishing that the float is a faithful representation of it.\n *\n * @returns the stored amount, exactly representable as a JS number.\n */\n/**\n * How an unlimited tier's monthly limit is stored.\n *\n * `getConfigMonthlyLimit` returns `Infinity` for an unlimited tier, and no\n * numeric column can hold that. Both adapters therefore store the ceiling of\n * the representable range instead: any real usage compares below it, so\n * \"unlimited\" keeps behaving like unlimited, and a reader that knows nothing\n * about the sentinel sees a very large allowance rather than a wrong one.\n *\n * This exists so the two adapters cannot drift. The SQL adapter previously\n * stored `0` here, which reads as *no* allowance — the exact opposite — while\n * the in-memory adapter kept `Infinity`.\n */\nexport function storedMonthlyLimit(limit: number): number {\n return Number.isFinite(limit) ? limit : CREDIT_AMOUNT_MAX;\n}\n\nexport function assertValidStoredAmountRaw(\n raw: unknown,\n context: Record<string, unknown>\n): number {\n const cents = numericToCents(raw);\n if (cents !== null && cents > 0n && cents <= BigInt(MAX_CENTS)) {\n return Number(cents) / 100;\n }\n throw new CreditError(\n `Stored credit amount ${String(raw)} is not a valid amount, so this ` +\n \"transition was refused before any state changed. The row must be \" +\n \"repaired before it can be committed, released or expired.\",\n CreditErrorCode.INVALID_AMOUNT,\n {\n amount: typeof raw === \"string\" ? raw : String(raw),\n reason: \"corrupt_stored_amount\",\n max: CREDIT_AMOUNT_MAX,\n scale: CREDIT_AMOUNT_SCALE,\n ...context,\n }\n );\n}\n\n/**\n * Reject a *persisted* amount that the ledger cannot honour.\n *\n * A reservation row is written once and read back on every transition, and\n * nothing stops a direct SQL write, a botched migration, or an older version of\n * this library from leaving an amount the invariants cannot reason about. A\n * negative one is the dangerous case: `reserved >= amount` is trivially true\n * for it, and `balance - (-10)` *adds* credits, so a transition that trusts the\n * stored value mints money. Every transition therefore re-validates what it\n * locked before it changes anything.\n *\n * Deliberately fails release and expire as well as commit. Returning a hold of\n * an unknown size is not obviously safer than spending one — it hands back\n * coverage that may never have been taken — so a corrupt row stops moving\n * entirely and waits for an operator, rather than being partially honoured.\n *\n * This is the float-typed form, used by the in-memory adapter where the stored\n * value *is* a JS number and no conversion has happened. A repository whose\n * storage returns some other representation must use\n * {@link assertValidStoredAmountRaw} instead, or the conversion will hide the\n * corruption from the check.\n */\nexport function assertValidStoredAmount(\n value: unknown,\n context: Record<string, unknown>\n): asserts value is number {\n if (isValidCreditAmount(value)) return;\n throw new CreditError(\n `Stored credit amount ${String(value)} is not a valid amount, so this ` +\n \"transition was refused before any state changed. The row must be \" +\n \"repaired before it can be committed, released or expired.\",\n CreditErrorCode.INVALID_AMOUNT,\n { amount: value, reason: \"corrupt_stored_amount\", max: CREDIT_AMOUNT_MAX, ...context }\n );\n}\n\n/**\n * Parse a value read back from a `numeric` column into exact cents.\n *\n * Drivers return `numeric` as a string precisely so no precision is lost in\n * transit; comparing the parsed floats would throw that away again. Returns\n * `null` for anything unparseable so callers can treat it as \"not equal\"\n * rather than crashing on malformed ledger data.\n */\nexport function numericToCents(value: unknown): bigint | null {\n if (typeof value === \"number\") {\n const cents = toCents(value);\n return cents === null ? null : BigInt(cents);\n }\n if (typeof value !== \"string\") return null;\n\n const match = /^([+-]?)(\\d+)(?:\\.(\\d*))?$/.exec(value.trim());\n if (!match) return null;\n\n const [, sign, whole, fraction = \"\"] = match;\n // More than two decimals is only acceptable when the extra digits are zeros;\n // anything else never came from a numeric(12,2) column.\n if (/[1-9]/.test(fraction.slice(CREDIT_AMOUNT_SCALE))) return null;\n\n const cents =\n BigInt(whole) * 100n + BigInt(fraction.slice(0, CREDIT_AMOUNT_SCALE).padEnd(CREDIT_AMOUNT_SCALE, \"0\"));\n return sign === \"-\" ? -cents : cents;\n}\n\n/**\n * Exact equality for two amounts that may be numbers or `numeric` strings.\n *\n * Unparseable input is *not* equal to anything, including itself — a\n * comparison against corrupt data must never come back \"matches\".\n */\nexport function sameAmount(a: unknown, b: unknown): boolean {\n const left = numericToCents(a);\n const right = numericToCents(b);\n return left !== null && right !== null && left === right;\n}\n","import { sumAmounts } from \"./amount.js\";\n/**\n * Portable credits types - framework and database agnostic\n *\n * These types use standard JavaScript types (string, Date) instead of\n * Firebase-specific types (Timestamp). This makes the credits system\n * portable to other environments without Firebase dependencies.\n *\n * Note: Firestore Timestamp is handled by the credits-firestore adapter.\n */\n\n// ==================== Utility Functions ====================\n\n/**\n * Calculate available credits from balance, bonus, and reserved amounts.\n *\n * Available = balance + bonusCredits - reserved\n *\n * @param balance - Regular monthly credits\n * @param bonusCredits - Purchased/admin credits\n * @param reserved - Credits locked for in-flight operations\n * @returns Available credits for new operations\n */\nexport function calculateAvailableCredits(\n balance: number,\n bonusCredits: number,\n reserved: number\n): number {\n return sumAmounts(balance, bonusCredits, -reserved);\n}\n\n/**\n * Convert various timestamp formats to ISO string.\n *\n * Handles:\n * - Date objects\n * - ISO string (returned as-is)\n * - Timestamp-like objects with toDate() method (Firebase)\n * - undefined/null (returns current time)\n *\n * @param value - Value to convert\n * @returns ISO 8601 string\n */\nexport function toPortableTimestamp(value: unknown): string {\n if (!value) {\n return new Date().toISOString();\n }\n\n if (typeof value === \"string\") {\n return value;\n }\n\n if (value instanceof Date) {\n return value.toISOString();\n }\n\n if (\n typeof value === \"object\" &&\n value !== null &&\n \"toDate\" in value &&\n typeof (value as { toDate: () => Date }).toDate === \"function\"\n ) {\n return (value as { toDate: () => Date }).toDate().toISOString();\n }\n\n return new Date().toISOString();\n}\n\n/**\n * Convert various timestamp formats to Date object.\n *\n * Handles:\n * - Date objects (returned as-is)\n * - ISO string\n * - Timestamp-like objects with toDate() method (Firebase)\n * - Invalid values (returns current date)\n *\n * @param value - Value to convert\n * @returns Date object\n */\nexport function toDate(value: unknown): Date {\n if (value instanceof Date) {\n return value;\n }\n\n if (typeof value === \"string\") {\n return new Date(value);\n }\n\n if (\n typeof value === \"object\" &&\n value !== null &&\n \"toDate\" in value &&\n typeof (value as { toDate: () => Date }).toDate === \"function\"\n ) {\n return (value as { toDate: () => Date }).toDate();\n }\n\n return new Date();\n}\n\n// ==================== Subscription Types ====================\n\n/**\n * Built-in tier ids (autocomplete) — apps may add more via config.\n */\nexport type BuiltinTier = \"free\" | \"basic\" | \"premium\" | \"unlimited\";\n\n/**\n * Subscription tiers for the credits system.\n *\n * Any built-in OR any config-defined tier id. The `(string & {})` keeps builtin\n * autocomplete while accepting arbitrary configured tiers.\n */\nexport type SubscriptionTier = BuiltinTier | (string & {});\n\n// ==================== Operation Types ====================\n\n/**\n * Operation types for cost tracking (provider-agnostic)\n *\n * Dynamic string type - any operation configured in the system is valid.\n */\nexport type CreditOperationType = string;\n\n/**\n * AI providers\n */\nexport type AIProviderType = \"gemini\";\n\n/**\n * Resource type for usage logging\n */\nexport type ResourceType = string;\n\n// ==================== User Credits ====================\n\n/**\n * Portable user credits balance\n *\n * Uses ISO string timestamps instead of Firebase Timestamp.\n * This type is safe for JSON serialization and works across frameworks.\n */\nexport interface PortableUserCredits {\n userId: string;\n /** Current available balance (monthly credits, reset each month) */\n balance: number;\n /** Bonus credits from purchases/admin (never reset, persist until used) */\n bonusCredits: number;\n /** Credits currently reserved for in-flight operations */\n reserved: number;\n /** User's subscription tier */\n tier: SubscriptionTier;\n /** Monthly credit limit based on tier (0 = unlimited) */\n monthlyLimit: number;\n /** Credits used this month (resets monthly) */\n monthlyUsed: number;\n /** When monthly credits reset (start of next month) - ISO 8601 */\n monthlyResetAt: string;\n /** Subscription expiry (null/undefined for free tier) - ISO 8601 or null */\n subscriptionExpiresAt?: string | null;\n /** Creation timestamp - ISO 8601 */\n createdAt: string;\n /** Last update timestamp - ISO 8601 */\n updatedAt: string;\n}\n\n// ==================== Reservation Types ====================\n\n/**\n * Credit reservation status for two-phase commit\n */\nexport type ReservationStatus = \"reserved\" | \"committed\" | \"released\" | \"expired\";\n\n/**\n * Portable credit reservation\n *\n * Used for two-phase commit to prevent double-spending.\n */\nexport interface PortableReservation {\n id: string;\n userId: string;\n /** Amount of credits reserved */\n amount: number;\n /** Operation type for tracking */\n operationType: CreditOperationType;\n /** Current status of reservation */\n status: ReservationStatus;\n /** When reservation was created - ISO 8601 */\n createdAt: string;\n /** When reservation expires (for cleanup) - ISO 8601 */\n expiresAt: string;\n /** When reservation was committed/released - ISO 8601 or undefined */\n completedAt?: string;\n /**\n * Caller-supplied idempotency key (V2). Absent on legacy reservations.\n * Unique per user; a replay with the same key returns this same reservation.\n */\n idempotencyKey?: string;\n /**\n * When the atomic reserve placed this hold - ISO 8601, or absent.\n *\n * Written by `reserveCreditsV2` inside the same transaction that increases\n * `reserved`, so its presence is proof that the hold exists. `createReservation`\n * never sets it, and the V2 transitions refuse to move a row without it.\n * See `assertHoldPlaced` in `core/reservation-integrity.ts`.\n */\n holdPlacedAt?: string;\n}\n\n// ==================== Result Types ====================\n\n/**\n * Result of a credit check operation\n */\nexport interface CreditCheckResult {\n /** Whether user has sufficient credits */\n hasCredits: boolean;\n /** Current balance (balance + bonusCredits) */\n balance: number;\n /** Required credits for operation */\n required: number;\n /** Shortfall if insufficient */\n shortfall: number;\n}\n\n/**\n * Result of a one-shot atomic credit deduction (see `CreditsService.deductCredits`).\n *\n * Discriminated on `success` so callers get exhaustive narrowing:\n * - `success: true` -> `newBalance` is populated, `available`/`shortfall` are not present.\n * - `success: false` -> `available`/`shortfall` describe the shortfall, no mutation occurred.\n */\nexport type DeductCreditsResult =\n | {\n success: true;\n /** Combined balance (balance + bonusCredits) after the deduction */\n newBalance: number;\n }\n | {\n success: false;\n reason: \"insufficient\";\n /** Combined balance (balance + bonusCredits - reserved) available before the attempt */\n available: number;\n /** Credits that were requested */\n required: number;\n /** How many more credits would have been needed */\n shortfall: number;\n };\n\n/**\n * Result of monthly reset operation\n */\nexport interface MonthlyResetResult {\n /** Whether the reset was performed */\n wasReset: boolean;\n /** The user credits after the operation */\n credits: PortableUserCredits;\n /**\n * `true` when the repository wrote the reset's journal entry inside the same\n * atomic step as the balance write. The service then skips its own journal\n * call — a separate call sits outside the reset's atomicity, and if it fails\n * after the CAS was consumed, the line is lost for good (no retry ever sees\n * the reset again). Absent/`false` means the repository did not journal and\n * the service falls back to the legacy non-atomic write.\n */\n journaled?: boolean;\n}\n\n/**\n * Result of subscription expiry check\n */\nexport interface SubscriptionExpiryResult {\n /** Whether the subscription was downgraded */\n wasDowngraded: boolean;\n /** Whether user is in grace period */\n inGracePeriod: boolean;\n /** Days remaining in grace period (0 if not in grace) */\n graceDaysRemaining: number;\n /** The user credits after the operation */\n credits: PortableUserCredits;\n /**\n * `true` when the repository wrote the downgrade's journal entry inside the\n * same atomic step as the tier write. The service then skips its own journal\n * call — a separate call sits outside the downgrade's atomicity, and if it\n * fails after the tier write committed, the account is downgraded with no\n * audit line and no retry ever fires (the row is no longer eligible).\n * Absent/`false` means the repository did not journal and the service falls\n * back to the legacy non-atomic write.\n */\n journaled?: boolean;\n}\n\n// ==================== Transaction Types ====================\n\n/**\n * Credit transaction type\n */\nexport type TransactionType = \"purchase\" | \"subscription\" | \"bonus\" | \"refund\" | \"adjustment\";\n\n/**\n * Portable credit transaction\n */\nexport interface PortableTransaction {\n id: string;\n userId: string;\n type: TransactionType;\n /** Amount of credits (positive for additions, negative for deductions) */\n amount: number;\n description: string;\n /** Reference to payment provider */\n paymentRef?: string;\n previousBalance: number;\n newBalance: number;\n createdAt: string;\n}\n\n// ==================== Journal Types ====================\n\n/**\n * Source of a credit journal entry\n */\nexport type CreditSource =\n | \"operation_commit\"\n | \"operation_release\"\n | \"purchase\"\n | \"subscription_grant\"\n | \"subscription_upgrade\"\n | \"subscription_downgrade\"\n | \"monthly_reset\"\n | \"bonus\"\n | \"refund\"\n | \"admin_adjustment\"\n | \"expiry\"\n | \"reservation_expired\";\n\n/**\n * Type of reference for a journal entry\n */\nexport type JournalReferenceType =\n | \"reservation\"\n | \"transaction\"\n | \"adjustment\"\n | \"reset\"\n | \"subscription\";\n\n/**\n * Portable credit journal entry for audit trail\n */\nexport interface PortableJournalEntry {\n id: string;\n userId: string;\n /** Type of entry - debit decreases balance, credit increases balance */\n entryType: \"debit\" | \"credit\";\n /** Amount of credits involved */\n amount: number;\n /** Balance after this entry */\n balanceAfter: number;\n /** Source of the credit change */\n source: CreditSource;\n /** Reference ID (e.g., reservationId, transactionId) */\n referenceId: string;\n /** Type of reference */\n referenceType: JournalReferenceType;\n /** Human-readable description */\n description: string;\n /** Additional metadata */\n metadata?: Record<string, unknown>;\n /**\n * Deterministic key that makes this entry unique per user (V2). Absent on\n * legacy entries; present entries cannot be written twice.\n */\n idempotencyKey?: string;\n /** When this entry was created - ISO 8601 */\n createdAt: string;\n}\n\n// ==================== Usage Types ====================\n\n/**\n * Portable usage log entry\n */\nexport interface PortableUsageLog {\n id: string;\n userId: string;\n operationType: CreditOperationType;\n provider: AIProviderType;\n creditsUsed: number;\n success: boolean;\n errorMessage?: string;\n resourceId?: string;\n resourceType?: ResourceType;\n requestId?: string;\n metadata?: Record<string, unknown>;\n createdAt: string;\n}\n\n/**\n * User-friendly usage history entry\n */\nexport interface UsageHistoryEntry {\n id: string;\n /** Type of entry for display */\n type: \"usage\" | \"purchase\" | \"bonus\" | \"reset\" | \"refund\" | \"adjustment\";\n /** Positive = earned, Negative = spent */\n creditsChange: number;\n /** Balance after this entry */\n balanceAfter: number;\n /** Human-readable description */\n description: string;\n /** When this occurred - ISO 8601 */\n createdAt: string;\n}\n\n/**\n * Paginated usage history response\n */\nexport interface UsageHistoryResponse {\n entries: UsageHistoryEntry[];\n pagination: {\n total: number;\n limit: number;\n offset: number;\n hasMore: boolean;\n };\n}\n\n// ==================== Tier Configuration ====================\n\n/**\n * Tier configuration for credit limits and pricing\n */\nexport interface TierConfig {\n tier: SubscriptionTier;\n monthlyCredits: number;\n priceUsd: number;\n features: string[];\n /** Free/default tier marker — no subscription expiry, balance untouched on tier change. Defaults to priceUsd === 0. */\n isFree?: boolean;\n /** Unlimited tier marker. Defaults to monthlyCredits === 0. */\n unlimited?: boolean;\n /** Tier assigned to brand-new users. Defaults to the tier flagged isFree. */\n isDefault?: boolean;\n}\n\n// ==================== Options Types ====================\n\n/**\n * Options for withCredits HOF\n */\nexport interface WithCreditsOptions {\n /** Operation type for cost lookup */\n operationType: CreditOperationType;\n /** AI provider (defaults to \"gemini\") */\n provider?: AIProviderType;\n /** Custom cost override (use with caution) */\n customCost?: number;\n /** Resource ID for usage logging */\n resourceId?: string;\n /** Resource type for usage logging */\n resourceType?: ResourceType;\n}\n\n// ==================== Constants ====================\n","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","import type {\n ICreditRepositoryCreditsV2,\n ICreditRepositoryV2,\n} from \"./v2-types.js\";\nimport type {\n PortableUserCredits,\n PortableReservation,\n PortableTransaction,\n PortableUsageLog,\n PortableJournalEntry,\n CreditOperationType,\n SubscriptionTier,\n ReservationStatus,\n AIProviderType,\n MonthlyResetResult,\n SubscriptionExpiryResult,\n CreditSource,\n JournalReferenceType,\n} from \"../core/types.js\";\n\n/**\n * Input for creating a credit reservation\n */\nexport interface CreateReservationInput {\n userId: string;\n amount: number;\n operationType: CreditOperationType;\n expiresAt: Date;\n /**\n * @deprecated Rejected — this writer does not place the hold.\n *\n * `createReservation` inserts a row and leaves `reserved` alone, so a keyed\n * row written here names a hold that does not exist, and `reserveCreditsV2`\n * would adopt it as a `replayed` reservation whose commit then spends another\n * hold's coverage. Both adapters throw `UNSUPPORTED_OPERATION` when this is\n * set. Pass the key to `reserveCredits` / `reserveCreditsV2` instead, which\n * claims the key and places the hold in one transaction.\n *\n * The field is kept rather than deleted so the refusal reaches a JavaScript\n * caller as a typed error instead of a silently ignored property.\n */\n idempotencyKey?: string;\n}\n\n/**\n * Input for creating a credit transaction\n */\nexport interface CreateTransactionInput {\n userId: string;\n type: PortableTransaction[\"type\"];\n amount: number;\n description: string;\n paymentRef?: string;\n previousBalance: number;\n newBalance: number;\n}\n\n/**\n * Input for logging usage\n */\nexport interface CreateUsageLogInput {\n userId: string;\n operationType: CreditOperationType;\n provider: AIProviderType;\n creditsUsed: number;\n success: boolean;\n errorMessage?: string;\n resourceId?: string;\n resourceType?: string;\n requestId?: string;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Query options for usage logs\n */\nexport interface UsageLogQuery {\n userId?: string;\n operationType?: CreditOperationType;\n success?: boolean;\n limit?: number;\n offset?: number;\n startDate?: Date;\n endDate?: Date;\n}\n\n/**\n * Input for creating a journal entry\n */\nexport interface CreateJournalEntryInput {\n userId: string;\n entryType: \"debit\" | \"credit\";\n amount: number;\n balanceAfter: number;\n source: CreditSource;\n referenceId: string;\n referenceType: JournalReferenceType;\n description: string;\n metadata?: Record<string, unknown>;\n /** Deterministic key making this entry unique per user (V2, optional). */\n idempotencyKey?: string;\n}\n\n/**\n * Query options for journal entries\n */\nexport interface JournalEntryQuery {\n userId: string;\n source?: CreditSource;\n referenceType?: JournalReferenceType;\n limit?: number;\n offset?: number;\n startDate?: Date;\n endDate?: Date;\n}\n\n/**\n * Partial update for user credits balance\n */\nexport interface CreditBalanceUpdate {\n balance?: number;\n bonusCredits?: number;\n reserved?: number;\n tier?: SubscriptionTier;\n monthlyLimit?: number;\n monthlyUsed?: number;\n monthlyResetAt?: Date | string;\n subscriptionExpiresAt?: Date | string | null;\n /** Increment balance by this amount (alternative to absolute value) */\n balanceIncrement?: number;\n /** Increment bonusCredits by this amount (alternative to absolute value) */\n bonusCreditsIncrement?: number;\n /** Increment reserved by this amount (alternative to absolute value) */\n reservedIncrement?: number;\n /** Increment monthlyUsed by this amount */\n monthlyUsedIncrement?: number;\n}\n\n/**\n * Input for tier update\n */\nexport interface TierUpdateInput {\n tier: SubscriptionTier;\n monthlyLimit: number;\n balance?: number;\n monthlyUsed?: number;\n subscriptionExpiresAt?: Date | string | null;\n}\n\n/**\n * Optional journal customization for `addCreditsAtomic`.\n *\n * By default a credit add records a journal entry with `source: \"purchase\"`,\n * `referenceType: \"transaction\"`, and `{ paymentRef }` metadata. These options\n * let callers override that — e.g. tag a signup grant as `source: \"bonus\"`, or\n * carry revenue-attribution fields (gross amount, credits granted) so a single\n * journal can serve as the app's revenue ledger.\n */\nexport interface AddCreditsAtomicOptions {\n /** Journal entry source (defaults to `\"purchase\"`). */\n source?: CreditSource;\n /** Journal reference type (defaults to `\"transaction\"`). */\n referenceType?: JournalReferenceType;\n /**\n * Extra metadata merged onto the journal entry. When `paymentRef` is present\n * it is merged in too (explicit keys here win on collision).\n */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Repository interface for credits database operations\n *\n * Implementations can use any database (Firestore, PostgreSQL, etc.)\n * All methods should handle their own error handling and transactions\n */\nexport interface ICreditRepository\n extends Partial<ICreditRepositoryV2>,\n Partial<ICreditRepositoryCreditsV2> {\n // ==================== User Credits ====================\n\n /**\n * Get user credits balance\n * @param userId - User ID\n * @returns User credits or null if not found\n */\n getUserCredits(userId: string): Promise<PortableUserCredits | null>;\n\n /**\n * Initialize credits for a new user\n * @param userId - User ID\n * @param tier - Initial subscription tier\n * @param initialBalance - Initial credit balance\n * @returns Initialized user credits\n */\n initializeUserCredits(\n userId: string,\n tier: SubscriptionTier,\n initialBalance: number\n ): Promise<PortableUserCredits>;\n\n /**\n * Update user credits balance\n * @param userId - User ID\n * @param updates - Partial updates to apply\n */\n updateUserCredits(userId: string, updates: CreditBalanceUpdate): Promise<void>;\n\n /**\n * Update user subscription tier\n * @param userId - User ID\n * @param input - Tier update data\n */\n updateUserTier(userId: string, input: TierUpdateInput): Promise<void>;\n\n // ==================== Reservations ====================\n\n /**\n * Create a reservation *record* — not a hold.\n *\n * Writes a row and leaves `reserved` untouched, so the row is not backed by\n * credits and no settlement path will move money for it: the commit /\n * release / expire transitions (legacy and V2 alike) refuse it with\n * `UNBACKED_RESERVATION`, and it refuses an `idempotencyKey` so it can never\n * be adopted as a V2 replay. Use it for imported or annotation-only records.\n *\n * To place a hold that can actually be committed, call `reserveCreditsAtomic`\n * or `reserveCreditsV2` — they raise `reserved` and write the row in one\n * atomic step.\n *\n * @param input - Reservation data\n * @returns Created reservation record\n */\n createReservation(input: CreateReservationInput): Promise<PortableReservation>;\n\n /**\n * Get a reservation by ID\n * @param userId - User ID\n * @param reservationId - Reservation ID\n * @returns Reservation or null\n */\n getReservation(userId: string, reservationId: string): Promise<PortableReservation | null>;\n\n /**\n * Annotate a reservation *record* with a status.\n *\n * Assigns a status and nothing else — no balance movement, no `reserved`\n * adjustment, no journal entry. It therefore refuses two writes that would\n * make the status lie about the ledger: any write to a row whose hold was\n * atomically placed (those statuses belong to commit/release/expire), and\n * any write back to `reserved` (nothing here re-places a hold). Rows written\n * by `createReservation` accept terminal statuses freely.\n *\n * @param userId - User ID\n * @param reservationId - Reservation ID\n * @param status - New status\n * @param completedAt - Completion timestamp\n */\n updateReservationStatus(\n userId: string,\n reservationId: string,\n status: ReservationStatus,\n completedAt?: Date\n ): Promise<void>;\n\n // ==================== Atomic Operations ====================\n\n /**\n * Reserve credits atomically (creates reservation + updates balance in transaction)\n * @param userId - User ID\n * @param amount - Credits to reserve\n * @param operationType - Operation type for tracking\n * @param expiresAt - Reservation expiry time\n * @returns Created reservation\n * @throws Error if insufficient credits\n */\n reserveCreditsAtomic(\n userId: string,\n amount: number,\n operationType: CreditOperationType,\n expiresAt: Date\n ): Promise<PortableReservation>;\n\n /**\n * Commit a reservation atomically (deducts credits + marks reservation committed)\n * @param userId - User ID\n * @param reservationId - Reservation ID\n * @throws Error if reservation not found or not in reserved state\n */\n commitReservationAtomic(userId: string, reservationId: string): Promise<void>;\n\n /**\n * Release a reservation atomically (releases reserved credits + marks reservation released)\n * @param userId - User ID\n * @param reservationId - Reservation ID\n */\n releaseReservationAtomic(userId: string, reservationId: string): Promise<void>;\n\n /**\n * Add credits atomically (creates transaction + updates balance)\n * @param userId - User ID\n * @param amount - Credits to add\n * @param description - Transaction description\n * @param paymentRef - Optional payment reference\n * @param options - Optional journal source / reference type / extra metadata\n * for the credit journal entry (e.g. revenue attribution fields). Lets\n * callers record a purchase's gross amount, a bonus/refund source, etc.,\n * instead of the default `source: \"purchase\"` + `{ paymentRef }` metadata.\n */\n addCreditsAtomic(\n userId: string,\n amount: number,\n description: string,\n paymentRef?: string,\n options?: AddCreditsAtomicOptions\n ): Promise<void>;\n\n /**\n * Deduct credits from a user's balance atomically.\n *\n * Splits the deduction across `balance` and `bonusCredits`, draining\n * `balance` (monthly, resets each cycle) first so persistent bonus\n * credits survive longer. Runs in a single atomic transaction so\n * concurrent deducts cannot drive either field negative.\n *\n * Callers are responsible for writing any audit record (journal /\n * transaction) — this method only moves credits.\n *\n * @param userId - User ID\n * @param amount - Credits to deduct (positive)\n * @returns Combined totals (balance + bonusCredits) before and after.\n * @throws If user has no credits doc or insufficient credits\n */\n deductCreditsAtomic(\n userId: string,\n amount: number\n ): Promise<{ previousBalance: number; newBalance: number }>;\n\n // ==================== Transactions ====================\n\n /**\n * Create a credit transaction *record* — no balance moves.\n *\n * Refuses a `paymentRef`: the reference is the global identity of a credit\n * event, and a record that carried one without crediting anyone would make a\n * later `addCredits` with the same reference report `replayed` and credit\n * nothing. Deliver referenced payments through `addCreditsAtomic` /\n * `addCreditsV2`, which claim the reference and move the balance atomically.\n *\n * @param input - Transaction data\n * @returns Created transaction\n */\n createTransaction(input: CreateTransactionInput): Promise<PortableTransaction>;\n\n /**\n * Get user's transaction history\n * @param userId - User ID\n * @param limit - Max results\n * @param offset - Skip results\n * @returns List of transactions\n */\n getTransactions(\n userId: string,\n limit?: number,\n offset?: number\n ): Promise<PortableTransaction[]>;\n\n // ==================== Usage Logs ====================\n\n /**\n * Log a usage event\n * @param input - Usage log data\n * @returns Created usage log\n */\n logUsage(input: CreateUsageLogInput): Promise<PortableUsageLog>;\n\n /**\n * Query usage logs\n * @param query - Query parameters\n * @returns List of usage logs\n */\n getUsageLogs(query: UsageLogQuery): Promise<PortableUsageLog[]>;\n\n /**\n * Get usage log count (for pagination)\n * @param query - Query parameters (without limit/offset)\n * @returns Count of matching logs\n */\n getUsageLogsCount(query: Omit<UsageLogQuery, \"limit\" | \"offset\">): Promise<number>;\n\n // ==================== Cleanup Operations ====================\n\n /**\n * Find and expire reservations past their expiration time\n * Used by cron job to clean up stale reservations\n * @param batchSize - Maximum number of reservations to process per batch (default: 100)\n * @param maxIterations - Maximum number of pagination iterations to prevent infinite loops (default: 100)\n * @returns Cleanup results with counts and errors\n */\n findAndExpireReservations(batchSize?: number, maxIterations?: number): Promise<{\n expiredCount: number;\n creditsReleased: number;\n errors: string[];\n }>;\n\n // ==================== Atomic Monthly Reset ====================\n\n /**\n * Atomically perform monthly reset if needed\n * Uses optimistic locking to prevent race conditions\n *\n * @param userId - User ID\n * @param tier - User's current subscription tier (for determining new balance)\n * @param expectedResetAt - The expected monthlyResetAt value (for optimistic locking)\n * @returns Result indicating whether reset was performed and updated credits\n */\n atomicMonthlyReset(\n userId: string,\n tier: SubscriptionTier,\n expectedResetAt: Date | string\n ): Promise<MonthlyResetResult>;\n\n // ==================== Subscription Expiry ====================\n\n /**\n * Check and handle subscription expiry with grace period\n * Auto-downgrades expired subscriptions after grace period\n *\n * @param userId - User ID\n * @param gracePeriodDays - Days to allow after expiry before downgrade (default: 3)\n * @returns Result indicating whether downgrade occurred\n */\n checkAndHandleSubscriptionExpiry(\n userId: string,\n gracePeriodDays?: number\n ): Promise<SubscriptionExpiryResult>;\n\n // ==================== Journal Entries ====================\n\n /**\n * Create a journal entry for audit trail\n * @param input - Journal entry data\n * @returns Created journal entry\n */\n createJournalEntry(input: CreateJournalEntryInput): Promise<PortableJournalEntry>;\n\n /**\n * Get journal entries for a user\n * @param query - Query parameters\n * @returns List of journal entries\n */\n getJournalEntries(query: JournalEntryQuery): Promise<PortableJournalEntry[]>;\n\n /**\n * Get journal entry count for pagination\n * @param query - Query parameters (without limit/offset)\n * @returns Count of matching entries\n */\n getJournalEntriesCount(query: Omit<JournalEntryQuery, \"limit\" | \"offset\">): Promise<number>;\n}\n\n/**\n * Factory type for creating repository instances\n */\nexport type CreditRepositoryFactory = () => ICreditRepository;\n\n/**\n * Narrow a repository to one that implements the full V2 boundary.\n *\n * V2 methods are optional on {@link ICreditRepository}, so callers that need\n * the idempotent/race-safe path must probe rather than assume. A repository\n * only counts as V2 when it implements *all four* transitions — a partial\n * implementation would leave one path silently unsafe.\n */\nexport function supportsCreditsV2(\n repository: ICreditRepository\n): repository is ICreditRepository & ICreditRepositoryV2 {\n return (\n typeof repository.reserveCreditsV2 === \"function\" &&\n typeof repository.commitReservationV2 === \"function\" &&\n typeof repository.releaseReservationV2 === \"function\" &&\n typeof repository.expireReservationV2 === \"function\"\n );\n}\n\n/**\n * Narrow a repository to one that credits idempotently against a `paymentRef`.\n *\n * Deliberately a separate probe from {@link supportsCreditsV2}: serialising\n * reservations and enforcing a global payment reference are different\n * guarantees resting on different database objects, and an adapter may have one\n * without the other.\n */\nexport function supportsIdempotentCredit(\n repository: ICreditRepository\n): repository is ICreditRepository & ICreditRepositoryCreditsV2 {\n return typeof repository.addCreditsV2 === \"function\";\n}\n\n/**\n * Convert PortableUserCredits to client-safe format\n * Utility function that implementations can use\n */\nexport function toClientUserCredits(credits: PortableUserCredits): PortableUserCredits {\n // Already in portable format, just ensure all timestamps are ISO strings\n return {\n userId: credits.userId,\n balance: credits.balance,\n bonusCredits: credits.bonusCredits ?? 0,\n reserved: credits.reserved,\n tier: credits.tier,\n monthlyLimit: credits.monthlyLimit,\n monthlyUsed: credits.monthlyUsed,\n monthlyResetAt: toISOString(credits.monthlyResetAt),\n subscriptionExpiresAt: credits.subscriptionExpiresAt\n ? toISOString(credits.subscriptionExpiresAt)\n : null,\n createdAt: toISOString(credits.createdAt),\n updatedAt: toISOString(credits.updatedAt),\n };\n}\n\n/**\n * Convert any timestamp-like value to ISO string\n */\nfunction toISOString(value: unknown): string {\n if (!value) return new Date().toISOString();\n if (typeof value === \"string\") return value;\n if (value instanceof Date) return value.toISOString();\n // Handle Firestore Timestamp-like objects\n if (typeof value === \"object\" && \"toDate\" in value && typeof (value as { toDate: () => Date }).toDate === \"function\") {\n return (value as { toDate: () => Date }).toDate().toISOString();\n }\n return new Date().toISOString();\n}\n","/**\n * One reservation flow for both repository generations.\n *\n * Adapters that implement the V2 boundary get the idempotent, race-safe path\n * and own their journal entry. Adapters that do not (Firestore, custom\n * implementations) keep the legacy read-then-write path, with the service\n * writing the journal exactly as it always did — so upgrading this package\n * does not change their behaviour, and does not double-write anyone's ledger.\n */\n\nimport { getOperationLabel } from \"../config/index.js\";\nimport { assertValidCreditAmount, sumAmounts } from \"../core/amount.js\";\nimport {\n createUnsupportedOperationError,\n isInsufficientCreditsError,\n} from \"../core/errors.js\";\nimport type {\n AddCreditsOutcome,\n CommitOutcome,\n ReleaseOutcome,\n ReserveOutcome,\n} from \"../core/outcomes.js\";\nimport { normalizePaymentRef } from \"../core/payment-ref.js\";\nimport type { ICreditRepository } from \"./types.js\";\nimport { supportsCreditsV2, supportsIdempotentCredit } from \"./types.js\";\nimport type {\n AddCreditsV2Input,\n ReservationTransitionOptions,\n ReserveCreditsV2Input,\n} from \"./v2-types.js\";\n\n/**\n * Reserve credits through V2 when available.\n *\n * A legacy adapter cannot honour an idempotency key — it has no unique index\n * to enforce it — so asking for one there is a caller error rather than a\n * silently ignored option.\n */\nexport async function reserveThroughRepository(\n repository: ICreditRepository,\n input: ReserveCreditsV2Input\n): Promise<ReserveOutcome> {\n const v2 = supportsCreditsV2(repository);\n\n // The capability check comes first, so a caller who asked for a guarantee\n // this repository cannot give always hears *that*, rather than whichever\n // other complaint the arguments happen to trigger. A legacy adapter has no\n // unique index to enforce the key, so it cannot deduplicate a replay, and\n // reporting `created` for the second delivery would be a lie that costs the\n // user real credits.\n if (!v2 && input.idempotencyKey !== undefined) {\n throw createUnsupportedOperationError(\n \"reserveCredits with an idempotencyKey\",\n \"This repository does not implement the V2 boundary, so it cannot \" +\n \"enforce idempotency keys. Use a V2 repository (check with \" +\n \"supportsCreditsV2) or omit the key and accept at-least-once holds.\"\n );\n }\n\n assertValidCreditAmount(input.amount, { userId: input.userId });\n\n if (v2) {\n return repository.reserveCreditsV2(input);\n }\n\n try {\n const reservation = await repository.reserveCreditsAtomic(\n input.userId,\n input.amount,\n input.operationType,\n input.expiresAt\n );\n return { outcome: \"created\", reservation };\n } catch (error) {\n // Only a genuine funds shortfall becomes the `insufficient` outcome. The\n // previous version asked the repository for the balance and called any\n // failure `insufficient` whenever that balance happened to be low — which\n // silently rebranded connection drops and driver faults as \"the user is\n // out of credits\", and hid real outages behind an upsell.\n if (!isInsufficientCreditsError(error)) throw error;\n\n const credits = await repository.getUserCredits(input.userId);\n const available = credits\n ? sumAmounts(credits.balance, credits.bonusCredits, -credits.reserved)\n : 0;\n return {\n outcome: \"insufficient\",\n available,\n required: input.amount,\n shortfall: Math.max(sumAmounts(input.amount, -available), 0),\n };\n }\n}\n\n/**\n * Commit through V2 when available, else the legacy read-then-write path.\n *\n * **The legacy path cannot promise a single winner.** It reads the status and\n * then writes, with no lock and no compare-and-set between the two, so two\n * concurrent commits of the same reservation can both observe `reserved` and\n * both proceed. The typed outcome still describes what *this* call saw, but on\n * a legacy adapter `committed` means \"this call did the work\", not \"this call\n * was the only one that did\". Callers needing exactly-once must use a\n * repository for which `supportsCreditsV2` returns `true`.\n */\nexport async function commitThroughRepository(\n repository: ICreditRepository,\n userId: string,\n reservationId: string,\n options?: ReservationTransitionOptions\n): Promise<CommitOutcome> {\n if (supportsCreditsV2(repository)) {\n return repository.commitReservationV2(userId, reservationId, options);\n }\n\n const reservation = await repository.getReservation(userId, reservationId);\n if (!reservation) return { outcome: \"not_found\", reservationId };\n if (reservation.status !== \"reserved\") {\n return {\n outcome: \"already_terminal\",\n reservation,\n terminalStatus: reservation.status,\n };\n }\n\n await repository.commitReservationAtomic(userId, reservationId);\n\n const credits = await repository.getUserCredits(userId);\n // The ledger balance, not the `balance` column alone: every other journal\n // writer — the V2 transitions, add and deduct — records\n // `balance + bonusCredits`, and recording less here made the same account's\n // audit trail disagree with itself whenever it held bonus credits.\n const balanceAfter = credits ? sumAmounts(credits.balance, credits.bonusCredits) : 0;\n const entry = await repository.createJournalEntry({\n userId,\n entryType: \"debit\",\n amount: reservation.amount,\n balanceAfter,\n source: \"operation_commit\",\n referenceId: reservationId,\n referenceType: \"reservation\",\n description:\n options?.description ??\n `Committed ${reservation.amount} credits for ${getOperationLabel(reservation.operationType)}`,\n // Deterministic fields last: they carry the identity of the event, and a\n // caller who happens to send an `operationType` or an `amount` must not\n // relabel what actually moved.\n metadata: {\n ...options?.metadata,\n operationType: reservation.operationType,\n amount: reservation.amount,\n },\n });\n\n return {\n outcome: \"committed\",\n reservation: { ...reservation, status: \"committed\" },\n amount: reservation.amount,\n balanceAfter,\n journalEntryId: entry.id,\n };\n}\n\n/**\n * Release through V2 when available, else the legacy read-then-write path.\n *\n * Same caveat as {@link commitThroughRepository}: on a legacy adapter the\n * read-then-write sequence is unguarded, so `released` does not exclude a\n * concurrent commit having also run. Only V2 repositories serialise the two.\n */\nexport async function releaseThroughRepository(\n repository: ICreditRepository,\n userId: string,\n reservationId: string,\n options?: ReservationTransitionOptions\n): Promise<ReleaseOutcome> {\n if (supportsCreditsV2(repository)) {\n return repository.releaseReservationV2(userId, reservationId, options);\n }\n\n const reservation = await repository.getReservation(userId, reservationId);\n if (!reservation) {\n // Legacy adapters vary on whether releasing an unknown reservation throws;\n // ask them anyway so that behaviour is preserved, then report not_found.\n await repository.releaseReservationAtomic(userId, reservationId);\n return { outcome: \"not_found\", reservationId };\n }\n if (reservation.status !== \"reserved\") {\n // The hold is already resolved, so there is nothing to hand back. Legacy\n // adapters disagree about whether releasing a processed reservation is an\n // error, and `releaseCredits` is specified to be a silent no-op here — so\n // the call is still made for adapters that use it to reconcile, and a\n // refusal is swallowed rather than propagated. The conflict is not hidden:\n // it is what `already_terminal` reports, and `releaseCreditsDetailed`\n // surfaces it to callers that ask.\n await repository.releaseReservationAtomic(userId, reservationId).catch(() => undefined);\n return {\n outcome: \"already_terminal\",\n reservation,\n terminalStatus: reservation.status,\n };\n }\n\n await repository.releaseReservationAtomic(userId, reservationId);\n\n const credits = await repository.getUserCredits(userId);\n const entry = await repository.createJournalEntry({\n userId,\n entryType: \"credit\",\n // No credits changed hands — the hold just moved back into \"available\".\n amount: 0,\n balanceAfter: credits ? sumAmounts(credits.balance, credits.bonusCredits) : 0,\n source: \"operation_release\",\n referenceId: reservationId,\n referenceType: \"reservation\",\n description:\n options?.description ??\n `Released ${reservation.amount} reserved credits for ${getOperationLabel(reservation.operationType)}`,\n metadata: {\n ...options?.metadata,\n operationType: reservation.operationType,\n amount: reservation.amount,\n },\n });\n\n return {\n outcome: \"released\",\n reservation: { ...reservation, status: \"released\" },\n amount: reservation.amount,\n journalEntryId: entry.id,\n };\n}\n\n/**\n * Credit an account through the idempotent path when the adapter has one.\n *\n * A legacy adapter cannot resolve `created` / `replayed` / `conflict`: it has\n * no global unique index over `payment_ref`, so it cannot tell a re-delivered\n * webhook from a second, genuinely different payment that reuses a reference.\n * Rather than invent an outcome, this reports `created` — which is what the\n * legacy method actually did — and the ambiguity is documented on the return\n * type instead of hidden inside it.\n *\n * The reference is normalised here as well as in the adapters, so a legacy\n * adapter that stores the raw string does not persist a whitespace-only\n * reference that would then deduplicate nothing.\n */\nexport async function addCreditsThroughRepository(\n repository: ICreditRepository,\n input: AddCreditsV2Input\n): Promise<AddCreditsOutcome> {\n assertValidCreditAmount(input.amount, { userId: input.userId, operation: \"addCredits\" });\n const paymentRef = normalizePaymentRef(input.paymentRef);\n\n if (supportsIdempotentCredit(repository)) {\n return repository.addCreditsV2({ ...input, paymentRef });\n }\n\n await repository.addCreditsAtomic(\n input.userId,\n input.amount,\n input.description,\n paymentRef,\n input.options\n );\n\n // The legacy method returns nothing, so there is no transaction to hand back\n // and no way to know whether it deduplicated. Report the one thing that is\n // true — a call was made and did not throw — rather than fabricate a record.\n return paymentRef ? { outcome: \"created\", paymentRef } : { outcome: \"created\" };\n}\n","import type {\n PortableUserCredits,\n PortableReservation,\n CreditCheckResult,\n CreditOperationType,\n SubscriptionTier,\n PortableUsageLog,\n PortableJournalEntry,\n UsageHistoryEntry,\n UsageHistoryResponse,\n DeductCreditsResult,\n} from \"../core/types.js\";\nimport { toDate } from \"../core/types.js\";\nimport type {\n AddCreditsOutcome,\n CommitOutcome,\n ReleaseOutcome,\n ReserveOutcome,\n} from \"../core/outcomes.js\";\nimport {\n CreditErrorCode,\n createIdempotencyConflictError,\n createInsufficientCreditsError,\n createReservationAlreadyProcessedError,\n createReservationNotFoundError,\n isCreditError,\n} from \"../core/errors.js\";\nimport {\n assertValidCreditAmount,\n storedMonthlyLimit,\n sumAmounts,\n} from \"../core/amount.js\";\nimport type { ReservationTransitionOptions } from \"../repository/v2-types.js\";\nimport {\n addCreditsThroughRepository,\n commitThroughRepository,\n releaseThroughRepository,\n reserveThroughRepository,\n} from \"../repository/flow.js\";\nimport type {\n ICreditRepository,\n CreateUsageLogInput,\n JournalEntryQuery,\n AddCreditsAtomicOptions,\n} from \"../repository/types.js\";\nimport { toClientUserCredits } from \"../repository/types.js\";\nimport {\n getConfig,\n getConfigMonthlyLimit,\n getOperationLabel,\n isFreeTier,\n isUnlimitedTier,\n getDefaultTier,\n getUnlimitedSentinelBalance,\n} from \"../config/index.js\";\n\n/**\n * Check if a date is past the monthly reset date\n */\nfunction isPastMonthlyReset(resetAt: unknown): boolean {\n if (!resetAt) return false;\n const resetDate = toDate(resetAt);\n return new Date() >= resetDate;\n}\n\n/**\n * Notification callback type for low balance notifications\n */\nexport type LowBalanceNotificationCallback = (userId: string, balance: number) => Promise<void>;\n\n/**\n * Notification callback type for subscription expired notifications\n */\nexport type SubscriptionExpiredNotificationCallback = (userId: string, wasDowngraded: boolean) => Promise<void>;\n\n/**\n * Options for reserving credits.\n */\nexport interface ReserveCreditsOptions {\n /**\n * Time-to-live for the reservation, in milliseconds, before the cleanup\n * sweep may expire it. Defaults to `config.reservationExpiryMs` (suitable\n * for synchronous, in-request operations). Long-running async jobs\n * (e.g. background media generation) should pass a TTL matching their\n * own lifecycle so the reservation is not expired while the job is still\n * legitimately in flight.\n */\n ttlMs?: number;\n /**\n * Caller-supplied idempotency key, unique per user.\n *\n * Retrying a reserve with the same key and the same amount/operation returns\n * the original reservation instead of placing a second hold — the fix for a\n * webhook or job runner delivering the same request twice. Reusing a key\n * with a *different* amount or operation is a\n * `CreditErrorCode.IDEMPOTENCY_CONFLICT`.\n *\n * Requires a repository implementing the V2 boundary (see\n * `supportsCreditsV2`). A legacy adapter has no unique index to enforce the\n * key, so it is ignored there rather than silently promised.\n */\n idempotencyKey?: string;\n}\n\n/**\n * Options for a one-shot atomic credit deduction via `deductCredits`.\n */\nexport interface DeductCreditsOptions {\n /**\n * Operation type for cost tracking / journal + usage-log labeling.\n * Falls back to a generic \"adjustment\" description when omitted.\n */\n operationType?: CreditOperationType;\n /** Resource ID to attach to the usage log (e.g. the generated asset's id) */\n resourceId?: string;\n /** Resource type to attach to the usage log */\n resourceType?: string;\n /** Request ID to attach to the usage log, for tracing */\n requestId?: string;\n /** Additional metadata recorded on the journal entry */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Credits service with dependency injection for repository\n *\n * Provides business logic for credit operations, delegating\n * database operations to the injected repository.\n */\nexport class CreditsService {\n private lowBalanceCallback?: LowBalanceNotificationCallback;\n private subscriptionExpiredCallback?: SubscriptionExpiredNotificationCallback;\n\n constructor(private readonly repository: ICreditRepository) {}\n\n /**\n * Set callback for low balance notifications\n */\n setLowBalanceCallback(callback: LowBalanceNotificationCallback): void {\n this.lowBalanceCallback = callback;\n }\n\n /**\n * Set callback for subscription expired notifications\n */\n setSubscriptionExpiredCallback(callback: SubscriptionExpiredNotificationCallback): void {\n this.subscriptionExpiredCallback = callback;\n }\n\n /**\n * Get user credits, performing monthly reset and subscription expiry checks if needed\n *\n * This method uses atomic operations to prevent race conditions:\n * 1. Checks subscription expiry with grace period\n * 2. Atomically performs monthly reset if needed (with optimistic locking)\n *\n * @param userId - User ID\n * @returns User credits or null if not found\n */\n async getUserCredits(userId: string): Promise<PortableUserCredits | null> {\n let data = await this.repository.getUserCredits(userId);\n\n if (!data) {\n return null;\n }\n\n // Step 1: Check subscription expiry (for non-free tiers)\n if (!isFreeTier(data.tier) && data.subscriptionExpiresAt) {\n const expiryResult = await this.repository.checkAndHandleSubscriptionExpiry(\n userId,\n getConfig().subscriptionGracePeriodDays\n );\n\n if (expiryResult.wasDowngraded && !expiryResult.journaled) {\n // Legacy path for repositories that do not journal the downgrade\n // themselves. This write sits outside the downgrade's atomic step: if\n // it fails after the tier write committed, the account is downgraded\n // with no audit line and no retry ever fires (the row is no longer\n // eligible). Repositories that can journal atomically return\n // `journaled: true` and this block is skipped.\n await this.repository.createJournalEntry({\n userId,\n entryType: \"debit\",\n amount: 0, // No credits deducted, just tier change\n // The ledger balance, matching every other journal writer: the V2\n // transitions and add/deduct all record `balance + bonusCredits`, so\n // recording `balance` alone made the audit trail disagree with itself\n // for any user holding bonus credits.\n balanceAfter: sumAmounts(\n expiryResult.credits.balance,\n expiryResult.credits.bonusCredits\n ),\n source: \"subscription_downgrade\",\n referenceId: `downgrade-${Date.now()}`,\n referenceType: \"subscription\",\n // The tier actually landed on, not a hard-coded \"free\": the downgrade\n // target is configurable, so naming `free` here could describe a\n // transition that never happened.\n description: `Subscription expired. Downgraded from ${data.tier} to ${expiryResult.credits.tier} tier.`,\n metadata: {\n previousTier: data.tier,\n previousBalance: data.balance,\n newBalance: expiryResult.credits.balance,\n },\n });\n }\n\n // Trigger subscription expired notification (non-blocking) — on every\n // downgrade, whichever side wrote the journal.\n if (expiryResult.wasDowngraded && this.subscriptionExpiredCallback) {\n this.subscriptionExpiredCallback(userId, true).catch((error) => {\n console.error(\"[Credits] Failed to send subscription expired notification:\", error);\n });\n }\n\n // Use the potentially updated credits\n data = expiryResult.credits;\n }\n\n // Step 2: Check if monthly reset is needed (use atomic operation)\n if (isPastMonthlyReset(data.monthlyResetAt)) {\n // Convert monthlyResetAt to a compatible type (Date or string)\n const expectedResetAt = toDate(data.monthlyResetAt);\n const resetResult = await this.repository.atomicMonthlyReset(\n userId,\n data.tier,\n expectedResetAt\n );\n\n if (resetResult.wasReset && !resetResult.journaled) {\n // Legacy path for repositories that do not journal the reset\n // themselves. This write sits outside the reset's atomic step: if it\n // fails after the CAS was consumed, the journal line is lost for good.\n // Repositories that can journal atomically return `journaled: true`\n // and this block is skipped.\n const balanceChange = sumAmounts(resetResult.credits.balance, -data.balance);\n if (balanceChange !== 0) {\n await this.repository.createJournalEntry({\n userId,\n entryType: balanceChange > 0 ? \"credit\" : \"debit\",\n amount: Math.abs(balanceChange),\n balanceAfter: sumAmounts(\n resetResult.credits.balance,\n resetResult.credits.bonusCredits\n ),\n source: \"monthly_reset\",\n referenceId: `reset-${Date.now()}`,\n referenceType: \"reset\",\n description: `Monthly credit reset for ${data.tier} tier.`,\n metadata: {\n tier: data.tier,\n previousBalance: data.balance,\n newBalance: resetResult.credits.balance,\n },\n });\n }\n }\n\n // Use the potentially updated credits\n data = resetResult.credits;\n }\n\n return toClientUserCredits(data);\n }\n\n /**\n * Initialize credits for a new user with free tier\n * @param userId - User ID\n * @returns Initialized user credits\n */\n async initializeUserCredits(userId: string): Promise<PortableUserCredits> {\n const credits = await this.repository.initializeUserCredits(\n userId,\n getDefaultTier(),\n getConfig().defaultFreeCredits\n );\n return toClientUserCredits(credits);\n }\n\n /**\n * Get or create user credits\n * Initializes with free tier if not exists\n * @param userId - User ID\n * @returns User credits\n */\n async getOrCreateUserCredits(userId: string): Promise<PortableUserCredits> {\n const existing = await this.getUserCredits(userId);\n if (existing) {\n return existing;\n }\n return this.initializeUserCredits(userId);\n }\n\n /**\n * Check if user has sufficient credits for an operation\n * @param userId - User ID\n * @param requiredCredits - Credits required\n * @returns Credit check result\n */\n async checkCredits(userId: string, requiredCredits: number): Promise<CreditCheckResult> {\n const credits = await this.getOrCreateUserCredits(userId);\n\n // Available = balance + bonusCredits - reserved\n const totalBalance = sumAmounts(credits.balance, credits.bonusCredits);\n const available = sumAmounts(totalBalance, -credits.reserved);\n const hasCredits = available >= requiredCredits;\n\n return {\n hasCredits,\n balance: totalBalance,\n required: requiredCredits,\n shortfall: hasCredits ? 0 : sumAmounts(requiredCredits, -available),\n };\n }\n\n /**\n * Reserve credits for an operation (phase 1 of two-phase commit)\n * Creates a reservation and locks the credits\n * @param userId - User ID\n * @param amount - Credits to reserve\n * @param operationType - Operation type for tracking\n * @param options - Optional settings (e.g. a custom `ttlMs` for long-running async jobs)\n * @returns Reservation object\n * @throws Error if insufficient credits\n */\n async reserveCredits(\n userId: string,\n amount: number,\n operationType: CreditOperationType,\n options?: ReserveCreditsOptions\n ): Promise<PortableReservation> {\n const outcome = await this.reserveCreditsDetailed(userId, amount, operationType, options);\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 createIdempotencyConflictError(outcome.idempotencyKey, {\n userId,\n requested: { amount, operationType },\n existing: {\n amount: outcome.existing.amount,\n operationType: outcome.existing.operationType,\n },\n });\n }\n\n /**\n * Reserve credits and get the typed outcome instead of an exception.\n *\n * Prefer this over {@link reserveCredits} in async callers: it distinguishes\n * a fresh hold from an idempotent replay, and reports insufficient funds as\n * a value rather than as control flow.\n */\n async reserveCreditsDetailed(\n userId: string,\n amount: number,\n operationType: CreditOperationType,\n options?: ReserveCreditsOptions\n ): Promise<ReserveOutcome> {\n const ttlMs = options?.ttlMs ?? getConfig().reservationExpiryMs;\n const expiresAt = new Date(Date.now() + ttlMs);\n return reserveThroughRepository(this.repository, {\n userId,\n amount,\n operationType,\n expiresAt,\n idempotencyKey: options?.idempotencyKey,\n });\n }\n\n /**\n * Commit a reservation (phase 2 of two-phase commit - success).\n *\n * Idempotent: re-delivering a commit for an already-committed reservation is\n * a no-op. Committing one that was released or expired throws, because the\n * credits are no longer held and pretending otherwise would hide a real bug.\n */\n async commitCredits(\n userId: string,\n reservationId: string,\n options?: ReservationTransitionOptions\n ): Promise<void> {\n const outcome = await this.commitCreditsDetailed(userId, reservationId, options);\n if (outcome.outcome === \"not_found\") {\n throw createReservationNotFoundError(reservationId);\n }\n if (outcome.outcome === \"already_terminal\" && outcome.terminalStatus !== \"committed\") {\n throw createReservationAlreadyProcessedError(reservationId, outcome.terminalStatus);\n }\n }\n\n /**\n * Commit a reservation and get the typed outcome.\n *\n * Exactly one concurrent caller sees `committed`; that call moved the balance\n * and wrote the single journal entry. On a V2 repository the journal is\n * written inside the same transaction, so this method adds none of its own —\n * the duplicate entry the previous implementation wrote is gone.\n *\n * The low-balance notification fires only for the winner, and only after the\n * transaction has committed, so no callback runs inside a database\n * transaction.\n */\n async commitCreditsDetailed(\n userId: string,\n reservationId: string,\n options?: ReservationTransitionOptions\n ): Promise<CommitOutcome> {\n const outcome = await commitThroughRepository(\n this.repository,\n userId,\n reservationId,\n options\n );\n\n if (outcome.outcome === \"committed\" && this.lowBalanceCallback) {\n this.lowBalanceCallback(userId, outcome.balanceAfter).catch((error) => {\n console.error(\"[Credits] Failed to send low balance notification:\", error);\n });\n }\n\n return outcome;\n }\n\n /**\n * Release a reservation (phase 2 of two-phase commit - failure).\n *\n * Throws `RESERVATION_NOT_FOUND` for an unknown reservation, matching the\n * pre-V2 behaviour — a release naming a reservation that does not exist is a\n * caller bug, and swallowing it hides the bug while the credits stay held.\n *\n * Releasing one that is already terminal — `released`, `expired`, or\n * `committed` — is a no-op, which is the behaviour this method has always\n * had. A release that loses a race to a concurrent commit is the common\n * case in a retry-heavy caller, and callers written against the pre-V2\n * contract handle it by not handling it.\n *\n * That does mean this method cannot tell you that the credits were spent\n * rather than returned. Use {@link releaseCreditsDetailed}, which reports\n * `already_terminal` with `terminalStatus: 'committed'`, when you need to\n * branch on it.\n */\n async releaseCredits(\n userId: string,\n reservationId: string,\n options?: ReservationTransitionOptions\n ): Promise<void> {\n const outcome = await this.releaseCreditsDetailed(userId, reservationId, options);\n if (outcome.outcome === \"not_found\") {\n throw createReservationNotFoundError(reservationId);\n }\n }\n\n /** Release a reservation and get the typed outcome. */\n async releaseCreditsDetailed(\n userId: string,\n reservationId: string,\n options?: ReservationTransitionOptions\n ): Promise<ReleaseOutcome> {\n return releaseThroughRepository(this.repository, userId, reservationId, options);\n }\n\n /**\n * Log usage for audit trail\n * @param log - Usage log data\n */\n async logUsage(log: Omit<PortableUsageLog, \"id\" | \"createdAt\">): Promise<void> {\n await this.repository.logUsage(log as CreateUsageLogInput);\n }\n\n /**\n * Add credits to user account (for purchases, bonuses, etc.)\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).\n * @returns Whether this delivery credited the account (`created`), repeated an\n * earlier one (`replayed`), or reused the reference for a different credit\n * event (`conflict`, which credited nothing). On a repository without\n * `addCreditsV2` the result is always `created` and carries no\n * deduplication guarantee — see {@link addCreditsThroughRepository}.\n */\n async addCredits(\n userId: string,\n amount: number,\n description: string,\n paymentRef?: string,\n options?: AddCreditsAtomicOptions\n ): Promise<AddCreditsOutcome> {\n return addCreditsThroughRepository(this.repository, {\n userId,\n amount,\n description,\n paymentRef,\n options,\n });\n }\n\n /**\n * One-shot atomic \"deduct-if-sufficient\" credit charge.\n *\n * Unlike the reserve/commit/release two-phase flow, this performs a single\n * atomic check-and-deduct against the repository — suited for synchronous,\n * in-request operations that don't need a hold across an async job. Exactly\n * one call is made to `repository.deductCreditsAtomic`, which enforces\n * atomicity so concurrent callers can never both succeed against the same\n * limited balance.\n *\n * On success, creates a journal entry (same audit trail as `commitCredits`)\n * and, if `options.operationType` is provided, a usage log entry via the\n * same `logUsage` path.\n *\n * @param userId - User ID\n * @param amount - Credits to deduct (must be > 0)\n * @param options - Optional usage-log / journal metadata\n * @returns Typed result: `{ success: true, newBalance }` or\n * `{ success: false, reason: 'insufficient', available, required, shortfall }`\n * @throws Error if amount is not a positive number\n */\n async deductCredits(\n userId: string,\n amount: number,\n options?: DeductCreditsOptions\n ): Promise<DeductCreditsResult> {\n // `amount > 0` accepted 1.005, Infinity and values past what a\n // `numeric(12, 2)` column can hold; each of those reached the repository's\n // raw arithmetic. Validate here, *before* the try, so a rejected amount can\n // never be mistaken for a shortfall by the catch below.\n assertValidCreditAmount(amount, { userId, operation: \"deductCredits\" });\n\n let deduction: { previousBalance: number; newBalance: number };\n try {\n deduction = await this.repository.deductCreditsAtomic(userId, amount);\n } catch (error) {\n // A rejected amount is a caller bug, not a balance problem, and must not\n // be reshaped into `{ success: false, reason: 'insufficient' }`.\n if (isCreditError(error) && error.code === CreditErrorCode.INVALID_AMOUNT) throw error;\n\n // The repository layer throws on insufficient funds (and on missing\n // user docs, which we surface as unavailable rather than a shortfall).\n const credits = await this.repository.getUserCredits(userId);\n const available = credits\n ? sumAmounts(credits.balance, credits.bonusCredits, -credits.reserved)\n : 0;\n\n if (available >= amount) {\n // Not an insufficient-credits condition (e.g. missing user record) —\n // this is unexpected, so let the original error propagate.\n throw error;\n }\n\n return {\n success: false,\n reason: \"insufficient\",\n available,\n required: amount,\n shortfall: sumAmounts(amount, -available),\n };\n }\n\n const operationType = options?.operationType;\n await this.repository.createJournalEntry({\n userId,\n entryType: \"debit\",\n amount,\n balanceAfter: deduction.newBalance,\n source: \"operation_commit\",\n referenceId: options?.requestId ?? `deduct-${Date.now()}`,\n referenceType: \"adjustment\",\n description: operationType\n ? `Deducted ${amount} credits for ${getOperationLabel(operationType)}`\n : `Deducted ${amount} credits`,\n metadata: {\n ...options?.metadata,\n ...(operationType && { operationType }),\n },\n });\n\n if (operationType) {\n await this.logUsage({\n userId,\n operationType,\n provider: \"gemini\",\n creditsUsed: amount,\n success: true,\n resourceId: options?.resourceId,\n resourceType: options?.resourceType,\n requestId: options?.requestId,\n metadata: options?.metadata,\n });\n }\n\n // Trigger low balance notification (non-blocking) — same hook commitCredits uses.\n if (this.lowBalanceCallback) {\n this.lowBalanceCallback(userId, deduction.newBalance).catch((error) => {\n console.error(\"[Credits] Failed to send low balance notification:\", error);\n });\n }\n\n return { success: true, newBalance: deduction.newBalance };\n }\n\n /**\n * Update user subscription tier\n * @param userId - User ID\n * @param tier - New subscription tier\n * @param expiresAt - Subscription expiry date (optional)\n */\n async updateTier(\n userId: string,\n tier: SubscriptionTier,\n expiresAt?: Date\n ): Promise<void> {\n const monthlyLimit = getConfigMonthlyLimit(tier);\n const unlimited = isUnlimitedTier(tier);\n const free = isFreeTier(tier);\n\n await this.repository.updateUserTier(userId, {\n tier,\n // Through the shared contract, like every path that resolves the tier's\n // limit from configuration. (The repository's `updateUserCredits` and\n // `updateUserTier` still store a caller-supplied `monthlyLimit` verbatim;\n // they are given a value, not a tier, so there is no sentinel to map.)\n // This used to store 0 for an unlimited tier under a \"0 means unlimited\"\n // convention that nothing actually implemented — no read path anywhere in\n // the library branches on it — so upgrading a user to unlimited gave them\n // an allowance of zero.\n monthlyLimit: storedMonthlyLimit(monthlyLimit),\n // Reset balance to new tier limit if upgrading\n balance: !free\n ? (unlimited ? getUnlimitedSentinelBalance() : monthlyLimit)\n : undefined,\n monthlyUsed: !free ? 0 : undefined,\n subscriptionExpiresAt: expiresAt ? expiresAt.toISOString() : null,\n });\n }\n\n /**\n * Get usage logs with optional filtering\n * @param userId - Optional user ID filter\n * @param limit - Max results\n * @param offset - Skip results\n * @returns List of usage logs\n */\n async getUsageLogs(\n userId?: string,\n limit = 50,\n offset = 0\n ): Promise<PortableUsageLog[]> {\n return this.repository.getUsageLogs({ userId, limit, offset });\n }\n\n /**\n * Get user-friendly usage history\n * Combines journal entries into a user-facing format\n *\n * @param userId - User ID\n * @param limit - Max results per page\n * @param offset - Skip results for pagination\n * @returns Paginated usage history response\n */\n async getUsageHistory(\n userId: string,\n limit = 20,\n offset = 0\n ): Promise<UsageHistoryResponse> {\n // Get journal entries\n const [entries, total] = await Promise.all([\n this.repository.getJournalEntries({ userId, limit, offset }),\n this.repository.getJournalEntriesCount({ userId }),\n ]);\n\n // Convert journal entries to user-friendly format\n const historyEntries: UsageHistoryEntry[] = entries.map((entry) => {\n const type = this.mapSourceToHistoryType(entry.source);\n const creditsChange = entry.entryType === \"credit\" ? entry.amount : -entry.amount;\n\n return {\n id: entry.id,\n type,\n creditsChange,\n balanceAfter: entry.balanceAfter,\n description: entry.description,\n createdAt: typeof entry.createdAt === \"string\"\n ? entry.createdAt\n : toDate(entry.createdAt).toISOString(),\n };\n });\n\n return {\n entries: historyEntries,\n pagination: {\n total,\n limit,\n offset,\n hasMore: offset + entries.length < total,\n },\n };\n }\n\n /**\n * Map journal entry source to user-friendly history type\n */\n private mapSourceToHistoryType(\n source: PortableJournalEntry[\"source\"]\n ): UsageHistoryEntry[\"type\"] {\n switch (source) {\n case \"operation_commit\":\n case \"reservation_expired\":\n return \"usage\";\n case \"purchase\":\n return \"purchase\";\n case \"subscription_grant\":\n case \"subscription_upgrade\":\n case \"bonus\":\n return \"bonus\";\n case \"monthly_reset\":\n return \"reset\";\n case \"refund\":\n case \"operation_release\":\n return \"refund\";\n case \"admin_adjustment\":\n case \"subscription_downgrade\":\n case \"expiry\":\n default:\n return \"adjustment\";\n }\n }\n\n /**\n * Get journal entries directly (for admin or debugging)\n * @param query - Journal entry query parameters\n * @returns List of journal entries\n */\n async getJournalEntries(query: JournalEntryQuery): Promise<PortableJournalEntry[]> {\n return this.repository.getJournalEntries(query);\n }\n\n /**\n * Get the underlying repository (for advanced use cases)\n */\n getRepository(): ICreditRepository {\n return this.repository;\n }\n}\n\n/**\n * Create a credits service with a repository\n */\nexport function createCreditsService(repository: ICreditRepository): CreditsService {\n return new CreditsService(repository);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACWO,IAAM,kBAAkB;AAAA,EAC7B,sBAAsB;AAAA,EACtB,uBAAuB;AAAA,EACvB,qBAAqB;AAAA,EACrB,+BAA+B;AAAA,EAC/B,gBAAgB;AAAA,EAChB,wBAAwB;AAAA,EACxB,qBAAqB;AAAA,EACrB,gBAAgB;AAAA;AAAA,EAEhB,sBAAsB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMtB,iBAAiB;AAAA;AAAA,EAEjB,uBAAuB;AAAA;AAAA,EAEvB,gBAAgB;AAAA;AAAA,EAEhB,yBAAyB;AAAA;AAAA;AAAA;AAAA;AAAA,EAKzB,4BAA4B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAM5B,sBAA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,CAAC,MAAM;AAE3E,aAAO;AAAA,QACL,IAAI,MAAM;AAAA,QACV;AAAA,QACA;AAAA,QACA,cAAc,MAAM;AAAA,QACpB,aAAa,MAAM;AAAA,QACnB,WAAW,OAAO,MAAM,cAAc,WAClC,MAAM,YACN,OAAO,MAAM,SAAS,EAAE,YAAY;AAAA,MAC1C;AAAA,IACF,CAAC;AAED,WAAO;AAAA,MACL,SAAS;AAAA,MACT,YAAY;AAAA,QACV;AAAA,QACA;AAAA,QACA;AAAA,QACA,SAAS,SAAS,QAAQ,SAAS;AAAA,MACrC;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKQ,uBACN,QAC2B;AAC3B,YAAQ,QAAQ;AAAA,MACd,KAAK;AAAA,MACL,KAAK;AACH,eAAO;AAAA,MACT,KAAK;AACH,eAAO;AAAA,MACT,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AACH,eAAO;AAAA,MACT,KAAK;AACH,eAAO;AAAA,MACT,KAAK;AAAA,MACL,KAAK;AACH,eAAO;AAAA,MACT,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,MACL;AACE,eAAO;AAAA,IACX;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,kBAAkB,OAA2D;AACjF,WAAO,KAAK,WAAW,kBAAkB,KAAK;AAAA,EAChD;AAAA;AAAA;AAAA;AAAA,EAKA,gBAAmC;AACjC,WAAO,KAAK;AAAA,EACd;AACF;AAKO,SAAS,qBAAqB,YAA+C;AAClF,SAAO,IAAI,eAAe,UAAU;AACtC;","names":[]}
1
+ {"version":3,"sources":["../../src/service/index.ts","../../src/core/errors.ts","../../src/core/amount.ts","../../src/core/types.ts","../../src/config/index.ts","../../src/config/provider.ts","../../src/core/payment-ref.ts","../../src/repository/types.ts","../../src/repository/flow.ts","../../src/service/credits-service.ts"],"sourcesContent":["export {\r\n CreditsService,\r\n createCreditsService,\r\n} from \"./credits-service.js\";\r\n\r\nexport type {\r\n LowBalanceNotificationCallback,\r\n SubscriptionExpiredNotificationCallback,\r\n ReserveCreditsOptions,\r\n DeductCreditsOptions,\r\n} from \"./credits-service.js\";\r\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","/**\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 * Portable credits types - framework and database agnostic\r\n *\r\n * These types use standard JavaScript types (string, Date) instead of\r\n * Firebase-specific types (Timestamp). This makes the credits system\r\n * portable to other environments without Firebase dependencies.\r\n *\r\n * Note: Firestore Timestamp is handled by the credits-firestore adapter.\r\n */\r\n\r\n// ==================== Utility Functions ====================\r\n\r\n/**\r\n * Calculate available credits from balance, bonus, and reserved amounts.\r\n *\r\n * Available = balance + bonusCredits - reserved\r\n *\r\n * @param balance - Regular monthly credits\r\n * @param bonusCredits - Purchased/admin credits\r\n * @param reserved - Credits locked for in-flight operations\r\n * @returns Available credits for new operations\r\n */\r\nexport function calculateAvailableCredits(\r\n balance: number,\r\n bonusCredits: number,\r\n reserved: number\r\n): number {\r\n return sumAmounts(balance, bonusCredits, -reserved);\r\n}\r\n\r\n/**\r\n * Convert various timestamp formats to ISO string.\r\n *\r\n * Handles:\r\n * - Date objects\r\n * - ISO string (returned as-is)\r\n * - Timestamp-like objects with toDate() method (Firebase)\r\n * - undefined/null (returns current time)\r\n *\r\n * @param value - Value to convert\r\n * @returns ISO 8601 string\r\n */\r\nexport function toPortableTimestamp(value: unknown): string {\r\n if (!value) {\r\n return new Date().toISOString();\r\n }\r\n\r\n if (typeof value === \"string\") {\r\n return value;\r\n }\r\n\r\n if (value instanceof Date) {\r\n return value.toISOString();\r\n }\r\n\r\n if (\r\n typeof value === \"object\" &&\r\n value !== null &&\r\n \"toDate\" in value &&\r\n typeof (value as { toDate: () => Date }).toDate === \"function\"\r\n ) {\r\n return (value as { toDate: () => Date }).toDate().toISOString();\r\n }\r\n\r\n return new Date().toISOString();\r\n}\r\n\r\n/**\r\n * Convert various timestamp formats to Date object.\r\n *\r\n * Handles:\r\n * - Date objects (returned as-is)\r\n * - ISO string\r\n * - Timestamp-like objects with toDate() method (Firebase)\r\n * - Invalid values (returns current date)\r\n *\r\n * @param value - Value to convert\r\n * @returns Date object\r\n */\r\nexport function toDate(value: unknown): Date {\r\n if (value instanceof Date) {\r\n return value;\r\n }\r\n\r\n if (typeof value === \"string\") {\r\n return new Date(value);\r\n }\r\n\r\n if (\r\n typeof value === \"object\" &&\r\n value !== null &&\r\n \"toDate\" in value &&\r\n typeof (value as { toDate: () => Date }).toDate === \"function\"\r\n ) {\r\n return (value as { toDate: () => Date }).toDate();\r\n }\r\n\r\n return new Date();\r\n}\r\n\r\n// ==================== Subscription Types ====================\r\n\r\n/**\r\n * Built-in tier ids (autocomplete) — apps may add more via config.\r\n */\r\nexport type BuiltinTier = \"free\" | \"basic\" | \"premium\" | \"unlimited\";\r\n\r\n/**\r\n * Subscription tiers for the credits system.\r\n *\r\n * Any built-in OR any config-defined tier id. The `(string & {})` keeps builtin\r\n * autocomplete while accepting arbitrary configured tiers.\r\n */\r\nexport type SubscriptionTier = BuiltinTier | (string & {});\r\n\r\n// ==================== Operation Types ====================\r\n\r\n/**\r\n * Operation types for cost tracking (provider-agnostic)\r\n *\r\n * Dynamic string type - any operation configured in the system is valid.\r\n */\r\nexport type CreditOperationType = string;\r\n\r\n/**\r\n * AI providers\r\n */\r\nexport type AIProviderType = \"gemini\";\r\n\r\n/**\r\n * Resource type for usage logging\r\n */\r\nexport type ResourceType = string;\r\n\r\n// ==================== User Credits ====================\r\n\r\n/**\r\n * Portable user credits balance\r\n *\r\n * Uses ISO string timestamps instead of Firebase Timestamp.\r\n * This type is safe for JSON serialization and works across frameworks.\r\n */\r\nexport interface PortableUserCredits {\r\n userId: string;\r\n /** Current available balance (monthly credits, reset each month) */\r\n balance: number;\r\n /** Bonus credits from purchases/admin (never reset, persist until used) */\r\n bonusCredits: number;\r\n /** Credits currently reserved for in-flight operations */\r\n reserved: number;\r\n /** User's subscription tier */\r\n tier: SubscriptionTier;\r\n /** Monthly credit limit based on tier (0 = unlimited) */\r\n monthlyLimit: number;\r\n /** Credits used this month (resets monthly) */\r\n monthlyUsed: number;\r\n /** When monthly credits reset (start of next month) - ISO 8601 */\r\n monthlyResetAt: string;\r\n /** Subscription expiry (null/undefined for free tier) - ISO 8601 or null */\r\n subscriptionExpiresAt?: string | null;\r\n /**\r\n * The part of `balance` a balance-lowering write kept only to back outstanding\r\n * holds. A commit consumes it; a release or expiry removes it from `balance`.\r\n * Absent means 0. See `planBalanceCap`.\r\n */\r\n expiredHoldBacking?: number;\r\n /**\r\n * Set when the account was created with a signup-grant claim: the amount\r\n * granted, 0 when the claim was already taken. Absent on any other account.\r\n */\r\n signupGrant?: number;\r\n /** Creation timestamp - ISO 8601 */\r\n createdAt: string;\r\n /** Last update timestamp - ISO 8601 */\r\n updatedAt: string;\r\n}\r\n\r\n// ==================== Reservation Types ====================\r\n\r\n/**\r\n * Credit reservation status for two-phase commit\r\n */\r\nexport type ReservationStatus = \"reserved\" | \"committed\" | \"released\" | \"expired\";\r\n\r\n/**\r\n * Portable credit reservation\r\n *\r\n * Used for two-phase commit to prevent double-spending.\r\n */\r\nexport interface PortableReservation {\r\n id: string;\r\n userId: string;\r\n /** Amount of credits reserved */\r\n amount: number;\r\n /** Operation type for tracking */\r\n operationType: CreditOperationType;\r\n /** Current status of reservation */\r\n status: ReservationStatus;\r\n /** When reservation was created - ISO 8601 */\r\n createdAt: string;\r\n /** When reservation expires (for cleanup) - ISO 8601 */\r\n expiresAt: string;\r\n /** When reservation was committed/released - ISO 8601 or undefined */\r\n completedAt?: string;\r\n /**\r\n * Caller-supplied idempotency key (V2). Absent on legacy reservations.\r\n * Unique per user; a replay with the same key returns this same reservation.\r\n */\r\n idempotencyKey?: string;\r\n /**\r\n * When the atomic reserve placed this hold - ISO 8601, or absent.\r\n *\r\n * Written by `reserveCreditsV2` inside the same transaction that increases\r\n * `reserved`, so its presence is proof that the hold exists. `createReservation`\r\n * never sets it, and the V2 transitions refuse to move a row without it.\r\n * See `assertHoldPlaced` in `core/reservation-integrity.ts`.\r\n */\r\n holdPlacedAt?: string;\r\n /**\r\n * The part of this hold backed by credits that expired while it was open, and so\r\n * leave the balance when it closes, however it closes. Absent means 0, as on every\r\n * hold placed after the expiry. Open holds' shares sum to the account's\r\n * `expiredHoldBacking`.\r\n */\r\n expiredBacking?: number;\r\n}\r\n\r\n// ==================== Result Types ====================\r\n\r\n/**\r\n * Result of a credit check operation\r\n */\r\nexport interface CreditCheckResult {\r\n /** Whether user has sufficient credits */\r\n hasCredits: boolean;\r\n /** Current balance (balance + bonusCredits) */\r\n balance: number;\r\n /** Required credits for operation */\r\n required: number;\r\n /** Shortfall if insufficient */\r\n shortfall: number;\r\n}\r\n\r\n/**\r\n * Result of a one-shot atomic credit deduction (see `CreditsService.deductCredits`).\r\n *\r\n * Discriminated on `success` so callers get exhaustive narrowing:\r\n * - `success: true` -> `newBalance` is populated, `available`/`shortfall` are not present.\r\n * - `success: false` -> `available`/`shortfall` describe the shortfall, no mutation occurred.\r\n */\r\nexport type DeductCreditsResult =\r\n | {\r\n success: true;\r\n /** Combined balance (balance + bonusCredits) after the deduction */\r\n newBalance: number;\r\n }\r\n | {\r\n success: false;\r\n reason: \"insufficient\";\r\n /** Combined balance (balance + bonusCredits - reserved) available before the attempt */\r\n available: number;\r\n /** Credits that were requested */\r\n required: number;\r\n /** How many more credits would have been needed */\r\n shortfall: number;\r\n };\r\n\r\n/**\r\n * Result of monthly reset operation\r\n */\r\nexport interface MonthlyResetResult {\r\n /** Whether the reset was performed */\r\n wasReset: boolean;\r\n /** The user credits after the operation */\r\n credits: PortableUserCredits;\r\n /**\r\n * `true` when the repository wrote the reset's journal entry inside the same\r\n * atomic step as the balance write. The service then skips its own journal\r\n * call — a separate call sits outside the reset's atomicity, and if it fails\r\n * after the CAS was consumed, the line is lost for good (no retry ever sees\r\n * the reset again). Absent/`false` means the repository did not journal and\r\n * the service falls back to the legacy non-atomic write.\r\n */\r\n journaled?: boolean;\r\n}\r\n\r\n/**\r\n * Result of subscription expiry check\r\n */\r\nexport interface SubscriptionExpiryResult {\r\n /** Whether the subscription was downgraded */\r\n wasDowngraded: boolean;\r\n /** Whether user is in grace period */\r\n inGracePeriod: boolean;\r\n /** Days remaining in grace period (0 if not in grace) */\r\n graceDaysRemaining: number;\r\n /** The user credits after the operation */\r\n credits: PortableUserCredits;\r\n /**\r\n * `true` when the repository wrote the downgrade's journal entry inside the\r\n * same atomic step as the tier write. The service then skips its own journal\r\n * call — a separate call sits outside the downgrade's atomicity, and if it\r\n * fails after the tier write committed, the account is downgraded with no\r\n * audit line and no retry ever fires (the row is no longer eligible).\r\n * Absent/`false` means the repository did not journal and the service falls\r\n * back to the legacy non-atomic write.\r\n */\r\n journaled?: boolean;\r\n}\r\n\r\n// ==================== Transaction Types ====================\r\n\r\n/**\r\n * Credit transaction type\r\n */\r\nexport type TransactionType = \"purchase\" | \"subscription\" | \"bonus\" | \"refund\" | \"adjustment\";\r\n\r\n/**\r\n * Portable credit transaction\r\n */\r\nexport interface PortableTransaction {\r\n id: string;\r\n userId: string;\r\n type: TransactionType;\r\n /** Amount of credits (positive for additions, negative for deductions) */\r\n amount: number;\r\n description: string;\r\n /** Reference to payment provider */\r\n paymentRef?: string;\r\n previousBalance: number;\r\n newBalance: number;\r\n createdAt: string;\r\n}\r\n\r\n// ==================== Journal Types ====================\r\n\r\n/**\r\n * Source of a credit journal entry\r\n */\r\nexport type CreditSource =\r\n | \"operation_commit\"\r\n | \"operation_release\"\r\n | \"purchase\"\r\n | \"subscription_grant\"\r\n | \"subscription_upgrade\"\r\n | \"subscription_downgrade\"\r\n | \"monthly_reset\"\r\n | \"bonus\"\r\n | \"refund\"\r\n | \"admin_adjustment\"\r\n | \"expiry\"\r\n | \"reservation_expired\";\r\n\r\n/**\r\n * Type of reference for a journal entry\r\n */\r\nexport type JournalReferenceType =\r\n | \"reservation\"\r\n | \"transaction\"\r\n | \"adjustment\"\r\n | \"reset\"\r\n | \"subscription\";\r\n\r\n/**\r\n * Portable credit journal entry for audit trail\r\n */\r\nexport interface PortableJournalEntry {\r\n id: string;\r\n userId: string;\r\n /** Type of entry - debit decreases balance, credit increases balance */\r\n entryType: \"debit\" | \"credit\";\r\n /** Amount of credits involved */\r\n amount: number;\r\n /** Balance after this entry */\r\n balanceAfter: number;\r\n /** Source of the credit change */\r\n source: CreditSource;\r\n /** Reference ID (e.g., reservationId, transactionId) */\r\n referenceId: string;\r\n /** Type of reference */\r\n referenceType: JournalReferenceType;\r\n /** Human-readable description */\r\n description: string;\r\n /** Additional metadata */\r\n metadata?: Record<string, unknown>;\r\n /**\r\n * Deterministic key that makes this entry unique per user (V2). Absent on\r\n * legacy entries; present entries cannot be written twice.\r\n */\r\n idempotencyKey?: string;\r\n /** When this entry was created - ISO 8601 */\r\n createdAt: string;\r\n}\r\n\r\n// ==================== Usage Types ====================\r\n\r\n/**\r\n * Portable usage log entry\r\n */\r\nexport interface PortableUsageLog {\r\n id: string;\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?: ResourceType;\r\n requestId?: string;\r\n metadata?: Record<string, unknown>;\r\n createdAt: string;\r\n}\r\n\r\n/**\r\n * User-friendly usage history entry\r\n */\r\nexport interface UsageHistoryEntry {\r\n id: string;\r\n /** Type of entry for display */\r\n type: \"usage\" | \"purchase\" | \"bonus\" | \"reset\" | \"refund\" | \"adjustment\";\r\n /** Positive = earned, Negative = spent */\r\n creditsChange: number;\r\n /** Balance after this entry */\r\n balanceAfter: number;\r\n /** Human-readable description */\r\n description: string;\r\n /** When this occurred - ISO 8601 */\r\n createdAt: string;\r\n}\r\n\r\n/**\r\n * Paginated usage history response\r\n */\r\nexport interface UsageHistoryResponse {\r\n entries: UsageHistoryEntry[];\r\n pagination: {\r\n total: number;\r\n limit: number;\r\n offset: number;\r\n hasMore: boolean;\r\n };\r\n}\r\n\r\n// ==================== Tier Configuration ====================\r\n\r\n/**\r\n * Tier configuration for credit limits and pricing\r\n */\r\nexport interface TierConfig {\r\n tier: SubscriptionTier;\r\n monthlyCredits: number;\r\n priceUsd: number;\r\n features: string[];\r\n /** Free/default tier marker — no subscription expiry, balance untouched on tier change. Defaults to priceUsd === 0. */\r\n isFree?: boolean;\r\n /** Unlimited tier marker. Defaults to monthlyCredits === 0. */\r\n unlimited?: boolean;\r\n /** Tier assigned to brand-new users. Defaults to the tier flagged isFree. */\r\n isDefault?: boolean;\r\n}\r\n\r\n// ==================== Options Types ====================\r\n\r\n/**\r\n * Options for withCredits HOF\r\n */\r\nexport interface WithCreditsOptions {\r\n /** Operation type for cost lookup */\r\n operationType: CreditOperationType;\r\n /** AI provider (defaults to \"gemini\") */\r\n provider?: AIProviderType;\r\n /**\r\n * Custom cost override (use with caution). Must be a movable amount: only a\r\n * cost of 0 in `operationCosts` makes an operation free, so a computed\r\n * override that lands on 0 is refused rather than run for nothing.\r\n */\r\n customCost?: number;\r\n /** Resource ID for usage logging */\r\n resourceId?: string;\r\n /** Resource type for usage logging */\r\n resourceType?: ResourceType;\r\n}\r\n\r\n// ==================== Constants ====================\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","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","/**\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","import type {\r\n PortableUserCredits,\r\n PortableReservation,\r\n CreditCheckResult,\r\n CreditOperationType,\r\n SubscriptionTier,\r\n PortableUsageLog,\r\n PortableJournalEntry,\r\n UsageHistoryEntry,\r\n UsageHistoryResponse,\r\n DeductCreditsResult,\r\n} from \"../core/types.js\";\r\nimport { toDate } from \"../core/types.js\";\r\nimport type {\r\n AddCreditsOutcome,\r\n CommitOutcome,\r\n ReleaseOutcome,\r\n ReserveOutcome,\r\n} from \"../core/outcomes.js\";\r\nimport {\r\n CreditErrorCode,\r\n createIdempotencyConflictError,\r\n createInsufficientCreditsError,\r\n createReservationAlreadyProcessedError,\r\n createReservationNotFoundError,\r\n isCreditError,\r\n} from \"../core/errors.js\";\r\nimport {\r\n assertValidCreditAmount,\r\n storedMonthlyLimit,\r\n sumAmounts,\r\n} from \"../core/amount.js\";\r\nimport type { ReservationTransitionOptions } from \"../repository/v2-types.js\";\r\nimport {\r\n addCreditsThroughRepository,\r\n commitThroughRepository,\r\n releaseThroughRepository,\r\n reserveThroughRepository,\r\n} from \"../repository/flow.js\";\r\nimport type {\r\n ICreditRepository,\r\n CreateUsageLogInput,\r\n JournalEntryQuery,\r\n AddCreditsAtomicOptions,\r\n} from \"../repository/types.js\";\r\nimport { toClientUserCredits } from \"../repository/types.js\";\r\nimport {\r\n getConfig,\r\n getConfigMonthlyLimit,\r\n getOperationLabel,\r\n isFreeTier,\r\n isUnlimitedTier,\r\n getDefaultTier,\r\n getUnlimitedSentinelBalance,\r\n} from \"../config/index.js\";\r\n\r\n/**\r\n * Check if a date is past the monthly reset date\r\n */\r\nfunction isPastMonthlyReset(resetAt: unknown): boolean {\r\n if (!resetAt) return false;\r\n const resetDate = toDate(resetAt);\r\n return new Date() >= resetDate;\r\n}\r\n\r\n/**\r\n * Notification callback type for low balance notifications\r\n */\r\nexport type LowBalanceNotificationCallback = (userId: string, balance: number) => Promise<void>;\r\n\r\n/**\r\n * Notification callback type for subscription expired notifications\r\n */\r\nexport type SubscriptionExpiredNotificationCallback = (userId: string, wasDowngraded: boolean) => Promise<void>;\r\n\r\n/**\r\n * Options for reserving credits.\r\n */\r\nexport interface ReserveCreditsOptions {\r\n /**\r\n * Time-to-live for the reservation, in milliseconds, before the cleanup\r\n * sweep may expire it. Defaults to `config.reservationExpiryMs` (suitable\r\n * for synchronous, in-request operations). Long-running async jobs\r\n * (e.g. background media generation) should pass a TTL matching their\r\n * own lifecycle so the reservation is not expired while the job is still\r\n * legitimately in flight.\r\n */\r\n ttlMs?: number;\r\n /**\r\n * Caller-supplied idempotency key, unique per user.\r\n *\r\n * Retrying a reserve with the same key and the same amount/operation returns\r\n * the original reservation instead of placing a second hold — the fix for a\r\n * webhook or job runner delivering the same request twice. Reusing a key\r\n * with a *different* amount or operation is a\r\n * `CreditErrorCode.IDEMPOTENCY_CONFLICT`.\r\n *\r\n * Requires a repository implementing the V2 boundary (see\r\n * `supportsCreditsV2`). A legacy adapter has no unique index to enforce the\r\n * key, so it is ignored there rather than silently promised.\r\n */\r\n idempotencyKey?: string;\r\n}\r\n\r\n/**\r\n * Options for a one-shot atomic credit deduction via `deductCredits`.\r\n */\r\nexport interface DeductCreditsOptions {\r\n /**\r\n * Operation type for cost tracking / journal + usage-log labeling.\r\n * Falls back to a generic \"adjustment\" description when omitted.\r\n */\r\n operationType?: CreditOperationType;\r\n /** Resource ID to attach to the usage log (e.g. the generated asset's id) */\r\n resourceId?: string;\r\n /** Resource type to attach to the usage log */\r\n resourceType?: string;\r\n /** Request ID to attach to the usage log, for tracing */\r\n requestId?: string;\r\n /** Additional metadata recorded on the journal entry */\r\n metadata?: Record<string, unknown>;\r\n}\r\n\r\n/**\r\n * Credits service with dependency injection for repository\r\n *\r\n * Provides business logic for credit operations, delegating\r\n * database operations to the injected repository.\r\n */\r\nexport class CreditsService {\r\n private lowBalanceCallback?: LowBalanceNotificationCallback;\r\n private subscriptionExpiredCallback?: SubscriptionExpiredNotificationCallback;\r\n\r\n constructor(private readonly repository: ICreditRepository) {}\r\n\r\n /**\r\n * Set callback for low balance notifications\r\n */\r\n setLowBalanceCallback(callback: LowBalanceNotificationCallback): void {\r\n this.lowBalanceCallback = callback;\r\n }\r\n\r\n /**\r\n * Set callback for subscription expired notifications\r\n */\r\n setSubscriptionExpiredCallback(callback: SubscriptionExpiredNotificationCallback): void {\r\n this.subscriptionExpiredCallback = callback;\r\n }\r\n\r\n /**\r\n * Get user credits, performing monthly reset and subscription expiry checks if needed\r\n *\r\n * This method uses atomic operations to prevent race conditions:\r\n * 1. Checks subscription expiry with grace period\r\n * 2. Atomically performs monthly reset if needed (with optimistic locking)\r\n *\r\n * @param userId - User ID\r\n * @returns User credits or null if not found\r\n */\r\n async getUserCredits(userId: string): Promise<PortableUserCredits | null> {\r\n let data = await this.repository.getUserCredits(userId);\r\n\r\n if (!data) {\r\n return null;\r\n }\r\n\r\n // Step 1: Check subscription expiry (for non-free tiers)\r\n if (!isFreeTier(data.tier) && data.subscriptionExpiresAt) {\r\n const expiryResult = await this.repository.checkAndHandleSubscriptionExpiry(\r\n userId,\r\n getConfig().subscriptionGracePeriodDays\r\n );\r\n\r\n if (expiryResult.wasDowngraded && !expiryResult.journaled) {\r\n // Legacy path for repositories that do not journal the downgrade\r\n // themselves. This write sits outside the downgrade's atomic step: if\r\n // it fails after the tier write committed, the account is downgraded\r\n // with no audit line and no retry ever fires (the row is no longer\r\n // eligible). Repositories that can journal atomically return\r\n // `journaled: true` and this block is skipped.\r\n await this.repository.createJournalEntry({\r\n userId,\r\n entryType: \"debit\",\r\n amount: 0, // No credits deducted, just tier change\r\n // The ledger balance, matching every other journal writer: the V2\r\n // transitions and add/deduct all record `balance + bonusCredits`, so\r\n // recording `balance` alone made the audit trail disagree with itself\r\n // for any user holding bonus credits.\r\n balanceAfter: sumAmounts(\r\n expiryResult.credits.balance,\r\n expiryResult.credits.bonusCredits\r\n ),\r\n source: \"subscription_downgrade\",\r\n referenceId: `downgrade-${Date.now()}`,\r\n referenceType: \"subscription\",\r\n // The tier actually landed on, not a hard-coded \"free\": the downgrade\r\n // target is configurable, so naming `free` here could describe a\r\n // transition that never happened.\r\n description: `Subscription expired. Downgraded from ${data.tier} to ${expiryResult.credits.tier} tier.`,\r\n metadata: {\r\n previousTier: data.tier,\r\n previousBalance: data.balance,\r\n newBalance: expiryResult.credits.balance,\r\n },\r\n });\r\n }\r\n\r\n // Trigger subscription expired notification (non-blocking) — on every\r\n // downgrade, whichever side wrote the journal.\r\n if (expiryResult.wasDowngraded && this.subscriptionExpiredCallback) {\r\n this.subscriptionExpiredCallback(userId, true).catch((error) => {\r\n console.error(\"[Credits] Failed to send subscription expired notification:\", error);\r\n });\r\n }\r\n\r\n // Use the potentially updated credits\r\n data = expiryResult.credits;\r\n }\r\n\r\n // Step 2: Check if monthly reset is needed (use atomic operation)\r\n if (isPastMonthlyReset(data.monthlyResetAt)) {\r\n // Convert monthlyResetAt to a compatible type (Date or string)\r\n const expectedResetAt = toDate(data.monthlyResetAt);\r\n const resetResult = await this.repository.atomicMonthlyReset(\r\n userId,\r\n data.tier,\r\n expectedResetAt\r\n );\r\n\r\n if (resetResult.wasReset && !resetResult.journaled) {\r\n // Legacy path for repositories that do not journal the reset\r\n // themselves. This write sits outside the reset's atomic step: if it\r\n // fails after the CAS was consumed, the journal line is lost for good.\r\n // Repositories that can journal atomically return `journaled: true`\r\n // and this block is skipped.\r\n const balanceChange = sumAmounts(resetResult.credits.balance, -data.balance);\r\n if (balanceChange !== 0) {\r\n await this.repository.createJournalEntry({\r\n userId,\r\n entryType: balanceChange > 0 ? \"credit\" : \"debit\",\r\n amount: Math.abs(balanceChange),\r\n balanceAfter: sumAmounts(\r\n resetResult.credits.balance,\r\n resetResult.credits.bonusCredits\r\n ),\r\n source: \"monthly_reset\",\r\n referenceId: `reset-${Date.now()}`,\r\n referenceType: \"reset\",\r\n // The tier the reset ran on, which a concurrent downgrade may have\r\n // changed since `data` was read.\r\n description: `Monthly credit reset for ${resetResult.credits.tier} tier.`,\r\n metadata: {\r\n tier: resetResult.credits.tier,\r\n previousBalance: data.balance,\r\n newBalance: resetResult.credits.balance,\r\n },\r\n });\r\n }\r\n }\r\n\r\n // Use the potentially updated credits\r\n data = resetResult.credits;\r\n }\r\n\r\n return toClientUserCredits(data);\r\n }\r\n\r\n /**\r\n * Initialize credits for a new user with free tier\r\n * @param userId - User ID\r\n * @returns Initialized user credits\r\n */\r\n async initializeUserCredits(userId: string): Promise<PortableUserCredits> {\r\n const credits = await this.repository.initializeUserCredits(\r\n userId,\r\n getDefaultTier(),\r\n getConfig().defaultFreeCredits\r\n );\r\n return toClientUserCredits(credits);\r\n }\r\n\r\n /**\r\n * Get or create user credits\r\n * Initializes with free tier if not exists\r\n * @param userId - User ID\r\n * @returns User credits\r\n */\r\n async getOrCreateUserCredits(userId: string): Promise<PortableUserCredits> {\r\n const existing = await this.getUserCredits(userId);\r\n if (existing) {\r\n return existing;\r\n }\r\n return this.initializeUserCredits(userId);\r\n }\r\n\r\n /**\r\n * Check if user has sufficient credits for an operation\r\n * @param userId - User ID\r\n * @param requiredCredits - Credits required\r\n * @returns Credit check result\r\n */\r\n async checkCredits(userId: string, requiredCredits: number): Promise<CreditCheckResult> {\r\n const credits = await this.getOrCreateUserCredits(userId);\r\n\r\n // Available = balance + bonusCredits - reserved\r\n const totalBalance = sumAmounts(credits.balance, credits.bonusCredits);\r\n const available = sumAmounts(totalBalance, -credits.reserved);\r\n const hasCredits = available >= requiredCredits;\r\n\r\n return {\r\n hasCredits,\r\n balance: totalBalance,\r\n required: requiredCredits,\r\n shortfall: hasCredits ? 0 : sumAmounts(requiredCredits, -available),\r\n };\r\n }\r\n\r\n /**\r\n * Reserve credits for an operation (phase 1 of two-phase commit)\r\n * Creates a reservation and locks the credits\r\n * @param userId - User ID\r\n * @param amount - Credits to reserve\r\n * @param operationType - Operation type for tracking\r\n * @param options - Optional settings (e.g. a custom `ttlMs` for long-running async jobs)\r\n * @returns Reservation object\r\n * @throws Error if insufficient credits\r\n */\r\n async reserveCredits(\r\n userId: string,\r\n amount: number,\r\n operationType: CreditOperationType,\r\n options?: ReserveCreditsOptions\r\n ): Promise<PortableReservation> {\r\n const outcome = await this.reserveCreditsDetailed(userId, amount, operationType, options);\r\n if (outcome.outcome === \"created\" || outcome.outcome === \"replayed\") {\r\n return outcome.reservation;\r\n }\r\n if (outcome.outcome === \"insufficient\") {\r\n throw createInsufficientCreditsError(outcome.required, outcome.available);\r\n }\r\n throw createIdempotencyConflictError(outcome.idempotencyKey, {\r\n userId,\r\n requested: { amount, operationType },\r\n existing: {\r\n amount: outcome.existing.amount,\r\n operationType: outcome.existing.operationType,\r\n },\r\n });\r\n }\r\n\r\n /**\r\n * Reserve credits and get the typed outcome instead of an exception.\r\n *\r\n * Prefer this over {@link reserveCredits} in async callers: it distinguishes\r\n * a fresh hold from an idempotent replay, and reports insufficient funds as\r\n * a value rather than as control flow.\r\n */\r\n async reserveCreditsDetailed(\r\n userId: string,\r\n amount: number,\r\n operationType: CreditOperationType,\r\n options?: ReserveCreditsOptions\r\n ): Promise<ReserveOutcome> {\r\n const ttlMs = options?.ttlMs ?? getConfig().reservationExpiryMs;\r\n const expiresAt = new Date(Date.now() + ttlMs);\r\n return reserveThroughRepository(this.repository, {\r\n userId,\r\n amount,\r\n operationType,\r\n expiresAt,\r\n idempotencyKey: options?.idempotencyKey,\r\n });\r\n }\r\n\r\n /**\r\n * Commit a reservation (phase 2 of two-phase commit - success).\r\n *\r\n * Idempotent: re-delivering a commit for an already-committed reservation is\r\n * a no-op. Committing one that was released or expired throws, because the\r\n * credits are no longer held and pretending otherwise would hide a real bug.\r\n */\r\n async commitCredits(\r\n userId: string,\r\n reservationId: string,\r\n options?: ReservationTransitionOptions\r\n ): Promise<void> {\r\n const outcome = await this.commitCreditsDetailed(userId, reservationId, options);\r\n if (outcome.outcome === \"not_found\") {\r\n throw createReservationNotFoundError(reservationId);\r\n }\r\n if (outcome.outcome === \"already_terminal\" && outcome.terminalStatus !== \"committed\") {\r\n throw createReservationAlreadyProcessedError(reservationId, outcome.terminalStatus);\r\n }\r\n }\r\n\r\n /**\r\n * Commit a reservation and get the typed outcome.\r\n *\r\n * Exactly one concurrent caller sees `committed`; that call moved the balance\r\n * and wrote the single journal entry. On a V2 repository the journal is\r\n * written inside the same transaction, so this method adds none of its own —\r\n * the duplicate entry the previous implementation wrote is gone.\r\n *\r\n * The low-balance notification fires only for the winner, and only after the\r\n * transaction has committed, so no callback runs inside a database\r\n * transaction.\r\n */\r\n async commitCreditsDetailed(\r\n userId: string,\r\n reservationId: string,\r\n options?: ReservationTransitionOptions\r\n ): Promise<CommitOutcome> {\r\n const outcome = await commitThroughRepository(\r\n this.repository,\r\n userId,\r\n reservationId,\r\n options\r\n );\r\n\r\n if (outcome.outcome === \"committed\" && this.lowBalanceCallback) {\r\n this.lowBalanceCallback(userId, outcome.balanceAfter).catch((error) => {\r\n console.error(\"[Credits] Failed to send low balance notification:\", error);\r\n });\r\n }\r\n\r\n return outcome;\r\n }\r\n\r\n /**\r\n * Release a reservation (phase 2 of two-phase commit - failure).\r\n *\r\n * Throws `RESERVATION_NOT_FOUND` for an unknown reservation, matching the\r\n * pre-V2 behaviour — a release naming a reservation that does not exist is a\r\n * caller bug, and swallowing it hides the bug while the credits stay held.\r\n *\r\n * Releasing one that is already terminal — `released`, `expired`, or\r\n * `committed` — is a no-op, which is the behaviour this method has always\r\n * had. A release that loses a race to a concurrent commit is the common\r\n * case in a retry-heavy caller, and callers written against the pre-V2\r\n * contract handle it by not handling it.\r\n *\r\n * That does mean this method cannot tell you that the credits were spent\r\n * rather than returned. Use {@link releaseCreditsDetailed}, which reports\r\n * `already_terminal` with `terminalStatus: 'committed'`, when you need to\r\n * branch on it.\r\n */\r\n async releaseCredits(\r\n userId: string,\r\n reservationId: string,\r\n options?: ReservationTransitionOptions\r\n ): Promise<void> {\r\n const outcome = await this.releaseCreditsDetailed(userId, reservationId, options);\r\n if (outcome.outcome === \"not_found\") {\r\n throw createReservationNotFoundError(reservationId);\r\n }\r\n }\r\n\r\n /** Release a reservation and get the typed outcome. */\r\n async releaseCreditsDetailed(\r\n userId: string,\r\n reservationId: string,\r\n options?: ReservationTransitionOptions\r\n ): Promise<ReleaseOutcome> {\r\n return releaseThroughRepository(this.repository, userId, reservationId, options);\r\n }\r\n\r\n /**\r\n * Log usage for audit trail\r\n * @param log - Usage log data\r\n */\r\n async logUsage(log: Omit<PortableUsageLog, \"id\" | \"createdAt\">): Promise<void> {\r\n await this.repository.logUsage(log as CreateUsageLogInput);\r\n }\r\n\r\n /**\r\n * Add credits to user account (for purchases, bonuses, etc.)\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).\r\n * @returns Whether this delivery credited the account (`created`), repeated an\r\n * earlier one (`replayed`), or reused the reference for a different credit\r\n * event (`conflict`, which credited nothing). On a repository without\r\n * `addCreditsV2` the result is always `created` and carries no\r\n * deduplication guarantee — see {@link addCreditsThroughRepository}.\r\n */\r\n async addCredits(\r\n userId: string,\r\n amount: number,\r\n description: string,\r\n paymentRef?: string,\r\n options?: AddCreditsAtomicOptions\r\n ): Promise<AddCreditsOutcome> {\r\n return addCreditsThroughRepository(this.repository, {\r\n userId,\r\n amount,\r\n description,\r\n paymentRef,\r\n options,\r\n });\r\n }\r\n\r\n /**\r\n * One-shot atomic \"deduct-if-sufficient\" credit charge.\r\n *\r\n * Unlike the reserve/commit/release two-phase flow, this performs a single\r\n * atomic check-and-deduct against the repository — suited for synchronous,\r\n * in-request operations that don't need a hold across an async job. Exactly\r\n * one call is made to `repository.deductCreditsAtomic`, which enforces\r\n * atomicity so concurrent callers can never both succeed against the same\r\n * limited balance.\r\n *\r\n * On success, creates a journal entry (same audit trail as `commitCredits`)\r\n * and, if `options.operationType` is provided, a usage log entry via the\r\n * same `logUsage` path.\r\n *\r\n * @param userId - User ID\r\n * @param amount - Credits to deduct (must be > 0)\r\n * @param options - Optional usage-log / journal metadata\r\n * @returns Typed result: `{ success: true, newBalance }` or\r\n * `{ success: false, reason: 'insufficient', available, required, shortfall }`\r\n * @throws Error if amount is not a positive number\r\n */\r\n async deductCredits(\r\n userId: string,\r\n amount: number,\r\n options?: DeductCreditsOptions\r\n ): Promise<DeductCreditsResult> {\r\n // `amount > 0` accepted 1.005, Infinity and values past what a\r\n // `numeric(12, 2)` column can hold; each of those reached the repository's\r\n // raw arithmetic. Validate here, *before* the try, so a rejected amount can\r\n // never be mistaken for a shortfall by the catch below.\r\n assertValidCreditAmount(amount, { userId, operation: \"deductCredits\" });\r\n\r\n let deduction: { previousBalance: number; newBalance: number };\r\n try {\r\n deduction = await this.repository.deductCreditsAtomic(userId, amount);\r\n } catch (error) {\r\n // A rejected amount is a caller bug, not a balance problem, and must not\r\n // be reshaped into `{ success: false, reason: 'insufficient' }`.\r\n if (isCreditError(error) && error.code === CreditErrorCode.INVALID_AMOUNT) throw error;\r\n\r\n // The repository layer throws on insufficient funds (and on missing\r\n // user docs, which we surface as unavailable rather than a shortfall).\r\n const credits = await this.repository.getUserCredits(userId);\r\n const available = credits\r\n ? sumAmounts(credits.balance, credits.bonusCredits, -credits.reserved)\r\n : 0;\r\n\r\n if (available >= amount) {\r\n // Not an insufficient-credits condition (e.g. missing user record) —\r\n // this is unexpected, so let the original error propagate.\r\n throw error;\r\n }\r\n\r\n return {\r\n success: false,\r\n reason: \"insufficient\",\r\n available,\r\n required: amount,\r\n shortfall: sumAmounts(amount, -available),\r\n };\r\n }\r\n\r\n const operationType = options?.operationType;\r\n await this.repository.createJournalEntry({\r\n userId,\r\n entryType: \"debit\",\r\n amount,\r\n balanceAfter: deduction.newBalance,\r\n source: \"operation_commit\",\r\n referenceId: options?.requestId ?? `deduct-${Date.now()}`,\r\n referenceType: \"adjustment\",\r\n description: operationType\r\n ? `Deducted ${amount} credits for ${getOperationLabel(operationType)}`\r\n : `Deducted ${amount} credits`,\r\n metadata: {\r\n ...options?.metadata,\r\n ...(operationType && { operationType }),\r\n },\r\n });\r\n\r\n if (operationType) {\r\n await this.logUsage({\r\n userId,\r\n operationType,\r\n provider: \"gemini\",\r\n creditsUsed: amount,\r\n success: true,\r\n resourceId: options?.resourceId,\r\n resourceType: options?.resourceType,\r\n requestId: options?.requestId,\r\n metadata: options?.metadata,\r\n });\r\n }\r\n\r\n // Trigger low balance notification (non-blocking) — same hook commitCredits uses.\r\n if (this.lowBalanceCallback) {\r\n this.lowBalanceCallback(userId, deduction.newBalance).catch((error) => {\r\n console.error(\"[Credits] Failed to send low balance notification:\", error);\r\n });\r\n }\r\n\r\n return { success: true, newBalance: deduction.newBalance };\r\n }\r\n\r\n /**\r\n * Update user subscription tier\r\n * @param userId - User ID\r\n * @param tier - New subscription tier\r\n * @param expiresAt - Subscription expiry date (optional)\r\n */\r\n async updateTier(\r\n userId: string,\r\n tier: SubscriptionTier,\r\n expiresAt?: Date\r\n ): Promise<void> {\r\n const monthlyLimit = getConfigMonthlyLimit(tier);\r\n const unlimited = isUnlimitedTier(tier);\r\n const free = isFreeTier(tier);\r\n\r\n await this.repository.updateUserTier(userId, {\r\n tier,\r\n // Through the shared contract, like every path that resolves the tier's\r\n // limit from configuration. (The repository's `updateUserCredits` and\r\n // `updateUserTier` still store a caller-supplied `monthlyLimit` verbatim;\r\n // they are given a value, not a tier, so there is no sentinel to map.)\r\n // This used to store 0 for an unlimited tier under a \"0 means unlimited\"\r\n // convention that nothing actually implemented — no read path anywhere in\r\n // the library branches on it — so upgrading a user to unlimited gave them\r\n // an allowance of zero.\r\n monthlyLimit: storedMonthlyLimit(monthlyLimit),\r\n // Reset balance to new tier limit if upgrading\r\n balance: !free\r\n ? (unlimited ? getUnlimitedSentinelBalance() : monthlyLimit)\r\n : undefined,\r\n monthlyUsed: !free ? 0 : undefined,\r\n subscriptionExpiresAt: expiresAt ? expiresAt.toISOString() : null,\r\n });\r\n }\r\n\r\n /**\r\n * Get usage logs with optional filtering\r\n * @param userId - Optional user ID filter\r\n * @param limit - Max results\r\n * @param offset - Skip results\r\n * @returns List of usage logs\r\n */\r\n async getUsageLogs(\r\n userId?: string,\r\n limit = 50,\r\n offset = 0\r\n ): Promise<PortableUsageLog[]> {\r\n return this.repository.getUsageLogs({ userId, limit, offset });\r\n }\r\n\r\n /**\r\n * Get user-friendly usage history\r\n * Combines journal entries into a user-facing format\r\n *\r\n * @param userId - User ID\r\n * @param limit - Max results per page\r\n * @param offset - Skip results for pagination\r\n * @returns Paginated usage history response\r\n */\r\n async getUsageHistory(\r\n userId: string,\r\n limit = 20,\r\n offset = 0\r\n ): Promise<UsageHistoryResponse> {\r\n // Get journal entries\r\n const [entries, total] = await Promise.all([\r\n this.repository.getJournalEntries({ userId, limit, offset }),\r\n this.repository.getJournalEntriesCount({ userId }),\r\n ]);\r\n\r\n // Convert journal entries to user-friendly format\r\n const historyEntries: UsageHistoryEntry[] = entries.map((entry) => {\r\n const type = this.mapSourceToHistoryType(entry.source);\r\n const creditsChange = entry.entryType === \"credit\" ? entry.amount : -entry.amount;\r\n\r\n return {\r\n id: entry.id,\r\n type,\r\n creditsChange,\r\n balanceAfter: entry.balanceAfter,\r\n description: entry.description,\r\n createdAt: typeof entry.createdAt === \"string\"\r\n ? entry.createdAt\r\n : toDate(entry.createdAt).toISOString(),\r\n };\r\n });\r\n\r\n return {\r\n entries: historyEntries,\r\n pagination: {\r\n total,\r\n limit,\r\n offset,\r\n hasMore: offset + entries.length < total,\r\n },\r\n };\r\n }\r\n\r\n /**\r\n * Map journal entry source to user-friendly history type\r\n */\r\n private mapSourceToHistoryType(\r\n source: PortableJournalEntry[\"source\"]\r\n ): UsageHistoryEntry[\"type\"] {\r\n switch (source) {\r\n case \"operation_commit\":\r\n case \"reservation_expired\":\r\n return \"usage\";\r\n case \"purchase\":\r\n return \"purchase\";\r\n case \"subscription_grant\":\r\n case \"subscription_upgrade\":\r\n case \"bonus\":\r\n return \"bonus\";\r\n case \"monthly_reset\":\r\n return \"reset\";\r\n case \"refund\":\r\n case \"operation_release\":\r\n return \"refund\";\r\n case \"admin_adjustment\":\r\n case \"subscription_downgrade\":\r\n case \"expiry\":\r\n default:\r\n return \"adjustment\";\r\n }\r\n }\r\n\r\n /**\r\n * Get journal entries directly (for admin or debugging)\r\n * @param query - Journal entry query parameters\r\n * @returns List of journal entries\r\n */\r\n async getJournalEntries(query: JournalEntryQuery): Promise<PortableJournalEntry[]> {\r\n return this.repository.getJournalEntries(query);\r\n }\r\n\r\n /**\r\n * Get the underlying repository (for advanced use cases)\r\n */\r\n getRepository(): ICreditRepository {\r\n return this.repository;\r\n }\r\n}\r\n\r\n/**\r\n * Create a credits service with a repository\r\n */\r\nexport function createCreditsService(repository: ICreditRepository): CreditsService {\r\n return new CreditsService(repository);\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACWO,IAAM,kBAAkB;AAAA,EAC7B,sBAAsB;AAAA,EACtB,uBAAuB;AAAA,EACvB,qBAAqB;AAAA,EACrB,+BAA+B;AAAA,EAC/B,gBAAgB;AAAA,EAChB,wBAAwB;AAAA,EACxB,qBAAqB;AAAA,EACrB,gBAAgB;AAAA;AAAA,EAEhB,sBAAsB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMtB,iBAAiB;AAAA;AAAA,EAEjB,uBAAuB;AAAA;AAAA,EAEvB,gBAAgB;AAAA;AAAA,EAEhB,yBAAyB;AAAA;AAAA;AAAA;AAAA;AAAA,EAKzB,4BAA4B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAM5B,sBAAsB;AACxB;AAYO,IAAM,cAAN,MAAM,qBAAoB,MAAM;AAAA,EACrB;AAAA,EACA;AAAA,EAEhB,YACE,SACA,MACA,SACA;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,UAAU;AAGf,QAAI,MAAM,mBAAmB;AAC3B,YAAM,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