@zonastery/bursar 1.0.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (404) hide show
  1. package/README.md +189 -62
  2. package/dist/billing/auto-recharge-port.d.ts +3 -3
  3. package/dist/billing/auto-recharge-port.d.ts.map +1 -1
  4. package/dist/billing/auto-recharge-port.js.map +1 -1
  5. package/dist/billing/auto-recharge-service.d.ts +5 -4
  6. package/dist/billing/auto-recharge-service.d.ts.map +1 -1
  7. package/dist/billing/auto-recharge-service.js +64 -34
  8. package/dist/billing/auto-recharge-service.js.map +1 -1
  9. package/dist/billing/billing-service.d.ts +5 -5
  10. package/dist/billing/billing-service.d.ts.map +1 -1
  11. package/dist/billing/billing-service.js +2 -2
  12. package/dist/billing/billing-service.js.map +1 -1
  13. package/dist/billing/billing-store.d.ts +10 -9
  14. package/dist/billing/billing-store.d.ts.map +1 -1
  15. package/dist/billing/billing-store.js.map +1 -1
  16. package/dist/billing/contracts.d.ts +31 -31
  17. package/dist/billing/contracts.d.ts.map +1 -1
  18. package/dist/billing/contracts.js.map +1 -1
  19. package/dist/billing/event-handlers.d.ts.map +1 -1
  20. package/dist/billing/event-handlers.js +49 -10
  21. package/dist/billing/event-handlers.js.map +1 -1
  22. package/dist/billing/event-processor.d.ts +1 -0
  23. package/dist/billing/event-processor.d.ts.map +1 -1
  24. package/dist/billing/event-processor.js +37 -10
  25. package/dist/billing/event-processor.js.map +1 -1
  26. package/dist/billing/financial-event-handlers.d.ts.map +1 -1
  27. package/dist/billing/financial-event-handlers.js +69 -72
  28. package/dist/billing/financial-event-handlers.js.map +1 -1
  29. package/dist/billing/index.d.ts +2 -1
  30. package/dist/billing/index.d.ts.map +1 -1
  31. package/dist/billing/index.js.map +1 -1
  32. package/dist/billing/management.d.ts +5 -5
  33. package/dist/billing/management.d.ts.map +1 -1
  34. package/dist/billing/management.js +2 -2
  35. package/dist/billing/management.js.map +1 -1
  36. package/dist/billing/policy-window.js.map +1 -1
  37. package/dist/billing/postgres/repositories/auto-recharge.d.ts +3 -3
  38. package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -1
  39. package/dist/billing/postgres/repositories/auto-recharge.js +205 -60
  40. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
  41. package/dist/billing/postgres/repositories/customer.d.ts.map +1 -1
  42. package/dist/billing/postgres/repositories/customer.js +19 -11
  43. package/dist/billing/postgres/repositories/customer.js.map +1 -1
  44. package/dist/billing/postgres/repositories/dispute.d.ts.map +1 -1
  45. package/dist/billing/postgres/repositories/dispute.js +3 -1
  46. package/dist/billing/postgres/repositories/dispute.js.map +1 -1
  47. package/dist/billing/postgres/repositories/event.d.ts +14 -7
  48. package/dist/billing/postgres/repositories/event.d.ts.map +1 -1
  49. package/dist/billing/postgres/repositories/event.js +21 -20
  50. package/dist/billing/postgres/repositories/event.js.map +1 -1
  51. package/dist/billing/postgres/repositories/invoice.d.ts +3 -3
  52. package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -1
  53. package/dist/billing/postgres/repositories/invoice.js +53 -11
  54. package/dist/billing/postgres/repositories/invoice.js.map +1 -1
  55. package/dist/billing/postgres/repositories/offer.d.ts +20 -17
  56. package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
  57. package/dist/billing/postgres/repositories/offer.js +123 -57
  58. package/dist/billing/postgres/repositories/offer.js.map +1 -1
  59. package/dist/billing/postgres/repositories/payment.d.ts +23 -20
  60. package/dist/billing/postgres/repositories/payment.d.ts.map +1 -1
  61. package/dist/billing/postgres/repositories/payment.js +43 -37
  62. package/dist/billing/postgres/repositories/payment.js.map +1 -1
  63. package/dist/billing/postgres/repositories/preferences.d.ts +3 -9
  64. package/dist/billing/postgres/repositories/preferences.d.ts.map +1 -1
  65. package/dist/billing/postgres/repositories/preferences.js +45 -7
  66. package/dist/billing/postgres/repositories/preferences.js.map +1 -1
  67. package/dist/billing/postgres/repositories/refund.d.ts +1 -1
  68. package/dist/billing/postgres/repositories/refund.d.ts.map +1 -1
  69. package/dist/billing/postgres/repositories/refund.js +13 -9
  70. package/dist/billing/postgres/repositories/refund.js.map +1 -1
  71. package/dist/billing/postgres/repositories/subscription-change.d.ts +15 -0
  72. package/dist/billing/postgres/repositories/subscription-change.d.ts.map +1 -0
  73. package/dist/billing/postgres/repositories/subscription-change.js +234 -0
  74. package/dist/billing/postgres/repositories/subscription-change.js.map +1 -0
  75. package/dist/billing/postgres/repositories/subscription.d.ts +38 -17
  76. package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -1
  77. package/dist/billing/postgres/repositories/subscription.js +199 -91
  78. package/dist/billing/postgres/repositories/subscription.js.map +1 -1
  79. package/dist/billing/postgres/repositories/topup.d.ts +13 -15
  80. package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
  81. package/dist/billing/postgres/repositories/topup.js +65 -34
  82. package/dist/billing/postgres/repositories/topup.js.map +1 -1
  83. package/dist/billing/postgres/store.d.ts +23 -14
  84. package/dist/billing/postgres/store.d.ts.map +1 -1
  85. package/dist/billing/postgres/store.js +265 -228
  86. package/dist/billing/postgres/store.js.map +1 -1
  87. package/dist/billing/service-types.d.ts +6 -5
  88. package/dist/billing/service-types.d.ts.map +1 -1
  89. package/dist/billing/service-types.js.map +1 -1
  90. package/dist/billing/types/auto-recharge.d.ts +6 -4
  91. package/dist/billing/types/auto-recharge.d.ts.map +1 -1
  92. package/dist/billing/types/auto-recharge.js.map +1 -1
  93. package/dist/billing/types/catalog.d.ts +18 -35
  94. package/dist/billing/types/catalog.d.ts.map +1 -1
  95. package/dist/billing/types/catalog.js.map +1 -1
  96. package/dist/billing/types/common.d.ts +0 -1
  97. package/dist/billing/types/common.d.ts.map +1 -1
  98. package/dist/billing/types/common.js.map +1 -1
  99. package/dist/billing/types/documents.d.ts +38 -12
  100. package/dist/billing/types/documents.d.ts.map +1 -1
  101. package/dist/billing/types/documents.js.map +1 -1
  102. package/dist/billing/types/events.d.ts +2 -0
  103. package/dist/billing/types/events.d.ts.map +1 -1
  104. package/dist/billing/types/events.js +238 -0
  105. package/dist/billing/types/events.js.map +1 -1
  106. package/dist/billing/types/index.js.map +1 -1
  107. package/dist/billing/types/preferences.js.map +1 -1
  108. package/dist/billing/types/subscriptions.d.ts +8 -8
  109. package/dist/billing/types/subscriptions.d.ts.map +1 -1
  110. package/dist/billing/types/subscriptions.js.map +1 -1
  111. package/dist/breakdown.js.map +1 -1
  112. package/dist/browser.js.map +1 -1
  113. package/dist/bursar.d.ts +33 -11
  114. package/dist/bursar.d.ts.map +1 -1
  115. package/dist/bursar.js +58 -22
  116. package/dist/bursar.js.map +1 -1
  117. package/dist/catalog.d.ts +1 -0
  118. package/dist/catalog.d.ts.map +1 -1
  119. package/dist/catalog.js +1 -0
  120. package/dist/catalog.js.map +1 -1
  121. package/dist/commerce/errors.d.ts +4 -14
  122. package/dist/commerce/errors.d.ts.map +1 -1
  123. package/dist/commerce/errors.js +4 -21
  124. package/dist/commerce/errors.js.map +1 -1
  125. package/dist/commerce/index.d.ts +1 -0
  126. package/dist/commerce/index.d.ts.map +1 -1
  127. package/dist/commerce/index.js.map +1 -1
  128. package/dist/commerce/plan-change.js.map +1 -1
  129. package/dist/commerce/provider-registry.d.ts.map +1 -1
  130. package/dist/commerce/provider-registry.js +27 -2
  131. package/dist/commerce/provider-registry.js.map +1 -1
  132. package/dist/commerce/service.d.ts +15 -7
  133. package/dist/commerce/service.d.ts.map +1 -1
  134. package/dist/commerce/service.js +130 -77
  135. package/dist/commerce/service.js.map +1 -1
  136. package/dist/commerce/types.d.ts +33 -13
  137. package/dist/commerce/types.d.ts.map +1 -1
  138. package/dist/commerce/types.js.map +1 -1
  139. package/dist/config/parse-access.js.map +1 -1
  140. package/dist/config/parse-commerce.js.map +1 -1
  141. package/dist/config/parse-credits.js.map +1 -1
  142. package/dist/config/parse-plans.d.ts.map +1 -1
  143. package/dist/config/parse-plans.js +30 -13
  144. package/dist/config/parse-plans.js.map +1 -1
  145. package/dist/config/parse-pricing.d.ts.map +1 -1
  146. package/dist/config/parse-pricing.js +16 -5
  147. package/dist/config/parse-pricing.js.map +1 -1
  148. package/dist/config/parse-utils.js.map +1 -1
  149. package/dist/config/types.d.ts +14 -1
  150. package/dist/config/types.d.ts.map +1 -1
  151. package/dist/config/types.js.map +1 -1
  152. package/dist/config.d.ts +7 -1
  153. package/dist/config.d.ts.map +1 -1
  154. package/dist/config.js +64 -1
  155. package/dist/config.js.map +1 -1
  156. package/dist/credits/{pricing-runtime.d.ts → catalog-runtime.d.ts} +9 -8
  157. package/dist/credits/catalog-runtime.d.ts.map +1 -0
  158. package/dist/credits/{pricing-runtime.js → catalog-runtime.js} +58 -38
  159. package/dist/credits/catalog-runtime.js.map +1 -0
  160. package/dist/credits/events.d.ts +4 -4
  161. package/dist/credits/events.d.ts.map +1 -1
  162. package/dist/credits/events.js +1 -1
  163. package/dist/credits/events.js.map +1 -1
  164. package/dist/credits/lease-workflow.d.ts +14 -14
  165. package/dist/credits/lease-workflow.d.ts.map +1 -1
  166. package/dist/credits/lease-workflow.js +18 -17
  167. package/dist/credits/lease-workflow.js.map +1 -1
  168. package/dist/credits/low-balance-monitor.d.ts +2 -2
  169. package/dist/credits/low-balance-monitor.d.ts.map +1 -1
  170. package/dist/credits/low-balance-monitor.js.map +1 -1
  171. package/dist/credits/postgres/repositories/analytics.d.ts +39 -35
  172. package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -1
  173. package/dist/credits/postgres/repositories/analytics.js +55 -53
  174. package/dist/credits/postgres/repositories/analytics.js.map +1 -1
  175. package/dist/credits/postgres/repositories/balance.d.ts +28 -30
  176. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
  177. package/dist/credits/postgres/repositories/balance.js +100 -59
  178. package/dist/credits/postgres/repositories/balance.js.map +1 -1
  179. package/dist/credits/postgres/repositories/bucket.d.ts +14 -8
  180. package/dist/credits/postgres/repositories/bucket.d.ts.map +1 -1
  181. package/dist/credits/postgres/repositories/bucket.js +22 -21
  182. package/dist/credits/postgres/repositories/bucket.js.map +1 -1
  183. package/dist/credits/postgres/repositories/catalog.d.ts +31 -0
  184. package/dist/credits/postgres/repositories/catalog.d.ts.map +1 -0
  185. package/dist/credits/postgres/repositories/catalog.js +90 -0
  186. package/dist/credits/postgres/repositories/catalog.js.map +1 -0
  187. package/dist/credits/postgres/repositories/deduction.d.ts +32 -21
  188. package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -1
  189. package/dist/credits/postgres/repositories/deduction.js +171 -62
  190. package/dist/credits/postgres/repositories/deduction.js.map +1 -1
  191. package/dist/credits/postgres/repositories/lease.d.ts +21 -18
  192. package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
  193. package/dist/credits/postgres/repositories/lease.js +157 -65
  194. package/dist/credits/postgres/repositories/lease.js.map +1 -1
  195. package/dist/credits/postgres/repositories/plan.d.ts +94 -42
  196. package/dist/credits/postgres/repositories/plan.d.ts.map +1 -1
  197. package/dist/credits/postgres/repositories/plan.js +134 -104
  198. package/dist/credits/postgres/repositories/plan.js.map +1 -1
  199. package/dist/credits/postgres/repositories/team.d.ts +36 -27
  200. package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
  201. package/dist/credits/postgres/repositories/team.js +96 -52
  202. package/dist/credits/postgres/repositories/team.js.map +1 -1
  203. package/dist/credits/postgres/store.d.ts +31 -21
  204. package/dist/credits/postgres/store.d.ts.map +1 -1
  205. package/dist/credits/postgres/store.js +325 -235
  206. package/dist/credits/postgres/store.js.map +1 -1
  207. package/dist/credits/postgres/value-mappers.d.ts +7 -9
  208. package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
  209. package/dist/credits/postgres/value-mappers.js +42 -63
  210. package/dist/credits/postgres/value-mappers.js.map +1 -1
  211. package/dist/credits/queries.d.ts +5 -5
  212. package/dist/credits/queries.d.ts.map +1 -1
  213. package/dist/credits/queries.js +4 -4
  214. package/dist/credits/queries.js.map +1 -1
  215. package/dist/credits/service-errors.js.map +1 -1
  216. package/dist/credits/service-types.d.ts +42 -7
  217. package/dist/credits/service-types.d.ts.map +1 -1
  218. package/dist/credits/service-types.js.map +1 -1
  219. package/dist/credits/service.d.ts +51 -58
  220. package/dist/credits/service.d.ts.map +1 -1
  221. package/dist/credits/service.js +178 -113
  222. package/dist/credits/service.js.map +1 -1
  223. package/dist/credits/store.d.ts +25 -22
  224. package/dist/credits/store.d.ts.map +1 -1
  225. package/dist/credits/store.js +9 -5
  226. package/dist/credits/store.js.map +1 -1
  227. package/dist/credits/types/account.d.ts +50 -12
  228. package/dist/credits/types/account.d.ts.map +1 -1
  229. package/dist/credits/types/account.js.map +1 -1
  230. package/dist/credits/types/admission.d.ts +17 -6
  231. package/dist/credits/types/admission.d.ts.map +1 -1
  232. package/dist/credits/types/admission.js.map +1 -1
  233. package/dist/credits/types/analytics.d.ts +2 -2
  234. package/dist/credits/types/analytics.d.ts.map +1 -1
  235. package/dist/credits/types/analytics.js.map +1 -1
  236. package/dist/credits/types/catalog.d.ts +21 -14
  237. package/dist/credits/types/catalog.d.ts.map +1 -1
  238. package/dist/credits/types/catalog.js.map +1 -1
  239. package/dist/credits/types/grants.d.ts +22 -8
  240. package/dist/credits/types/grants.d.ts.map +1 -1
  241. package/dist/credits/types/grants.js.map +1 -1
  242. package/dist/credits/types/index.js.map +1 -1
  243. package/dist/credits/types/ledger.d.ts +19 -0
  244. package/dist/credits/types/ledger.d.ts.map +1 -1
  245. package/dist/credits/types/ledger.js.map +1 -1
  246. package/dist/credits/types/quotas.js.map +1 -1
  247. package/dist/credits/types/teams.d.ts +18 -6
  248. package/dist/credits/types/teams.d.ts.map +1 -1
  249. package/dist/credits/types/teams.js.map +1 -1
  250. package/dist/engine.d.ts.map +1 -1
  251. package/dist/engine.js +24 -10
  252. package/dist/engine.js.map +1 -1
  253. package/dist/errors.d.ts +105 -8
  254. package/dist/errors.d.ts.map +1 -1
  255. package/dist/errors.js +137 -9
  256. package/dist/errors.js.map +1 -1
  257. package/dist/expr/ast.d.ts.map +1 -1
  258. package/dist/expr/ast.js.map +1 -1
  259. package/dist/expr/evaluator.d.ts.map +1 -1
  260. package/dist/expr/evaluator.js +29 -17
  261. package/dist/expr/evaluator.js.map +1 -1
  262. package/dist/expr/language.js.map +1 -1
  263. package/dist/expr/parser.d.ts.map +1 -1
  264. package/dist/expr/parser.js +11 -4
  265. package/dist/expr/parser.js.map +1 -1
  266. package/dist/expr/tokenizer.d.ts.map +1 -1
  267. package/dist/expr/tokenizer.js +17 -13
  268. package/dist/expr/tokenizer.js.map +1 -1
  269. package/dist/expr.d.ts +2 -2
  270. package/dist/expr.d.ts.map +1 -1
  271. package/dist/expr.js +7 -9
  272. package/dist/expr.js.map +1 -1
  273. package/dist/generated/pricing-config.schema.json +30 -9
  274. package/dist/generated/pricing-config.types.d.ts +14 -3
  275. package/dist/generated/pricing-config.types.d.ts.map +1 -1
  276. package/dist/generated/pricing-config.types.js.map +1 -1
  277. package/dist/index.d.ts +11 -7
  278. package/dist/index.d.ts.map +1 -1
  279. package/dist/index.js +2 -2
  280. package/dist/index.js.map +1 -1
  281. package/dist/integrations/better-auth.d.ts +23 -0
  282. package/dist/integrations/better-auth.d.ts.map +1 -0
  283. package/dist/integrations/better-auth.js +54 -0
  284. package/dist/integrations/better-auth.js.map +1 -0
  285. package/dist/{load-pricing-file.d.ts → load-config-file.d.ts} +4 -4
  286. package/dist/load-config-file.d.ts.map +1 -0
  287. package/dist/{load-pricing-file.js → load-config-file.js} +23 -14
  288. package/dist/load-config-file.js.map +1 -0
  289. package/dist/metrics.js.map +1 -1
  290. package/dist/node.d.ts +3 -3
  291. package/dist/node.d.ts.map +1 -1
  292. package/dist/node.js +2 -2
  293. package/dist/node.js.map +1 -1
  294. package/dist/providers/_shared.d.ts +5 -0
  295. package/dist/providers/_shared.d.ts.map +1 -1
  296. package/dist/providers/_shared.js +77 -14
  297. package/dist/providers/_shared.js.map +1 -1
  298. package/dist/providers/dodo/better-auth.d.ts +29 -0
  299. package/dist/providers/dodo/better-auth.d.ts.map +1 -0
  300. package/dist/providers/dodo/better-auth.js +23 -0
  301. package/dist/providers/dodo/better-auth.js.map +1 -0
  302. package/dist/providers/dodo/client-contract.d.ts +32 -70
  303. package/dist/providers/dodo/client-contract.d.ts.map +1 -1
  304. package/dist/providers/dodo/client-contract.js.map +1 -1
  305. package/dist/providers/dodo/event-mapper.d.ts +3 -1
  306. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  307. package/dist/providers/dodo/event-mapper.js +219 -148
  308. package/dist/providers/dodo/event-mapper.js.map +1 -1
  309. package/dist/providers/dodo/index.d.ts +5 -2
  310. package/dist/providers/dodo/index.d.ts.map +1 -1
  311. package/dist/providers/dodo/index.js +2 -1
  312. package/dist/providers/dodo/index.js.map +1 -1
  313. package/dist/providers/dodo/nextjs.d.ts +16 -0
  314. package/dist/providers/dodo/nextjs.d.ts.map +1 -0
  315. package/dist/providers/dodo/nextjs.js +16 -0
  316. package/dist/providers/dodo/nextjs.js.map +1 -0
  317. package/dist/providers/dodo/provider.d.ts +30 -11
  318. package/dist/providers/dodo/provider.d.ts.map +1 -1
  319. package/dist/providers/dodo/provider.js +192 -122
  320. package/dist/providers/dodo/provider.js.map +1 -1
  321. package/dist/providers/dodo/react-native.d.ts +56 -0
  322. package/dist/providers/dodo/react-native.d.ts.map +1 -0
  323. package/dist/providers/dodo/react-native.js +57 -0
  324. package/dist/providers/dodo/react-native.js.map +1 -0
  325. package/dist/providers/dodo/webhook-bridge.d.ts +17 -0
  326. package/dist/providers/dodo/webhook-bridge.d.ts.map +1 -0
  327. package/dist/providers/dodo/webhook-bridge.js +21 -0
  328. package/dist/providers/dodo/webhook-bridge.js.map +1 -0
  329. package/dist/providers/index.d.ts +1 -1
  330. package/dist/providers/index.d.ts.map +1 -1
  331. package/dist/providers/index.js.map +1 -1
  332. package/dist/providers/mock/index.d.ts +1 -0
  333. package/dist/providers/mock/index.d.ts.map +1 -1
  334. package/dist/providers/mock/index.js.map +1 -1
  335. package/dist/providers/mock/provider.d.ts +8 -8
  336. package/dist/providers/mock/provider.d.ts.map +1 -1
  337. package/dist/providers/mock/provider.js +26 -19
  338. package/dist/providers/mock/provider.js.map +1 -1
  339. package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
  340. package/dist/providers/stripe/event-mapper.js +214 -173
  341. package/dist/providers/stripe/event-mapper.js.map +1 -1
  342. package/dist/providers/stripe/index.d.ts +1 -0
  343. package/dist/providers/stripe/index.d.ts.map +1 -1
  344. package/dist/providers/stripe/index.js.map +1 -1
  345. package/dist/providers/stripe/provider.d.ts +13 -11
  346. package/dist/providers/stripe/provider.d.ts.map +1 -1
  347. package/dist/providers/stripe/provider.js +287 -107
  348. package/dist/providers/stripe/provider.js.map +1 -1
  349. package/dist/providers/types.d.ts +1 -2
  350. package/dist/providers/types.d.ts.map +1 -1
  351. package/dist/providers/types.js.map +1 -1
  352. package/dist/retry.d.ts +26 -4
  353. package/dist/retry.d.ts.map +1 -1
  354. package/dist/retry.js +65 -23
  355. package/dist/retry.js.map +1 -1
  356. package/dist/shared/diagnostics.d.ts +7 -0
  357. package/dist/shared/diagnostics.d.ts.map +1 -0
  358. package/dist/shared/diagnostics.js +18 -0
  359. package/dist/shared/diagnostics.js.map +1 -0
  360. package/dist/shared/logger.js.map +1 -1
  361. package/dist/shared/postgres-client.d.ts +43 -5
  362. package/dist/shared/postgres-client.d.ts.map +1 -1
  363. package/dist/shared/postgres-client.js +282 -30
  364. package/dist/shared/postgres-client.js.map +1 -1
  365. package/dist/shared/postgres-errors.d.ts +11 -0
  366. package/dist/shared/postgres-errors.d.ts.map +1 -0
  367. package/dist/shared/postgres-errors.js +105 -0
  368. package/dist/shared/postgres-errors.js.map +1 -0
  369. package/dist/shared/postgres-types.js.map +1 -1
  370. package/dist/shared/postgres-validation.d.ts +15 -3
  371. package/dist/shared/postgres-validation.d.ts.map +1 -1
  372. package/dist/shared/postgres-validation.js +58 -14
  373. package/dist/shared/postgres-validation.js.map +1 -1
  374. package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
  375. package/dist/storage/adapters/clickhouse.js +18 -3
  376. package/dist/storage/adapters/clickhouse.js.map +1 -1
  377. package/dist/storage/adapters/s3.d.ts +0 -6
  378. package/dist/storage/adapters/s3.d.ts.map +1 -1
  379. package/dist/storage/adapters/s3.js +0 -2
  380. package/dist/storage/adapters/s3.js.map +1 -1
  381. package/dist/storage/outbox-worker.d.ts +2 -1
  382. package/dist/storage/outbox-worker.d.ts.map +1 -1
  383. package/dist/storage/outbox-worker.js +17 -3
  384. package/dist/storage/outbox-worker.js.map +1 -1
  385. package/dist/storage/ports.d.ts +1 -1
  386. package/dist/storage/ports.d.ts.map +1 -1
  387. package/dist/storage/ports.js.map +1 -1
  388. package/dist/storage/postgres-repository.d.ts +1 -1
  389. package/dist/storage/postgres-repository.d.ts.map +1 -1
  390. package/dist/storage/postgres-repository.js +13 -3
  391. package/dist/storage/postgres-repository.js.map +1 -1
  392. package/dist/storage/runtime.d.ts +35 -7
  393. package/dist/storage/runtime.d.ts.map +1 -1
  394. package/dist/storage/runtime.js +166 -53
  395. package/dist/storage/runtime.js.map +1 -1
  396. package/package.json +62 -7
  397. package/dist/credits/postgres/repositories/pricing.d.ts +0 -28
  398. package/dist/credits/postgres/repositories/pricing.d.ts.map +0 -1
  399. package/dist/credits/postgres/repositories/pricing.js +0 -70
  400. package/dist/credits/postgres/repositories/pricing.js.map +0 -1
  401. package/dist/credits/pricing-runtime.d.ts.map +0 -1
  402. package/dist/credits/pricing-runtime.js.map +0 -1
  403. package/dist/load-pricing-file.d.ts.map +0 -1
  404. package/dist/load-pricing-file.js.map +0 -1
