@zonastery/bursar 2.0.1 → 2.0.3

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 (285) hide show
  1. package/README.md +22 -14
  2. package/dist/billing/auto-recharge-service.d.ts +1 -1
  3. package/dist/billing/auto-recharge-service.d.ts.map +1 -1
  4. package/dist/billing/auto-recharge-service.js +9 -6
  5. package/dist/billing/auto-recharge-service.js.map +1 -1
  6. package/dist/billing/billing-store.d.ts +4 -1
  7. package/dist/billing/billing-store.d.ts.map +1 -1
  8. package/dist/billing/billing-store.js +2 -0
  9. package/dist/billing/billing-store.js.map +1 -1
  10. package/dist/billing/contracts.d.ts +2 -1
  11. package/dist/billing/contracts.d.ts.map +1 -1
  12. package/dist/billing/contracts.js.map +1 -1
  13. package/dist/billing/event-handlers.d.ts +2 -3
  14. package/dist/billing/event-handlers.d.ts.map +1 -1
  15. package/dist/billing/event-handlers.js +38 -49
  16. package/dist/billing/event-handlers.js.map +1 -1
  17. package/dist/billing/event-processor.d.ts.map +1 -1
  18. package/dist/billing/event-processor.js +22 -10
  19. package/dist/billing/event-processor.js.map +1 -1
  20. package/dist/billing/financial-event-handlers.d.ts +2 -2
  21. package/dist/billing/financial-event-handlers.d.ts.map +1 -1
  22. package/dist/billing/financial-event-handlers.js +7 -7
  23. package/dist/billing/financial-event-handlers.js.map +1 -1
  24. package/dist/billing/postgres/repositories/auto-recharge.js +1 -1
  25. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
  26. package/dist/billing/postgres/repositories/event.d.ts.map +1 -1
  27. package/dist/billing/postgres/repositories/event.js +33 -1
  28. package/dist/billing/postgres/repositories/event.js.map +1 -1
  29. package/dist/billing/postgres/repositories/offer.d.ts +1 -1
  30. package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
  31. package/dist/billing/postgres/repositories/offer.js +1 -1
  32. package/dist/billing/postgres/repositories/offer.js.map +1 -1
  33. package/dist/billing/postgres/repositories/topup.d.ts +1 -1
  34. package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
  35. package/dist/billing/postgres/repositories/topup.js +1 -1
  36. package/dist/billing/postgres/repositories/topup.js.map +1 -1
  37. package/dist/billing/postgres/store.d.ts +6 -2
  38. package/dist/billing/postgres/store.d.ts.map +1 -1
  39. package/dist/billing/postgres/store.js +21 -6
  40. package/dist/billing/postgres/store.js.map +1 -1
  41. package/dist/billing/service-types.d.ts +2 -15
  42. package/dist/billing/service-types.d.ts.map +1 -1
  43. package/dist/billing/service-types.js.map +1 -1
  44. package/dist/billing/types/auto-recharge.d.ts +1 -1
  45. package/dist/billing/types/auto-recharge.d.ts.map +1 -1
  46. package/dist/billing/types/auto-recharge.js.map +1 -1
  47. package/dist/billing/types/catalog.d.ts +1 -1
  48. package/dist/billing/types/catalog.d.ts.map +1 -1
  49. package/dist/billing/types/catalog.js.map +1 -1
  50. package/dist/billing/types/documents.d.ts +1 -1
  51. package/dist/billing/types/documents.d.ts.map +1 -1
  52. package/dist/billing/types/documents.js.map +1 -1
  53. package/dist/billing/types/events.d.ts +11 -2
  54. package/dist/billing/types/events.d.ts.map +1 -1
  55. package/dist/billing/types/events.js +2 -2
  56. package/dist/billing/types/events.js.map +1 -1
  57. package/dist/billing/types/subscriptions.d.ts.map +1 -1
  58. package/dist/billing/types/subscriptions.js.map +1 -1
  59. package/dist/breakdown.d.ts +1 -1
  60. package/dist/breakdown.d.ts.map +1 -1
  61. package/dist/breakdown.js +1 -1
  62. package/dist/breakdown.js.map +1 -1
  63. package/dist/bursar.d.ts +21 -11
  64. package/dist/bursar.d.ts.map +1 -1
  65. package/dist/bursar.js +40 -4
  66. package/dist/bursar.js.map +1 -1
  67. package/dist/catalog.d.ts.map +1 -1
  68. package/dist/catalog.js +1 -1
  69. package/dist/catalog.js.map +1 -1
  70. package/dist/commerce/index.d.ts +0 -1
  71. package/dist/commerce/index.d.ts.map +1 -1
  72. package/dist/commerce/index.js +0 -1
  73. package/dist/commerce/index.js.map +1 -1
  74. package/dist/commerce/service.d.ts.map +1 -1
  75. package/dist/commerce/service.js +154 -106
  76. package/dist/commerce/service.js.map +1 -1
  77. package/dist/commerce/types.d.ts +9 -5
  78. package/dist/commerce/types.d.ts.map +1 -1
  79. package/dist/commerce/types.js.map +1 -1
  80. package/dist/config/parse-credits.d.ts.map +1 -1
  81. package/dist/config/parse-credits.js +0 -6
  82. package/dist/config/parse-credits.js.map +1 -1
  83. package/dist/config/parse-utils.d.ts +1 -1
  84. package/dist/config/parse-utils.d.ts.map +1 -1
  85. package/dist/config/parse-utils.js +1 -1
  86. package/dist/config/parse-utils.js.map +1 -1
  87. package/dist/config/types.d.ts +1 -6
  88. package/dist/config/types.d.ts.map +1 -1
  89. package/dist/config/types.js.map +1 -1
  90. package/dist/config.d.ts.map +1 -1
  91. package/dist/config.js +8 -1
  92. package/dist/config.js.map +1 -1
  93. package/dist/credits/amount.d.ts +8 -0
  94. package/dist/credits/amount.d.ts.map +1 -0
  95. package/dist/credits/amount.js +32 -0
  96. package/dist/credits/amount.js.map +1 -0
  97. package/dist/credits/catalog-runtime.d.ts +5 -7
  98. package/dist/credits/catalog-runtime.d.ts.map +1 -1
  99. package/dist/credits/catalog-runtime.js +4 -13
  100. package/dist/credits/catalog-runtime.js.map +1 -1
  101. package/dist/credits/lease-workflow.d.ts +2 -2
  102. package/dist/credits/lease-workflow.d.ts.map +1 -1
  103. package/dist/credits/lease-workflow.js +24 -21
  104. package/dist/credits/lease-workflow.js.map +1 -1
  105. package/dist/credits/low-balance-monitor.d.ts +1 -1
  106. package/dist/credits/low-balance-monitor.d.ts.map +1 -1
  107. package/dist/credits/low-balance-monitor.js +3 -4
  108. package/dist/credits/low-balance-monitor.js.map +1 -1
  109. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
  110. package/dist/credits/postgres/repositories/balance.js +1 -1
  111. package/dist/credits/postgres/repositories/balance.js.map +1 -1
  112. package/dist/credits/postgres/repositories/bucket.js +1 -1
  113. package/dist/credits/postgres/repositories/bucket.js.map +1 -1
  114. package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
  115. package/dist/credits/postgres/repositories/lease.js +4 -2
  116. package/dist/credits/postgres/repositories/lease.js.map +1 -1
  117. package/dist/credits/postgres/repositories/team.d.ts +2 -1
  118. package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
  119. package/dist/credits/postgres/repositories/team.js +19 -5
  120. package/dist/credits/postgres/repositories/team.js.map +1 -1
  121. package/dist/credits/postgres/store.d.ts +18 -14
  122. package/dist/credits/postgres/store.d.ts.map +1 -1
  123. package/dist/credits/postgres/store.js +30 -18
  124. package/dist/credits/postgres/store.js.map +1 -1
  125. package/dist/credits/postgres/value-mappers.d.ts +1 -1
  126. package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
  127. package/dist/credits/postgres/value-mappers.js +1 -1
  128. package/dist/credits/postgres/value-mappers.js.map +1 -1
  129. package/dist/credits/service-errors.d.ts +1 -1
  130. package/dist/credits/service-errors.d.ts.map +1 -1
  131. package/dist/credits/service-errors.js +1 -1
  132. package/dist/credits/service-errors.js.map +1 -1
  133. package/dist/credits/service-types.d.ts +21 -16
  134. package/dist/credits/service-types.d.ts.map +1 -1
  135. package/dist/credits/service-types.js.map +1 -1
  136. package/dist/credits/service.d.ts +21 -17
  137. package/dist/credits/service.d.ts.map +1 -1
  138. package/dist/credits/service.js +81 -38
  139. package/dist/credits/service.js.map +1 -1
  140. package/dist/credits/store.d.ts +26 -23
  141. package/dist/credits/store.d.ts.map +1 -1
  142. package/dist/credits/store.js +4 -2
  143. package/dist/credits/store.js.map +1 -1
  144. package/dist/credits/types/account.d.ts +1 -1
  145. package/dist/credits/types/account.d.ts.map +1 -1
  146. package/dist/credits/types/account.js.map +1 -1
  147. package/dist/credits/types/grants.d.ts.map +1 -1
  148. package/dist/credits/types/grants.js.map +1 -1
  149. package/dist/credits/types/teams.d.ts +1 -0
  150. package/dist/credits/types/teams.d.ts.map +1 -1
  151. package/dist/credits/types/teams.js.map +1 -1
  152. package/dist/engine.js +1 -1
  153. package/dist/engine.js.map +1 -1
  154. package/dist/errors.d.ts +4 -0
  155. package/dist/errors.d.ts.map +1 -1
  156. package/dist/errors.js +34 -0
  157. package/dist/errors.js.map +1 -1
  158. package/dist/expr/ast.d.ts.map +1 -1
  159. package/dist/expr/ast.js.map +1 -1
  160. package/dist/expr/evaluator.d.ts +1 -1
  161. package/dist/expr/evaluator.d.ts.map +1 -1
  162. package/dist/expr/evaluator.js +1 -1
  163. package/dist/expr/evaluator.js.map +1 -1
  164. package/dist/expr/parser.d.ts +1 -0
  165. package/dist/expr/parser.d.ts.map +1 -1
  166. package/dist/expr/parser.js +15 -3
  167. package/dist/expr/parser.js.map +1 -1
  168. package/dist/expr.d.ts +1 -1
  169. package/dist/expr.d.ts.map +1 -1
  170. package/dist/expr.js +1 -1
  171. package/dist/expr.js.map +1 -1
  172. package/dist/generated/pricing-config.schema.json +31 -29
  173. package/dist/generated/pricing-config.types.d.ts +6 -18
  174. package/dist/generated/pricing-config.types.d.ts.map +1 -1
  175. package/dist/generated/pricing-config.types.js.map +1 -1
  176. package/dist/index.d.ts +7 -3
  177. package/dist/index.d.ts.map +1 -1
  178. package/dist/index.js +2 -0
  179. package/dist/index.js.map +1 -1
  180. package/dist/load-config-file.d.ts +2 -3
  181. package/dist/load-config-file.d.ts.map +1 -1
  182. package/dist/load-config-file.js +14 -29
  183. package/dist/load-config-file.js.map +1 -1
  184. package/dist/metrics.d.ts +1 -1
  185. package/dist/metrics.d.ts.map +1 -1
  186. package/dist/metrics.js.map +1 -1
  187. package/dist/node.d.ts +6 -3
  188. package/dist/node.d.ts.map +1 -1
  189. package/dist/node.js +1 -0
  190. package/dist/node.js.map +1 -1
  191. package/dist/providers/_shared.d.ts +3 -3
  192. package/dist/providers/_shared.d.ts.map +1 -1
  193. package/dist/providers/_shared.js +11 -6
  194. package/dist/providers/_shared.js.map +1 -1
  195. package/dist/providers/dodo/client-contract.d.ts +8 -13
  196. package/dist/providers/dodo/client-contract.d.ts.map +1 -1
  197. package/dist/providers/dodo/client-contract.js.map +1 -1
  198. package/dist/providers/dodo/event-mapper.d.ts +1 -1
  199. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  200. package/dist/providers/dodo/event-mapper.js +23 -15
  201. package/dist/providers/dodo/event-mapper.js.map +1 -1
  202. package/dist/providers/dodo/provider.d.ts +4 -6
  203. package/dist/providers/dodo/provider.d.ts.map +1 -1
  204. package/dist/providers/dodo/provider.js +44 -82
  205. package/dist/providers/dodo/provider.js.map +1 -1
  206. package/dist/providers/dodo/webhook-bridge.d.ts +1 -2
  207. package/dist/providers/dodo/webhook-bridge.d.ts.map +1 -1
  208. package/dist/providers/dodo/webhook-bridge.js +0 -1
  209. package/dist/providers/dodo/webhook-bridge.js.map +1 -1
  210. package/dist/providers/environment.d.ts +6 -0
  211. package/dist/providers/environment.d.ts.map +1 -0
  212. package/dist/providers/environment.js +10 -0
  213. package/dist/providers/environment.js.map +1 -0
  214. package/dist/providers/index.d.ts +3 -7
  215. package/dist/providers/index.d.ts.map +1 -1
  216. package/dist/providers/index.js +1 -5
  217. package/dist/providers/index.js.map +1 -1
  218. package/dist/providers/mock/provider.d.ts +6 -8
  219. package/dist/providers/mock/provider.d.ts.map +1 -1
  220. package/dist/providers/mock/provider.js +18 -50
  221. package/dist/providers/mock/provider.js.map +1 -1
  222. package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
  223. package/dist/providers/stripe/event-mapper.js +82 -14
  224. package/dist/providers/stripe/event-mapper.js.map +1 -1
  225. package/dist/providers/stripe/provider.d.ts +3 -3
  226. package/dist/providers/stripe/provider.d.ts.map +1 -1
  227. package/dist/providers/stripe/provider.js +37 -24
  228. package/dist/providers/stripe/provider.js.map +1 -1
  229. package/dist/providers/types.d.ts +9 -20
  230. package/dist/providers/types.d.ts.map +1 -1
  231. package/dist/providers/types.js.map +1 -1
  232. package/dist/shared/diagnostics.d.ts +8 -0
  233. package/dist/shared/diagnostics.d.ts.map +1 -1
  234. package/dist/shared/diagnostics.js +49 -0
  235. package/dist/shared/diagnostics.js.map +1 -1
  236. package/dist/shared/idempotency.d.ts +9 -0
  237. package/dist/shared/idempotency.d.ts.map +1 -0
  238. package/dist/shared/idempotency.js +34 -0
  239. package/dist/shared/idempotency.js.map +1 -0
  240. package/dist/shared/postgres-client.d.ts +7 -0
  241. package/dist/shared/postgres-client.d.ts.map +1 -1
  242. package/dist/shared/postgres-client.js +21 -4
  243. package/dist/shared/postgres-client.js.map +1 -1
  244. package/dist/shared/postgres-errors.d.ts.map +1 -1
  245. package/dist/shared/postgres-errors.js.map +1 -1
  246. package/dist/storage/adapters/clickhouse.d.ts +9 -2
  247. package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
  248. package/dist/storage/adapters/clickhouse.js +142 -36
  249. package/dist/storage/adapters/clickhouse.js.map +1 -1
  250. package/dist/storage/adapters/s3.d.ts +44 -6
  251. package/dist/storage/adapters/s3.d.ts.map +1 -1
  252. package/dist/storage/adapters/s3.js +59 -21
  253. package/dist/storage/adapters/s3.js.map +1 -1
  254. package/dist/storage/diagnostics.d.ts +105 -0
  255. package/dist/storage/diagnostics.d.ts.map +1 -0
  256. package/dist/storage/diagnostics.js +227 -0
  257. package/dist/storage/diagnostics.js.map +1 -0
  258. package/dist/storage/maintenance.d.ts +88 -0
  259. package/dist/storage/maintenance.d.ts.map +1 -0
  260. package/dist/storage/maintenance.js +266 -0
  261. package/dist/storage/maintenance.js.map +1 -0
  262. package/dist/storage/outbox-worker.d.ts +20 -0
  263. package/dist/storage/outbox-worker.d.ts.map +1 -1
  264. package/dist/storage/outbox-worker.js +172 -42
  265. package/dist/storage/outbox-worker.js.map +1 -1
  266. package/dist/storage/ports.d.ts +43 -1
  267. package/dist/storage/ports.d.ts.map +1 -1
  268. package/dist/storage/ports.js.map +1 -1
  269. package/dist/storage/postgres-repository.d.ts +7 -2
  270. package/dist/storage/postgres-repository.d.ts.map +1 -1
  271. package/dist/storage/postgres-repository.js +155 -54
  272. package/dist/storage/postgres-repository.js.map +1 -1
  273. package/dist/storage/runtime.d.ts +30 -9
  274. package/dist/storage/runtime.d.ts.map +1 -1
  275. package/dist/storage/runtime.js +268 -37
  276. package/dist/storage/runtime.js.map +1 -1
  277. package/dist/telemetry/index.d.ts +37 -0
  278. package/dist/telemetry/index.d.ts.map +1 -0
  279. package/dist/telemetry/index.js +115 -0
  280. package/dist/telemetry/index.js.map +1 -0
  281. package/dist/telemetry/opentelemetry.d.ts +25 -0
  282. package/dist/telemetry/opentelemetry.d.ts.map +1 -0
  283. package/dist/telemetry/opentelemetry.js +74 -0
  284. package/dist/telemetry/opentelemetry.js.map +1 -0
  285. package/package.json +62 -36