@@ -1,27 +1,33 @@
1
1
  import Decimal from "decimal.js";
2
2
  import { randomUUID } from "node:crypto";
3
- import { CapReachedError, ConfigError, InsufficientCreditsError, RefundError } from "../errors.js";
3
+ import { CapReachedError, ConfigError, InsufficientCreditsError, RefundError, StoreError, } from "../errors.js";
4
4
  import { raiseDeductError } from "./service-errors.js";
5
5
  import { LowBalanceMonitor } from "./low-balance-monitor.js";
6
6
  import { CreditQueries } from "./queries.js";
7
- import { PricingRuntime, toDecimal } from "./pricing-runtime.js";
7
+ import { CatalogRuntime, toDecimal } from "./catalog-runtime.js";
8
8
  import { CreditLeaseWorkflow } from "./lease-workflow.js";
9
9
  /**
10
- * Default lease TTL (seconds) for ``reserve``/``runBilled`` (interface plan §3).
10
+ * Default lease TTL (seconds) for ``reserve`` and ``runBilled``.
11
11
  * Long batch/agentic jobs call the configured lease TTL before this elapses.
12
12
  */
13
13
  const DEFAULT_LEASE_TTL_SECONDS = 600;
14
14
  const POLICY_PRESETS = new Set(["strict_prepaid", "overdraft"]);
15
+ function positiveAmount(value, operation) {
16
+ const amount = toDecimal(value);
17
+ if (!amount.isFinite() || !amount.gt(0)) {
18
+ throw new RangeError(`${operation} amount must be finite and greater than zero`);
19
+ }
20
+ return amount;
21
+ }
15
22
  import { normalizeLogger } from "../shared/logger.js";
16
23
  /**
17
24
  * Orchestrates credit operations.
18
25
  *
19
26
  * The deduction path is a single atomic, idempotency-keyed store call
20
27
  * (``deductWithAllowance``) that consumes free allowance, enforces plan policy,
21
- * and debits the net amount in one transaction
22
- * (contract §2). The manager is a thin layer that calculates the cost, maps
28
+ * and debits the net amount in one transaction. The service calculates the cost, maps
23
29
  * the store's typed ``error`` codes to exceptions, and emits lifecycle events
24
- * **only after** the operation has succeeded (contract §6).
30
+ * **only after** the operation has succeeded.
25
31
  *
26
32
  * Optionally accepts a ``CreditEventEmitter`` to emit lifecycle events
27
33
  * (deducted, deduct_failed, added, refunded, refund_failed, expired,
@@ -30,7 +36,7 @@ import { normalizeLogger } from "../shared/logger.js";
30
36
  export class CreditsService {
31
37
  store;
32
38
  queries;
33
- pricing;
39
+ catalogRuntime;
34
40
  leases;
35
41
  emitter = null;
36
42
  balanceMonitor;
@@ -52,10 +58,10 @@ export class CreditsService {
52
58
  this.logger = normalizeLogger(options?.logger);
53
59
  if (options?.postDeduction)
54
60
  this.postDeductionHooks.add(options.postDeduction);
55
- this.pricing = new PricingRuntime(store, engine ?? null, this.logger, options?.pricingTtl ?? 300_000);
61
+ this.catalogRuntime = new CatalogRuntime(store, engine ?? null, this.logger, options?.catalogCacheTtlMs ?? 300_000);
56
62
  this.balanceMonitor = new LowBalanceMonitor(options?.lowBalance, (type, userId, data) => this.emit(type, userId, data), this.logger);
57
63
  this.lazyExpiry = options?.lazyExpiry ?? false;
58
- this.leases = new CreditLeaseWorkflow(store, this.pricing, this.logger, this.balanceMonitor, policy, options?.overdraftFloor != null ? toDecimal(options.overdraftFloor) : null, options?.maxConcurrent ?? null, options?.defaultTtlSeconds ?? DEFAULT_LEASE_TTL_SECONDS, (type, userId, data) => this.emit(type, userId, data), (userId, idempotencyKey) => this.emitQuotaEvents(userId, idempotencyKey), (userId) => this.maybeLazyExpire(userId), (userId, result) => this.afterDeduction(userId, "settle", result));
64
+ this.leases = new CreditLeaseWorkflow(store, this.catalogRuntime, this.logger, this.balanceMonitor, policy, options?.overdraftFloor != null ? toDecimal(options.overdraftFloor) : null, options?.maxConcurrent ?? null, options?.defaultTtlSeconds ?? DEFAULT_LEASE_TTL_SECONDS, (type, userId, data) => this.emit(type, userId, data), (userId, idempotencyKey) => this.emitQuotaEvents(userId, idempotencyKey), (userId) => this.maybeLazyExpire(userId), (userId, result) => this.afterDeduction(userId, "settle", result));
59
65
  }
60
66
  /**
61
67
  * Register an awaited post-commit deduction hook. A failing hook is logged
@@ -79,8 +85,8 @@ export class CreditsService {
79
85
  }
80
86
  }
81
87
  }
82
- async getActivePricing() {
83
- return this.queries.getActivePricing();
88
+ async getActiveCatalog() {
89
+ return this.queries.getActiveCatalog();
84
90
  }
85
91
  async getUserPlan(userId) {
86
92
  return this.queries.getUserPlan(userId);
@@ -101,7 +107,16 @@ export class CreditsService {
101
107
  return this.queries.migratePlanBatch(migrationId, batchSize);
102
108
  }
103
109
  async revokeCreditsByEntryType(userId, entryType) {
104
- return this.queries.revokeCreditsByEntryType(userId, entryType);
110
+ const result = await this.queries.revokeCreditsByEntryType(userId, entryType);
111
+ if (result.revoked.gt(0)) {
112
+ this.emit("credits.revoked", userId, {
113
+ userId,
114
+ entryType,
115
+ amount: result.revoked,
116
+ balanceAfter: result.balanceAfter,
117
+ });
118
+ }
119
+ return result;
105
120
  }
106
121
  /** Execute an application-driven catalog grant program. */