@@ -1 +1 @@
1
- {"version":3,"file":"service.js","sourceRoot":"","sources":["../../src/credits/service.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AACjC,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EACL,eAAe,EACf,WAAW,EACX,wBAAwB,EACxB,WAAW,EACX,UAAU,GACX,MAAM,cAAc,CAAC;AA+CtB,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AACjE,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAyC1D;;;GAGG;AACH,MAAM,yBAAyB,GAAG,GAAG,CAAC;AAEtC,MAAM,cAAc,GAAG,IAAI,GAAG,CAAe,CAAC,gBAAgB,EAAE,WAAW,CAAC,CAAC,CAAC;AAE9E,SAAS,cAAc,CAAC,KAAuB,EAAE,SAAiB;IAChE,MAAM,MAAM,GAAG,SAAS,CAAC,KAAK,CAAC,CAAC;IAChC,IAAI,CAAC,MAAM,CAAC,QAAQ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,MAAM,IAAI,QAAQ,EAAE;gBAC/C,YAAY,EAAE,MAAM,CAAC,YAAY;gBACjC,aAAa,EAAE,MAAM,CAAC,aAAa;gBACnC,eAAe,EAAE,MAAM,CAAC,eAAe,IAAI,IAAI;aAChD,CAAC,CAAC;QACL,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,mBAAmB,CAAC,MAAM,GAAG,KAAK;QACtC,OAAO,MAAM,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;IACrC,CAAC;CACF","sourcesContent":["import Decimal from \"decimal.js\";\nimport { randomUUID } from \"node:crypto\";\nimport {\n CapReachedError,\n ConfigError,\n InsufficientCreditsError,\n RefundError,\n StoreError,\n} from \"../errors.js\";\nimport type { PricingEngine } from \"../engine.js\";\nimport type { CatalogRollout } from \"../config.js\";\nimport type {\n AddCreditsResult,\n AggregateStats,\n AllowanceResult,\n AvailableResult,\n BalanceResult,\n CatalogRevision,\n BucketBalancesResult,\n CanAffordResult,\n CheckFeatureResult,\n CreditMetadata,\n DailySpendRow,\n DeductionResult,\n DeductWithAllowanceOptions,\n ExecuteGrantProgramRequest,\n GetUserPlanResult,\n GrantProgramAwardResult,\n LedgerEntry,\n LedgerPage,\n LeaseSuccess,\n ListLedgerEntriesOptions,\n ListQuotaEventsOptions,\n ListUsageChargesOptions,\n ListUsageEntriesOptions,\n PlanMigrationBatchResult,\n PlanMigrationStartResult,\n QuotaEvent,\n QuotaState,\n RefundSuccess,\n RevokeCreditsResult,\n ReleaseResult,\n SetUserPlanResult,\n UnsetUserPlanResult,\n SpendByModelRow,\n SpendByUserRow,\n SweepResult,\n TeamDeductionResult,\n TopUserRow,\n UsageChargePage,\n UsageRecordResult,\n} from \"./types/index.js\";\nimport type { CreditStore } from \"./store.js\";\nimport type { CreditEventEmitter, CreditEventType } from \"./events.js\";\nimport type { UsageMetrics } from \"../metrics.js\";\nimport { raiseDeductError } from \"./service-errors.js\";\nimport { LowBalanceMonitor } from \"./low-balance-monitor.js\";\nimport { CreditQueries } from \"./queries.js\";\nimport { CatalogRuntime, toDecimal } from \"./catalog-runtime.js\";\nimport { CreditLeaseWorkflow } from \"./lease-workflow.js\";\nimport type {\n AddCreditsOptions,\n BeginBilledOperationOptions,\n BilledOperation,\n CanAffordOptions,\n CreditsServiceOptions,\n DeductCreditsOptions,\n DeductFlatJobOptions,\n DeductOptions,\n DeductTeamOptions,\n GrantSubscriptionCycleOptions,\n MetricsOrAmount,\n PolicyPreset,\n PostDeductionContext,\n RecordUsageOptions,\n RefundCreditsOptions,\n ReserveOptions,\n RunBilledOptions,\n SettleOptions,\n} from \"./service-types.js\";\nexport type {\n AddCreditsOptions,\n BeginBilledOperationOptions,\n BilledOperation,\n CanAffordOptions,\n CreditsServiceOptions,\n DeductCreditsOptions,\n DeductFlatJobOptions,\n DeductOptions,\n DeductTeamOptions,\n GrantSubscriptionCycleOptions,\n LowBalanceConfig,\n PolicyPreset,\n PostDeductionContext,\n RecordUsageOptions,\n RefundCreditsOptions,\n ReserveOptions,\n RunBilledOptions,\n SettleOptions,\n} from \"./service-types.js\";\n/**\n * Default lease TTL (seconds) for ``reserve`` and ``runBilled``.\n * Long batch/agentic jobs call the configured lease TTL before this elapses.\n */\nconst DEFAULT_LEASE_TTL_SECONDS = 600;\n\nconst POLICY_PRESETS = new Set<PolicyPreset>([\"strict_prepaid\", \"overdraft\"]);\n\nfunction positiveAmount(value: Decimal | number, operation: string): Decimal {\n const amount = toDecimal(value);\n if (!amount.isFinite() || !amount.gt(0)) {\n throw new RangeError(`${operation} amount must be finite and greater than zero`);\n }\n return amount;\n}\n\nimport { type NormalizedLogger, normalizeLogger } from \"../shared/logger.js\";\n\n/**\n * Orchestrates credit operations.\n *\n * The deduction path is a single atomic, idempotency-keyed store call\n * (``deductWithAllowance``) that consumes free allowance, enforces plan policy,\n * and debits the net amount in one transaction. The service calculates the cost, maps\n * the store's typed ``error`` codes to exceptions, and emits lifecycle events\n * **only after** the operation has succeeded.\n *\n * Optionally accepts a ``CreditEventEmitter`` to emit lifecycle events\n * (deducted, deduct_failed, added, refunded, refund_failed, expired,\n * low_balance).\n */\nexport class CreditsService {\n private readonly store: CreditStore;\n private readonly queries: CreditQueries;\n private readonly catalogRuntime: CatalogRuntime;\n private readonly leases: CreditLeaseWorkflow;\n private emitter: CreditEventEmitter | null = null;\n private balanceMonitor: LowBalanceMonitor;\n // Lazy-on-read credit expiry (closes the gap with allowance windows/lease\n // TTLs, which are already lazy-on-read). Default `false` — unchanged\n // behaviour; explicit `sweepExpiredCredits`/cron remains required.\n private lazyExpiry: boolean;\n private logger: NormalizedLogger;\n private readonly postDeductionHooks = new Set<\n (context: PostDeductionContext) => void | Promise<void>\n >();\n constructor(\n store: CreditStore,\n engine?: PricingEngine | null,\n emitter?: CreditEventEmitter | null,\n options?: CreditsServiceOptions | null,\n ) {\n this.store = store;\n this.queries = new CreditQueries(\n store,\n options?.analytics ?? store,\n options?.usageStore ?? store,\n );\n const policy = options?.policy ?? \"strict_prepaid\";\n if (!POLICY_PRESETS.has(policy)) {\n throw new ConfigError(\n `unknown policy preset '${policy}'; expected one of ${[...POLICY_PRESETS].sort().join(\", \")}`,\n );\n }\n if (emitter) this.emitter = emitter;\n this.logger = normalizeLogger(options?.logger);\n if (options?.postDeduction) this.postDeductionHooks.add(options.postDeduction);\n this.catalogRuntime = new CatalogRuntime(\n store,\n engine ?? null,\n this.logger,\n options?.catalogCacheTtlMs ?? 300_000,\n );\n this.balanceMonitor = new LowBalanceMonitor(\n options?.lowBalance,\n (type, userId, data) => this.emit(type, userId, data),\n this.logger,\n );\n this.lazyExpiry = options?.lazyExpiry ?? false;\n this.leases = new CreditLeaseWorkflow(\n store,\n this.catalogRuntime,\n this.logger,\n this.balanceMonitor,\n policy,\n options?.overdraftFloor != null ? toDecimal(options.overdraftFloor) : null,\n options?.maxConcurrent ?? null,\n options?.defaultTtlSeconds ?? DEFAULT_LEASE_TTL_SECONDS,\n (type, userId, data) => this.emit(type, userId, data),\n (userId, idempotencyKey) => this.emitQuotaEvents(userId, idempotencyKey),\n (userId) => this.maybeLazyExpire(userId),\n (userId, result) => this.afterDeduction(userId, \"settle\", result),\n );\n }\n\n /**\n * Register an awaited post-commit deduction hook. A failing hook is logged\n * and isolated so it can never roll back an already committed charge.\n */\n addPostDeductionHook(hook: (context: PostDeductionContext) => void | Promise<void>): () => void {\n this.postDeductionHooks.add(hook);\n return () => this.postDeductionHooks.delete(hook);\n }\n\n private async afterDeduction(\n userId: string,\n source: PostDeductionContext[\"source\"],\n deduction: PostDeductionContext[\"deduction\"],\n ): Promise<void> {\n for (const hook of this.postDeductionHooks) {\n try {\n await hook({ userId, source, deduction });\n } catch (error) {\n this.logger.warn(\"[CreditsService] post-deduction hook failed\", {\n userId,\n source,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n }\n\n async getActiveCatalog(): Promise<CatalogRevision | null> {\n return this.queries.getActiveCatalog();\n }\n\n async getUserPlan(userId: string): Promise<GetUserPlanResult> {\n return this.queries.getUserPlan(userId);\n }\n\n async checkFeature(userId: string, feature: string): Promise<CheckFeatureResult> {\n return this.queries.checkFeature(userId, feature);\n }\n\n async getQuotaState(userId: string, quotaKey?: string | null): Promise<QuotaState[]> {\n return this.queries.getQuotaState(userId, quotaKey);\n }\n\n async listQuotaEvents(userId: string, options?: ListQuotaEventsOptions): Promise<QuotaEvent[]> {\n return this.queries.listQuotaEvents(userId, options);\n }\n\n async startPlanMigration(\n fromPlanId: string | null,\n toPlanId: string,\n ): Promise<PlanMigrationStartResult> {\n return this.queries.startPlanMigration(fromPlanId, toPlanId);\n }\n\n async migratePlanBatch(\n migrationId: string,\n batchSize?: number,\n ): Promise<PlanMigrationBatchResult> {\n return this.queries.migratePlanBatch(migrationId, batchSize);\n }\n\n async revokeCreditsByEntryType(userId: string, entryType: string): Promise<RevokeCreditsResult> {\n const result = await this.queries.revokeCreditsByEntryType(userId, entryType);\n if (result.revoked.gt(0)) {\n this.emit(\"credits.revoked\", userId, {\n userId,\n entryType,\n amount: result.revoked,\n balanceAfter: result.balanceAfter,\n });\n }\n return result;\n }\n\n /** Execute an application-driven catalog grant program. */\n async executeGrantProgram(\n request: ExecuteGrantProgramRequest,\n ): Promise<GrantProgramAwardResult[]> {\n return this.store.executeGrantProgram(request);\n }\n\n async getLedgerEntry(userId: string, entryId: string): Promise<LedgerEntry | null> {\n return this.queries.getLedgerEntry(userId, entryId);\n }\n\n async getAvailable(userId: string): Promise<AvailableResult> {\n return this.queries.getAvailable(userId);\n }\n\n async aggregateStats(start: Date, end: Date): Promise<AggregateStats> {\n return this.queries.aggregateStats(start, end);\n }\n\n async spendByUser(start: Date, end: Date): Promise<SpendByUserRow[]> {\n return this.queries.spendByUser(start, end);\n }\n\n async spendByModel(start: Date, end: Date): Promise<SpendByModelRow[]> {\n return this.queries.spendByModel(start, end);\n }\n\n async listLedgerEntries(userId: string, options?: ListLedgerEntriesOptions): Promise<LedgerPage> {\n return this.queries.listLedgerEntries(userId, options);\n }\n\n async listUsageEntries(userId: string, options?: ListUsageEntriesOptions): Promise<LedgerPage> {\n return this.queries.listUsageEntries(userId, options);\n }\n\n async listUsageCharges(\n userId: string,\n options?: ListUsageChargesOptions,\n ): Promise<UsageChargePage> {\n return this.queries.listUsageCharges(userId, options);\n }\n\n async topUsers(limit: number, start: Date, end: Date): Promise<TopUserRow[]> {\n return this.queries.topUsers(limit, start, end);\n }\n\n async dailySpend(start: Date, end: Date): Promise<DailySpendRow[]> {\n return this.queries.dailySpend(start, end);\n }\n\n /** Emit a credit lifecycle event. No-op if no emitter is configured. */\n private emit(type: CreditEventType, userId: string, data?: Record<string, unknown>): void {\n this.emitter?.emit({ type, timestamp: new Date(), userId, data });\n }\n\n private async emitQuotaEvents(userId: string, idempotencyKey: string): Promise<void> {\n const events = await this.store.listQuotaEvents(userId, {\n idempotencyKey,\n limit: 100,\n });\n for (const event of events) {\n const data = {\n quotaKey: event.quotaKey,\n operation: event.operation,\n measure: event.measure,\n thresholdPercent: event.thresholdPercent,\n usageChargeId: event.usageChargeId,\n idempotencyKey: event.idempotencyKey,\n };\n if (event.eventType === \"blocked\") {\n this.emit(\"credits.quota_blocked\", userId, data);\n } else {\n this.emit(\"credits.quota_threshold\", userId, data);\n }\n }\n }\n\n /** Load the active catalog revision from the store. */\n async loadCatalogFromStore(): Promise<void> {\n await this.catalogRuntime.loadFromStore();\n }\n\n /**\n * If the cached PricingEngine is stale (TTL expired), reload it from the\n * store. Concurrent callers are deduplicated via the underlying\n * ``lru-cache.fetch()`` — only one ``loadCatalogFromStore`` runs and all\n * callers await the same result.\n *\n * When ``catalogCacheTtlMs`` is ``0``, this is a no-op (the consumer must call\n * ``loadCatalogFromStore`` manually).\n */\n async refreshCatalogIfStale(): Promise<void> {\n await this.catalogRuntime.refreshIfStale();\n }\n\n /**\n * Invalidate the catalog cache so the next ``refreshCatalogIfStale`` call\n * reloads from the store. Useful after a manual ``loadCatalogFromStore``\n * that bypasses the cache, or when the consumer knows the remote config\n * has changed.\n */\n invalidateCatalog(): void {\n this.catalogRuntime.invalidate();\n }\n\n /**\n * Publish and activate a catalog revision, then update the local engine.\n *\n * The store write is awaited, so\n * a persistence failure surfaces to the caller instead of becoming an\n * unhandled promise rejection.\n */\n async publishAndActivateCatalog(\n config: Record<string, unknown>,\n label?: string | null,\n rollout?: CatalogRollout | Record<string, unknown> | null,\n ): Promise<string> {\n return this.catalogRuntime.publishAndActivate(config, label, rollout);\n }\n\n /** Publish a validated, inactive catalog draft. */\n async publishCatalogDraft(\n config: Record<string, unknown>,\n label?: string | null,\n ): Promise<string> {\n return this.catalogRuntime.publishDraft(config, label);\n }\n\n /** Activate an existing catalog version and reload the local engine. */\n async activateCatalogRevision(\n version: number,\n rollout?: CatalogRollout | Record<string, unknown> | null,\n ): Promise<string> {\n return this.catalogRuntime.activateRevision(version, rollout);\n }\n\n /** The current PricingEngine, or null if not loaded. */\n get pricingEngine(): PricingEngine | null {\n return this.catalogRuntime.currentEngine;\n }\n\n /**\n * Set a user's subscription plan and emit ``credits.plan_changed``.\n *\n * The store call is awaited so a persistence failure surfaces to the caller.\n * The event is emitted only after the store write succeeds.\n */\n async setUserPlan(\n userId: string,\n planKey: string,\n planAssignedAt?: Date | null,\n ): Promise<SetUserPlanResult> {\n this.logger.info(\"[CreditsService] setUserPlan\", { planKey, planAssignedAt });\n const result = await this.store.setUserPlan(userId, planKey, planAssignedAt);\n this.emit(\"credits.plan_changed\", userId, {\n userId,\n planKey,\n planAssignedAt: result.planAssignedAt,\n assignmentState: result.assignmentState,\n timestamp: new Date().toISOString(),\n });\n return result;\n }\n\n /** Unset a user's subscription plan and emit the plan-change event. */\n async unsetUserPlan(userId: string): Promise<UnsetUserPlanResult> {\n const result = await this.store.unsetUserPlan(userId);\n this.emit(\"credits.plan_changed\", userId, {\n userId,\n planKey: null,\n timestamp: new Date().toISOString(),\n });\n return result;\n }\n\n /** Pin or unpin the user's current assignment revision. */\n async setPlanRevisionPin(userId: string, pinned: boolean): Promise<boolean> {\n return this.store.setPlanRevisionPin(userId, pinned);\n }\n\n /** Apply one bounded batch of renewal-effective plan changes. */\n async applyDuePlanChanges(limit = 100): Promise<number> {\n return this.store.applyDuePlanChanges(limit);\n }\n\n /** Sweep this user's expired lots when lazy expiry is enabled. */\n private async maybeLazyExpire(userId: string): Promise<void> {\n if (!this.lazyExpiry) return;\n await this.runSweep(false, userId);\n }\n\n async getBalance(userId: string): Promise<BalanceResult> {\n await this.maybeLazyExpire(userId);\n return await this.store.getBalance(userId);\n }\n\n /** Add credits to a user's account. */\n async addCredits(\n userId: string,\n amount: Decimal | number,\n options?: AddCreditsOptions,\n ): Promise<AddCreditsResult> {\n const type = options?.type ?? \"adjustment\";\n this.logger.info(\"[CreditsService] addCredits\", { amount, type, bucket: options?.bucket });\n const result = await this.store.addCredits(\n userId,\n positiveAmount(amount, \"addCredits\"),\n type,\n options?.metadata,\n options?.expiresAt,\n options?.bucket,\n options?.idempotencyKey,\n );\n this.emit(\"credits.added\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n newBalance: result.newBalance,\n type,\n idempotent: result.idempotent ?? false,\n });\n this.balanceMonitor.rearmAfterCredit(userId, result.newBalance);\n return result;\n }\n\n /**\n * Deduct a raw credit amount from a user's account.\n *\n * Uses the store's `addCredits` with `type='adjustment'` and a negated\n * amount — the existing validation path for negative/zero adjustments.\n * Use this for refund clawbacks and other administrative deductions that\n * bypass the usage-based `deduct()` flow.\n */\n async deductCredits(\n userId: string,\n amount: Decimal | number,\n options?: DeductCreditsOptions,\n ): Promise<AddCreditsResult> {\n const entryType = options?.entryType ?? \"adjustment\";\n this.logger.info(\"[CreditsService] deductCredits\", {\n amount,\n entryType,\n bucket: options?.bucket,\n });\n const result = await this.store.addCredits(\n userId,\n positiveAmount(amount, \"deductCredits\").neg(),\n entryType,\n options?.metadata ?? null,\n null,\n options?.bucket ?? undefined,\n options?.idempotencyKey,\n );\n this.emit(\"credits.deducted\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n newBalance: result.newBalance,\n entryType,\n idempotent: result.idempotent ?? false,\n });\n if (!result.idempotent) {\n await this.afterDeduction(userId, \"raw\", {\n entryId: result.entryId,\n userId,\n amount: result.amount.abs(),\n allowanceConsumed: new Decimal(0),\n balanceAfter: result.newBalance,\n idempotent: false,\n usageChargeId: null,\n error: null,\n bucketBreakdown: null,\n });\n }\n return result;\n }\n\n /**\n * Grant one billing-cycle's worth of credits — idempotent-safe for a\n * payment-provider webhook handler (Stripe, etc. — bursar stays\n * provider-agnostic) to call even on webhook redelivery.\n *\n * 1. At most one of ``expiresAt``/``ttlDays`` may be given (throws\n * ``ConfigError`` otherwise).\n * 2. When ``ttlDays`` is given, ``expiresAt = now + ttlDays`` days.\n * 3. The new cycle is granted via a direct ``store.addCredits`` call\n * (bypassing {@link addCredits} so only ``credits.cycle_renewed`` fires,\n * not a duplicate ``credits.added``), threading ``idempotencyKey`` so a\n * redelivered webhook replays the prior grant instead of double-crediting.\n * 4. Existing bucket credits are never removed here. Subscription renewal\n * policies that replace prior lots run atomically through BillingService.\n * 5. When ``planKey`` is given, assigns it via {@link setUserPlan}.\n * 6. Emits ``credits.cycle_renewed`` and returns the grant result.\n */\n async grantSubscriptionCycle(\n userId: string,\n amount: Decimal | number,\n options?: GrantSubscriptionCycleOptions,\n ): Promise<AddCreditsResult> {\n this.logger.info(\"[CreditsService] grantSubscriptionCycle\", {\n amount,\n bucket: options?.bucket,\n planKey: options?.planKey,\n });\n if (options?.expiresAt != null && options?.ttlDays != null) {\n throw new ConfigError(\n \"grantSubscriptionCycle: specify at most one of 'expiresAt' or 'ttlDays', not both\",\n );\n }\n const bucket = options?.bucket ?? \"subscription\";\n const expiresAt: Date | undefined =\n options?.ttlDays != null\n ? new Date(Date.now() + options.ttlDays * 86_400_000)\n : options?.expiresAt;\n const amountDec = positiveAmount(amount, \"grantSubscriptionCycle\");\n\n const result = await this.store.addCredits(\n userId,\n amountDec,\n \"purchase\",\n options?.metadata,\n expiresAt,\n bucket,\n options?.idempotencyKey,\n );\n\n // The store contract exposes the mutation's replay result directly, avoiding\n // a racy lifetime-balance comparison and an extra database round trip.\n const isFreshGrant = !result.idempotent;\n if (options?.planKey) {\n // A fresh cycle intentionally re-anchors plan-assignment windows. On a\n // webhook replay, repair a previously interrupted grant->assignment saga\n // without re-anchoring an assignment that already succeeded.\n if (isFreshGrant || (await this.getUserPlan(userId)).planKey !== options.planKey) {\n await this.setUserPlan(userId, options.planKey);\n }\n }\n\n this.emit(\"credits.cycle_renewed\", userId, {\n entryId: result.entryId,\n amount: amountDec,\n newBalance: result.newBalance,\n bucket,\n planKey: options?.planKey ?? null,\n idempotencyKey: options?.idempotencyKey ?? null,\n idempotent: result.idempotent,\n });\n\n return result;\n }\n\n // ── Lease lifecycle: atomic admission ───────────────────────────────\n\n async reserve(\n userId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: ReserveOptions,\n ): Promise<LeaseSuccess> {\n return this.leases.reserve(userId, metricsOrAmount, options);\n }\n\n async settle(\n userId: string,\n leaseId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: SettleOptions,\n ): Promise<DeductionResult> {\n return this.leases.settle(userId, leaseId, metricsOrAmount, options);\n }\n\n async release(userId: string, leaseId: string): Promise<ReleaseResult> {\n return this.leases.release(userId, leaseId);\n }\n\n async renew(userId: string, leaseId: string, ttl?: number | null): Promise<LeaseSuccess> {\n return this.leases.renew(userId, leaseId, ttl);\n }\n\n async canAfford(\n userId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: CanAffordOptions,\n ): Promise<CanAffordResult> {\n return this.leases.canAfford(userId, metricsOrAmount, options);\n }\n\n async getBucketBalances(userId: string): Promise<BucketBalancesResult> {\n return this.leases.getBucketBalances(userId);\n }\n\n async checkAllowance(userId: string): Promise<AllowanceResult | null> {\n return this.leases.checkAllowance(userId);\n }\n\n async runBilled<T>(\n userId: string,\n options: RunBilledOptions<T>,\n ): Promise<{ result: T; deduction: DeductionResult }> {\n return this.leases.runBilled(userId, options);\n }\n\n async beginBilledOperation(\n userId: string,\n options: BeginBilledOperationOptions,\n ): Promise<BilledOperation> {\n return this.leases.beginBilledOperation(userId, options);\n }\n\n /**\n * Full deduction flow as one atomic store call.\n *\n * 1. ``breakdown = engine.calculate(metrics)``; ``cost = breakdown.total``\n * (exact `Decimal`, **no truncation**).\n * 2. ``store.deductWithAllowance`` records the usage, enforces policy, consumes\n * allowance, and debits any remainder — idempotency-keyed end-to-end.\n *\n * On a store ``error`` a ``credits.deduct_failed`` event is emitted and a\n * typed exception is thrown. No success event is emitted on error.\n */\n async deduct(\n userId: string,\n metrics: UsageMetrics,\n options?: DeductOptions,\n ): Promise<DeductionResult> {\n await this.maybeLazyExpire(userId);\n this.logger.debug(\"[CreditsService] deduct\", {\n model: metrics.dimensions?.model,\n feature: options?.feature,\n });\n const engine = await this.catalogRuntime.engineForUser(userId);\n const plan = await this.store.getUserPlan(userId);\n const effectiveIdempotencyKey = options?.idempotencyKey ?? `usage:${randomUUID()}`;\n\n // 1) Calculate cost as an exact Decimal, never truncated.\n const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });\n const cost = breakdown.total;\n\n // Build ledger metadata: caller fields FIRST, system fields LAST so the\n // protected system fields win.\n const meta: Record<string, unknown> = {};\n if (options?.metadata) {\n for (const [k, v] of Object.entries(options.metadata)) {\n if (v != null) meta[k] = v;\n }\n }\n meta[\"operation\"] = metrics.operation;\n meta[\"measures\"] = { ...(metrics.measures ?? {}) };\n meta[\"dimensions\"] = { ...(metrics.dimensions ?? {}) };\n meta[\"breakdownTotal\"] = breakdown.total.toString();\n meta[\"idempotencyKey\"] = effectiveIdempotencyKey;\n\n const deductionOptions: DeductWithAllowanceOptions = {\n idempotencyKey: effectiveIdempotencyKey,\n operation: metrics.operation,\n feature: options?.feature ?? null,\n model: typeof metrics.dimensions?.model === \"string\" ? metrics.dimensions.model : null,\n region: typeof metrics.dimensions?.region === \"string\" ? metrics.dimensions.region : null,\n measures: { ...(metrics.measures ?? {}) },\n dimensions: { ...(metrics.dimensions ?? {}) },\n metadata: meta as CreditMetadata,\n };\n\n // 2) Atomic charge. This records zero-cost usage too, so authorization,\n // quotas, and usage history cannot be bypassed by a free rate.\n const result = await this.store.deductWithAllowance(userId, cost, deductionOptions);\n\n if (result.error !== null) {\n if (result.error === \"quota_exceeded\") {\n await this.emitQuotaEvents(userId, effectiveIdempotencyKey);\n }\n this.logger.warn(\"[CreditsService] deduct failed\", {\n error: result.error,\n amount: cost,\n model: metrics.dimensions?.model,\n feature: options?.feature,\n });\n this.emit(\"credits.deduct_failed\", userId, {\n error: result.error,\n amount: cost,\n model: metrics.dimensions?.model ?? null,\n });\n raiseDeductError(result.error, userId, cost);\n }\n\n // Success — emit deducted, then any cap warning, then edge-triggered low-balance.\n this.emit(\"credits.deducted\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n allowanceConsumed: result.allowanceConsumed,\n balanceAfter: result.balanceAfter,\n model: metrics.dimensions?.model ?? null,\n idempotent: result.idempotent,\n });\n\n // low_balance is edge-triggered: only fire when this deduction crossed\n // the threshold. A replayed (idempotent) result did not move the balance, so\n // it never crosses. balanceBefore = balanceAfter + amount charged.\n if (!result.idempotent) {\n const balanceBefore = result.balanceAfter.plus(result.amount);\n await this.balanceMonitor.signalCrossing(userId, balanceBefore, result.balanceAfter);\n await this.emitQuotaEvents(userId, effectiveIdempotencyKey);\n await this.afterDeduction(userId, \"deduct\", result);\n }\n\n return result;\n }\n\n /**\n * Record priced usage for a workflow without debiting the account again.\n *\n * This supports priced usage receipts that should be retained without\n * affecting the account balance, such as externally billed usage.\n */\n async recordUsage(\n userId: string,\n metrics: UsageMetrics,\n options?: RecordUsageOptions,\n ): Promise<UsageRecordResult> {\n const engine = await this.catalogRuntime.engineForUser(userId);\n const plan = await this.store.getUserPlan(userId);\n const effectiveIdempotencyKey = options?.idempotencyKey ?? `usage-record:${randomUUID()}`;\n const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });\n const meta: Record<string, unknown> = {};\n if (options?.metadata) {\n for (const [key, value] of Object.entries(options.metadata)) {\n if (value != null) meta[key] = value;\n }\n }\n meta.operation = metrics.operation;\n meta.measures = { ...(metrics.measures ?? {}) };\n meta.dimensions = { ...(metrics.dimensions ?? {}) };\n meta.breakdownTotal = breakdown.total.toString();\n meta.idempotencyKey = effectiveIdempotencyKey;\n\n const result = await this.store.recordUsage(userId, metrics.operation, breakdown.total, {\n idempotencyKey: effectiveIdempotencyKey,\n operation: metrics.operation,\n model: typeof metrics.dimensions?.model === \"string\" ? metrics.dimensions.model : null,\n region: typeof metrics.dimensions?.region === \"string\" ? metrics.dimensions.region : null,\n measures: { ...(metrics.measures ?? {}) },\n dimensions: { ...(metrics.dimensions ?? {}) },\n metadata: meta as CreditMetadata,\n });\n if (result.error !== null) {\n throw new StoreError(`Usage record failed: ${result.error}`);\n }\n return result;\n }\n\n /**\n * Refund a previous credit deduction.\n *\n * Returns the RefundResult. A successful refund\n * emits ``credits.refunded``; a failed/duplicate/over-refund emits\n * ``credits.refund_failed`` (no success event is ever emitted for a failed\n * refund).\n */\n /** Deduct the configured fixed cost for one named job. */\n async deductFlatJob(\n userId: string,\n jobName: string,\n options?: DeductFlatJobOptions,\n ): Promise<DeductionResult> {\n return this.deduct(userId, { operation: jobName, measures: { jobs: 1 } }, options);\n }\n\n async refundCredits(entryId: string, options?: RefundCreditsOptions): Promise<RefundSuccess> {\n const refundAmount =\n options?.amount != null ? positiveAmount(options.amount, \"refundCredits\") : undefined;\n this.logger.info(\"[CreditsService] refundCredits\", {\n entryId,\n refundAmount,\n reason: options?.reason,\n });\n const result = await this.store.refundCredits(\n entryId,\n refundAmount,\n options?.reason,\n options?.metadata,\n options?.idempotencyKey,\n );\n\n if (result.error !== null) {\n this.logger.warn(\"[CreditsService] refundCredits failed\", {\n entryId,\n error: result.error,\n });\n if (result.userId !== null) {\n this.emit(\"credits.refund_failed\", result.userId, {\n entryId,\n error: result.error,\n reason: options?.reason ?? null,\n });\n }\n throw new RefundError(`Refund rejected: ${result.error}`);\n }\n\n this.emit(\"credits.refunded\", result.userId, {\n entryId,\n refundEntryId: result.refundEntryId,\n amount: result.amount,\n newBalance: result.newBalance,\n reason: options?.reason ?? null,\n });\n return result;\n }\n\n /**\n * Deduct from a team's shared balance pool.\n *\n * Calculates the cost via the pricing engine (exact `Decimal`, no truncation),\n * then debits the team balance. Threads an optional ``idempotencyKey`` through\n * to the store so retried team charges are not double-counted.\n */\n async deductTeam(\n teamId: string,\n userId: string,\n metrics: UsageMetrics,\n options?: DeductTeamOptions,\n ): Promise<TeamDeductionResult> {\n await this.maybeLazyExpire(userId);\n // Lazy expiry is scoped to the individual member's credits, not the team's\n // shared pool — there's no per-team expiry concept.\n const engine = await this.catalogRuntime.engineForUser(userId);\n const plan = await this.store.getUserPlan(userId);\n\n const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });\n const cost = breakdown.total;\n\n if (cost.lte(0)) {\n const teamBal = await this.store.getTeamBalance(teamId);\n if (teamBal === null) {\n throw new StoreError(`Team not found: ${teamId}`);\n }\n return {\n entryId: null,\n teamId,\n userId,\n amount: new Decimal(0),\n teamBalanceAfter: teamBal.balance,\n idempotent: false,\n error: null,\n };\n }\n\n const teamMetadata: CreditMetadata = {\n ...(options?.metadata ?? {}),\n operation: metrics.operation,\n measures: { ...(metrics.measures ?? {}) },\n dimensions: Object.fromEntries(\n Object.entries(metrics.dimensions ?? {}).map(([key, value]) => [key, String(value)]),\n ),\n breakdownTotal: breakdown.total.toString(),\n };\n const result = await this.store.deductTeam(\n teamId,\n userId,\n cost,\n teamMetadata,\n options?.idempotencyKey,\n );\n // Surface store errors: emit credits.deduct_failed and throw,\n // mirroring the Python credit service implementation. Previously returned a silent\n // success-shaped object with an .error field, so failed charges looked OK.\n if (result.error !== null) {\n this.emit(\"credits.deduct_failed\", userId, {\n error: result.error,\n amount: cost,\n teamId,\n deductType: \"team\",\n });\n if (result.error === \"member_spend_cap_exceeded\") {\n throw new CapReachedError(\n `Team member spend cap exceeded. Team=${teamId}, user=${userId}, requested=${cost}`,\n );\n }\n throw new InsufficientCreditsError(\n `Team deduction failed: ${result.error}. Team=${teamId}, user=${userId}, requested=${cost}`,\n );\n }\n this.emit(\"credits.deducted\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n teamBalanceAfter: result.teamBalanceAfter,\n teamId,\n deductType: \"team\",\n });\n return result;\n }\n private async runSweep(dryRun: boolean, userId?: string): Promise<SweepResult> {\n const result = await this.store.sweepExpiredCredits(dryRun, userId);\n if (!dryRun && result.expiredCount > 0) {\n this.emit(\"credits.expired\", userId ?? \"system\", {\n expiredCount: result.expiredCount,\n expiredAmount: result.expiredAmount,\n expiredByBucket: result.expiredByBucket ?? null,\n });\n }\n return result;\n }\n\n /**\n * Sweep expired credits from all users' balances.\n *\n * When ``dryRun`` is true, reports what would expire without mutating\n * balances. Automatic lazy sweeps remain scoped to one subject.\n */\n async sweepExpiredCredits(dryRun = false): Promise<SweepResult> {\n return await this.runSweep(dryRun);\n }\n}\n"]}
1
+ {"version":3,"file":"service.js","sourceRoot":"","sources":["../../src/credits/service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EACL,eAAe,EACf,WAAW,EACX,wBAAwB,EACxB,WAAW,EACX,UAAU,GACX,MAAM,cAAc,CAAC;AA+CtB,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAC5D,OAAO,EAAE,yBAAyB,EAAwB,MAAM,uBAAuB,CAAC;AA2CxF;;;GAGG;AACH,MAAM,yBAAyB,GAAG,GAAG,CAAC;AAEtC,MAAM,cAAc,GAAG,IAAI,GAAG,CAAe,CAAC,gBAAgB,EAAE,WAAW,CAAC,CAAC,CAAC;AAE9E,SAAS,cAAc,CAAC,KAAkB,EAAE,SAAiB;IAC3D,MAAM,MAAM,GAAG,SAAS,CAAC,KAAK,CAAC,CAAC;IAChC,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACxC,MAAM,IAAI,UAAU,CAAC,GAAG,SAAS,8CAA8C,CAAC,CAAC;IACnF,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,OAAO,EAAyB,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAE7E;;;;;;;;;;;;GAYG;AACH,MAAM,OAAO,cAAc;IACR,KAAK,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;QACpE,IAAI,CAAC,MAAM,IAAI,MAAM,CAAC,YAAY,GAAG,CAAC,EAAE,CAAC;YACvC,IAAI,CAAC,IAAI,CAAC,iBAAiB,EAAE,MAAM,IAAI,QAAQ,EAAE;gBAC/C,YAAY,EAAE,MAAM,CAAC,YAAY;gBACjC,aAAa,EAAE,MAAM,CAAC,aAAa;gBACnC,eAAe,EAAE,MAAM,CAAC,eAAe,IAAI,IAAI;aAChD,CAAC,CAAC;QACL,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,mBAAmB,CAAC,MAAM,GAAG,KAAK;QACtC,OAAO,MAAM,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;IACrC,CAAC;CACF","sourcesContent":["import { Decimal } from \"decimal.js\";\nimport {\n CapReachedError,\n ConfigError,\n InsufficientCreditsError,\n RefundError,\n StoreError,\n} from \"../errors.js\";\nimport type { PricingEngine } from \"../engine.js\";\nimport type { BursarConfigData, CatalogRollout } from \"../config.js\";\nimport type {\n AddCreditsResult,\n AggregateStats,\n AllowanceResult,\n AvailableResult,\n BalanceResult,\n CatalogRevision,\n BucketBalancesResult,\n CanAffordResult,\n CheckFeatureResult,\n CreditMetadata,\n DailySpendRow,\n DeductionResult,\n DeductWithAllowanceOptions,\n ExecuteGrantProgramRequest,\n GetUserPlanResult,\n GrantProgramAwardResult,\n LedgerEntry,\n LedgerPage,\n LeaseSuccess,\n ListLedgerEntriesOptions,\n ListQuotaEventsOptions,\n ListUsageChargesOptions,\n ListUsageEntriesOptions,\n PlanMigrationBatchResult,\n PlanMigrationStartResult,\n QuotaEvent,\n QuotaState,\n RefundSuccess,\n RevokeCreditsResult,\n ReleaseResult,\n SetUserPlanResult,\n UnsetUserPlanResult,\n SpendByModelRow,\n SpendByUserRow,\n SweepResult,\n TeamDeductionResult,\n TopUserRow,\n UsageChargePage,\n UsageRecordResult,\n} from \"./types/index.js\";\nimport type { CreditStore } from \"./store.js\";\nimport type { CreditEventEmitter, CreditEventType } from \"./events.js\";\nimport type { UsageMetrics } from \"../metrics.js\";\nimport { raiseDeductError } from \"./service-errors.js\";\nimport { LowBalanceMonitor } from \"./low-balance-monitor.js\";\nimport { CreditQueries } from \"./queries.js\";\nimport { CatalogRuntime } from \"./catalog-runtime.js\";\nimport { toDecimal } from \"./amount.js\";\nimport { CreditLeaseWorkflow } from \"./lease-workflow.js\";\nimport { requireStableKey } from \"../shared/idempotency.js\";\nimport { getDefaultInstrumentation, type Instrumentation } from \"../telemetry/index.js\";\nimport type {\n AddCreditsOptions,\n BeginBilledOperationOptions,\n BilledOperation,\n CanAffordOptions,\n CreditsServiceOptions,\n DeductCreditsOptions,\n DeductFlatJobOptions,\n DeductOptions,\n DeductTeamOptions,\n ExactAmount,\n GrantSubscriptionCycleOptions,\n MetricsOrAmount,\n PolicyPreset,\n PostDeductionContext,\n RecordUsageOptions,\n RefundCreditsOptions,\n ReserveOptions,\n RunBilledOptions,\n SettleOptions,\n} from \"./service-types.js\";\nexport type {\n AddCreditsOptions,\n BeginBilledOperationOptions,\n BilledOperation,\n CanAffordOptions,\n CreditsServiceOptions,\n DeductCreditsOptions,\n DeductFlatJobOptions,\n DeductOptions,\n DeductTeamOptions,\n ExactAmount,\n GrantSubscriptionCycleOptions,\n LowBalanceConfig,\n PolicyPreset,\n PostDeductionContext,\n RecordUsageOptions,\n RefundCreditsOptions,\n ReserveOptions,\n RunBilledOptions,\n SettleOptions,\n} from \"./service-types.js\";\n/**\n * Default lease TTL (seconds) for ``reserve`` and ``runBilled``.\n * Long batch/agentic jobs call the configured lease TTL before this elapses.\n */\nconst DEFAULT_LEASE_TTL_SECONDS = 600;\n\nconst POLICY_PRESETS = new Set<PolicyPreset>([\"strict_prepaid\", \"overdraft\"]);\n\nfunction positiveAmount(value: ExactAmount, operation: string): Decimal {\n const amount = toDecimal(value);\n if (!amount.isFinite() || !amount.gt(0)) {\n throw new RangeError(`${operation} amount must be finite and greater than zero`);\n }\n return amount;\n}\n\nimport { type NormalizedLogger, normalizeLogger } from \"../shared/logger.js\";\n\n/**\n * Orchestrates credit operations.\n *\n * The deduction path is a single atomic, idempotency-keyed store call\n * (``deductWithAllowance``) that consumes free allowance, enforces plan policy,\n * and debits the net amount in one transaction. The service calculates the cost, maps\n * the store's typed ``error`` codes to exceptions, and emits lifecycle events\n * **only after** the operation has succeeded.\n *\n * Optionally accepts a ``CreditEventEmitter`` to emit lifecycle events\n * (deducted, deduct_failed, added, refunded, refund_failed, expired,\n * low_balance).\n */\nexport class CreditsService {\n private readonly store: CreditStore;\n private readonly queries: CreditQueries;\n private readonly catalogRuntime: CatalogRuntime;\n private readonly leases: CreditLeaseWorkflow;\n private emitter: CreditEventEmitter | null = null;\n private balanceMonitor: LowBalanceMonitor;\n // Lazy-on-read credit expiry (closes the gap with allowance windows/lease\n // TTLs, which are already lazy-on-read). Default `false` — unchanged\n // behaviour; explicit `sweepExpiredCredits`/cron remains required.\n private lazyExpiry: boolean;\n private logger: NormalizedLogger;\n private readonly instrumentation: Instrumentation;\n private readonly postDeductionHooks = new Set<\n (context: PostDeductionContext) => void | Promise<void>\n >();\n constructor(\n store: CreditStore,\n engine?: PricingEngine | null,\n emitter?: CreditEventEmitter | null,\n options?: CreditsServiceOptions | null,\n ) {\n this.store = store;\n this.instrumentation = options?.instrumentation ?? getDefaultInstrumentation();\n this.queries = new CreditQueries(\n store,\n options?.analytics ?? store,\n options?.usageStore ?? store,\n );\n const policy = options?.policy ?? \"strict_prepaid\";\n if (!POLICY_PRESETS.has(policy)) {\n throw new ConfigError(\n `unknown policy preset '${policy}'; expected one of ${[...POLICY_PRESETS].sort().join(\", \")}`,\n );\n }\n if (emitter) this.emitter = emitter;\n this.logger = normalizeLogger(options?.logger);\n if (options?.postDeduction) this.postDeductionHooks.add(options.postDeduction);\n this.catalogRuntime = new CatalogRuntime(\n store,\n engine ?? null,\n this.logger,\n options?.catalogCacheTtlMs ?? 300_000,\n );\n this.balanceMonitor = new LowBalanceMonitor(\n options?.lowBalance,\n (type, userId, data) => this.emit(type, userId, data),\n this.logger,\n );\n this.lazyExpiry = options?.lazyExpiry ?? false;\n this.leases = new CreditLeaseWorkflow(\n store,\n this.catalogRuntime,\n this.logger,\n this.balanceMonitor,\n policy,\n options?.overdraftFloor != null ? toDecimal(options.overdraftFloor) : null,\n options?.maxConcurrent ?? null,\n options?.defaultTtlSeconds ?? DEFAULT_LEASE_TTL_SECONDS,\n (type, userId, data) => this.emit(type, userId, data),\n (userId, idempotencyKey) => this.emitQuotaEvents(userId, idempotencyKey),\n (userId) => this.maybeLazyExpire(userId),\n (userId, result) => this.afterDeduction(userId, \"settle\", result),\n );\n }\n\n /**\n * Register an awaited post-commit deduction hook. A failing hook is logged\n * and isolated so it can never roll back an already committed charge.\n */\n addPostDeductionHook(hook: (context: PostDeductionContext) => void | Promise<void>): () => void {\n this.postDeductionHooks.add(hook);\n return () => this.postDeductionHooks.delete(hook);\n }\n\n private async afterDeduction(\n userId: string,\n source: PostDeductionContext[\"source\"],\n deduction: PostDeductionContext[\"deduction\"],\n ): Promise<void> {\n for (const hook of this.postDeductionHooks) {\n try {\n await hook({ userId, source, deduction });\n } catch (error) {\n this.logger.warn(\"[CreditsService] post-deduction hook failed\", {\n userId,\n source,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n }\n\n async getActiveCatalog(): Promise<CatalogRevision | null> {\n return this.queries.getActiveCatalog();\n }\n\n async getUserPlan(userId: string): Promise<GetUserPlanResult> {\n return this.queries.getUserPlan(userId);\n }\n\n async checkFeature(userId: string, feature: string): Promise<CheckFeatureResult> {\n return this.queries.checkFeature(userId, feature);\n }\n\n async getQuotaState(userId: string, quotaKey?: string | null): Promise<QuotaState[]> {\n return this.queries.getQuotaState(userId, quotaKey);\n }\n\n async listQuotaEvents(userId: string, options?: ListQuotaEventsOptions): Promise<QuotaEvent[]> {\n return this.queries.listQuotaEvents(userId, options);\n }\n\n async startPlanMigration(\n fromPlanId: string | null,\n toPlanId: string,\n ): Promise<PlanMigrationStartResult> {\n return this.queries.startPlanMigration(fromPlanId, toPlanId);\n }\n\n async migratePlanBatch(\n migrationId: string,\n batchSize?: number,\n ): Promise<PlanMigrationBatchResult> {\n return this.queries.migratePlanBatch(migrationId, batchSize);\n }\n\n async revokeCreditsByEntryType(userId: string, entryType: string): Promise<RevokeCreditsResult> {\n const result = await this.queries.revokeCreditsByEntryType(userId, entryType);\n if (result.revoked.gt(0)) {\n this.emit(\"credits.revoked\", userId, {\n userId,\n entryType,\n amount: result.revoked,\n balanceAfter: result.balanceAfter,\n });\n }\n return result;\n }\n\n /** Execute an application-driven catalog grant program. */\n async executeGrantProgram(\n request: ExecuteGrantProgramRequest,\n ): Promise<GrantProgramAwardResult[]> {\n return this.instrumentation.run(\"credits.grant_program\", undefined, () =>\n this.store.executeGrantProgram(request),\n );\n }\n\n async getLedgerEntry(userId: string, entryId: string): Promise<LedgerEntry | null> {\n return this.queries.getLedgerEntry(userId, entryId);\n }\n\n async getAvailable(userId: string): Promise<AvailableResult> {\n return this.queries.getAvailable(userId);\n }\n\n async aggregateStats(start: Date, end: Date): Promise<AggregateStats> {\n return this.queries.aggregateStats(start, end);\n }\n\n async spendByUser(start: Date, end: Date): Promise<SpendByUserRow[]> {\n return this.queries.spendByUser(start, end);\n }\n\n async spendByModel(start: Date, end: Date): Promise<SpendByModelRow[]> {\n return this.queries.spendByModel(start, end);\n }\n\n async listLedgerEntries(userId: string, options?: ListLedgerEntriesOptions): Promise<LedgerPage> {\n return this.queries.listLedgerEntries(userId, options);\n }\n\n async listUsageEntries(userId: string, options?: ListUsageEntriesOptions): Promise<LedgerPage> {\n return this.queries.listUsageEntries(userId, options);\n }\n\n async listUsageCharges(\n userId: string,\n options?: ListUsageChargesOptions,\n ): Promise<UsageChargePage> {\n return this.queries.listUsageCharges(userId, options);\n }\n\n async topUsers(limit: number, start: Date, end: Date): Promise<TopUserRow[]> {\n return this.queries.topUsers(limit, start, end);\n }\n\n async dailySpend(start: Date, end: Date): Promise<DailySpendRow[]> {\n return this.queries.dailySpend(start, end);\n }\n\n /** Emit a credit lifecycle event. No-op if no emitter is configured. */\n private emit(type: CreditEventType, userId: string, data?: Record<string, unknown>): void {\n this.emitter?.emit({ type, timestamp: new Date(), userId, data });\n }\n\n private async emitQuotaEvents(userId: string, idempotencyKey: string): Promise<void> {\n const events = await this.store.listQuotaEvents(userId, {\n idempotencyKey,\n limit: 100,\n });\n for (const event of events) {\n const data = {\n quotaKey: event.quotaKey,\n operation: event.operation,\n measure: event.measure,\n thresholdPercent: event.thresholdPercent,\n usageChargeId: event.usageChargeId,\n idempotencyKey: event.idempotencyKey,\n };\n if (event.eventType === \"blocked\") {\n this.emit(\"credits.quota_blocked\", userId, data);\n } else {\n this.emit(\"credits.quota_threshold\", userId, data);\n }\n }\n }\n\n /** Load the active catalog revision from the store. */\n async loadCatalogFromStore(): Promise<void> {\n await this.catalogRuntime.loadFromStore();\n }\n\n /**\n * If the cached PricingEngine is stale (TTL expired), reload it from the\n * store. Concurrent callers are deduplicated via the underlying\n * ``lru-cache.fetch()`` — only one ``loadCatalogFromStore`` runs and all\n * callers await the same result.\n *\n * When ``catalogCacheTtlMs`` is ``0``, this is a no-op (the consumer must call\n * ``loadCatalogFromStore`` manually).\n */\n async refreshCatalogIfStale(): Promise<void> {\n await this.catalogRuntime.refreshIfStale();\n }\n\n /**\n * Invalidate the catalog cache so the next ``refreshCatalogIfStale`` call\n * reloads from the store. Useful after a manual ``loadCatalogFromStore``\n * that bypasses the cache, or when the consumer knows the remote config\n * has changed.\n */\n invalidateCatalog(): void {\n this.catalogRuntime.invalidate();\n }\n\n /**\n * Publish and activate a catalog revision, then update the local engine.\n *\n * The store write is awaited, so\n * a persistence failure surfaces to the caller instead of becoming an\n * unhandled promise rejection.\n */\n async publishAndActivateCatalog(\n config: BursarConfigData,\n label?: string | null,\n rollout?: CatalogRollout | null,\n ): Promise<string> {\n return this.catalogRuntime.publishAndActivate(config, label, rollout);\n }\n\n /** Publish a validated, inactive catalog draft. */\n async publishCatalogDraft(config: BursarConfigData, label?: string | null): Promise<string> {\n return this.catalogRuntime.publishDraft(config, label);\n }\n\n /** Activate an existing catalog version and reload the local engine. */\n async activateCatalogRevision(version: number, rollout?: CatalogRollout | null): Promise<string> {\n return this.catalogRuntime.activateRevision(version, rollout);\n }\n\n /** The current PricingEngine, or null if not loaded. */\n get pricingEngine(): PricingEngine | null {\n return this.catalogRuntime.currentEngine;\n }\n\n /**\n * Set a user's subscription plan and emit ``credits.plan_changed``.\n *\n * The store call is awaited so a persistence failure surfaces to the caller.\n * The event is emitted only after the store write succeeds.\n */\n async setUserPlan(\n userId: string,\n planKey: string,\n planAssignedAt?: Date | null,\n ): Promise<SetUserPlanResult> {\n this.logger.info(\"[CreditsService] setUserPlan\", { planKey, planAssignedAt });\n const result = await this.store.setUserPlan(userId, planKey, planAssignedAt);\n this.emit(\"credits.plan_changed\", userId, {\n userId,\n planKey,\n planAssignedAt: result.planAssignedAt,\n assignmentState: result.assignmentState,\n timestamp: new Date().toISOString(),\n });\n return result;\n }\n\n /** Unset a user's subscription plan and emit the plan-change event. */\n async unsetUserPlan(userId: string): Promise<UnsetUserPlanResult> {\n const result = await this.store.unsetUserPlan(userId);\n this.emit(\"credits.plan_changed\", userId, {\n userId,\n planKey: null,\n timestamp: new Date().toISOString(),\n });\n return result;\n }\n\n /** Pin or unpin the user's current assignment revision. */\n async setPlanRevisionPin(userId: string, pinned: boolean): Promise<boolean> {\n return this.store.setPlanRevisionPin(userId, pinned);\n }\n\n /** Apply one bounded batch of renewal-effective plan changes. */\n async applyDuePlanChanges(limit = 100): Promise<number> {\n return this.store.applyDuePlanChanges(limit);\n }\n\n /** Sweep this user's expired lots when lazy expiry is enabled. */\n private async maybeLazyExpire(userId: string): Promise<void> {\n if (!this.lazyExpiry) return;\n await this.runSweep(false, userId);\n }\n\n async getBalance(userId: string): Promise<BalanceResult> {\n await this.maybeLazyExpire(userId);\n return await this.store.getBalance(userId);\n }\n\n /** Add credits to a user's account. */\n async addCredits(\n userId: string,\n amount: ExactAmount,\n options: AddCreditsOptions,\n ): Promise<AddCreditsResult> {\n return this.instrumentation.run(\"credits.grant\", undefined, () =>\n this.addCreditsUninstrumented(userId, amount, options),\n );\n }\n\n private async addCreditsUninstrumented(\n userId: string,\n amount: ExactAmount,\n options: AddCreditsOptions,\n ): Promise<AddCreditsResult> {\n const idempotencyKey = requireStableKey(options?.idempotencyKey);\n const type = options.type ?? \"adjustment\";\n this.logger.info(\"[CreditsService] addCredits\", { amount, type, bucket: options.bucket });\n const result = await this.store.addCredits(userId, positiveAmount(amount, \"addCredits\"), {\n ...options,\n type,\n idempotencyKey,\n });\n this.emit(\"credits.added\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n newBalance: result.newBalance,\n type,\n idempotent: result.idempotent ?? false,\n });\n this.balanceMonitor.rearmAfterCredit(userId, result.newBalance);\n return result;\n }\n\n /**\n * Deduct a raw credit amount from a user's account.\n *\n * Uses the store's `addCredits` with `type='adjustment'` and a negated\n * amount — the existing validation path for negative/zero adjustments.\n * Use this for refund clawbacks and other administrative deductions that\n * bypass the usage-based `deduct()` flow.\n */\n async deductCredits(\n userId: string,\n amount: ExactAmount,\n options: DeductCreditsOptions,\n ): Promise<AddCreditsResult> {\n const idempotencyKey = requireStableKey(options?.idempotencyKey);\n const entryType = options.entryType ?? \"adjustment\";\n this.logger.info(\"[CreditsService] deductCredits\", {\n amount,\n entryType,\n bucket: options.bucket,\n });\n const result = await this.store.addCredits(\n userId,\n positiveAmount(amount, \"deductCredits\").neg(),\n {\n type: entryType,\n metadata: options.metadata,\n bucket: options.bucket,\n idempotencyKey,\n },\n );\n this.emit(\"credits.deducted\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n newBalance: result.newBalance,\n entryType,\n idempotent: result.idempotent ?? false,\n });\n if (!result.idempotent) {\n await this.afterDeduction(userId, \"raw\", {\n entryId: result.entryId,\n userId,\n amount: result.amount.abs(),\n allowanceConsumed: new Decimal(0),\n balanceAfter: result.newBalance,\n idempotent: false,\n usageChargeId: null,\n error: null,\n bucketBreakdown: null,\n });\n }\n return result;\n }\n\n /**\n * Grant one billing-cycle's worth of credits — idempotent-safe for a\n * payment-provider webhook handler (Stripe, etc. — bursar stays\n * provider-agnostic) to call even on webhook redelivery.\n *\n * 1. At most one of ``expiresAt``/``ttlDays`` may be given (throws\n * ``ConfigError`` otherwise).\n * 2. When ``ttlDays`` is given, ``expiresAt = now + ttlDays`` days.\n * 3. The new cycle is granted via a direct ``store.addCredits`` call\n * (bypassing {@link addCredits} so only ``credits.cycle_renewed`` fires,\n * not a duplicate ``credits.added``), threading ``idempotencyKey`` so a\n * redelivered webhook replays the prior grant instead of double-crediting.\n * 4. Existing bucket credits are never removed here. Subscription renewal\n * policies that replace prior lots run atomically through BillingService.\n * 5. When ``planKey`` is given, assigns it via {@link setUserPlan}.\n * 6. Emits ``credits.cycle_renewed`` and returns the grant result.\n */\n async grantSubscriptionCycle(\n userId: string,\n amount: ExactAmount,\n options: GrantSubscriptionCycleOptions,\n ): Promise<AddCreditsResult> {\n return this.instrumentation.run(\"credits.grant_subscription_cycle\", undefined, () =>\n this.grantSubscriptionCycleUninstrumented(userId, amount, options),\n );\n }\n\n private async grantSubscriptionCycleUninstrumented(\n userId: string,\n amount: ExactAmount,\n options: GrantSubscriptionCycleOptions,\n ): Promise<AddCreditsResult> {\n const idempotencyKey = requireStableKey(options?.idempotencyKey);\n this.logger.info(\"[CreditsService] grantSubscriptionCycle\", {\n amount,\n bucket: options.bucket,\n planKey: options.planKey,\n });\n if (options.expiresAt != null && options.ttlDays != null) {\n throw new ConfigError(\n \"grantSubscriptionCycle: specify at most one of 'expiresAt' or 'ttlDays', not both\",\n );\n }\n const bucket = options.bucket ?? \"subscription\";\n const expiresAt: Date | undefined =\n options.ttlDays != null\n ? new Date(Date.now() + options.ttlDays * 86_400_000)\n : options.expiresAt;\n const amountDec = positiveAmount(amount, \"grantSubscriptionCycle\");\n\n const result = await this.store.addCredits(userId, amountDec, {\n type: \"purchase\",\n metadata: options.metadata,\n expiresAt,\n bucket,\n idempotencyKey,\n });\n\n // The store contract exposes the mutation's replay result directly, avoiding\n // a racy lifetime-balance comparison and an extra database round trip.\n const isFreshGrant = !result.idempotent;\n if (options.planKey) {\n // A fresh cycle intentionally re-anchors plan-assignment windows. On a\n // webhook replay, repair a previously interrupted grant->assignment saga\n // without re-anchoring an assignment that already succeeded.\n if (isFreshGrant || (await this.getUserPlan(userId)).planKey !== options.planKey) {\n await this.setUserPlan(userId, options.planKey);\n }\n }\n\n this.emit(\"credits.cycle_renewed\", userId, {\n entryId: result.entryId,\n amount: amountDec,\n newBalance: result.newBalance,\n bucket,\n planKey: options.planKey ?? null,\n idempotencyKey,\n idempotent: result.idempotent,\n });\n\n return result;\n }\n\n // ── Lease lifecycle: atomic admission ───────────────────────────────\n\n async reserve(\n userId: string,\n metricsOrAmount: MetricsOrAmount,\n options: ReserveOptions,\n ): Promise<LeaseSuccess> {\n return this.instrumentation.run(\"credits.reserve\", undefined, () =>\n this.leases.reserve(userId, metricsOrAmount, options),\n );\n }\n\n async settle(\n userId: string,\n leaseId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: SettleOptions,\n ): Promise<DeductionResult> {\n return this.instrumentation.run(\"credits.settle\", undefined, () =>\n this.leases.settle(userId, leaseId, metricsOrAmount, options),\n );\n }\n\n async release(userId: string, leaseId: string): Promise<ReleaseResult> {\n return this.instrumentation.run(\"credits.release\", undefined, () =>\n this.leases.release(userId, leaseId),\n );\n }\n\n async renew(userId: string, leaseId: string, ttl?: number | null): Promise<LeaseSuccess> {\n return this.leases.renew(userId, leaseId, ttl);\n }\n\n async canAfford(\n userId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: CanAffordOptions,\n ): Promise<CanAffordResult> {\n return this.leases.canAfford(userId, metricsOrAmount, options);\n }\n\n async getBucketBalances(userId: string): Promise<BucketBalancesResult> {\n return this.leases.getBucketBalances(userId);\n }\n\n async checkAllowance(userId: string): Promise<AllowanceResult | null> {\n return this.leases.checkAllowance(userId);\n }\n\n async runBilled<T>(\n userId: string,\n options: RunBilledOptions<T>,\n ): Promise<{ result: T; deduction: DeductionResult }> {\n return this.leases.runBilled(userId, options);\n }\n\n async beginBilledOperation(\n userId: string,\n options: BeginBilledOperationOptions,\n ): Promise<BilledOperation> {\n return this.leases.beginBilledOperation(userId, options);\n }\n\n /**\n * Full deduction flow as one atomic store call.\n *\n * 1. ``breakdown = engine.calculate(metrics)``; ``cost = breakdown.total``\n * (exact `Decimal`, **no truncation**).\n * 2. ``store.deductWithAllowance`` records the usage, enforces policy, consumes\n * allowance, and debits any remainder — idempotency-keyed end-to-end.\n *\n * On a store ``error`` a ``credits.deduct_failed`` event is emitted and a\n * typed exception is thrown. No success event is emitted on error.\n */\n async deduct(\n userId: string,\n metrics: UsageMetrics,\n options: DeductOptions,\n ): Promise<DeductionResult> {\n return this.instrumentation.run(\"credits.deduct\", undefined, () =>\n this.deductUninstrumented(userId, metrics, options),\n );\n }\n\n private async deductUninstrumented(\n userId: string,\n metrics: UsageMetrics,\n options: DeductOptions,\n ): Promise<DeductionResult> {\n await this.maybeLazyExpire(userId);\n this.logger.debug(\"[CreditsService] deduct\", {\n model: metrics.dimensions?.model,\n feature: options.feature,\n });\n const engine = await this.catalogRuntime.engineForUser(userId);\n const plan = await this.store.getUserPlan(userId);\n const effectiveIdempotencyKey = requireStableKey(options?.idempotencyKey);\n\n // 1) Calculate cost as an exact Decimal, never truncated.\n const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });\n const cost = breakdown.total;\n\n // Build ledger metadata: caller fields FIRST, system fields LAST so the\n // protected system fields win.\n const meta: Record<string, unknown> = {};\n if (options.metadata) {\n for (const [k, v] of Object.entries(options.metadata)) {\n if (v != null) meta[k] = v;\n }\n }\n meta[\"operation\"] = metrics.operation;\n meta[\"measures\"] = { ...(metrics.measures ?? {}) };\n meta[\"dimensions\"] = { ...(metrics.dimensions ?? {}) };\n meta[\"breakdownTotal\"] = breakdown.total.toString();\n meta[\"idempotencyKey\"] = effectiveIdempotencyKey;\n\n const deductionOptions: DeductWithAllowanceOptions = {\n idempotencyKey: effectiveIdempotencyKey,\n operation: metrics.operation,\n feature: options.feature ?? null,\n model: typeof metrics.dimensions?.model === \"string\" ? metrics.dimensions.model : null,\n region: typeof metrics.dimensions?.region === \"string\" ? metrics.dimensions.region : null,\n measures: { ...(metrics.measures ?? {}) },\n dimensions: { ...(metrics.dimensions ?? {}) },\n metadata: meta as CreditMetadata,\n };\n\n // 2) Atomic charge. This records zero-cost usage too, so authorization,\n // quotas, and usage history cannot be bypassed by a free rate.\n const result = await this.store.deductWithAllowance(userId, cost, deductionOptions);\n\n if (result.error !== null) {\n if (result.error === \"quota_exceeded\") {\n await this.emitQuotaEvents(userId, effectiveIdempotencyKey);\n }\n this.logger.warn(\"[CreditsService] deduct failed\", {\n error: result.error,\n amount: cost,\n model: metrics.dimensions?.model,\n feature: options.feature,\n });\n this.emit(\"credits.deduct_failed\", userId, {\n error: result.error,\n amount: cost,\n model: metrics.dimensions?.model ?? null,\n });\n raiseDeductError(result.error, userId, cost);\n }\n\n // Success — emit deducted, then any cap warning, then edge-triggered low-balance.\n this.emit(\"credits.deducted\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n allowanceConsumed: result.allowanceConsumed,\n balanceAfter: result.balanceAfter,\n model: metrics.dimensions?.model ?? null,\n idempotent: result.idempotent,\n });\n\n // low_balance is edge-triggered: only fire when this deduction crossed\n // the threshold. A replayed (idempotent) result did not move the balance, so\n // it never crosses. balanceBefore = balanceAfter + amount charged.\n if (!result.idempotent) {\n const balanceBefore = result.balanceAfter.plus(result.amount);\n await this.balanceMonitor.signalCrossing(userId, balanceBefore, result.balanceAfter);\n await this.emitQuotaEvents(userId, effectiveIdempotencyKey);\n await this.afterDeduction(userId, \"deduct\", result);\n }\n\n return result;\n }\n\n /**\n * Record priced usage for a workflow without debiting the account again.\n *\n * This supports priced usage receipts that should be retained without\n * affecting the account balance, such as externally billed usage.\n */\n async recordUsage(\n userId: string,\n metrics: UsageMetrics,\n options: RecordUsageOptions,\n ): Promise<UsageRecordResult> {\n const engine = await this.catalogRuntime.engineForUser(userId);\n const plan = await this.store.getUserPlan(userId);\n const effectiveIdempotencyKey = requireStableKey(options?.idempotencyKey);\n const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });\n const meta: Record<string, unknown> = {};\n if (options.metadata) {\n for (const [key, value] of Object.entries(options.metadata)) {\n if (value != null) meta[key] = value;\n }\n }\n meta.operation = metrics.operation;\n meta.measures = { ...(metrics.measures ?? {}) };\n meta.dimensions = { ...(metrics.dimensions ?? {}) };\n meta.breakdownTotal = breakdown.total.toString();\n meta.idempotencyKey = effectiveIdempotencyKey;\n\n const result = await this.store.recordUsage(userId, metrics.operation, breakdown.total, {\n idempotencyKey: effectiveIdempotencyKey,\n operation: metrics.operation,\n model: typeof metrics.dimensions?.model === \"string\" ? metrics.dimensions.model : null,\n region: typeof metrics.dimensions?.region === \"string\" ? metrics.dimensions.region : null,\n measures: { ...(metrics.measures ?? {}) },\n dimensions: { ...(metrics.dimensions ?? {}) },\n metadata: meta as CreditMetadata,\n });\n if (result.error !== null) {\n throw new StoreError(`Usage record failed: ${result.error}`);\n }\n return result;\n }\n\n /**\n * Refund a previous credit deduction.\n *\n * Returns the RefundResult. A successful refund\n * emits ``credits.refunded``; a failed/duplicate/over-refund emits\n * ``credits.refund_failed`` (no success event is ever emitted for a failed\n * refund).\n */\n /** Deduct the configured fixed cost for one named job. */\n async deductFlatJob(\n userId: string,\n jobName: string,\n options: DeductFlatJobOptions,\n ): Promise<DeductionResult> {\n return this.deduct(userId, { operation: jobName, measures: { jobs: 1 } }, options);\n }\n\n async refundCredits(entryId: string, options: RefundCreditsOptions): Promise<RefundSuccess> {\n return this.instrumentation.run(\"credits.refund\", undefined, () =>\n this.refundCreditsUninstrumented(entryId, options),\n );\n }\n\n private async refundCreditsUninstrumented(\n entryId: string,\n options: RefundCreditsOptions,\n ): Promise<RefundSuccess> {\n const idempotencyKey = requireStableKey(options?.idempotencyKey);\n const refundAmount =\n options.amount != null ? positiveAmount(options.amount, \"refundCredits\") : undefined;\n this.logger.info(\"[CreditsService] refundCredits\", {\n entryId,\n refundAmount,\n reason: options.reason,\n });\n const result = await this.store.refundCredits(entryId, {\n ...options,\n amount: refundAmount,\n idempotencyKey,\n });\n\n if (result.error !== null) {\n this.logger.warn(\"[CreditsService] refundCredits failed\", {\n entryId,\n error: result.error,\n });\n if (result.userId !== null) {\n this.emit(\"credits.refund_failed\", result.userId, {\n entryId,\n error: result.error,\n reason: options.reason ?? null,\n });\n }\n throw new RefundError(`Refund rejected: ${result.error}`);\n }\n\n this.emit(\"credits.refunded\", result.userId, {\n entryId,\n refundEntryId: result.refundEntryId,\n amount: result.amount,\n newBalance: result.newBalance,\n reason: options.reason ?? null,\n });\n return result;\n }\n\n /**\n * Deduct from a team's shared balance pool.\n *\n * Calculates the cost via the pricing engine (exact `Decimal`, no truncation),\n * then debits the team balance. Threads a required ``idempotencyKey`` through\n * to the store so retried team charges are not double-counted.\n */\n async deductTeam(\n teamId: string,\n userId: string,\n metrics: UsageMetrics,\n options: DeductTeamOptions,\n ): Promise<TeamDeductionResult> {\n const idempotencyKey = requireStableKey(options?.idempotencyKey);\n await this.maybeLazyExpire(userId);\n // Lazy expiry is scoped to the individual member's credits, not the team's\n // shared pool — there's no per-team expiry concept.\n const engine = await this.catalogRuntime.engineForUser(userId);\n const plan = await this.store.getUserPlan(userId);\n\n const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });\n const cost = breakdown.total;\n\n if (cost.lte(0)) {\n const teamBal = await this.store.getTeamBalance(teamId);\n if (teamBal === null) {\n throw new StoreError(`Team not found: ${teamId}`);\n }\n return {\n entryId: null,\n teamId,\n userId,\n amount: new Decimal(0),\n teamBalanceAfter: teamBal.balance,\n idempotent: false,\n error: null,\n };\n }\n\n const teamMetadata: CreditMetadata = {\n ...(options.metadata ?? {}),\n operation: metrics.operation,\n measures: { ...(metrics.measures ?? {}) },\n dimensions: Object.fromEntries(\n Object.entries(metrics.dimensions ?? {}).map(([key, value]) => [key, String(value)]),\n ),\n breakdownTotal: breakdown.total.toString(),\n };\n const result = await this.store.deductTeam(teamId, userId, cost, {\n metadata: teamMetadata,\n idempotencyKey,\n });\n // Surface store errors: emit credits.deduct_failed and throw,\n // mirroring the Python credit service implementation. Previously returned a silent\n // success-shaped object with an .error field, so failed charges looked OK.\n if (result.error !== null) {\n this.emit(\"credits.deduct_failed\", userId, {\n error: result.error,\n amount: cost,\n teamId,\n deductType: \"team\",\n });\n if (result.error === \"member_spend_cap_exceeded\") {\n throw new CapReachedError(\n `Team member spend cap exceeded. Team=${teamId}, user=${userId}, requested=${cost}`,\n );\n }\n throw new InsufficientCreditsError(\n `Team deduction failed: ${result.error}. Team=${teamId}, user=${userId}, requested=${cost}`,\n );\n }\n this.emit(\"credits.deducted\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n teamBalanceAfter: result.teamBalanceAfter,\n teamId,\n deductType: \"team\",\n });\n return result;\n }\n private async runSweep(dryRun: boolean, userId?: string): Promise<SweepResult> {\n const result = await this.store.sweepExpiredCredits(dryRun, userId);\n if (!dryRun && result.expiredCount > 0) {\n this.emit(\"credits.expired\", userId ?? \"system\", {\n expiredCount: result.expiredCount,\n expiredAmount: result.expiredAmount,\n expiredByBucket: result.expiredByBucket ?? null,\n });\n }\n return result;\n }\n\n /**\n * Sweep expired credits from all users' balances.\n *\n * When ``dryRun`` is true, reports what would expire without mutating\n * balances. Automatic lazy sweeps remain scoped to one subject.\n */\n async sweepExpiredCredits(dryRun = false): Promise<SweepResult> {\n return await this.runSweep(dryRun);\n }\n}\n"]}
@@ -1,6 +1,8 @@
1
1
  import type { Decimal } from "decimal.js";
2
2
  import type { AddCreditsResult, AddTeamMemberResult, AggregateStats, AllowanceResult, AvailableResult, BalanceResult, BillingMode, BucketBalancesResult, CheckFeatureResult, CreateTeamResult, CreditMetadata, DailySpendRow, DeductionResult, DeductWithAllowanceOptions, ExecuteGrantProgramRequest, GrantProgramAwardResult, GetUserPlanResult, ListQuotaEventsOptions, PlanMigrationBatchResult, PlanMigrationStartResult, QuotaEvent, QuotaState, LeaseResult, LeasePricingContext, ListLedgerEntriesOptions, ListUsageChargesOptions, ListUsageEntriesOptions, LedgerPage, UsageChargePage, UsageRecordResult, CatalogRevisionSummary, CatalogRevision, RefundResult, RevokeCreditsResult, ReleaseResult, SetUserPlanResult, UnsetUserPlanResult, SpendByModelRow, SpendByUserRow, SweepResult, TeamBalanceResult, TeamDeductionResult, TeamMember, TeamRole, TopUserRow, LedgerEntry } from "./types/index.js";
3
- import type { CatalogRollout } from "../config.js";
3
+ import type { BursarConfigData, CatalogRollout } from "../config.js";
4
+ import type { ProviderEnvironment } from "../providers/environment.js";
5
+ import type { AddCreditsOptions, DeductTeamOptions, RefundCreditsOptions } from "./service-types.js";
4
6
  export interface OperationUsageOptions {
5
7
  /** Entitlement feature that must be enabled for the operation. */
6
8
  feature?: string | null;
@@ -15,7 +17,7 @@ export interface CreateLeaseOptions extends OperationUsageOptions {
15
17
  * Replay-safe acquisition key. Supplying the same key with the same request
16
18
  * returns the original lease; conflicting reuse is rejected.
17
19
  */
18
- idempotencyKey?: string | null;
20
+ idempotencyKey: string;
19
21
  billingMode?: BillingMode;
20
22
  floor?: Decimal;
21
23
  maxConcurrent?: number | null;
@@ -23,9 +25,18 @@ export interface CreateLeaseOptions extends OperationUsageOptions {
23
25
  ttlSeconds?: number;
24
26
  metadata?: CreditMetadata | null;
25
27
  }
28
+ /** Options for replay-safe team creation. */
29
+ export interface CreateTeamOptions {
30
+ /**
31
+ * Caller-owned operation key. Reusing it with the same request returns the
32
+ * original team; changing the owner, name, or balance is rejected.
33
+ */
34
+ idempotencyKey: string;
35
+ initialBalance?: Decimal;
36
+ }
26
37
  /** Options for charging the actual cost against a lease. */
27
38
  export interface SettleLeaseOptions extends OperationUsageOptions {
28
- idempotencyKey?: string | null;
39
+ idempotencyKey?: string;
29
40
  metadata?: CreditMetadata | null;
30
41
  }
31
42
  /**
@@ -41,23 +52,17 @@ export interface SettleLeaseOptions extends OperationUsageOptions {
41
52
  * throws {@link CapabilityNotSupportedError} instead of forcing a stub.
42
53
  */
43
54
  export declare abstract class CreditStore {
55
+ /** Optional provider namespace exposed by environment-aware stores. */
56
+ readonly providerEnvironment?: ProviderEnvironment;
44
57
  constructor();
45
58
  abstract getBalance(userId: string): Promise<BalanceResult>;
46
- abstract addCredits(userId: string, amount: Decimal, type?: string, metadata?: CreditMetadata | null, expiresAt?: Date | null,
47
- /** Target credit bucket; omitted/`null` resolves to the config's default bucket. */
48
- bucket?: string | null,
49
- /**
50
- * Replay-safe idempotency key (parity with the `deduct`/`settle`/`refund`
51
- * idempotency idiom). When a prior grant for this `userId` carries the same
52
- * key, the prior result is returned unchanged and no new credits are granted.
53
- */
54
- idempotencyKey?: string | null): Promise<AddCreditsResult>;
59
+ abstract addCredits(userId: string, amount: Decimal, options: AddCreditsOptions): Promise<AddCreditsResult>;
55
60
  /**
56
61
  * Atomically calculate-and-charge in one server-side transaction:
57
62
  * consume free allowance, enforce plan policy and quotas, and debit the net
58
63
  * amount, idempotency-keyed end-to-end.
59
64
  */
60
- abstract deductWithAllowance(userId: string, amount: Decimal, options?: DeductWithAllowanceOptions): Promise<DeductionResult>;
65
+ abstract deductWithAllowance(userId: string, amount: Decimal, options: DeductWithAllowanceOptions): Promise<DeductionResult>;
61
66
  /**
62
67
  * Atomically acquire a lease (hold) — the only authoritative admission control.
63
68
  *
@@ -69,7 +74,7 @@ export declare abstract class CreditStore {
69
74
  * an ``active`` lease expiring after ``ttlSeconds``. Business failures are
70
75
  * returned via ``LeaseResult.error``; the store never raises domain exceptions.
71
76
  */
72
- abstract createLease(userId: string, amount: Decimal, operationType: string, options?: CreateLeaseOptions): Promise<LeaseResult>;
77
+ abstract createLease(userId: string, amount: Decimal, operationType: string, options: CreateLeaseOptions): Promise<LeaseResult>;
73
78
  /**
74
79
  * Charge the actual cost against a lease, then mark it settled.
75
80
  *
@@ -105,11 +110,11 @@ export declare abstract class CreditStore {
105
110
  */
106
111
  abstract getAvailable(userId: string): Promise<AvailableResult>;
107
112
  abstract getActiveCatalog(): Promise<CatalogRevision | null>;
108
- abstract publishAndActivateCatalog(config: Record<string, unknown>, label?: string | null, rollout?: CatalogRollout | Record<string, unknown> | null): Promise<string>;
109
- abstract publishCatalogDraft(config: Record<string, unknown>, label?: string | null): Promise<string>;
113
+ abstract publishAndActivateCatalog(config: BursarConfigData, label?: string | null, rollout?: CatalogRollout | null): Promise<string>;
114
+ abstract publishCatalogDraft(config: BursarConfigData, label?: string | null): Promise<string>;
110
115
  abstract getCatalogHistory(): Promise<CatalogRevisionSummary[]>;
111
116
  abstract getCatalogRevision(version: number): Promise<CatalogRevision | null>;
112
- abstract activateCatalogRevision(version: number, rollout?: CatalogRollout | Record<string, unknown> | null): Promise<string>;
117
+ abstract activateCatalogRevision(version: number, rollout?: CatalogRollout | null): Promise<string>;
113
118
  abstract getUserPlan(userId: string): Promise<GetUserPlanResult>;
114
119
  abstract setUserPlan(userId: string, planKey: string, planAssignedAt?: Date | null): Promise<SetUserPlanResult>;
115
120
  abstract unsetUserPlan(userId: string): Promise<UnsetUserPlanResult>;
@@ -122,9 +127,7 @@ export declare abstract class CreditStore {
122
127
  abstract listQuotaEvents(userId: string, options?: ListQuotaEventsOptions): Promise<QuotaEvent[]>;
123
128
  abstract checkAllowance(userId: string): Promise<AllowanceResult | null>;
124
129
  abstract revokeCreditsByEntryType(userId: string, entryType: string): Promise<RevokeCreditsResult>;
125
- abstract refundCredits(entryId: string, amount?: Decimal, reason?: string, metadata?: CreditMetadata | null,
126
- /** Replay-safe key; pass a unique key for multiple equal partial refunds. */
127
- idempotencyKey?: string | null): Promise<RefundResult>;
130
+ abstract refundCredits(entryId: string, options: RefundCreditsOptions): Promise<RefundResult>;
128
131
  /**
129
132
  * Sweep expired credit grants and debit the aggregate/tier balances.
130
133
  *
@@ -154,17 +157,17 @@ export declare abstract class CreditStore {
154
157
  /** Read metered usage charges, including allowance-covered events. */
155
158
  listUsageCharges(_userId: string, _options?: ListUsageChargesOptions): Promise<UsageChargePage>;
156
159
  /** Append priced usage telemetry without debiting the account again. */
157
- recordUsage(_userId: string, _operation: string, _requested: Decimal, _options?: DeductWithAllowanceOptions): Promise<UsageRecordResult>;
160
+ recordUsage(_userId: string, _operation: string, _requested: Decimal, _options: DeductWithAllowanceOptions): Promise<UsageRecordResult>;
158
161
  /**
159
162
  * Fetch a single transaction by ID. Returns `null` when the transaction
160
163
  * does not exist or belongs to a different user.
161
164
  */
162
165
  getLedgerEntry(_userId: string, _entryId: string): Promise<LedgerEntry | null>;
163
- createTeam(_ownerSubjectId: string, _name: string, _initialBalance?: Decimal): Promise<CreateTeamResult>;
166
+ createTeam(_ownerSubjectId: string, _name: string, _options: CreateTeamOptions): Promise<CreateTeamResult>;
164
167
  getTeamBalance(_teamId: string): Promise<TeamBalanceResult | null>;
165
168
  addTeamMember(_teamId: string, _userId: string, _role?: TeamRole, _spendCap?: Decimal | null): Promise<AddTeamMemberResult>;
166
169
  getTeamMembers(_teamId: string): Promise<TeamMember[]>;
167
170
  removeTeamMember(_teamId: string, _userId: string): Promise<boolean>;
168
- deductTeam(_teamId: string, _userId: string, _amount: Decimal, _metadata?: CreditMetadata | null, _idempotencyKey?: string | null): Promise<TeamDeductionResult>;
171
+ deductTeam(_teamId: string, _userId: string, _amount: Decimal, _options: DeductTeamOptions): Promise<TeamDeductionResult>;
169
172
  }
170
173
  //# sourceMappingURL=store.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/credits/store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAE1C,OAAO,KAAK,EACV,gBAAgB,EAChB,mBAAmB,EACnB,cAAc,EACd,eAAe,EACf,eAAe,EAC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O,CAAC,OAAO,CAAC;IAGpE,UAAU,CACd,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,OAAO,EAChB,SAAS,CAAC,EAAE,cAAc,GAAG,IAAI,EACjC,eAAe,CAAC,EAAE,MAAM,GAAG,IAAI,GAC9B,OAAO,CAAC,mBAAmB,CAAC;CAGhC"}
1
+ {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/credits/store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAE1C,OAAO,KAAK,EACV,gBAAgB,EAChB,mBAAmB,EACnB,cAAc,EACd,eAAe,EACf,eAAe,EACf,aAAa,EACb,WAAW,EACX,oBAAoB,EACpB,kBAAkB,EAClB,gBAAgB,EAChB,cAAc,EACd,aAAa,EACb,eAAe,EACf,0BAA0B,EAC1B,0BAA0B,EAC1B,uBAAuB,EACvB,iBAAiB,EACjB,sBAAsB,EACtB,wBAAwB,EACxB,wBAAwB,EACxB,UAAU,EACV,UAAU,EACV,WAAW,EACX,mBAAmB,EACnB,wBAAwB,EACxB,uBAAuB,EACvB,uBAAuB,EACvB,UAAU,EACV,eAAe,EACf,iBAAiB,EACjB,sBAAsB,EACtB,eAAe,EACf,YAAY,EACZ,mBAAmB,EACnB,aAAa,EACb,iBAAiB,EACjB,mBAAmB,EACnB,eAAe,EACf,cAAc,EACd,WAAW,EACX,iBAAiB,EACjB,mBAAmB,EACnB,UAAU,EACV,QAAQ,EACR,UAAU,EACV,WAAW,EACZ,MAAM,kBAAkB,CAAC;AAC1B,OAAO,KAAK,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AACrE,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AACvE,OAAO,KAAK,EACV,iBAAiB,EACjB,iBAAiB,EACjB,oBAAoB,EACrB,MAAM,oBAAoB,CAAC;AAE5B,MAAM,WAAW,qBAAqB;IACp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O,EAAE,MAAM,EACf,KAAK,CAAC,EAAE,QAAQ,EAChB,SAAS,CAAC,EAAE,OAAO,GAAG,IAAI,GACzB,OAAO,CAAC,mBAAmB,CAAC;IAGzB,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,EAAE,CAAC;IAGtD,gBAAgB,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAGpE,UAAU,CACd,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,OAAO,EAChB,QAAQ,EAAE,iBAAiB,GAC1B,OAAO,CAAC,mBAAmB,CAAC;CAGhC"}
@@ -12,6 +12,8 @@ import { CapabilityNotSupportedError } from "../errors.js";
12
12
  * throws {@link CapabilityNotSupportedError} instead of forcing a stub.
13
13
  */
14
14
  export class CreditStore {
15
+ /** Optional provider namespace exposed by environment-aware stores. */
16
+ providerEnvironment;
15
17
  constructor() { }
16
18
  /** Expire a bounded batch of abandoned leases and release their reservations. */
17
19
  async expireLeases(_limit) {
@@ -58,7 +60,7 @@ export class CreditStore {
58
60
  throw new CapabilityNotSupportedError("getLedgerEntry is not supported by this store");
59
61
  }
60
62
  // ── Team/shared balance pools (optional capability) ──────────────────
61
- async createTeam(_ownerSubjectId, _name, _initialBalance) {
63
+ async createTeam(_ownerSubjectId, _name, _options) {
62
64
  throw new CapabilityNotSupportedError("createTeam is not supported by this store");
63
65
  }
64
66
  async getTeamBalance(_teamId) {
@@ -73,7 +75,7 @@ export class CreditStore {
73
75
  async removeTeamMember(_teamId, _userId) {
74
76
  throw new CapabilityNotSupportedError("removeTeamMember is not supported by this store");
75
77
  }
76
- async deductTeam(_teamId, _userId, _amount, _metadata, _idempotencyKey) {
78
+ async deductTeam(_teamId, _userId, _amount, _options) {
77
79
  throw new CapabilityNotSupportedError("deductTeam is not supported by this store");
78
80
  }
79
81
  }
@@ -1 +1 @@
1
- {"version":3,"file":"store.js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CAAC,CAAC;IAC3F,CAAC;IAED,wEAAwE;IACxE,KAAK,CAAC,WAAW,CACf,OAAe,EACf,UAAkB,EAClB,UAAmB,EACnB,QAAqC;QAErC,MAAM,IAAI,2BAA2B,CAAC,4CAA4C,CAAC,CAAC;IACtF,CAAC;IAED,wEAAwE;IACxE;;;OAGG;IACH,KAAK,CAAC,cAAc,CAAC,OAAe,EAAE,QAAgB;QACpD,MAAM,IAAI,2BAA2B,CAAC,+CAA+C,CAAC,CAAC;IACzF,CAAC;IAED,wEAAwE;IACxE,KAAK,CAAC,UAAU,CACd,eAAuB,EACvB,KAAa,EACb,eAAyB;QAEzB,MAAM,IAAI,2BAA2B,CAAC,2CAA2C,CAAC,CAAC;IACrF,CAAC;IACD,KAAK,CAAC,cAAc,CAAC,OAAe;QAClC,MAAM,IAAI,2BAA2B,CAAC,+CAA+C,CAAC,CAAC;IACzF,CAAC;IACD,KAAK,CAAC,aAAa,CACjB,OAAe,EACf,OAAe,EACf,KAAgB,EAChB,SAA0B;QAE1B,MAAM,IAAI,2BAA2B,CAAC,8CAA8C,CAAC,CAAC;IACxF,CAAC;IACD,KAAK,CAAC,cAAc,CAAC,OAAe;QAClC,MAAM,IAAI,2BAA2B,CAAC,+CAA+C,CAAC,CAAC;IACzF,CAAC;IACD,KAAK,CAAC,gBAAgB,CAAC,OAAe,EAAE,OAAe;QACrD,MAAM,IAAI,2BAA2B,CAAC,iDAAiD,CAAC,CAAC;IAC3F,CAAC;IACD,KAAK,CAAC,UAAU,CACd,OAAe,EACf,OAAe,EACf,OAAgB,EAChB,SAAiC,EACjC,eAA+B;QAE/B,MAAM,IAAI,2BAA2B,CAAC,2CAA2C,CAAC,CAAC;IACrF,CAAC;CACF","sourcesContent":["import type { Decimal } from \"decimal.js\";\nimport { CapabilityNotSupportedError } from \"../errors.js\";\nimport type {\n AddCreditsResult,\n AddTeamMemberResult,\n AggregateStats,\n AllowanceResult,\n AvailableResult,\n BalanceResult,\n BillingMode,\n BucketBalancesResult,\n CheckFeatureResult,\n CreateTeamResult,\n CreditMetadata,\n DailySpendRow,\n DeductionResult,\n DeductWithAllowanceOptions,\n ExecuteGrantProgramRequest,\n GrantProgramAwardResult,\n GetUserPlanResult,\n ListQuotaEventsOptions,\n PlanMigrationBatchResult,\n PlanMigrationStartResult,\n QuotaEvent,\n QuotaState,\n LeaseResult,\n LeasePricingContext,\n ListLedgerEntriesOptions,\n ListUsageChargesOptions,\n ListUsageEntriesOptions,\n LedgerPage,\n UsageChargePage,\n UsageRecordResult,\n CatalogRevisionSummary,\n CatalogRevision,\n RefundResult,\n RevokeCreditsResult,\n ReleaseResult,\n SetUserPlanResult,\n UnsetUserPlanResult,\n SpendByModelRow,\n SpendByUserRow,\n SweepResult,\n TeamBalanceResult,\n TeamDeductionResult,\n TeamMember,\n TeamRole,\n TopUserRow,\n LedgerEntry,\n} from \"./types/index.js\";\nimport type { CatalogRollout } from \"../config.js\";\n\nexport interface OperationUsageOptions {\n /** Entitlement feature that must be enabled for the operation. */\n feature?: string | null;\n model?: string | null;\n region?: string | null;\n measures?: Record<string, unknown> | null;\n dimensions?: Record<string, unknown> | null;\n}\n\n/** Options for atomically acquiring a lease. */\nexport interface CreateLeaseOptions extends OperationUsageOptions {\n /**\n * Replay-safe acquisition key. Supplying the same key with the same request\n * returns the original lease; conflicting reuse is rejected.\n */\n idempotencyKey?: string | null;\n billingMode?: BillingMode;\n floor?: Decimal;\n maxConcurrent?: number | null;\n overdraftFloor?: Decimal | null;\n ttlSeconds?: number;\n metadata?: CreditMetadata | null;\n}\n\n/** Options for charging the actual cost against a lease. */\nexport interface SettleLeaseOptions extends OperationUsageOptions {\n idempotencyKey?: string | null;\n metadata?: CreditMetadata | null;\n}\n\n/**\n * Abstract base for credit storage backends.\n *\n * Split into two tiers:\n * - **Core** (abstract, must be implemented): balance/credit ops, the atomic\n * lease lifecycle, bursar-config versioning, plan management,\n * refunds, and expiry sweeping. Every backend needs these.\n * - **Optional capabilities** (concrete, default-throwing): usage analytics,\n * ledger listing, and shared team-balance pools. A custom store that\n * doesn't need these can skip them entirely — the default implementation\n * throws {@link CapabilityNotSupportedError} instead of forcing a stub.\n */\nexport abstract class CreditStore {\n constructor() {}\n\n abstract getBalance(userId: string): Promise<BalanceResult>;\n abstract addCredits(\n userId: string,\n amount: Decimal,\n type?: string,\n metadata?: CreditMetadata | null,\n expiresAt?: Date | null,\n /** Target credit bucket; omitted/`null` resolves to the config's default bucket. */\n bucket?: string | null,\n /**\n * Replay-safe idempotency key (parity with the `deduct`/`settle`/`refund`\n * idempotency idiom). When a prior grant for this `userId` carries the same\n * key, the prior result is returned unchanged and no new credits are granted.\n */\n idempotencyKey?: string | null,\n ): Promise<AddCreditsResult>;\n /**\n * Atomically calculate-and-charge in one server-side transaction:\n * consume free allowance, enforce plan policy and quotas, and debit the net\n * amount, idempotency-keyed end-to-end.\n */\n abstract deductWithAllowance(\n userId: string,\n amount: Decimal,\n options?: DeductWithAllowanceOptions,\n ): Promise<DeductionResult>;\n\n // ── Lease lifecycle (atomic admission) ─────────────────────────────\n //\n // The lease is the canonical admission primitive.\n // ``reserve``/``settle``/``release`` on the manager map onto these.\n // Leases reuse the credit_reservations table/records extended with a status\n // (active → settled | released | expired), a billing mode, and an overdraft\n // floor. ``available = balance − Σ(amount WHERE status='active' AND unexpired)``.\n\n /**\n * Atomically acquire a lease (hold) — the only authoritative admission control.\n *\n * Under one critical section the store: (1) ensures the balance row exists;\n * (2) enforces ``maxConcurrent`` by counting active leases for ``(userId,\n * operationType)``; (3) enforces plan entitlements and quotas; (4) computes\n * ``available = balance − Σ active holds`` and rejects with\n * ``error=\"insufficient_credits\"`` if ``available − amount < floor``; (5) inserts\n * an ``active`` lease expiring after ``ttlSeconds``. Business failures are\n * returned via ``LeaseResult.error``; the store never raises domain exceptions.\n */\n abstract createLease(\n userId: string,\n amount: Decimal,\n operationType: string,\n options?: CreateLeaseOptions,\n ): Promise<LeaseResult>;\n\n /**\n * Charge the actual cost against a lease, then mark it settled.\n *\n * De-clamped: charges ``amount`` even if it exceeds the lease hold (overdraft)\n * and never clamps to the reserved ceiling. The balance may go negative in\n * overdraft. ``amount === 0`` releases the lease without charging.\n * Lease-state failures (``lease_not_found``/``lease_expired``) are returned via\n * ``DeductionResult.error``; a replay returns the original result idempotently.\n */\n abstract settleLease(\n userId: string,\n leaseId: string,\n amount: Decimal,\n options?: SettleLeaseOptions,\n ): Promise<DeductionResult>;\n\n /** Read the immutable catalog and rate card captured at lease admission. */\n abstract getLeasePricingContext(\n userId: string,\n leaseId: string,\n ): Promise<LeasePricingContext | null>;\n\n /**\n * Release a lease without charging; safe to repeat after failed or aborted work.\n *\n * Transitions an ``active``/``expired`` lease to ``released`` and reports\n * ``released=true``; otherwise reports ``released=false`` with a ``reason``.\n */\n abstract releaseLease(userId: string, leaseId: string): Promise<ReleaseResult>;\n\n /**\n * Extend an active lease's TTL (long batch/agentic jobs, resolves B4).\n *\n * Returns ``error=\"lease_expired\"`` if the TTL already elapsed and\n * ``error=\"lease_not_found\"`` if missing/other-user/finalized.\n */\n abstract renewLease(userId: string, leaseId: string, ttlSeconds: number): Promise<LeaseResult>;\n\n /** Expire a bounded batch of abandoned leases and release their reservations. */\n async expireLeases(_limit?: number): Promise<number> {\n throw new CapabilityNotSupportedError(\"expireLeases is not supported by this store\");\n }\n\n /**\n * Advisory, non-locking read of ``available = balance − Σ active holds``.\n *\n * For UI only — never an admission gate; may be stale the instant it is read.\n */\n\n abstract getAvailable(userId: string): Promise<AvailableResult>;\n\n abstract getActiveCatalog(): Promise<CatalogRevision | null>;\n abstract publishAndActivateCatalog(\n config: Record<string, unknown>,\n label?: string | null,\n rollout?: CatalogRollout | Record<string, unknown> | null,\n ): Promise<string>;\n abstract publishCatalogDraft(\n config: Record<string, unknown>,\n label?: string | null,\n ): Promise<string>;\n\n // Catalog revision history and activation.\n abstract getCatalogHistory(): Promise<CatalogRevisionSummary[]>;\n abstract getCatalogRevision(version: number): Promise<CatalogRevision | null>;\n abstract activateCatalogRevision(\n version: number,\n rollout?: CatalogRollout | Record<string, unknown> | null,\n ): Promise<string>;\n\n abstract getUserPlan(userId: string): Promise<GetUserPlanResult>;\n abstract setUserPlan(\n userId: string,\n planKey: string,\n planAssignedAt?: Date | null,\n ): Promise<SetUserPlanResult>;\n abstract unsetUserPlan(userId: string): Promise<UnsetUserPlanResult>;\n abstract setPlanRevisionPin(userId: string, pinned: boolean): Promise<boolean>;\n abstract applyDuePlanChanges(limit?: number): Promise<number>;\n abstract startPlanMigration(\n fromPlanId: string | null,\n toPlanId: string,\n ): Promise<PlanMigrationStartResult>;\n abstract migratePlanBatch(\n migrationId: string,\n batchSize?: number,\n ): Promise<PlanMigrationBatchResult>;\n abstract checkFeature(userId: string, feature: string): Promise<CheckFeatureResult>;\n abstract getQuotaState(userId: string, quotaKey?: string | null): Promise<QuotaState[]>;\n abstract listQuotaEvents(userId: string, options?: ListQuotaEventsOptions): Promise<QuotaEvent[]>;\n abstract checkAllowance(userId: string): Promise<AllowanceResult | null>;\n\n abstract revokeCreditsByEntryType(\n userId: string,\n entryType: string,\n ): Promise<RevokeCreditsResult>;\n\n // ── Refunds ────────────────────────────────────────────────────────\n abstract refundCredits(\n entryId: string,\n amount?: Decimal,\n reason?: string,\n metadata?: CreditMetadata | null,\n /** Replay-safe key; pass a unique key for multiple equal partial refunds. */\n idempotencyKey?: string | null,\n ): Promise<RefundResult>;\n\n // ── Credit expiry ────────────────────────────────────────────────────\n /**\n * Sweep expired credit grants and debit the aggregate/tier balances.\n *\n * When `userId` is omitted (default), sweeps globally across every user —\n * unchanged behaviour/output shape from before this parameter existed. When\n * given, restricts the scan/expiry to that user's transactions only (used by\n * bounded expiry sweep operation).\n */\n abstract sweepExpiredCredits(\n dryRun?: boolean,\n userId?: string,\n limit?: number,\n ): Promise<SweepResult>;\n\n // ── Credit buckets ─────────────────────────────────────────────────────\n /**\n * Per-bucket credit balances for a user (credit buckets).\n *\n * Sorted by `priority` ascending. When no buckets are configured, synthesizes\n * a single `\"default\"` entry from the aggregate balance so the shape is\n * uniform either way.\n */\n abstract getBucketBalances(userId: string): Promise<BucketBalancesResult>;\n\n /** Execute one configured grant-program event. */\n async executeGrantProgram(\n _request: ExecuteGrantProgramRequest,\n ): Promise<GrantProgramAwardResult[]> {\n throw new CapabilityNotSupportedError(\"executeGrantProgram is not supported by this store\");\n }\n\n // ── Usage analytics (optional capability) ────────────────────────────\n async spendByUser(_start: Date, _end: Date): Promise<SpendByUserRow[]> {\n throw new CapabilityNotSupportedError(\"spendByUser is not supported by this store\");\n }\n async spendByModel(_start: Date, _end: Date): Promise<SpendByModelRow[]> {\n throw new CapabilityNotSupportedError(\"spendByModel is not supported by this store\");\n }\n async topUsers(_limit: number, _start: Date, _end: Date): Promise<TopUserRow[]> {\n throw new CapabilityNotSupportedError(\"topUsers is not supported by this store\");\n }\n async dailySpend(_start: Date, _end: Date): Promise<DailySpendRow[]> {\n throw new CapabilityNotSupportedError(\"dailySpend is not supported by this store\");\n }\n async aggregateStats(_start: Date, _end: Date): Promise<AggregateStats> {\n throw new CapabilityNotSupportedError(\"aggregateStats is not supported by this store\");\n }\n\n // ── Transaction listing (optional capability) ────────────────────────\n async listLedgerEntries(\n _userId: string,\n _options?: ListLedgerEntriesOptions,\n ): Promise<LedgerPage> {\n throw new CapabilityNotSupportedError(\"listLedgerEntries is not supported by this store\");\n }\n abstract listUsageEntries(userId: string, options?: ListUsageEntriesOptions): Promise<LedgerPage>;\n\n /** Read metered usage charges, including allowance-covered events. */\n async listUsageCharges(\n _userId: string,\n _options?: ListUsageChargesOptions,\n ): Promise<UsageChargePage> {\n throw new CapabilityNotSupportedError(\"listUsageCharges is not supported by this store\");\n }\n\n /** Append priced usage telemetry without debiting the account again. */\n async recordUsage(\n _userId: string,\n _operation: string,\n _requested: Decimal,\n _options?: DeductWithAllowanceOptions,\n ): Promise<UsageRecordResult> {\n throw new CapabilityNotSupportedError(\"recordUsage is not supported by this store\");\n }\n\n // ── Single transaction lookup (optional capability) ──────────────────\n /**\n * Fetch a single transaction by ID. Returns `null` when the transaction\n * does not exist or belongs to a different user.\n */\n async getLedgerEntry(_userId: string, _entryId: string): Promise<LedgerEntry | null> {\n throw new CapabilityNotSupportedError(\"getLedgerEntry is not supported by this store\");\n }\n\n // ── Team/shared balance pools (optional capability) ──────────────────\n async createTeam(\n _ownerSubjectId: string,\n _name: string,\n _initialBalance?: Decimal,\n ): Promise<CreateTeamResult> {\n throw new CapabilityNotSupportedError(\"createTeam is not supported by this store\");\n }\n async getTeamBalance(_teamId: string): Promise<TeamBalanceResult | null> {\n throw new CapabilityNotSupportedError(\"getTeamBalance is not supported by this store\");\n }\n async addTeamMember(\n _teamId: string,\n _userId: string,\n _role?: TeamRole,\n _spendCap?: Decimal | null,\n ): Promise<AddTeamMemberResult> {\n throw new CapabilityNotSupportedError(\"addTeamMember is not supported by this store\");\n }\n async getTeamMembers(_teamId: string): Promise<TeamMember[]> {\n throw new CapabilityNotSupportedError(\"getTeamMembers is not supported by this store\");\n }\n async removeTeamMember(_teamId: string, _userId: string): Promise<boolean> {\n throw new CapabilityNotSupportedError(\"removeTeamMember is not supported by this store\");\n }\n async deductTeam(\n _teamId: string,\n _userId: string,\n _amount: Decimal,\n _metadata?: CreditMetadata | null,\n _idempotencyKey?: string | null,\n ): Promise<TeamDeductionResult> {\n throw new CapabilityNotSupportedError(\"deductTeam is not supported by this store\");\n }\n}\n"]}
1
+ {"version":3,"file":"store.js","sourceRoot":"","sources":["../../src/credits/store.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAiG3D;;;;;;;;;;;GAWG;AACH,MAAM,OAAgB,WAAW;IAC/B,uEAAuE;IAC9D,mBAAmB,CAAuB;IACnD,gBAAe,CAAC;IAmFhB,iFAAiF;IACjF,KAAK,CAAC,YAAY,CAAC,MAAe;QAChC,MAAM,IAAI,2BAA2B,CAAC,6CAA6C,CAAC,CAAC;IACvF,CAAC;IAiFD,kDAAkD;IAClD,K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IACzF,CAAC;IAED,wEAAwE;IACxE,KAAK,CAAC,UAAU,CACd,eAAuB,EACvB,KAAa,EACb,QAA2B;QAE3B,MAAM,IAAI,2BAA2B,CAAC,2CAA2C,CAAC,CAAC;IACrF,CAAC;IACD,KAAK,CAAC,cAAc,CAAC,OAAe;QAClC,MAAM,IAAI,2BAA2B,CAAC,+CAA+C,CAAC,CAAC;IACzF,CAAC;IACD,KAAK,CAAC,aAAa,CACjB,OAAe,EACf,OAAe,EACf,KAAgB,EAChB,SAA0B;QAE1B,MAAM,IAAI,2BAA2B,CAAC,8CAA8C,CAAC,CAAC;IACxF,CAAC;IACD,KAAK,CAAC,cAAc,CAAC,OAAe;QAClC,MAAM,IAAI,2BAA2B,CAAC,+CAA+C,CAAC,CAAC;IACzF,CAAC;IACD,KAAK,CAAC,gBAAgB,CAAC,OAAe,EAAE,OAAe;QACrD,MAAM,IAAI,2BAA2B,CAAC,iDAAiD,CAAC,CAAC;IAC3F,CAAC;IACD,KAAK,CAAC,UAAU,CACd,OAAe,EACf,OAAe,EACf,OAAgB,EAChB,QAA2B;QAE3B,MAAM,IAAI,2BAA2B,CAAC,2CAA2C,CAAC,CAAC;IACrF,CAAC;CACF","sourcesContent":["import type { Decimal } from \"decimal.js\";\nimport { CapabilityNotSupportedError } from \"../errors.js\";\nimport type {\n AddCreditsResult,\n AddTeamMemberResult,\n AggregateStats,\n AllowanceResult,\n AvailableResult,\n BalanceResult,\n BillingMode,\n BucketBalancesResult,\n CheckFeatureResult,\n CreateTeamResult,\n CreditMetadata,\n DailySpendRow,\n DeductionResult,\n DeductWithAllowanceOptions,\n ExecuteGrantProgramRequest,\n GrantProgramAwardResult,\n GetUserPlanResult,\n ListQuotaEventsOptions,\n PlanMigrationBatchResult,\n PlanMigrationStartResult,\n QuotaEvent,\n QuotaState,\n LeaseResult,\n LeasePricingContext,\n ListLedgerEntriesOptions,\n ListUsageChargesOptions,\n ListUsageEntriesOptions,\n LedgerPage,\n UsageChargePage,\n UsageRecordResult,\n CatalogRevisionSummary,\n CatalogRevision,\n RefundResult,\n RevokeCreditsResult,\n ReleaseResult,\n SetUserPlanResult,\n UnsetUserPlanResult,\n SpendByModelRow,\n SpendByUserRow,\n SweepResult,\n TeamBalanceResult,\n TeamDeductionResult,\n TeamMember,\n TeamRole,\n TopUserRow,\n LedgerEntry,\n} from \"./types/index.js\";\nimport type { BursarConfigData, CatalogRollout } from \"../config.js\";\nimport type { ProviderEnvironment } from \"../providers/environment.js\";\nimport type {\n AddCreditsOptions,\n DeductTeamOptions,\n RefundCreditsOptions,\n} from \"./service-types.js\";\n\nexport interface OperationUsageOptions {\n /** Entitlement feature that must be enabled for the operation. */\n feature?: string | null;\n model?: string | null;\n region?: string | null;\n measures?: Record<string, unknown> | null;\n dimensions?: Record<string, unknown> | null;\n}\n\n/** Options for atomically acquiring a lease. */\nexport interface CreateLeaseOptions extends OperationUsageOptions {\n /**\n * Replay-safe acquisition key. Supplying the same key with the same request\n * returns the original lease; conflicting reuse is rejected.\n */\n idempotencyKey: string;\n billingMode?: BillingMode;\n floor?: Decimal;\n maxConcurrent?: number | null;\n overdraftFloor?: Decimal | null;\n ttlSeconds?: number;\n metadata?: CreditMetadata | null;\n}\n\n/** Options for replay-safe team creation. */\nexport interface CreateTeamOptions {\n /**\n * Caller-owned operation key. Reusing it with the same request returns the\n * original team; changing the owner, name, or balance is rejected.\n */\n idempotencyKey: string;\n initialBalance?: Decimal;\n}\n\n/** Options for charging the actual cost against a lease. */\nexport interface SettleLeaseOptions extends OperationUsageOptions {\n idempotencyKey?: string;\n metadata?: CreditMetadata | null;\n}\n\n/**\n * Abstract base for credit storage backends.\n *\n * Split into two tiers:\n * - **Core** (abstract, must be implemented): balance/credit ops, the atomic\n * lease lifecycle, bursar-config versioning, plan management,\n * refunds, and expiry sweeping. Every backend needs these.\n * - **Optional capabilities** (concrete, default-throwing): usage analytics,\n * ledger listing, and shared team-balance pools. A custom store that\n * doesn't need these can skip them entirely — the default implementation\n * throws {@link CapabilityNotSupportedError} instead of forcing a stub.\n */\nexport abstract class CreditStore {\n /** Optional provider namespace exposed by environment-aware stores. */\n readonly providerEnvironment?: ProviderEnvironment;\n constructor() {}\n\n abstract getBalance(userId: string): Promise<BalanceResult>;\n abstract addCredits(\n userId: string,\n amount: Decimal,\n options: AddCreditsOptions,\n ): Promise<AddCreditsResult>;\n /**\n * Atomically calculate-and-charge in one server-side transaction:\n * consume free allowance, enforce plan policy and quotas, and debit the net\n * amount, idempotency-keyed end-to-end.\n */\n abstract deductWithAllowance(\n userId: string,\n amount: Decimal,\n options: DeductWithAllowanceOptions,\n ): Promise<DeductionResult>;\n\n // ── Lease lifecycle (atomic admission) ─────────────────────────────\n //\n // The lease is the canonical admission primitive.\n // ``reserve``/``settle``/``release`` on the manager map onto these.\n // Leases reuse the credit_reservations table/records extended with a status\n // (active → settled | released | expired), a billing mode, and an overdraft\n // floor. ``available = balance − Σ(amount WHERE status='active' AND unexpired)``.\n\n /**\n * Atomically acquire a lease (hold) — the only authoritative admission control.\n *\n * Under one critical section the store: (1) ensures the balance row exists;\n * (2) enforces ``maxConcurrent`` by counting active leases for ``(userId,\n * operationType)``; (3) enforces plan entitlements and quotas; (4) computes\n * ``available = balance − Σ active holds`` and rejects with\n * ``error=\"insufficient_credits\"`` if ``available − amount < floor``; (5) inserts\n * an ``active`` lease expiring after ``ttlSeconds``. Business failures are\n * returned via ``LeaseResult.error``; the store never raises domain exceptions.\n */\n abstract createLease(\n userId: string,\n amount: Decimal,\n operationType: string,\n options: CreateLeaseOptions,\n ): Promise<LeaseResult>;\n\n /**\n * Charge the actual cost against a lease, then mark it settled.\n *\n * De-clamped: charges ``amount`` even if it exceeds the lease hold (overdraft)\n * and never clamps to the reserved ceiling. The balance may go negative in\n * overdraft. ``amount === 0`` releases the lease without charging.\n * Lease-state failures (``lease_not_found``/``lease_expired``) are returned via\n * ``DeductionResult.error``; a replay returns the original result idempotently.\n */\n abstract settleLease(\n userId: string,\n leaseId: string,\n amount: Decimal,\n options?: SettleLeaseOptions,\n ): Promise<DeductionResult>;\n\n /** Read the immutable catalog and rate card captured at lease admission. */\n abstract getLeasePricingContext(\n userId: string,\n leaseId: string,\n ): Promise<LeasePricingContext | null>;\n\n /**\n * Release a lease without charging; safe to repeat after failed or aborted work.\n *\n * Transitions an ``active``/``expired`` lease to ``released`` and reports\n * ``released=true``; otherwise reports ``released=false`` with a ``reason``.\n */\n abstract releaseLease(userId: string, leaseId: string): Promise<ReleaseResult>;\n\n /**\n * Extend an active lease's TTL (long batch/agentic jobs, resolves B4).\n *\n * Returns ``error=\"lease_expired\"`` if the TTL already elapsed and\n * ``error=\"lease_not_found\"`` if missing/other-user/finalized.\n */\n abstract renewLease(userId: string, leaseId: string, ttlSeconds: number): Promise<LeaseResult>;\n\n /** Expire a bounded batch of abandoned leases and release their reservations. */\n async expireLeases(_limit?: number): Promise<number> {\n throw new CapabilityNotSupportedError(\"expireLeases is not supported by this store\");\n }\n\n /**\n * Advisory, non-locking read of ``available = balance − Σ active holds``.\n *\n * For UI only — never an admission gate; may be stale the instant it is read.\n */\n\n abstract getAvailable(userId: string): Promise<AvailableResult>;\n\n abstract getActiveCatalog(): Promise<CatalogRevision | null>;\n abstract publishAndActivateCatalog(\n config: BursarConfigData,\n label?: string | null,\n rollout?: CatalogRollout | null,\n ): Promise<string>;\n abstract publishCatalogDraft(config: BursarConfigData, label?: string | null): Promise<string>;\n\n // Catalog revision history and activation.\n abstract getCatalogHistory(): Promise<CatalogRevisionSummary[]>;\n abstract getCatalogRevision(version: number): Promise<CatalogRevision | null>;\n abstract activateCatalogRevision(\n version: number,\n rollout?: CatalogRollout | null,\n ): Promise<string>;\n\n abstract getUserPlan(userId: string): Promise<GetUserPlanResult>;\n abstract setUserPlan(\n userId: string,\n planKey: string,\n planAssignedAt?: Date | null,\n ): Promise<SetUserPlanResult>;\n abstract unsetUserPlan(userId: string): Promise<UnsetUserPlanResult>;\n abstract setPlanRevisionPin(userId: string, pinned: boolean): Promise<boolean>;\n abstract applyDuePlanChanges(limit?: number): Promise<number>;\n abstract startPlanMigration(\n fromPlanId: string | null,\n toPlanId: string,\n ): Promise<PlanMigrationStartResult>;\n abstract migratePlanBatch(\n migrationId: string,\n batchSize?: number,\n ): Promise<PlanMigrationBatchResult>;\n abstract checkFeature(userId: string, feature: string): Promise<CheckFeatureResult>;\n abstract getQuotaState(userId: string, quotaKey?: string | null): Promise<QuotaState[]>;\n abstract listQuotaEvents(userId: string, options?: ListQuotaEventsOptions): Promise<QuotaEvent[]>;\n abstract checkAllowance(userId: string): Promise<AllowanceResult | null>;\n\n abstract revokeCreditsByEntryType(\n userId: string,\n entryType: string,\n ): Promise<RevokeCreditsResult>;\n\n // ── Refunds ────────────────────────────────────────────────────────\n abstract refundCredits(entryId: string, options: RefundCreditsOptions): Promise<RefundResult>;\n\n // ── Credit expiry ────────────────────────────────────────────────────\n /**\n * Sweep expired credit grants and debit the aggregate/tier balances.\n *\n * When `userId` is omitted (default), sweeps globally across every user —\n * unchanged behaviour/output shape from before this parameter existed. When\n * given, restricts the scan/expiry to that user's transactions only (used by\n * bounded expiry sweep operation).\n */\n abstract sweepExpiredCredits(\n dryRun?: boolean,\n userId?: string,\n limit?: number,\n ): Promise<SweepResult>;\n\n // ── Credit buckets ─────────────────────────────────────────────────────\n /**\n * Per-bucket credit balances for a user (credit buckets).\n *\n * Sorted by `priority` ascending. When no buckets are configured, synthesizes\n * a single `\"default\"` entry from the aggregate balance so the shape is\n * uniform either way.\n */\n abstract getBucketBalances(userId: string): Promise<BucketBalancesResult>;\n\n /** Execute one configured grant-program event. */\n async executeGrantProgram(\n _request: ExecuteGrantProgramRequest,\n ): Promise<GrantProgramAwardResult[]> {\n throw new CapabilityNotSupportedError(\"executeGrantProgram is not supported by this store\");\n }\n\n // ── Usage analytics (optional capability) ────────────────────────────\n async spendByUser(_start: Date, _end: Date): Promise<SpendByUserRow[]> {\n throw new CapabilityNotSupportedError(\"spendByUser is not supported by this store\");\n }\n async spendByModel(_start: Date, _end: Date): Promise<SpendByModelRow[]> {\n throw new CapabilityNotSupportedError(\"spendByModel is not supported by this store\");\n }\n async topUsers(_limit: number, _start: Date, _end: Date): Promise<TopUserRow[]> {\n throw new CapabilityNotSupportedError(\"topUsers is not supported by this store\");\n }\n async dailySpend(_start: Date, _end: Date): Promise<DailySpendRow[]> {\n throw new CapabilityNotSupportedError(\"dailySpend is not supported by this store\");\n }\n async aggregateStats(_start: Date, _end: Date): Promise<AggregateStats> {\n throw new CapabilityNotSupportedError(\"aggregateStats is not supported by this store\");\n }\n\n // ── Transaction listing (optional capability) ────────────────────────\n async listLedgerEntries(\n _userId: string,\n _options?: ListLedgerEntriesOptions,\n ): Promise<LedgerPage> {\n throw new CapabilityNotSupportedError(\"listLedgerEntries is not supported by this store\");\n }\n abstract listUsageEntries(userId: string, options?: ListUsageEntriesOptions): Promise<LedgerPage>;\n\n /** Read metered usage charges, including allowance-covered events. */\n async listUsageCharges(\n _userId: string,\n _options?: ListUsageChargesOptions,\n ): Promise<UsageChargePage> {\n throw new CapabilityNotSupportedError(\"listUsageCharges is not supported by this store\");\n }\n\n /** Append priced usage telemetry without debiting the account again. */\n async recordUsage(\n _userId: string,\n _operation: string,\n _requested: Decimal,\n _options: DeductWithAllowanceOptions,\n ): Promise<UsageRecordResult> {\n throw new CapabilityNotSupportedError(\"recordUsage is not supported by this store\");\n }\n\n // ── Single transaction lookup (optional capability) ──────────────────\n /**\n * Fetch a single transaction by ID. Returns `null` when the transaction\n * does not exist or belongs to a different user.\n */\n async getLedgerEntry(_userId: string, _entryId: string): Promise<LedgerEntry | null> {\n throw new CapabilityNotSupportedError(\"getLedgerEntry is not supported by this store\");\n }\n\n // ── Team/shared balance pools (optional capability) ──────────────────\n async createTeam(\n _ownerSubjectId: string,\n _name: string,\n _options: CreateTeamOptions,\n ): Promise<CreateTeamResult> {\n throw new CapabilityNotSupportedError(\"createTeam is not supported by this store\");\n }\n async getTeamBalance(_teamId: string): Promise<TeamBalanceResult | null> {\n throw new CapabilityNotSupportedError(\"getTeamBalance is not supported by this store\");\n }\n async addTeamMember(\n _teamId: string,\n _userId: string,\n _role?: TeamRole,\n _spendCap?: Decimal | null,\n ): Promise<AddTeamMemberResult> {\n throw new CapabilityNotSupportedError(\"addTeamMember is not supported by this store\");\n }\n async getTeamMembers(_teamId: string): Promise<TeamMember[]> {\n throw new CapabilityNotSupportedError(\"getTeamMembers is not supported by this store\");\n }\n async removeTeamMember(_teamId: string, _userId: string): Promise<boolean> {\n throw new CapabilityNotSupportedError(\"removeTeamMember is not supported by this store\");\n }\n async deductTeam(\n _teamId: string,\n _userId: string,\n _amount: Decimal,\n _options: DeductTeamOptions,\n ): Promise<TeamDeductionResult> {\n throw new CapabilityNotSupportedError(\"deductTeam is not supported by this store\");\n }\n}\n"]}
@@ -74,7 +74,7 @@ export interface DeductionFailure extends DeductionResultBase {
74
74
  }
75
75
  export type DeductionResult = DeductionSuccess | DeductionFailure;
76
76
  export interface DeductWithAllowanceOptions {
77
- idempotencyKey?: string | null;
77
+ idempotencyKey: string;
78
78
  operation?: string | null;
79
79
  feature?: string | null;
80
80
  model?: string | null;
@@ -1 +1 @@
1
- {"version":3,"file":"account.d.ts","sourceRoot":"","sources":["../../../src/credits/types/account.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAE1C,MAAM,MAAM,WAAW,GAAG,QAAQ,GAAG,WAAW,CAAC;AAEjD,MAAM,WAAW,cAAc;IAC7B,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;IAC1C,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC;IAC9E,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC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AAM,WAAW,WAAW;IAC1B,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,EAAE,OAAO,CAAC;IACvB,MAAM,EAAE,OAAO,CAAC;IAChB,eAAe,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAC1C"}
@@ -1 +1 @@
1
- {"version":3,"file":"account.js","sourceRoot":"","sources":["../../../src/credits/types/account.ts"],"names":[],"mappings":"","sourcesContent":["import type { Decimal } from \"decimal.js\";\n\nexport type BillingMode = \"strict\" | \"overdraft\";\n\nexport interface CreditMetadata {\n operation?: string | null;\n measures?: Record<string, unknown> | null;\n dimensions?: Record<string, string | number | boolean | Decimal.Value> | null;\n breakdownTotal?: string | null;\n referenceType?: string | null;\n referenceId?: string | null;\n idempotencyKey?: string | null;\n providerRequestId?: string | null;\n traceId?: string | null;\n spanId?: string | null;\n [key: string]: unknown;\n}\n\nexport interface BucketDefinition {\n label: string;\n priority: number;\n expires: boolean;\n ttlDays?: number | null;\n allowOverdraft?: boolean;\n default?: boolean;\n}\n\nexport interface BucketBalance {\n bucketKey: string;\n label: string;\n priority: number;\n expires: boolean;\n balance: Decimal;\n}\n\nexport interface BucketBalancesResult {\n userId: string;\n buckets: BucketBalance[];\n totalBalance: Decimal;\n}\n\nexport interface BalanceResult {\n userId: string;\n balance: Decimal;\n lifetimePurchased: Decimal;\n}\n\nexport interface AddCreditsResult {\n entryId: string;\n userId: string;\n amount: Decimal;\n newBalance: Decimal;\n lifetimePurchased: Decimal;\n /** Destination bucket for grants; `null` when a debit spans one or more lots. */\n bucket: string | null;\n idempotent: boolean;\n}\n\ninterface DeductionResultBase {\n userId: string;\n amount: Decimal;\n allowanceConsumed: Decimal;\n idempotent: boolean;\n}\n\n/** A committed usage charge. Allowance-only charges legitimately have no ledger entry. */\nexport interface DeductionSuccess extends DeductionResultBase {\n error: null;\n entryId: string | null;\n /** Canonical usage receipt, including zero-cost or allowance-only charges. */\n usageChargeId: string | null;\n balanceAfter: Decimal;\n bucketBreakdown: Record<string, Decimal> | null;\n}\n\n/** An expected database rejection. Nullable fields were not committed and are not fabricated. */\nexport interface DeductionFailure extends DeductionResultBase {\n error: string;\n entryId: null;\n usageChargeId: string | null;\n balanceAfter: Decimal | null;\n idempotent: false;\n bucketBreakdown: null;\n}\n\nexport type DeductionResult = DeductionSuccess | DeductionFailure;\n\nexport interface DeductWithAllowanceOptions {\n idempotencyKey?: string | null;\n operation?: string | null;\n feature?: string | null;\n model?: string | null;\n region?: string | null;\n measures?: Record<string, unknown> | null;\n dimensions?: Record<string, unknown> | null;\n metadata?: CreditMetadata | null;\n}\n\ninterface RefundResultBase {\n originalEntryId: string;\n userId: string | null;\n}\n\nexport interface RefundSuccess extends RefundResultBase {\n error: null;\n refundEntryId: string;\n userId: string;\n amount: Decimal;\n newBalance: Decimal;\n bucketBreakdown: Record<string, Decimal> | null;\n}\n\nexport interface RefundFailure extends RefundResultBase {\n error: string;\n refundEntryId: null;\n amount: Decimal | null;\n newBalance: Decimal | null;\n bucketBreakdown: null;\n}\n\nexport type RefundResult = RefundSuccess | RefundFailure;\n\n/** Credits removed from all remaining lots created by one ledger operation. */\nexport interface RevokeCreditsResult {\n userId: string;\n entryType: string;\n revoked: Decimal;\n balanceAfter: Decimal;\n}\n\nexport interface SweepResult {\n expiredCount: number;\n expiredAmount: Decimal;\n dryRun: boolean;\n expiredByBucket: Record<string, Decimal>;\n}\n"]}
1
+ {"version":3,"file":"account.js","sourceRoot":"","sources":["../../../src/credits/types/account.ts"],"names":[],"mappings":"","sourcesContent":["import type { Decimal } from \"decimal.js\";\n\nexport type BillingMode = \"strict\" | \"overdraft\";\n\nexport interface CreditMetadata {\n operation?: string | null;\n measures?: Record<string, unknown> | null;\n dimensions?: Record<string, string | number | boolean | Decimal.Value> | null;\n breakdownTotal?: string | null;\n referenceType?: string | null;\n referenceId?: string | null;\n idempotencyKey?: string | null;\n providerRequestId?: string | null;\n traceId?: string | null;\n spanId?: string | null;\n [key: string]: unknown;\n}\n\nexport interface BucketDefinition {\n label: string;\n priority: number;\n expires: boolean;\n ttlDays?: number | null;\n allowOverdraft?: boolean;\n default?: boolean;\n}\n\nexport interface BucketBalance {\n bucketKey: string;\n label: string;\n priority: number;\n expires: boolean;\n balance: Decimal;\n}\n\nexport interface BucketBalancesResult {\n userId: string;\n buckets: BucketBalance[];\n totalBalance: Decimal;\n}\n\nexport interface BalanceResult {\n userId: string;\n balance: Decimal;\n lifetimePurchased: Decimal;\n}\n\nexport interface AddCreditsResult {\n entryId: string;\n userId: string;\n amount: Decimal;\n newBalance: Decimal;\n lifetimePurchased: Decimal;\n /** Destination bucket for grants; `null` when a debit spans one or more lots. */\n bucket: string | null;\n idempotent: boolean;\n}\n\ninterface DeductionResultBase {\n userId: string;\n amount: Decimal;\n allowanceConsumed: Decimal;\n idempotent: boolean;\n}\n\n/** A committed usage charge. Allowance-only charges legitimately have no ledger entry. */\nexport interface DeductionSuccess extends DeductionResultBase {\n error: null;\n entryId: string | null;\n /** Canonical usage receipt, including zero-cost or allowance-only charges. */\n usageChargeId: string | null;\n balanceAfter: Decimal;\n bucketBreakdown: Record<string, Decimal> | null;\n}\n\n/** An expected database rejection. Nullable fields were not committed and are not fabricated. */\nexport interface DeductionFailure extends DeductionResultBase {\n error: string;\n entryId: null;\n usageChargeId: string | null;\n balanceAfter: Decimal | null;\n idempotent: false;\n bucketBreakdown: null;\n}\n\nexport type DeductionResult = DeductionSuccess | DeductionFailure;\n\nexport interface DeductWithAllowanceOptions {\n idempotencyKey: string;\n operation?: string | null;\n feature?: string | null;\n model?: string | null;\n region?: string | null;\n measures?: Record<string, unknown> | null;\n dimensions?: Record<string, unknown> | null;\n metadata?: CreditMetadata | null;\n}\n\ninterface RefundResultBase {\n originalEntryId: string;\n userId: string | null;\n}\n\nexport interface RefundSuccess extends RefundResultBase {\n error: null;\n refundEntryId: string;\n userId: string;\n amount: Decimal;\n newBalance: Decimal;\n bucketBreakdown: Record<string, Decimal> | null;\n}\n\nexport interface RefundFailure extends RefundResultBase {\n error: string;\n refundEntryId: null;\n amount: Decimal | null;\n newBalance: Decimal | null;\n bucketBreakdown: null;\n}\n\nexport type RefundResult = RefundSuccess | RefundFailure;\n\n/** Credits removed from all remaining lots created by one ledger operation. */\nexport interface RevokeCreditsResult {\n userId: string;\n entryType: string;\n revoked: Decimal;\n balanceAfter: Decimal;\n}\n\nexport interface SweepResult {\n expiredCount: number;\n expiredAmount: Decimal;\n dryRun: boolean;\n expiredByBucket: Record<string, Decimal>;\n}\n"]}