107
122
  async executeGrantProgram(request) {
@@ -163,62 +178,58 @@ export class CreditsService {
163
178
  }
164
179
  }
165
180
  }
166
- /** Load pricing from a raw dict and sync it. */
167
- async publishPricingFromDict(data) {
168
- await this.pricing.publishFromDict(data);
169
- }
170
- /** Load the active pricing config from the store. */
171
- async loadPricingFromStore() {
172
- await this.pricing.loadFromStore();
181
+ /** Load the active catalog revision from the store. */
182
+ async loadCatalogFromStore() {
183
+ await this.catalogRuntime.loadFromStore();
173
184
  }
174
185
  /**
175
186
  * If the cached PricingEngine is stale (TTL expired), reload it from the
176
187
  * store. Concurrent callers are deduplicated via the underlying
177
- * ``lru-cache.fetch()`` — only one ``loadPricingFromStore`` runs and all
188
+ * ``lru-cache.fetch()`` — only one ``loadCatalogFromStore`` runs and all
178
189
  * callers await the same result.
179
190
  *
180
- * When ``pricingTtl`` is ``0``, this is a no-op (the consumer must call
181
- * ``loadPricingFromStore`` manually).
191
+ * When ``catalogCacheTtlMs`` is ``0``, this is a no-op (the consumer must call
192
+ * ``loadCatalogFromStore`` manually).
182
193
  */
183
- async refreshIfStale() {
184
- await this.pricing.refreshIfStale();
194
+ async refreshCatalogIfStale() {
195
+ await this.catalogRuntime.refreshIfStale();
185
196
  }
186
197
  /**
187
- * Invalidate the pricing cache so the next ``refreshIfStale`` call
188
- * reloads from the store. Useful after a manual ``loadPricingFromStore``
198
+ * Invalidate the catalog cache so the next ``refreshCatalogIfStale`` call
199
+ * reloads from the store. Useful after a manual ``loadCatalogFromStore``
189
200
  * that bypasses the cache, or when the consumer knows the remote config
190
201
  * has changed.
191
202
  */
192
- invalidatePricing() {
193
- this.pricing.invalidate();
203
+ invalidateCatalog() {
204
+ this.catalogRuntime.invalidate();
194
205
  }
195
206
  /**
196
- * Publish new pricing and update the engine in one call.
207
+ * Publish and activate a catalog revision, then update the local engine.
197
208
  *
198
- * H10: the store write is now **awaited** (was a fire-and-forget `void`), so
209
+ * The store write is awaited, so
199
210
  * a persistence failure surfaces to the caller instead of becoming an
200
211
  * unhandled promise rejection.
201
212
  */
202
- async publishPricing(config, label) {
203
- await this.pricing.publish(config, label);
213
+ async publishAndActivateCatalog(config, label, rollout) {
214
+ return this.catalogRuntime.publishAndActivate(config, label, rollout);
204
215
  }
205
216
  /** Publish a validated, inactive catalog draft. */
206
- async publishPricingDraft(config, label) {
207
- return this.pricing.publishDraft(config, label);
217
+ async publishCatalogDraft(config, label) {
218
+ return this.catalogRuntime.publishDraft(config, label);
208
219
  }
209
220
  /** Activate an existing catalog version and reload the local engine. */
210
- async activatePricing(version) {
211
- return this.pricing.activate(version);
221
+ async activateCatalogRevision(version, rollout) {
222
+ return this.catalogRuntime.activateRevision(version, rollout);
212
223
  }
213
224
  /** The current PricingEngine, or null if not loaded. */
214
225
  get pricingEngine() {
215
- return this.pricing.currentEngine;
226
+ return this.catalogRuntime.currentEngine;
216
227
  }
217
228
  /**
218
229
  * Set a user's subscription plan and emit ``credits.plan_changed``.
219
230
  *
220
231
  * The store call is awaited so a persistence failure surfaces to the caller.
221
- * The event is emitted only after the store write succeeds (contract §6).
232
+ * The event is emitted only after the store write succeeds.
222
233
  */
223
234
  async setUserPlan(userId, planKey, planAssignedAt) {
224
235
  this.logger.info("[CreditsService] setUserPlan", { planKey, planAssignedAt });
@@ -226,18 +237,29 @@ export class CreditsService {
226
237
  this.emit("credits.plan_changed", userId, {
227
238
  userId,
228
239
  planKey,
229
- planAssignedAt: result.planAssignedAt ?? null,
240
+ planAssignedAt: result.planAssignedAt,
241
+ assignmentState: result.assignmentState,
230
242
  timestamp: new Date().toISOString(),
231
243
  });
244
+ return result;
232
245
  }
233
246
  /** Unset a user's subscription plan and emit the plan-change event. */
234
247
  async unsetUserPlan(userId) {
235
- await this.store.unsetUserPlan(userId);
248
+ const result = await this.store.unsetUserPlan(userId);
236
249
  this.emit("credits.plan_changed", userId, {
237
250
  userId,
238
251
  planKey: null,
239
252
  timestamp: new Date().toISOString(),
240
253
  });
254
+ return result;
255
+ }
256
+ /** Pin or unpin the user's current assignment revision. */
257
+ async setPlanRevisionPin(userId, pinned) {
258
+ return this.store.setPlanRevisionPin(userId, pinned);
259
+ }
260
+ /** Apply one bounded batch of renewal-effective plan changes. */
261
+ async applyDuePlanChanges(limit = 100) {
262
+ return this.store.applyDuePlanChanges(limit);
241
263
  }
242
264
  /** Sweep this user's expired lots when lazy expiry is enabled. */
243
265
  async maybeLazyExpire(userId) {
@@ -253,7 +275,7 @@ export class CreditsService {
253
275
  async addCredits(userId, amount, options) {
254
276
  const type = options?.type ?? "adjustment";
255
277
  this.logger.info("[CreditsService] addCredits", { amount, type, bucket: options?.bucket });
256
- const result = await this.store.addCredits(userId, toDecimal(amount), type, options?.metadata, options?.expiresAt, options?.bucket, options?.idempotencyKey);
278
+ const result = await this.store.addCredits(userId, positiveAmount(amount, "addCredits"), type, options?.metadata, options?.expiresAt, options?.bucket, options?.idempotencyKey);
257
279
  this.emit("credits.added", userId, {
258
280
  entryId: result.entryId,
259
281
  amount: result.amount,
@@ -279,21 +301,27 @@ export class CreditsService {
279
301
  entryType,
280
302
  bucket: options?.bucket,
281
303
  });
282
- const result = await this.store.addCredits(userId, toDecimal(amount).neg(), entryType, options?.metadata ?? null, null, options?.bucket ?? undefined, undefined);
304
+ const result = await this.store.addCredits(userId, positiveAmount(amount, "deductCredits").neg(), entryType, options?.metadata ?? null, null, options?.bucket ?? undefined, options?.idempotencyKey);
283
305
  this.emit("credits.deducted", userId, {
284
306
  entryId: result.entryId,
285
307
  amount: result.amount,
286
308
  newBalance: result.newBalance,
287
309
  entryType,
288
- });
289
- await this.afterDeduction(userId, "raw", {
290
- entryId: result.entryId,
291
- userId,
292
- amount: result.amount.abs(),
293
- allowanceConsumed: new Decimal(0),
294
- balanceAfter: result.newBalance,
295
310
  idempotent: result.idempotent ?? false,
296
311
  });
312
+ if (!result.idempotent) {
313
+ await this.afterDeduction(userId, "raw", {
314
+ entryId: result.entryId,
315
+ userId,
316
+ amount: result.amount.abs(),
317
+ allowanceConsumed: new Decimal(0),
318
+ balanceAfter: result.newBalance,
319
+ idempotent: false,
320
+ usageChargeId: null,
321
+ error: null,
322
+ bucketBreakdown: null,
323
+ });
324
+ }
297
325
  return result;
298
326
  }
299
327
  /**
@@ -304,14 +332,12 @@ export class CreditsService {
304
332
  * 1. At most one of ``expiresAt``/``ttlDays`` may be given (throws
305
333
  * ``ConfigError`` otherwise).
306
334
  * 2. When ``ttlDays`` is given, ``expiresAt = now + ttlDays`` days.
307
- * 3. When ``replacePrior`` (default ``true``), any remaining balance in
308
- * ``bucket`` is expired immediately via a direct ``store.addCredits``
309
- * negative adjustment — naturally idempotent (a replay finds the bucket
310
- * already at zero and skips the call).
311
- * 4. The new cycle is granted via a direct ``store.addCredits`` call
335
+ * 3. The new cycle is granted via a direct ``store.addCredits`` call
312
336
  * (bypassing {@link addCredits} so only ``credits.cycle_renewed`` fires,
313
337
  * not a duplicate ``credits.added``), threading ``idempotencyKey`` so a
314
338
  * redelivered webhook replays the prior grant instead of double-crediting.
339
+ * 4. Existing bucket credits are never removed here. Subscription renewal
340
+ * policies that replace prior lots run atomically through BillingService.
315
341
  * 5. When ``planKey`` is given, assigns it via {@link setUserPlan}.
316
342
  * 6. Emits ``credits.cycle_renewed`` and returns the grant result.
317
343
  */
@@ -325,32 +351,21 @@ export class CreditsService {
325
351
  throw new ConfigError("grantSubscriptionCycle: specify at most one of 'expiresAt' or 'ttlDays', not both");
326
352
  }
327
353
  const bucket = options?.bucket ?? "subscription";
328
- const replacePrior = options?.replacePrior ?? true;
329
354
  const expiresAt = options?.ttlDays != null
330
355
  ? new Date(Date.now() + options.ttlDays * 86_400_000)
331
356
  : options?.expiresAt;
332
- const amountDec = toDecimal(amount);
333
- // Snapshot the bucket's leftover balance before granting. A redelivered
334
- // webhook must skip the replace-prior wipe as well as the duplicate grant.
335
- let priorLeftover = new Decimal(0);
336
- if (replacePrior) {
337
- const bucketsBefore = await this.getBucketBalances(userId);
338
- const current = bucketsBefore.buckets.find((t) => t.bucketKey === bucket);
339
- if (current)
340
- priorLeftover = current.balance;
341
- }
342
- let result = await this.store.addCredits(userId, amountDec, "purchase", options?.metadata, expiresAt, bucket, options?.idempotencyKey);
357
+ const amountDec = positiveAmount(amount, "grantSubscriptionCycle");
358
+ const result = await this.store.addCredits(userId, amountDec, "purchase", options?.metadata, expiresAt, bucket, options?.idempotencyKey);
343
359
  // The store contract exposes the mutation's replay result directly, avoiding
344
360
  // a racy lifetime-balance comparison and an extra database round trip.
345
361
  const isFreshGrant = !result.idempotent;
346
- if (replacePrior && isFreshGrant && priorLeftover.gt(0)) {
347
- await this.store.addCredits(userId, priorLeftover.negated(), "adjustment", { reason: "cycle_replaced" }, undefined, bucket);
348
- // Reflect the post-replace balance so the returned result is accurate
349
- // (the grant call above only knows the pre-replace balance).
350
- result = { ...result, newBalance: (await this.getBalance(userId)).balance };
351
- }
352
362
  if (options?.planKey) {
353
- await this.setUserPlan(userId, options.planKey);
363
+ // A fresh cycle intentionally re-anchors plan-assignment windows. On a
364
+ // webhook replay, repair a previously interrupted grant->assignment saga
365
+ // without re-anchoring an assignment that already succeeded.
366
+ if (isFreshGrant || (await this.getUserPlan(userId)).planKey !== options.planKey) {
367
+ await this.setUserPlan(userId, options.planKey);
368
+ }
354
369
  }
355
370
  this.emit("credits.cycle_renewed", userId, {
356
371
  entryId: result.entryId,
@@ -359,10 +374,11 @@ export class CreditsService {
359
374
  bucket,
360
375
  planKey: options?.planKey ?? null,
361
376
  idempotencyKey: options?.idempotencyKey ?? null,
377
+ idempotent: result.idempotent,
362
378
  });
363
379
  return result;
364
380
  }
365
- // ── Lease lifecycle: atomic admission (interface plan §3/§4) ────────
381
+ // ── Lease lifecycle: atomic admission ───────────────────────────────
366
382
  async reserve(userId, metricsOrAmount, options) {
367
383
  return this.leases.reserve(userId, metricsOrAmount, options);
368
384
  }
@@ -391,7 +407,7 @@ export class CreditsService {
391
407
  return this.leases.beginBilledOperation(userId, options);
392
408
  }
393
409
  /**
394
- * Full deduction flow as one atomic store call (contract §2).
410
+ * Full deduction flow as one atomic store call.
395
411
  *
396
412
  * 1. ``breakdown = engine.calculate(metrics)``; ``cost = breakdown.total``
397
413
  * (exact `Decimal`, **no truncation**).
@@ -401,22 +417,23 @@ export class CreditsService {
401
417
  * On a store ``error`` a ``credits.deduct_failed`` event is emitted and a
402
418
  * typed exception is thrown. No success event is emitted on error.
403
419
  */
404
- async deduct(userId, metrics, idempotencyKey, metadata,
405
- /** Entitlement feature required for this operation. */
406
- feature) {
420
+ async deduct(userId, metrics, options) {
407
421
  await this.maybeLazyExpire(userId);
408
- this.logger.debug("[CreditsService] deduct", { model: metrics.dimensions?.model, feature });
409
- const engine = await this.pricing.engineForUser(userId);
422
+ this.logger.debug("[CreditsService] deduct", {
423
+ model: metrics.dimensions?.model,
424
+ feature: options?.feature,
425
+ });
426
+ const engine = await this.catalogRuntime.engineForUser(userId);
410
427
  const plan = await this.store.getUserPlan(userId);
411
- const effectiveIdempotencyKey = idempotencyKey ?? `usage:${randomUUID()}`;
412
- // 1) Calculate cost — exact Decimal, never truncated (H1).
428
+ const effectiveIdempotencyKey = options?.idempotencyKey ?? `usage:${randomUUID()}`;
429
+ // 1) Calculate cost as an exact Decimal, never truncated.
413
430
  const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });
414
431
  const cost = breakdown.total;
415
432
  // Build ledger metadata: caller fields FIRST, system fields LAST so the
416
- // system fields win (contract §5 / M7).
433
+ // protected system fields win.
417
434
  const meta = {};
418
- if (metadata) {
419
- for (const [k, v] of Object.entries(metadata)) {
435
+ if (options?.metadata) {
436
+ for (const [k, v] of Object.entries(options.metadata)) {
420
437
  if (v != null)
421
438
  meta[k] = v;
422
439
  }
@@ -426,10 +443,10 @@ export class CreditsService {
426
443
  meta["dimensions"] = { ...(metrics.dimensions ?? {}) };
427
444
  meta["breakdownTotal"] = breakdown.total.toString();
428
445
  meta["idempotencyKey"] = effectiveIdempotencyKey;
429
- const options = {
446
+ const deductionOptions = {
430
447
  idempotencyKey: effectiveIdempotencyKey,
431
448
  operation: metrics.operation,
432
- feature: feature ?? null,
449
+ feature: options?.feature ?? null,
433
450
  model: typeof metrics.dimensions?.model === "string" ? metrics.dimensions.model : null,
434
451
  region: typeof metrics.dimensions?.region === "string" ? metrics.dimensions.region : null,
435
452
  measures: { ...(metrics.measures ?? {}) },
@@ -438,8 +455,8 @@ export class CreditsService {
438
455
  };
439
456
  // 2) Atomic charge. This records zero-cost usage too, so authorization,
440
457
  // quotas, and usage history cannot be bypassed by a free rate.
441
- const result = await this.store.deductWithAllowance(userId, cost, options);
442
- if (result.error) {
458
+ const result = await this.store.deductWithAllowance(userId, cost, deductionOptions);
459
+ if (result.error !== null) {
443
460
  if (result.error === "quota_exceeded") {
444
461
  await this.emitQuotaEvents(userId, effectiveIdempotencyKey);
445
462
  }
@@ -447,7 +464,7 @@ export class CreditsService {
447
464
  error: result.error,
448
465
  amount: cost,
449
466
  model: metrics.dimensions?.model,
450
- feature,
467
+ feature: options?.feature,
451
468
  });
452
469
  this.emit("credits.deduct_failed", userId, {
453
470
  error: result.error,
@@ -465,7 +482,7 @@ export class CreditsService {
465
482
  model: metrics.dimensions?.model ?? null,
466
483
  idempotent: result.idempotent,
467
484
  });
468
- // low_balance is EDGE-triggered (M18): only fire when THIS deduction crossed
485
+ // low_balance is edge-triggered: only fire when this deduction crossed
469
486
  // the threshold. A replayed (idempotent) result did not move the balance, so
470
487
  // it never crosses. balanceBefore = balanceAfter + amount charged.
471
488
  if (!result.idempotent) {
@@ -476,6 +493,43 @@ export class CreditsService {
476
493
  }
477
494
  return result;
478
495
  }
496
+ /**
497
+ * Record priced usage for a workflow without debiting the account again.
498
+ *
499
+ * This supports priced usage receipts that should be retained without
500
+ * affecting the account balance, such as externally billed usage.
501
+ */
502
+ async recordUsage(userId, metrics, options) {
503
+ const engine = await this.catalogRuntime.engineForUser(userId);
504
+ const plan = await this.store.getUserPlan(userId);
505
+ const effectiveIdempotencyKey = options?.idempotencyKey ?? `usage-record:${randomUUID()}`;
506
+ const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });
507
+ const meta = {};
508
+ if (options?.metadata) {
509
+ for (const [key, value] of Object.entries(options.metadata)) {
510
+ if (value != null)
511
+ meta[key] = value;
512
+ }
513
+ }
514
+ meta.operation = metrics.operation;
515
+ meta.measures = { ...(metrics.measures ?? {}) };
516
+ meta.dimensions = { ...(metrics.dimensions ?? {}) };
517
+ meta.breakdownTotal = breakdown.total.toString();
518
+ meta.idempotencyKey = effectiveIdempotencyKey;
519
+ const result = await this.store.recordUsage(userId, metrics.operation, breakdown.total, {
520
+ idempotencyKey: effectiveIdempotencyKey,
521
+ operation: metrics.operation,
522
+ model: typeof metrics.dimensions?.model === "string" ? metrics.dimensions.model : null,
523
+ region: typeof metrics.dimensions?.region === "string" ? metrics.dimensions.region : null,
524
+ measures: { ...(metrics.measures ?? {}) },
525
+ dimensions: { ...(metrics.dimensions ?? {}) },
526
+ metadata: meta,
527
+ });
528
+ if (result.error !== null) {
529
+ throw new StoreError(`Usage record failed: ${result.error}`);
530
+ }
531
+ return result;
532
+ }
479
533
  /**
480
534
  * Refund a previous credit deduction.
481
535
  *
@@ -485,23 +539,29 @@ export class CreditsService {
485
539
  * refund).
486
540
  */
487
541
  /** Deduct the configured fixed cost for one named job. */
488
- async deductFlatJob(userId, jobName, idempotencyKey, metadata, feature) {
489
- return this.deduct(userId, { operation: jobName, measures: { jobs: 1 } }, idempotencyKey, metadata, feature);
490
- }
491
- async refundCredits(entryId, amount, reason, metadata, idempotencyKey) {
492
- const refundAmount = amount != null ? toDecimal(amount) : undefined;
493
- this.logger.info("[CreditsService] refundCredits", { entryId, refundAmount, reason });
494
- const result = await this.store.refundCredits(entryId, refundAmount, reason, metadata, idempotencyKey);
495
- if (result.error) {
542
+ async deductFlatJob(userId, jobName, options) {
543
+ return this.deduct(userId, { operation: jobName, measures: { jobs: 1 } }, options);
544
+ }
545
+ async refundCredits(entryId, options) {
546
+ const refundAmount = options?.amount != null ? positiveAmount(options.amount, "refundCredits") : undefined;
547
+ this.logger.info("[CreditsService] refundCredits", {
548
+ entryId,
549
+ refundAmount,
550
+ reason: options?.reason,
551
+ });
552
+ const result = await this.store.refundCredits(entryId, refundAmount, options?.reason, options?.metadata, options?.idempotencyKey);
553
+ if (result.error !== null) {
496
554
  this.logger.warn("[CreditsService] refundCredits failed", {
497
555
  entryId,
498
556
  error: result.error,
499
557
  });
500
- this.emit("credits.refund_failed", result.userId, {
501
- entryId,
502
- error: result.error,
503
- reason: reason ?? null,
504
- });
558
+ if (result.userId !== null) {
559
+ this.emit("credits.refund_failed", result.userId, {
560
+ entryId,
561
+ error: result.error,
562
+ reason: options?.reason ?? null,
563
+ });
564
+ }
505
565
  throw new RefundError(`Refund rejected: ${result.error}`);
506
566
  }
507
567
  this.emit("credits.refunded", result.userId, {
@@ -509,7 +569,7 @@ export class CreditsService {
509
569
  refundEntryId: result.refundEntryId,
510
570
  amount: result.amount,
511
571
  newBalance: result.newBalance,
512
- reason: reason ?? null,
572
+ reason: options?.reason ?? null,
513
573
  });
514
574
  return result;
515
575
  }
@@ -518,38 +578,43 @@ export class CreditsService {
518
578
  *
519
579
  * Calculates the cost via the pricing engine (exact `Decimal`, no truncation),
520
580
  * then debits the team balance. Threads an optional ``idempotencyKey`` through
521
- * to the store so retried team charges are not double-counted (H12).
581
+ * to the store so retried team charges are not double-counted.
522
582
  */
523
- async deductTeam(teamId, userId, metrics, idempotencyKey, metadata) {
583
+ async deductTeam(teamId, userId, metrics, options) {
524
584
  await this.maybeLazyExpire(userId);
525
585
  // Lazy expiry is scoped to the individual member's credits, not the team's
526
586
  // shared pool — there's no per-team expiry concept.
527
- const engine = await this.pricing.engineForUser(userId);
587
+ const engine = await this.catalogRuntime.engineForUser(userId);
528
588
  const plan = await this.store.getUserPlan(userId);
529
589
  const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });
530
590
  const cost = breakdown.total;
531
591
  if (cost.lte(0)) {
532
592
  const teamBal = await this.store.getTeamBalance(teamId);
593
+ if (teamBal === null) {
594
+ throw new StoreError(`Team not found: ${teamId}`);
595
+ }
533
596
  return {
534
- entryId: "",
597
+ entryId: null,
535
598
  teamId,
536
599
  userId,
537
600
  amount: new Decimal(0),
538
601
  teamBalanceAfter: teamBal.balance,
602
+ idempotent: false,
603
+ error: null,
539
604
  };
540
605
  }
541
606
  const teamMetadata = {
542
- ...(metadata ?? {}),
607
+ ...(options?.metadata ?? {}),
543
608
  operation: metrics.operation,
544
609
  measures: { ...(metrics.measures ?? {}) },
545
610
  dimensions: Object.fromEntries(Object.entries(metrics.dimensions ?? {}).map(([key, value]) => [key, String(value)])),
546
611
  breakdownTotal: breakdown.total.toString(),
547
612
  };
548
- const result = await this.store.deductTeam(teamId, userId, cost, teamMetadata, idempotencyKey);
549
- // H2 fix: surface store errors — emit credits.deduct_failed and throw,
613
+ const result = await this.store.deductTeam(teamId, userId, cost, teamMetadata, options?.idempotencyKey);
614
+ // Surface store errors: emit credits.deduct_failed and throw,
550
615
  // mirroring the Python credit service implementation. Previously returned a silent
551
616
  // success-shaped object with an .error field, so failed charges looked OK.
552
- if (result.error) {
617
+ if (result.error !== null) {
553
618
  this.emit("credits.deduct_failed", userId, {
554
619
  error: result.error,
555
620
  amount: cost,