@zonastery/bursar 0.0.1 → 1.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 (483) hide show
  1. package/README.md +85 -344
  2. package/dist/billing/auto-recharge-port.d.ts +27 -0
  3. package/dist/billing/auto-recharge-port.d.ts.map +1 -0
  4. package/dist/billing/auto-recharge-port.js +2 -0
  5. package/dist/billing/auto-recharge-port.js.map +1 -0
  6. package/dist/billing/auto-recharge-service.d.ts +43 -0
  7. package/dist/billing/auto-recharge-service.d.ts.map +1 -0
  8. package/dist/billing/auto-recharge-service.js +218 -0
  9. package/dist/billing/auto-recharge-service.js.map +1 -0
  10. package/dist/billing/billing-service.d.ts +71 -0
  11. package/dist/billing/billing-service.d.ts.map +1 -0
  12. package/dist/billing/billing-service.js +172 -0
  13. package/dist/billing/billing-service.js.map +1 -0
  14. package/dist/billing/billing-store.d.ts +59 -0
  15. package/dist/billing/billing-store.d.ts.map +1 -0
  16. package/dist/billing/billing-store.js +9 -0
  17. package/dist/billing/billing-store.js.map +1 -0
  18. package/dist/billing/contracts.d.ts +149 -0
  19. package/dist/billing/contracts.d.ts.map +1 -0
  20. package/dist/billing/contracts.js +2 -0
  21. package/dist/billing/contracts.js.map +1 -0
  22. package/dist/billing/event-handlers.d.ts +57 -0
  23. package/dist/billing/event-handlers.d.ts.map +1 -0
  24. package/dist/billing/event-handlers.js +667 -0
  25. package/dist/billing/event-handlers.js.map +1 -0
  26. package/dist/billing/event-processor.d.ts +19 -0
  27. package/dist/billing/event-processor.d.ts.map +1 -0
  28. package/dist/billing/event-processor.js +105 -0
  29. package/dist/billing/event-processor.js.map +1 -0
  30. package/dist/billing/financial-event-handlers.d.ts +26 -0
  31. package/dist/billing/financial-event-handlers.d.ts.map +1 -0
  32. package/dist/billing/financial-event-handlers.js +241 -0
  33. package/dist/billing/financial-event-handlers.js.map +1 -0
  34. package/dist/billing/index.d.ts +10 -0
  35. package/dist/billing/index.d.ts.map +1 -0
  36. package/dist/billing/index.js +6 -0
  37. package/dist/billing/index.js.map +1 -0
  38. package/dist/billing/management.d.ts +59 -0
  39. package/dist/billing/management.d.ts.map +1 -0
  40. package/dist/billing/management.js +113 -0
  41. package/dist/billing/management.js.map +1 -0
  42. package/dist/billing/policy-window.d.ts +24 -0
  43. package/dist/billing/policy-window.d.ts.map +1 -0
  44. package/dist/billing/policy-window.js +88 -0
  45. package/dist/billing/policy-window.js.map +1 -0
  46. package/dist/billing/postgres/repositories/auto-recharge.d.ts +32 -0
  47. package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -0
  48. package/dist/billing/postgres/repositories/auto-recharge.js +178 -0
  49. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -0
  50. package/dist/billing/postgres/repositories/customer.d.ts +12 -0
  51. package/dist/billing/postgres/repositories/customer.d.ts.map +1 -0
  52. package/dist/billing/postgres/repositories/customer.js +33 -0
  53. package/dist/billing/postgres/repositories/customer.js.map +1 -0
  54. package/dist/billing/postgres/repositories/dispute.d.ts +7 -0
  55. package/dist/billing/postgres/repositories/dispute.d.ts.map +1 -0
  56. package/dist/billing/postgres/repositories/dispute.js +18 -0
  57. package/dist/billing/postgres/repositories/dispute.js.map +1 -0
  58. package/dist/billing/postgres/repositories/event.d.ts +21 -0
  59. package/dist/billing/postgres/repositories/event.d.ts.map +1 -0
  60. package/dist/billing/postgres/repositories/event.js +47 -0
  61. package/dist/billing/postgres/repositories/event.js.map +1 -0
  62. package/dist/billing/postgres/repositories/invoice.d.ts +9 -0
  63. package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -0
  64. package/dist/billing/postgres/repositories/invoice.js +36 -0
  65. package/dist/billing/postgres/repositories/invoice.js.map +1 -0
  66. package/dist/billing/postgres/repositories/offer.d.ts +26 -0
  67. package/dist/billing/postgres/repositories/offer.d.ts.map +1 -0
  68. package/dist/billing/postgres/repositories/offer.js +73 -0
  69. package/dist/billing/postgres/repositories/offer.js.map +1 -0
  70. package/dist/billing/postgres/repositories/payment.d.ts +32 -0
  71. package/dist/billing/postgres/repositories/payment.d.ts.map +1 -0
  72. package/dist/billing/postgres/repositories/payment.js +78 -0
  73. package/dist/billing/postgres/repositories/payment.js.map +1 -0
  74. package/dist/billing/postgres/repositories/preferences.d.ts +15 -0
  75. package/dist/billing/postgres/repositories/preferences.d.ts.map +1 -0
  76. package/dist/billing/postgres/repositories/preferences.js +23 -0
  77. package/dist/billing/postgres/repositories/preferences.js.map +1 -0
  78. package/dist/billing/postgres/repositories/refund.d.ts +7 -0
  79. package/dist/billing/postgres/repositories/refund.d.ts.map +1 -0
  80. package/dist/billing/postgres/repositories/refund.js +32 -0
  81. package/dist/billing/postgres/repositories/refund.js.map +1 -0
  82. package/dist/billing/postgres/repositories/subscription.d.ts +46 -0
  83. package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -0
  84. package/dist/billing/postgres/repositories/subscription.js +187 -0
  85. package/dist/billing/postgres/repositories/subscription.js.map +1 -0
  86. package/dist/billing/postgres/repositories/topup.d.ts +27 -0
  87. package/dist/billing/postgres/repositories/topup.d.ts.map +1 -0
  88. package/dist/billing/postgres/repositories/topup.js +51 -0
  89. package/dist/billing/postgres/repositories/topup.js.map +1 -0
  90. package/dist/billing/postgres/store.d.ts +87 -0
  91. package/dist/billing/postgres/store.d.ts.map +1 -0
  92. package/dist/billing/postgres/store.js +527 -0
  93. package/dist/billing/postgres/store.js.map +1 -0
  94. package/dist/billing/service-types.d.ts +37 -0
  95. package/dist/billing/service-types.d.ts.map +1 -0
  96. package/dist/billing/service-types.js +2 -0
  97. package/dist/billing/service-types.js.map +1 -0
  98. package/dist/billing/types/auto-recharge.d.ts +56 -0
  99. package/dist/billing/types/auto-recharge.d.ts.map +1 -0
  100. package/dist/billing/types/auto-recharge.js +2 -0
  101. package/dist/billing/types/auto-recharge.js.map +1 -0
  102. package/dist/billing/types/catalog.d.ts +47 -0
  103. package/dist/billing/types/catalog.d.ts.map +1 -0
  104. package/dist/billing/types/catalog.js +2 -0
  105. package/dist/billing/types/catalog.js.map +1 -0
  106. package/dist/billing/types/common.d.ts +16 -0
  107. package/dist/billing/types/common.d.ts.map +1 -0
  108. package/dist/billing/types/common.js +2 -0
  109. package/dist/billing/types/common.js.map +1 -0
  110. package/dist/billing/types/documents.d.ts +39 -0
  111. package/dist/billing/types/documents.d.ts.map +1 -0
  112. package/dist/billing/types/documents.js +2 -0
  113. package/dist/billing/types/documents.js.map +1 -0
  114. package/dist/billing/types/events.d.ts +75 -0
  115. package/dist/billing/types/events.d.ts.map +1 -0
  116. package/dist/billing/types/events.js +38 -0
  117. package/dist/billing/types/events.js.map +1 -0
  118. package/dist/billing/types/index.d.ts +8 -0
  119. package/dist/billing/types/index.d.ts.map +1 -0
  120. package/dist/billing/types/index.js +8 -0
  121. package/dist/billing/types/index.js.map +1 -0
  122. package/dist/billing/types/preferences.d.ts +13 -0
  123. package/dist/billing/types/preferences.d.ts.map +1 -0
  124. package/dist/billing/types/preferences.js +2 -0
  125. package/dist/billing/types/preferences.js.map +1 -0
  126. package/dist/billing/types/subscriptions.d.ts +97 -0
  127. package/dist/billing/types/subscriptions.d.ts.map +1 -0
  128. package/dist/billing/types/subscriptions.js +12 -0
  129. package/dist/billing/types/subscriptions.js.map +1 -0
  130. package/dist/breakdown.d.ts +3 -1
  131. package/dist/breakdown.d.ts.map +1 -1
  132. package/dist/breakdown.js +4 -1
  133. package/dist/breakdown.js.map +1 -1
  134. package/dist/browser.d.ts +8 -0
  135. package/dist/browser.d.ts.map +1 -0
  136. package/dist/browser.js +7 -0
  137. package/dist/browser.js.map +1 -0
  138. package/dist/bursar.d.ts +80 -0
  139. package/dist/bursar.d.ts.map +1 -0
  140. package/dist/bursar.js +129 -0
  141. package/dist/bursar.js.map +1 -0
  142. package/dist/catalog.d.ts +61 -0
  143. package/dist/catalog.d.ts.map +1 -0
  144. package/dist/catalog.js +95 -0
  145. package/dist/catalog.js.map +1 -0
  146. package/dist/commerce/errors.d.ts +69 -0
  147. package/dist/commerce/errors.d.ts.map +1 -0
  148. package/dist/commerce/errors.js +107 -0
  149. package/dist/commerce/errors.js.map +1 -0
  150. package/dist/commerce/index.d.ts +6 -0
  151. package/dist/commerce/index.d.ts.map +1 -0
  152. package/dist/commerce/index.js +6 -0
  153. package/dist/commerce/index.js.map +1 -0
  154. package/dist/commerce/plan-change.d.ts +10 -0
  155. package/dist/commerce/plan-change.d.ts.map +1 -0
  156. package/dist/commerce/plan-change.js +42 -0
  157. package/dist/commerce/plan-change.js.map +1 -0
  158. package/dist/commerce/provider-registry.d.ts +18 -0
  159. package/dist/commerce/provider-registry.d.ts.map +1 -0
  160. package/dist/commerce/provider-registry.js +70 -0
  161. package/dist/commerce/provider-registry.js.map +1 -0
  162. package/dist/commerce/service.d.ts +73 -0
  163. package/dist/commerce/service.d.ts.map +1 -0
  164. package/dist/commerce/service.js +981 -0
  165. package/dist/commerce/service.js.map +1 -0
  166. package/dist/commerce/types.d.ts +217 -0
  167. package/dist/commerce/types.d.ts.map +1 -0
  168. package/dist/commerce/types.js.map +1 -0
  169. package/dist/config/parse-access.d.ts +6 -0
  170. package/dist/config/parse-access.d.ts.map +1 -0
  171. package/dist/config/parse-access.js +72 -0
  172. package/dist/config/parse-access.js.map +1 -0
  173. package/dist/config/parse-commerce.d.ts +3 -0
  174. package/dist/config/parse-commerce.d.ts.map +1 -0
  175. package/dist/config/parse-commerce.js +236 -0
  176. package/dist/config/parse-commerce.js.map +1 -0
  177. package/dist/config/parse-credits.d.ts +3 -0
  178. package/dist/config/parse-credits.d.ts.map +1 -0
  179. package/dist/config/parse-credits.js +99 -0
  180. package/dist/config/parse-credits.js.map +1 -0
  181. package/dist/config/parse-plans.d.ts +5 -0
  182. package/dist/config/parse-plans.d.ts.map +1 -0
  183. package/dist/config/parse-plans.js +126 -0
  184. package/dist/config/parse-plans.js.map +1 -0
  185. package/dist/config/parse-pricing.d.ts +4 -0
  186. package/dist/config/parse-pricing.d.ts.map +1 -0
  187. package/dist/config/parse-pricing.js +252 -0
  188. package/dist/config/parse-pricing.js.map +1 -0
  189. package/dist/config/parse-utils.d.ts +18 -0
  190. package/dist/config/parse-utils.d.ts.map +1 -0
  191. package/dist/config/parse-utils.js +118 -0
  192. package/dist/config/parse-utils.js.map +1 -0
  193. package/dist/config/types.d.ts +327 -0
  194. package/dist/config/types.d.ts.map +1 -0
  195. package/dist/config/types.js +2 -0
  196. package/dist/config/types.js.map +1 -0
  197. package/dist/config.d.ts +6 -22
  198. package/dist/config.d.ts.map +1 -1
  199. package/dist/config.js +82 -263
  200. package/dist/config.js.map +1 -1
  201. package/dist/{stores → credits}/events.d.ts +6 -6
  202. package/dist/credits/events.d.ts.map +1 -0
  203. package/dist/{stores → credits}/events.js +5 -5
  204. package/dist/credits/events.js.map +1 -0
  205. package/dist/credits/lease-workflow.d.ts +90 -0
  206. package/dist/credits/lease-workflow.d.ts.map +1 -0
  207. package/dist/credits/lease-workflow.js +378 -0
  208. package/dist/credits/lease-workflow.js.map +1 -0
  209. package/dist/credits/low-balance-monitor.d.ts +26 -0
  210. package/dist/credits/low-balance-monitor.d.ts.map +1 -0
  211. package/dist/credits/low-balance-monitor.js +110 -0
  212. package/dist/credits/low-balance-monitor.js.map +1 -0
  213. package/dist/credits/postgres/repositories/analytics.d.ts +77 -0
  214. package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -0
  215. package/dist/credits/postgres/repositories/analytics.js +151 -0
  216. package/dist/credits/postgres/repositories/analytics.js.map +1 -0
  217. package/dist/credits/postgres/repositories/balance.d.ts +66 -0
  218. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -0
  219. package/dist/credits/postgres/repositories/balance.js +139 -0
  220. package/dist/credits/postgres/repositories/balance.js.map +1 -0
  221. package/dist/credits/postgres/repositories/bucket.d.ts +25 -0
  222. package/dist/credits/postgres/repositories/bucket.d.ts.map +1 -0
  223. package/dist/credits/postgres/repositories/bucket.js +52 -0
  224. package/dist/credits/postgres/repositories/bucket.js.map +1 -0
  225. package/dist/credits/postgres/repositories/deduction.d.ts +55 -0
  226. package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -0
  227. package/dist/credits/postgres/repositories/deduction.js +130 -0
  228. package/dist/credits/postgres/repositories/deduction.js.map +1 -0
  229. package/dist/credits/postgres/repositories/lease.d.ts +69 -0
  230. package/dist/credits/postgres/repositories/lease.d.ts.map +1 -0
  231. package/dist/credits/postgres/repositories/lease.js +148 -0
  232. package/dist/credits/postgres/repositories/lease.js.map +1 -0
  233. package/dist/credits/postgres/repositories/plan.d.ts +105 -0
  234. package/dist/credits/postgres/repositories/plan.d.ts.map +1 -0
  235. package/dist/credits/postgres/repositories/plan.js +182 -0
  236. package/dist/credits/postgres/repositories/plan.js.map +1 -0
  237. package/dist/credits/postgres/repositories/pricing.d.ts +28 -0
  238. package/dist/credits/postgres/repositories/pricing.d.ts.map +1 -0
  239. package/dist/credits/postgres/repositories/pricing.js +70 -0
  240. package/dist/credits/postgres/repositories/pricing.js.map +1 -0
  241. package/dist/credits/postgres/repositories/team.d.ts +63 -0
  242. package/dist/credits/postgres/repositories/team.d.ts.map +1 -0
  243. package/dist/credits/postgres/repositories/team.js +120 -0
  244. package/dist/credits/postgres/repositories/team.js.map +1 -0
  245. package/dist/credits/postgres/store.d.ts +84 -0
  246. package/dist/credits/postgres/store.d.ts.map +1 -0
  247. package/dist/credits/postgres/store.js +765 -0
  248. package/dist/credits/postgres/store.js.map +1 -0
  249. package/dist/credits/postgres/value-mappers.d.ts +17 -0
  250. package/dist/credits/postgres/value-mappers.d.ts.map +1 -0
  251. package/dist/credits/postgres/value-mappers.js +98 -0
  252. package/dist/credits/postgres/value-mappers.js.map +1 -0
  253. package/dist/credits/pricing-runtime.d.ts +34 -0
  254. package/dist/credits/pricing-runtime.d.ts.map +1 -0
  255. package/dist/credits/pricing-runtime.js +141 -0
  256. package/dist/credits/pricing-runtime.js.map +1 -0
  257. package/dist/credits/queries.d.ts +33 -0
  258. package/dist/credits/queries.d.ts.map +1 -0
  259. package/dist/credits/queries.js +71 -0
  260. package/dist/credits/queries.js.map +1 -0
  261. package/dist/credits/service-errors.d.ts +4 -0
  262. package/dist/credits/service-errors.d.ts.map +1 -0
  263. package/dist/credits/service-errors.js +57 -0
  264. package/dist/credits/service-errors.js.map +1 -0
  265. package/dist/credits/service-types.d.ts +122 -0
  266. package/dist/credits/service-types.d.ts.map +1 -0
  267. package/dist/credits/service-types.js +2 -0
  268. package/dist/credits/service-types.js.map +1 -0
  269. package/dist/credits/service.d.ts +207 -0
  270. package/dist/credits/service.d.ts.map +1 -0
  271. package/dist/credits/service.js +594 -0
  272. package/dist/credits/service.js.map +1 -0
  273. package/dist/{stores/credit-store.d.ts → credits/store.d.ts} +67 -71
  274. package/dist/credits/store.d.ts.map +1 -0
  275. package/dist/{stores/credit-store.js → credits/store.js} +30 -6
  276. package/dist/credits/store.js.map +1 -0
  277. package/dist/credits/types/account.d.ts +82 -0
  278. package/dist/credits/types/account.d.ts.map +1 -0
  279. package/dist/credits/types/account.js +2 -0
  280. package/dist/credits/types/account.js.map +1 -0
  281. package/dist/credits/types/admission.d.ts +39 -0
  282. package/dist/credits/types/admission.d.ts.map +1 -0
  283. package/dist/credits/types/admission.js +2 -0
  284. package/dist/credits/types/admission.js.map +1 -0
  285. package/dist/credits/types/analytics.d.ts +52 -0
  286. package/dist/credits/types/analytics.d.ts.map +1 -0
  287. package/dist/credits/types/analytics.js +2 -0
  288. package/dist/credits/types/analytics.js.map +1 -0
  289. package/dist/credits/types/catalog.d.ts +69 -0
  290. package/dist/credits/types/catalog.d.ts.map +1 -0
  291. package/dist/credits/types/catalog.js +2 -0
  292. package/dist/credits/types/catalog.js.map +1 -0
  293. package/dist/credits/types/grants.d.ts +24 -0
  294. package/dist/credits/types/grants.d.ts.map +1 -0
  295. package/dist/credits/types/grants.js +2 -0
  296. package/dist/credits/types/grants.js.map +1 -0
  297. package/dist/credits/types/index.d.ts +9 -0
  298. package/dist/credits/types/index.d.ts.map +1 -0
  299. package/dist/credits/types/index.js +2 -0
  300. package/dist/credits/types/index.js.map +1 -0
  301. package/dist/credits/types/ledger.d.ts +77 -0
  302. package/dist/credits/types/ledger.d.ts.map +1 -0
  303. package/dist/credits/types/ledger.js +2 -0
  304. package/dist/credits/types/ledger.js.map +1 -0
  305. package/dist/credits/types/quotas.d.ts +40 -0
  306. package/dist/credits/types/quotas.d.ts.map +1 -0
  307. package/dist/credits/types/quotas.js +2 -0
  308. package/dist/credits/types/quotas.js.map +1 -0
  309. package/dist/credits/types/teams.d.ts +44 -0
  310. package/dist/credits/types/teams.d.ts.map +1 -0
  311. package/dist/credits/types/teams.js +2 -0
  312. package/dist/credits/types/teams.js.map +1 -0
  313. package/dist/engine.d.ts +18 -39
  314. package/dist/engine.d.ts.map +1 -1
  315. package/dist/engine.js +169 -145
  316. package/dist/engine.js.map +1 -1
  317. package/dist/errors.d.ts +84 -25
  318. package/dist/errors.d.ts.map +1 -1
  319. package/dist/errors.js +117 -24
  320. package/dist/errors.js.map +1 -1
  321. package/dist/expr/ast.d.ts +46 -0
  322. package/dist/expr/ast.d.ts.map +1 -0
  323. package/dist/expr/ast.js +18 -0
  324. package/dist/expr/ast.js.map +1 -0
  325. package/dist/expr/evaluator.d.ts +4 -0
  326. package/dist/expr/evaluator.d.ts.map +1 -0
  327. package/dist/expr/evaluator.js +144 -0
  328. package/dist/expr/evaluator.js.map +1 -0
  329. package/dist/expr/language.d.ts +5 -0
  330. package/dist/expr/language.d.ts.map +1 -0
  331. package/dist/expr/language.js +73 -0
  332. package/dist/expr/language.js.map +1 -0
  333. package/dist/expr/parser.d.ts +24 -0
  334. package/dist/expr/parser.d.ts.map +1 -0
  335. package/dist/expr/parser.js +175 -0
  336. package/dist/expr/parser.js.map +1 -0
  337. package/dist/expr/tokenizer.d.ts +7 -0
  338. package/dist/expr/tokenizer.d.ts.map +1 -0
  339. package/dist/expr/tokenizer.js +85 -0
  340. package/dist/expr/tokenizer.js.map +1 -0
  341. package/dist/expr.d.ts +7 -58
  342. package/dist/expr.d.ts.map +1 -1
  343. package/dist/expr.js +41 -640
  344. package/dist/expr.js.map +1 -1
  345. package/dist/generated/pricing-config.schema.json +2764 -0
  346. package/dist/generated/pricing-config.types.d.ts +674 -0
  347. package/dist/generated/pricing-config.types.d.ts.map +1 -0
  348. package/dist/generated/pricing-config.types.js +8 -0
  349. package/dist/generated/pricing-config.types.js.map +1 -0
  350. package/dist/index.d.ts +21 -15
  351. package/dist/index.d.ts.map +1 -1
  352. package/dist/index.js +13 -9
  353. package/dist/index.js.map +1 -1
  354. package/dist/load-pricing-file.d.ts.map +1 -1
  355. package/dist/load-pricing-file.js +61 -6
  356. package/dist/load-pricing-file.js.map +1 -1
  357. package/dist/metrics.d.ts +6 -16
  358. package/dist/metrics.d.ts.map +1 -1
  359. package/dist/node.d.ts +9 -2
  360. package/dist/node.d.ts.map +1 -1
  361. package/dist/node.js +6 -2
  362. package/dist/node.js.map +1 -1
  363. package/dist/providers/_shared.d.ts +9 -0
  364. package/dist/providers/_shared.d.ts.map +1 -0
  365. package/dist/providers/_shared.js +25 -0
  366. package/dist/providers/_shared.js.map +1 -0
  367. package/dist/providers/dodo/client-contract.d.ts +106 -0
  368. package/dist/providers/dodo/client-contract.d.ts.map +1 -0
  369. package/dist/providers/dodo/client-contract.js +2 -0
  370. package/dist/providers/dodo/client-contract.js.map +1 -0
  371. package/dist/providers/dodo/event-mapper.d.ts +6 -0
  372. package/dist/providers/dodo/event-mapper.d.ts.map +1 -0
  373. package/dist/providers/dodo/event-mapper.js +344 -0
  374. package/dist/providers/dodo/event-mapper.js.map +1 -0
  375. package/dist/providers/dodo/index.d.ts +4 -0
  376. package/dist/providers/dodo/index.d.ts.map +1 -0
  377. package/dist/providers/dodo/index.js +3 -0
  378. package/dist/providers/dodo/index.js.map +1 -0
  379. package/dist/providers/dodo/provider.d.ts +53 -0
  380. package/dist/providers/dodo/provider.d.ts.map +1 -0
  381. package/dist/providers/dodo/provider.js +353 -0
  382. package/dist/providers/dodo/provider.js.map +1 -0
  383. package/dist/providers/index.d.ts +9 -0
  384. package/dist/providers/index.d.ts.map +1 -0
  385. package/dist/providers/index.js +7 -0
  386. package/dist/providers/index.js.map +1 -0
  387. package/dist/providers/mock/index.d.ts +2 -0
  388. package/dist/providers/mock/index.d.ts.map +1 -0
  389. package/dist/providers/mock/index.js +2 -0
  390. package/dist/providers/mock/index.js.map +1 -0
  391. package/dist/providers/mock/provider.d.ts +41 -0
  392. package/dist/providers/mock/provider.d.ts.map +1 -0
  393. package/dist/providers/mock/provider.js +124 -0
  394. package/dist/providers/mock/provider.js.map +1 -0
  395. package/dist/providers/stripe/event-mapper.d.ts +7 -0
  396. package/dist/providers/stripe/event-mapper.d.ts.map +1 -0
  397. package/dist/providers/stripe/event-mapper.js +342 -0
  398. package/dist/providers/stripe/event-mapper.js.map +1 -0
  399. package/dist/providers/stripe/index.d.ts +3 -0
  400. package/dist/providers/stripe/index.d.ts.map +1 -0
  401. package/dist/providers/stripe/index.js +3 -0
  402. package/dist/providers/stripe/index.js.map +1 -0
  403. package/dist/providers/stripe/provider.d.ts +48 -0
  404. package/dist/providers/stripe/provider.d.ts.map +1 -0
  405. package/dist/providers/stripe/provider.js +289 -0
  406. package/dist/providers/stripe/provider.js.map +1 -0
  407. package/dist/providers/types.d.ts +175 -0
  408. package/dist/providers/types.d.ts.map +1 -0
  409. package/dist/providers/types.js +18 -0
  410. package/dist/providers/types.js.map +1 -0
  411. package/dist/retry.d.ts +13 -0
  412. package/dist/retry.d.ts.map +1 -0
  413. package/dist/retry.js +28 -0
  414. package/dist/retry.js.map +1 -0
  415. package/dist/shared/logger.d.ts +10 -0
  416. package/dist/shared/logger.d.ts.map +1 -0
  417. package/dist/shared/logger.js +15 -0
  418. package/dist/shared/logger.js.map +1 -0
  419. package/dist/shared/postgres-client.d.ts +51 -0
  420. package/dist/shared/postgres-client.d.ts.map +1 -0
  421. package/dist/shared/postgres-client.js +101 -0
  422. package/dist/shared/postgres-client.js.map +1 -0
  423. package/dist/shared/postgres-types.d.ts +7 -0
  424. package/dist/shared/postgres-types.d.ts.map +1 -0
  425. package/dist/shared/postgres-types.js +2 -0
  426. package/dist/shared/postgres-types.js.map +1 -0
  427. package/dist/shared/postgres-validation.d.ts +8 -0
  428. package/dist/shared/postgres-validation.d.ts.map +1 -0
  429. package/dist/shared/postgres-validation.js +40 -0
  430. package/dist/shared/postgres-validation.js.map +1 -0
  431. package/dist/storage/adapters/clickhouse.d.ts +61 -0
  432. package/dist/storage/adapters/clickhouse.d.ts.map +1 -0
  433. package/dist/storage/adapters/clickhouse.js +329 -0
  434. package/dist/storage/adapters/clickhouse.js.map +1 -0
  435. package/dist/storage/adapters/s3.d.ts +35 -0
  436. package/dist/storage/adapters/s3.d.ts.map +1 -0
  437. package/dist/storage/adapters/s3.js +100 -0
  438. package/dist/storage/adapters/s3.js.map +1 -0
  439. package/dist/storage/outbox-worker.d.ts +40 -0
  440. package/dist/storage/outbox-worker.d.ts.map +1 -0
  441. package/dist/storage/outbox-worker.js +132 -0
  442. package/dist/storage/outbox-worker.js.map +1 -0
  443. package/dist/storage/ports.d.ts +77 -0
  444. package/dist/storage/ports.d.ts.map +1 -0
  445. package/dist/storage/ports.js +2 -0
  446. package/dist/storage/ports.js.map +1 -0
  447. package/dist/storage/postgres-repository.d.ts +14 -0
  448. package/dist/storage/postgres-repository.d.ts.map +1 -0
  449. package/dist/storage/postgres-repository.js +130 -0
  450. package/dist/storage/postgres-repository.js.map +1 -0
  451. package/dist/storage/runtime.d.ts +67 -0
  452. package/dist/storage/runtime.d.ts.map +1 -0
  453. package/dist/storage/runtime.js +313 -0
  454. package/dist/storage/runtime.js.map +1 -0
  455. package/package.json +70 -12
  456. package/dist/allowance.d.ts +0 -48
  457. package/dist/allowance.d.ts.map +0 -1
  458. package/dist/allowance.js +0 -140
  459. package/dist/allowance.js.map +0 -1
  460. package/dist/manager.d.ts +0 -421
  461. package/dist/manager.d.ts.map +0 -1
  462. package/dist/manager.js +0 -1112
  463. package/dist/manager.js.map +0 -1
  464. package/dist/stores/credit-store.d.ts.map +0 -1
  465. package/dist/stores/credit-store.js.map +0 -1
  466. package/dist/stores/events.d.ts.map +0 -1
  467. package/dist/stores/events.js.map +0 -1
  468. package/dist/stores/memory-store.d.ts +0 -178
  469. package/dist/stores/memory-store.d.ts.map +0 -1
  470. package/dist/stores/memory-store.js +0 -1833
  471. package/dist/stores/memory-store.js.map +0 -1
  472. package/dist/stores/postgres-store.d.ts +0 -95
  473. package/dist/stores/postgres-store.d.ts.map +0 -1
  474. package/dist/stores/postgres-store.js +0 -872
  475. package/dist/stores/postgres-store.js.map +0 -1
  476. package/dist/stores/supabase-store.d.ts +0 -76
  477. package/dist/stores/supabase-store.d.ts.map +0 -1
  478. package/dist/stores/supabase-store.js +0 -865
  479. package/dist/stores/supabase-store.js.map +0 -1
  480. package/dist/types.d.ts +0 -462
  481. package/dist/types.d.ts.map +0 -1
  482. package/dist/types.js.map +0 -1
  483. /package/dist/{types.js → commerce/types.js} +0 -0
@@ -1,1833 +0,0 @@
1
- import { randomUUID } from "crypto";
2
- import Decimal from "decimal.js";
3
- import { quantizeMoney } from "../expr.js";
4
- import { StoreError } from "../errors.js";
5
- import { resolveAllowanceWindow, resolveCalendarWindow } from "../allowance.js";
6
- import { CreditStore } from "./credit-store.js";
7
- const ZERO = new Decimal(0);
8
- /** Coerce a presence-or-truthiness feature value per contract §5 (M6). */
9
- function featurePresent(value) {
10
- // Identity form: numeric 0 / "" count as present. Matches Python
11
- // `value is not None and value is not False`. Do NOT use Boolean(value).
12
- return value !== null && value !== undefined && value !== false;
13
- }
14
- /**
15
- * Normalise a raw plan object (possibly snake_case from a JSON fixture or raw dict)
16
- * into a proper PlanDefinition with Decimal fields. Accepts both camelCase and
17
- * snake_case keys so configs written in either style work without preprocessing.
18
- */
19
- function normalisePlanDefinition(planKey, raw) {
20
- const p = raw;
21
- const freeAllowanceRaw = (p["freeAllowance"] ?? p["free_allowance"]);
22
- const defaultBillingModeRaw = (p["defaultBillingMode"] ??
23
- p["billingMode"] ??
24
- p["default_billing_mode"] ??
25
- p["billing_mode"]);
26
- const overdraftFloorRaw = (p["overdraftFloor"] ?? p["overdraft_floor"]);
27
- const rateOverridesRaw = (p["rateOverrides"] ?? p["rate_overrides"]);
28
- const perOperationRaw = (p["perOperation"] ?? p["per_operation"]);
29
- const maxConcurrentRaw = (p["maxConcurrent"] ?? p["max_concurrent"]);
30
- const allowancePeriodRaw = (p["allowancePeriod"] ?? p["allowance_period"]);
31
- const featureLimitsRaw = (p["featureLimits"] ?? p["feature_limits"]);
32
- const billingMode = (defaultBillingModeRaw === "overdraft" ? "overdraft" : "strict");
33
- return {
34
- id: p["id"] ?? planKey,
35
- name: p["name"] ?? planKey,
36
- freeAllowance: freeAllowanceRaw != null ? new Decimal(freeAllowanceRaw) : ZERO,
37
- rateOverrides: rateOverridesRaw ?? null,
38
- features: p["features"] ?? null,
39
- featureLimits: normaliseFeatureLimitsMap(featureLimitsRaw),
40
- defaultBillingMode: billingMode,
41
- overdraftFloor: overdraftFloorRaw != null ? new Decimal(overdraftFloorRaw) : null,
42
- maxConcurrent: maxConcurrentRaw ?? null,
43
- perOperation: perOperationRaw ?? undefined,
44
- allowancePeriod: allowancePeriodRaw ?? "calendar_month",
45
- };
46
- }
47
- /**
48
- * Normalise a raw `featureLimits`/`feature_limits` map (possibly snake_case,
49
- * from a JSON fixture or raw dict) into typed `FeatureLimit` records. Mirrors
50
- * `normalisePlanDefinition`'s camelCase/snake_case tolerance.
51
- */
52
- function normaliseFeatureLimitsMap(raw) {
53
- if (!raw)
54
- return null;
55
- const out = {};
56
- for (const [featureKey, rawLimit] of Object.entries(raw)) {
57
- const l = (rawLimit ?? {});
58
- const maxCallsRaw = (l["maxCalls"] ?? l["max_calls"]);
59
- out[featureKey] = {
60
- maxCalls: maxCallsRaw != null ? Number(maxCallsRaw) : 0,
61
- period: l["period"] ?? "monthly",
62
- action: l["action"] ?? "deny",
63
- };
64
- }
65
- return out;
66
- }
67
- /**
68
- * Normalise a raw tier definition object (possibly snake_case from a JSON
69
- * fixture or raw dict) into a proper `TierDefinition`. Accepts both camelCase
70
- * and snake_case keys, mirroring `normalisePlanDefinition` (credit tiers).
71
- */
72
- function normaliseTierDefinition(tierKey, raw) {
73
- const t = raw;
74
- const defaultTtlDaysRaw = (t["defaultTtlDays"] ?? t["default_ttl_days"]);
75
- const allowOverdraftRaw = (t["allowOverdraft"] ?? t["allow_overdraft"]);
76
- const isDefaultRaw = (t["isDefault"] ?? t["is_default"]);
77
- return {
78
- name: t["name"] ?? tierKey,
79
- priority: Number(t["priority"] ?? 0),
80
- expires: Boolean(t["expires"] ?? false),
81
- defaultTtlDays: defaultTtlDaysRaw != null ? Number(defaultTtlDaysRaw) : null,
82
- allowOverdraft: Boolean(allowOverdraftRaw ?? false),
83
- isDefault: Boolean(isDefaultRaw ?? false),
84
- };
85
- }
86
- /** Default lease TTL (seconds) for the lease lifecycle (interface plan §3). */
87
- const DEFAULT_LEASE_TTL_SECONDS = 600;
88
- /**
89
- * Credit store backed by in-memory maps.
90
- * Zero dependencies. Useful for unit testing and local development.
91
- *
92
- * Money is exact `Decimal` everywhere (contract §1). Because JavaScript is
93
- * single-threaded, every mutating method performs its read-modify-write
94
- * **synchronously** (no `await` between reading a balance and writing it back),
95
- * so a `Promise.all` of concurrent deductions cannot interleave and double-spend
96
- * (C2). A test-only injectable clock is exposed for deterministic time tests.
97
- */
98
- export class MemoryStore extends CreditStore {
99
- balances = new Map();
100
- lifetime = new Map();
101
- transactions = [];
102
- reservations = new Map();
103
- pricingVersion = 0;
104
- pricingLabel = null;
105
- pricingHistory = [];
106
- planDefinitions = new Map();
107
- // Credit tiers: definitions keyed by tier key (config key); balances keyed by
108
- // a composite `${userId}:${tierKey}` string — JS Maps compare object/tuple
109
- // keys by reference, so a plain string key is required (repo CLAUDE.md).
110
- tierDefinitions = new Map();
111
- tierBalances = new Map();
112
- userPlanMap = new Map();
113
- /** Timestamp each user's CURRENT plan was assigned — anchor for WS9 non-calendar periods. */
114
- userPlanAssignedAt = new Map();
115
- usageWindows = [];
116
- spendCaps = [];
117
- teams = new Map();
118
- teamMembers = new Map();
119
- /**
120
- * Injectable clock for deterministic time-dependent tests. Defaults to the
121
- * real wall clock. Tests set this to a fixed `Date` to avoid `setTimeout`
122
- * sleeps (contract §8).
123
- */
124
- clock = () => new Date();
125
- /** Override the clock used for all time comparisons (test-only). */
126
- setClock(clock) {
127
- this.clock = clock;
128
- }
129
- now() {
130
- return this.clock();
131
- }
132
- balance(userId) {
133
- return this.balances.get(userId) ?? ZERO;
134
- }
135
- // ── Credit tiers: per-(user, tier) balance map ──────────────────────
136
- tierBalanceKey(userId, tierKey) {
137
- return `${userId}:${tierKey}`;
138
- }
139
- getTierBalance(userId, tierKey) {
140
- return this.tierBalances.get(this.tierBalanceKey(userId, tierKey)) ?? ZERO;
141
- }
142
- adjustTierBalance(userId, tierKey, delta) {
143
- const key = this.tierBalanceKey(userId, tierKey);
144
- this.tierBalances.set(key, (this.tierBalances.get(key) ?? ZERO).plus(delta));
145
- }
146
- /**
147
- * The tier-priority walk order (plan §4): configured tiers ascending by
148
- * priority (ties broken by tier key ascending), or the synthetic
149
- * `[{"default", priority: 0, allowOverdraft: true}]` when no tiers are
150
- * configured — PLUS any tier keys not in that list, appended last (the
151
- * config-drift safety net). `extraKeys`, when supplied, is the exact set of
152
- * "orphaned" keys to consider (e.g. a debit's own tier_breakdown keys, for
153
- * refund restoration); when omitted, orphaned keys are discovered from any
154
- * nonzero balance the user currently holds under an unconfigured tier key.
155
- */
156
- tierWalkOrder(userId, extraKeys) {
157
- const configured = [...this.tierDefinitions.entries()]
158
- .map(([tierKey, def]) => ({
159
- tierKey,
160
- priority: def.priority,
161
- allowOverdraft: def.allowOverdraft ?? false,
162
- }))
163
- .sort((a, b) => a.priority - b.priority || a.tierKey.localeCompare(b.tierKey));
164
- const base = configured.length > 0
165
- ? configured
166
- : [{ tierKey: "default", priority: 0, allowOverdraft: true }];
167
- const known = new Set(base.map((t) => t.tierKey));
168
- const orphaned = new Set();
169
- if (extraKeys) {
170
- for (const k of extraKeys)
171
- if (!known.has(k))
172
- orphaned.add(k);
173
- }
174
- else {
175
- const prefix = `${userId}:`;
176
- for (const [key, bal] of this.tierBalances) {
177
- if (!key.startsWith(prefix))
178
- continue;
179
- const tierKey = key.slice(prefix.length);
180
- if (!known.has(tierKey) && !bal.isZero())
181
- orphaned.add(tierKey);
182
- }
183
- }
184
- return [
185
- ...base,
186
- ...[...orphaned]
187
- .sort()
188
- .map((tierKey) => ({ tierKey, priority: Number.MAX_SAFE_INTEGER, allowOverdraft: false })),
189
- ];
190
- }
191
- /**
192
- * Resolve the `addCredits` target tier (plan §3):
193
- * - no tiers configured ⇒ `tier` must be omitted/null/`"default"`.
194
- * - tiers configured + explicit `tier` ⇒ must be a known key.
195
- * - tiers configured + omitted `tier` ⇒ resolve via the `isDefault: true`
196
- * tier, else throw (deliberately strict — never silently misroute money).
197
- */
198
- resolveAddCreditsTier(tier) {
199
- if (this.tierDefinitions.size === 0) {
200
- if (tier != null && tier !== "default") {
201
- throw new StoreError(`tier_not_found: ${tier}`);
202
- }
203
- return "default";
204
- }
205
- if (tier != null) {
206
- if (!this.tierDefinitions.has(tier)) {
207
- throw new StoreError(`tier_not_found: ${tier}`);
208
- }
209
- return tier;
210
- }
211
- for (const [key, def] of this.tierDefinitions) {
212
- if (def.isDefault)
213
- return key;
214
- }
215
- throw new StoreError("tier_required");
216
- }
217
- /**
218
- * Reconcile a caller-supplied `expiresAt` against the resolved tier's
219
- * `expires` flag (plan §3):
220
- * - no tiers configured ⇒ unchanged existing behaviour (no restriction).
221
- * - non-expiring tier + explicit `expiresAt` ⇒ throw.
222
- * - expiring tier + explicit `expiresAt` ⇒ validate `> now`, use it.
223
- * - expiring tier + omitted `expiresAt` ⇒ use `defaultTtlDays` if set,
224
- * else throw.
225
- */
226
- resolveAddCreditsExpiry(tierKey, expiresAt) {
227
- if (this.tierDefinitions.size === 0) {
228
- return expiresAt ?? null;
229
- }
230
- const def = this.tierDefinitions.get(tierKey);
231
- if (!def)
232
- return expiresAt ?? null;
233
- if (!def.expires) {
234
- if (expiresAt != null) {
235
- throw new StoreError(`tier_does_not_expire: ${tierKey}`);
236
- }
237
- return null;
238
- }
239
- if (expiresAt != null) {
240
- if (expiresAt <= this.now()) {
241
- throw new StoreError(`invalid_expires_at: ${expiresAt.toISOString()} must be in the future`);
242
- }
243
- return expiresAt;
244
- }
245
- if (def.defaultTtlDays != null) {
246
- return new Date(this.now().getTime() + def.defaultTtlDays * 86_400_000);
247
- }
248
- throw new StoreError("expires_at_required");
249
- }
250
- /**
251
- * Billing-period key (YYYY-MM-DD) used as the in-memory usage-window bucket.
252
- *
253
- * When an explicit ``periodStart`` is supplied (WS9 — a non-calendar-month
254
- * allowance window resolved by the manager), it is used directly. Otherwise
255
- * falls back to the UTC calendar-month start for the current clock, exactly
256
- * matching pre-WS9 behaviour.
257
- */
258
- billingPeriod(periodStart) {
259
- if (periodStart)
260
- return periodStart.toISOString().slice(0, 10);
261
- const now = this.now();
262
- return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1))
263
- .toISOString()
264
- .slice(0, 10);
265
- }
266
- async setup(_databaseUrl) {
267
- return {
268
- tablesCreated: [
269
- "001_core_schema.sql",
270
- "002_credit_rpcs.sql",
271
- "003_pricing_config.sql",
272
- "004_plans.sql",
273
- "005_spend_caps.sql",
274
- "006_refunds_and_expiry.sql",
275
- "007_analytics.sql",
276
- "008_teams.sql",
277
- "009_deduct_and_leases.sql",
278
- "010_credit_tiers.sql",
279
- // NOTE: the contract doc for this feature named this migration
280
- // "011_feature_limits.sql", but "011_lazy_expiry.sql" already occupies
281
- // that slot in python/src/bursar/sql/ (a numbering collision between two
282
- // parallel work tracks) — using the next free number here instead.
283
- "012_feature_limits.sql",
284
- ],
285
- rpcsCreated: [],
286
- errors: [],
287
- success: true,
288
- };
289
- }
290
- async getBalance(userId) {
291
- return {
292
- userId,
293
- balance: this.balance(userId),
294
- lifetimePurchased: this.lifetime.get(userId) ?? ZERO,
295
- };
296
- }
297
- async addCredits(userId, amount, type = "adjustment", metadata, expiresAt, tier, idempotencyKey) {
298
- // Idempotency (user-scoped): replay the original result, mirroring the
299
- // idiom used by deductWithAllowance/settleLease/refundCredits — scan for an
300
- // existing transaction for this user whose metadata.idempotencyKey matches.
301
- if (idempotencyKey) {
302
- const existing = this.transactions.find((t) => t.userId === userId && t.metadata?.["idempotencyKey"] === idempotencyKey);
303
- if (existing) {
304
- return {
305
- transactionId: existing.id,
306
- userId,
307
- amount: existing.amount,
308
- newBalance: this.balance(userId),
309
- lifetimePurchased: this.lifetime.get(userId) ?? ZERO,
310
- tier: existing.metadata?.["tier"] ?? "default",
311
- idempotent: true,
312
- };
313
- }
314
- }
315
- // L2: reject non-finite amounts always, and non-positive amounts unless this
316
- // is an explicit `adjustment` (parity with SQL `credits_add`). A negative or
317
- // zero purchase/grant must never drive the balance below the floor.
318
- if (!amount.isFinite()) {
319
- throw new StoreError(`addCredits: amount must be finite, got ${amount.toString()}`);
320
- }
321
- if (type !== "adjustment" && amount.lte(0)) {
322
- throw new StoreError(`addCredits: ${type} amount must be > 0, got ${amount.toString()} (use type='adjustment' for negative/zero)`);
323
- }
324
- // Credit tiers: resolve the target tier and reconcile expiresAt against it.
325
- const resolvedTier = this.resolveAddCreditsTier(tier);
326
- const resolvedExpiresAt = this.resolveAddCreditsExpiry(resolvedTier, expiresAt);
327
- const amt = quantizeMoney(amount);
328
- const current = this.balance(userId);
329
- this.balances.set(userId, current.plus(amt));
330
- this.adjustTierBalance(userId, resolvedTier, amt);
331
- const lifetimeAdd = type === "purchase" ? amt : ZERO;
332
- this.lifetime.set(userId, (this.lifetime.get(userId) ?? ZERO).plus(lifetimeAdd));
333
- const txId = randomUUID();
334
- const txMeta = metadata ? this.cleanMetadata(metadata) : {};
335
- txMeta["tier"] = resolvedTier;
336
- if (idempotencyKey)
337
- txMeta["idempotencyKey"] = idempotencyKey;
338
- const tx = {
339
- id: txId,
340
- userId,
341
- amount: amt,
342
- type,
343
- metadata: txMeta,
344
- createdAt: this.now(),
345
- expiresAt: resolvedExpiresAt,
346
- };
347
- this.transactions.push(tx);
348
- return {
349
- transactionId: txId,
350
- userId,
351
- amount: amt,
352
- newBalance: this.balance(userId),
353
- lifetimePurchased: this.lifetime.get(userId) ?? ZERO,
354
- tier: resolvedTier,
355
- idempotent: false,
356
- };
357
- }
358
- cleanMetadata(metadata) {
359
- const out = {};
360
- for (const [k, v] of Object.entries(metadata)) {
361
- if (v != null)
362
- out[k] = v;
363
- }
364
- return out;
365
- }
366
- /**
367
- * Tier-priority walk (plan §4), shared by `deductWithAllowance` and
368
- * `settleLease`: drains `net` from tier balances in priority order (exact
369
- * greedy Decimal walk, never a proportional split). If `net` exceeds the
370
- * sum of configured-tier balances (only reachable under a negative floor /
371
- * overdraft — the floor check already guarantees coverage otherwise), the
372
- * remainder routes to the `allowOverdraft` tier, else the max-priority
373
- * tier, else `"default"`. Returns a breakdown whose values sum exactly to
374
- * `net`.
375
- */
376
- walkTiers(userId, net) {
377
- const order = this.tierWalkOrder(userId);
378
- const breakdown = {};
379
- let remaining = net;
380
- for (const t of order) {
381
- if (remaining.lte(0))
382
- break;
383
- const bal = this.getTierBalance(userId, t.tierKey);
384
- const take = Decimal.min(bal, remaining);
385
- if (take.gt(0)) {
386
- breakdown[t.tierKey] = (breakdown[t.tierKey] ?? ZERO).plus(take);
387
- this.adjustTierBalance(userId, t.tierKey, take.negated());
388
- remaining = remaining.minus(take);
389
- }
390
- }
391
- if (remaining.gt(0)) {
392
- const overdraftTier = order.find((t) => t.allowOverdraft);
393
- const sink = overdraftTier
394
- ? overdraftTier.tierKey
395
- : order.length > 0
396
- ? order.reduce((best, t) => (t.priority > best.priority ? t : best)).tierKey
397
- : "default";
398
- breakdown[sink] = (breakdown[sink] ?? ZERO).plus(remaining);
399
- this.adjustTierBalance(userId, sink, remaining.negated());
400
- }
401
- return breakdown;
402
- }
403
- /**
404
- * Atomic "calculate-then-charge" in a single synchronous critical section
405
- * (contract §2). Mirrors the SQL `deduct_with_allowance` RPC:
406
- * idempotency-first → consume allowance → cap on net → balance floor → debit.
407
- * A `deny` cap or floor breach consumes NO allowance.
408
- */
409
- async deductWithAllowance(userId, amount, options) {
410
- const idempotencyKey = options?.idempotencyKey ?? null;
411
- const minBalance = options?.minBalance ?? ZERO;
412
- const model = options?.model ?? null;
413
- const metadata = options?.metadata ?? null;
414
- const periodStart = options?.periodStart ?? null;
415
- const feature = options?.feature ?? null;
416
- const featureLimit = options?.featureLimit ?? null;
417
- const featurePeriodStart = options?.featurePeriodStart ?? null;
418
- // ── critical section (synchronous; no awaits) ──
419
- // Reject non-finite / negative amounts. Zero is a valid no-op charge.
420
- if (!amount.isFinite() || amount.lt(0)) {
421
- return {
422
- transactionId: "",
423
- userId,
424
- amount: ZERO,
425
- allowanceConsumed: ZERO,
426
- balanceAfter: this.balance(userId),
427
- idempotent: false,
428
- capWarning: null,
429
- featureLimitWarning: null,
430
- error: "invalid_amount",
431
- };
432
- }
433
- // (2) Idempotency (user-scoped): replay the original result.
434
- if (idempotencyKey) {
435
- const existing = this.transactions.find((t) => t.userId === userId && t.metadata?.["idempotencyKey"] === idempotencyKey);
436
- if (existing) {
437
- const consumed = existing.metadata?.["allowanceConsumed"];
438
- return {
439
- transactionId: existing.id,
440
- userId,
441
- amount: existing.amount.abs(),
442
- allowanceConsumed: consumed instanceof Decimal ? consumed : new Decimal(String(consumed ?? 0)),
443
- balanceAfter: this.balance(userId),
444
- idempotent: true,
445
- capWarning: null,
446
- featureLimitWarning: null,
447
- // Idempotent replay echoes the ORIGINAL tier breakdown — never recomputed.
448
- tierBreakdown: existing.metadata?.["tierBreakdown"] ?? null,
449
- };
450
- }
451
- }
452
- const gross = quantizeMoney(amount);
453
- // (3) Allowance: consume as much of the cost as remaining free allowance covers.
454
- let consume = ZERO;
455
- const planId = this.userPlanMap.get(userId);
456
- const planDef = planId ? this.planDefinitions.get(planId) : undefined;
457
- if (planId && planDef) {
458
- const billingPeriod = this.billingPeriod(periodStart);
459
- let used = ZERO;
460
- for (const w of this.usageWindows) {
461
- if (w.userId === userId && w.planId === planId && w.billingPeriod === billingPeriod) {
462
- used = used.plus(w.usage);
463
- }
464
- }
465
- const remaining = Decimal.max(ZERO, planDef.freeAllowance.minus(used));
466
- consume = Decimal.min(remaining, gross);
467
- }
468
- const net = gross.minus(consume);
469
- // (4) Spend cap on the NET amount. Deny aborts WITHOUT consuming allowance.
470
- let capWarning = null;
471
- const userCaps = this.spendCaps.filter((c) => c.userId === userId && (c.model == null || c.model === model));
472
- // Deny caps first (most restrictive), then soft caps.
473
- const ordered = [...userCaps].sort((a, b) => (a.action === "deny" ? 0 : 1) - (b.action === "deny" ? 0 : 1));
474
- for (const cap of ordered) {
475
- const windowStart = this.capWindowStart(cap.type);
476
- const currentSpend = this.spendInWindow(userId, windowStart, cap.model);
477
- if (currentSpend.plus(net).gt(cap.limit)) {
478
- if (cap.action === "deny") {
479
- // Abort: no allowance consumed, no balance change.
480
- return {
481
- transactionId: "",
482
- userId,
483
- amount: ZERO,
484
- allowanceConsumed: ZERO,
485
- balanceAfter: this.balance(userId),
486
- idempotent: false,
487
- capWarning: null,
488
- featureLimitWarning: null,
489
- error: "cap_reached",
490
- };
491
- }
492
- if (capWarning === null)
493
- capWarning = cap.action;
494
- }
495
- }
496
- // (4b) Feature limit: ledger-derived count of prior committed `usage`
497
- // transactions tagged metadata.feature === feature within
498
- // [featurePeriodStart, featurePeriodEnd). Skipped entirely when no
499
- // feature/limit was resolved by the caller (manager).
500
- let featureLimitWarning = null;
501
- if (feature != null && featureLimit != null && featurePeriodStart != null) {
502
- const featurePeriodEnd = resolveCalendarWindow(featurePeriodStart, featureLimit.period).end;
503
- const count = this.featureUsageCount(userId, feature, featurePeriodStart, featurePeriodEnd);
504
- if (count >= featureLimit.maxCalls) {
505
- if (featureLimit.action === "deny") {
506
- return {
507
- transactionId: "",
508
- userId,
509
- amount: ZERO,
510
- allowanceConsumed: ZERO,
511
- balanceAfter: this.balance(userId),
512
- idempotent: false,
513
- capWarning: null,
514
- featureLimitWarning: null,
515
- error: "feature_limit_reached",
516
- };
517
- }
518
- featureLimitWarning = featureLimit.action;
519
- }
520
- }
521
- // (5) Balance floor on the NET amount.
522
- const current = this.balance(userId);
523
- if (current.minus(net).lt(minBalance)) {
524
- return {
525
- transactionId: "",
526
- userId,
527
- amount: ZERO,
528
- allowanceConsumed: ZERO,
529
- balanceAfter: current,
530
- idempotent: false,
531
- capWarning: null,
532
- featureLimitWarning: null,
533
- error: "insufficient_credits",
534
- };
535
- }
536
- // (6) Commit: consume allowance, debit balance, insert ledger row.
537
- if (consume.gt(0) && planId) {
538
- this.incrementUsageWindowSync(userId, planId, consume, periodStart);
539
- }
540
- this.balances.set(userId, current.minus(net));
541
- const tierBreakdown = this.walkTiers(userId, net);
542
- const txMeta = metadata ? this.cleanMetadata(metadata) : {};
543
- if (idempotencyKey)
544
- txMeta["idempotencyKey"] = idempotencyKey;
545
- if (model != null)
546
- txMeta["model"] = model;
547
- // Tag metadata.feature whenever `feature` is given, regardless of whether a
548
- // limit is currently configured — this is what makes the ledger-derived
549
- // count accurate once a limit is enabled later.
550
- if (feature != null)
551
- txMeta["feature"] = feature;
552
- txMeta["allowanceConsumed"] = consume;
553
- txMeta["tierBreakdown"] = tierBreakdown;
554
- const txId = randomUUID();
555
- this.transactions.push({
556
- id: txId,
557
- userId,
558
- amount: net.negated(),
559
- type: "usage",
560
- metadata: txMeta,
561
- createdAt: this.now(),
562
- });
563
- return {
564
- transactionId: txId,
565
- userId,
566
- amount: net,
567
- allowanceConsumed: consume,
568
- balanceAfter: current.minus(net),
569
- idempotent: false,
570
- capWarning,
571
- featureLimitWarning,
572
- tierBreakdown,
573
- };
574
- }
575
- // ── Lease lifecycle (atomic admission) ─────────────────────────────
576
- /** Active, unexpired holds for a user (synchronous — no awaits in callers). */
577
- activeLeases(userId, operationType) {
578
- const now = this.now();
579
- const out = [];
580
- for (const r of this.reservations.values()) {
581
- if (r.userId === userId &&
582
- r.status === "active" &&
583
- r.expiresAt > now &&
584
- (operationType === undefined || r.operationType === operationType)) {
585
- out.push(r);
586
- }
587
- }
588
- return out;
589
- }
590
- async createLease(userId, amount, operationType, options) {
591
- const billingMode = options?.billingMode ?? "strict";
592
- const floor = options?.floor ?? ZERO;
593
- const maxConcurrent = options?.maxConcurrent ?? null;
594
- const ttlSeconds = options?.ttlSeconds ?? DEFAULT_LEASE_TTL_SECONDS;
595
- const model = options?.model ?? null;
596
- const overdraftFloor = options?.overdraftFloor ?? null;
597
- const metadata = options?.metadata ?? null;
598
- const feature = options?.feature ?? null;
599
- const featureLimit = options?.featureLimit ?? null;
600
- const featurePeriodStart = options?.featurePeriodStart ?? null;
601
- // ── critical section (synchronous; no awaits) ──
602
- if (!amount.isFinite() || amount.lte(0)) {
603
- return {
604
- leaseId: "",
605
- userId,
606
- amount: ZERO,
607
- available: ZERO,
608
- reservedTotal: ZERO,
609
- billingMode,
610
- expiresAt: "",
611
- error: "invalid_amount",
612
- };
613
- }
614
- // Ensure a balance row exists (overdraft admits brand-new users at 0).
615
- const balance = this.balance(userId);
616
- if (!this.balances.has(userId))
617
- this.balances.set(userId, balance);
618
- // (2) Concurrency: count active leases for this operation type.
619
- if (maxConcurrent !== null &&
620
- this.activeLeases(userId, operationType).length >= maxConcurrent) {
621
- return {
622
- leaseId: "",
623
- userId,
624
- amount: ZERO,
625
- available: ZERO,
626
- reservedTotal: ZERO,
627
- billingMode,
628
- expiresAt: "",
629
- error: "concurrency_limit",
630
- };
631
- }
632
- // (3) Deny spend cap at admission: a blocked user can't even start.
633
- const userCaps = this.spendCaps.filter((c) => c.userId === userId && (c.model == null || c.model === model));
634
- for (const cap of userCaps) {
635
- if (cap.action !== "deny")
636
- continue;
637
- const windowStart = this.capWindowStart(cap.type);
638
- const spend = this.spendInWindow(userId, windowStart, cap.model);
639
- if (spend.plus(amount).gt(cap.limit)) {
640
- return {
641
- leaseId: "",
642
- userId,
643
- amount: ZERO,
644
- available: ZERO,
645
- reservedTotal: ZERO,
646
- billingMode,
647
- expiresAt: "",
648
- error: "cap_reached",
649
- };
650
- }
651
- }
652
- // (3b) Deny-only feature limit at admission — same ledger-derived count as
653
- // deductWithAllowance/settleLease, but only ever enforces 'deny' (warn/notify
654
- // are not checked here: nothing has been charged yet, so there is nothing to
655
- // warn about). Skipped when no feature/limit was resolved by the caller.
656
- if (feature != null &&
657
- featureLimit != null &&
658
- featureLimit.action === "deny" &&
659
- featurePeriodStart != null) {
660
- const featurePeriodEnd = resolveCalendarWindow(featurePeriodStart, featureLimit.period).end;
661
- const count = this.featureUsageCount(userId, feature, featurePeriodStart, featurePeriodEnd);
662
- if (count >= featureLimit.maxCalls) {
663
- return {
664
- leaseId: "",
665
- userId,
666
- amount: ZERO,
667
- available: ZERO,
668
- reservedTotal: ZERO,
669
- billingMode,
670
- expiresAt: "",
671
- error: "feature_limit_reached",
672
- };
673
- }
674
- }
675
- // (4) available = balance − Σ active holds; reject if floor breached.
676
- let reservedTotal = ZERO;
677
- for (const r of this.activeLeases(userId))
678
- reservedTotal = reservedTotal.plus(r.amount);
679
- const available = balance.minus(reservedTotal);
680
- if (available.minus(amount).lt(floor)) {
681
- return {
682
- leaseId: "",
683
- userId,
684
- amount: ZERO,
685
- available,
686
- reservedTotal,
687
- billingMode,
688
- expiresAt: "",
689
- error: "insufficient_credits",
690
- };
691
- }
692
- // (5) Insert the active lease.
693
- const lid = randomUUID();
694
- const expiresAt = new Date(this.now().getTime() + ttlSeconds * 1000);
695
- this.reservations.set(lid, {
696
- id: lid,
697
- userId,
698
- amount,
699
- operationType,
700
- metadata: metadata ? this.cleanMetadata(metadata) : undefined,
701
- expiresAt,
702
- status: "active",
703
- billingMode,
704
- overdraftFloor,
705
- settleTxId: null,
706
- });
707
- return {
708
- leaseId: lid,
709
- userId,
710
- amount,
711
- available: available.minus(amount),
712
- reservedTotal: reservedTotal.plus(amount),
713
- billingMode,
714
- expiresAt: expiresAt.toISOString(),
715
- };
716
- }
717
- /** Build an idempotent-replay `DeductionResult` from a ledger row (synchronous). */
718
- replayDeduction(tx, userId, balance) {
719
- const consumed = tx.metadata?.["allowanceConsumed"];
720
- return {
721
- transactionId: tx.id,
722
- userId,
723
- amount: tx.amount.abs(),
724
- allowanceConsumed: consumed instanceof Decimal ? consumed : new Decimal(String(consumed ?? 0)),
725
- balanceAfter: balance,
726
- idempotent: true,
727
- capWarning: null,
728
- featureLimitWarning: null,
729
- // Idempotent replay echoes the ORIGINAL tier breakdown — never recomputed.
730
- tierBreakdown: tx.metadata?.["tierBreakdown"] ?? null,
731
- };
732
- }
733
- /**
734
- * Validate a lease for settle. Returns a short-circuit result, or `null` to
735
- * proceed (synchronous):
736
- * - missing / other-user / released → ``lease_not_found``
737
- * - already settled → idempotent replay of the original charge
738
- * - TTL elapsed → mark ``expired`` and return ``lease_expired``
739
- */
740
- settleLeaseState(lease, userId, balance) {
741
- const now = this.now();
742
- if (!lease || lease.userId !== userId || lease.status === "released") {
743
- return {
744
- transactionId: "",
745
- userId,
746
- amount: ZERO,
747
- allowanceConsumed: ZERO,
748
- balanceAfter: balance,
749
- idempotent: false,
750
- capWarning: null,
751
- featureLimitWarning: null,
752
- error: "lease_not_found",
753
- };
754
- }
755
- if (lease.status === "settled") {
756
- if (lease.settleTxId) {
757
- const tx = this.transactions.find((t) => t.id === lease.settleTxId);
758
- if (tx)
759
- return this.replayDeduction(tx, userId, balance);
760
- }
761
- return {
762
- transactionId: "",
763
- userId,
764
- amount: ZERO,
765
- allowanceConsumed: ZERO,
766
- balanceAfter: balance,
767
- idempotent: true,
768
- capWarning: null,
769
- featureLimitWarning: null,
770
- };
771
- }
772
- if (lease.status === "expired" || lease.expiresAt <= now) {
773
- lease.status = "expired";
774
- return {
775
- transactionId: "",
776
- userId,
777
- amount: ZERO,
778
- allowanceConsumed: ZERO,
779
- balanceAfter: balance,
780
- idempotent: false,
781
- capWarning: null,
782
- featureLimitWarning: null,
783
- error: "lease_expired",
784
- };
785
- }
786
- return null;
787
- }
788
- async settleLease(userId, leaseId, amount, options) {
789
- const idempotencyKey = options?.idempotencyKey ?? null;
790
- const model = options?.model ?? null;
791
- const metadata = options?.metadata ?? null;
792
- const periodStart = options?.periodStart ?? null;
793
- const feature = options?.feature ?? null;
794
- const featureLimit = options?.featureLimit ?? null;
795
- const featurePeriodStart = options?.featurePeriodStart ?? null;
796
- // ── critical section (synchronous; no awaits) ──
797
- if (!amount.isFinite() || amount.lt(0)) {
798
- return {
799
- transactionId: "",
800
- userId,
801
- amount: ZERO,
802
- allowanceConsumed: ZERO,
803
- balanceAfter: this.balance(userId),
804
- idempotent: false,
805
- capWarning: null,
806
- featureLimitWarning: null,
807
- error: "invalid_amount",
808
- };
809
- }
810
- const balance = this.balance(userId);
811
- // Idempotency replay (user-scoped).
812
- if (idempotencyKey) {
813
- const existing = this.transactions.find((t) => t.userId === userId && t.metadata?.["idempotencyKey"] === idempotencyKey);
814
- if (existing)
815
- return this.replayDeduction(existing, userId, balance);
816
- }
817
- const lease = this.reservations.get(leaseId);
818
- const precheck = this.settleLeaseState(lease, userId, balance);
819
- if (precheck !== null)
820
- return precheck;
821
- // settleLeaseState returns early on a missing lease, so `lease` is defined.
822
- const activeLease = lease;
823
- // Active & unexpired → settle. De-clamped: charge the ACTUAL cost (D5), never
824
- // clamp to the lease hold.
825
- // Zero-cost: release the lease without charging (resolves M3).
826
- if (amount.eq(0)) {
827
- activeLease.status = "settled";
828
- return {
829
- transactionId: "",
830
- userId,
831
- amount: ZERO,
832
- allowanceConsumed: ZERO,
833
- balanceAfter: balance,
834
- idempotent: false,
835
- capWarning: null,
836
- featureLimitWarning: null,
837
- };
838
- }
839
- // Allowance consume on the actual cost.
840
- let consume = ZERO;
841
- const planId = this.userPlanMap.get(userId);
842
- const planDef = planId ? this.planDefinitions.get(planId) : undefined;
843
- if (planId && planDef) {
844
- const billingPeriod = this.billingPeriod(periodStart);
845
- let used = ZERO;
846
- for (const w of this.usageWindows) {
847
- if (w.userId === userId && w.planId === planId && w.billingPeriod === billingPeriod) {
848
- used = used.plus(w.usage);
849
- }
850
- }
851
- const remaining = Decimal.max(ZERO, planDef.freeAllowance.minus(used));
852
- consume = Decimal.min(remaining, amount);
853
- }
854
- // Floor enforcement (C1): clamp net so balance stays ≥ floor.
855
- // The floor is derived from the lease's persisted billingMode and
856
- // overdraftFloor; options.minBalance is the engine's strict-mode floor.
857
- const settleFloor = activeLease.billingMode === "strict"
858
- ? (options?.minBalance ?? ZERO)
859
- : (activeLease.overdraftFloor ?? ZERO);
860
- const maxDebit = Decimal.max(ZERO, balance.minus(settleFloor));
861
- let net = amount.minus(consume);
862
- if (net.gt(maxDebit)) {
863
- net = maxDebit;
864
- // Re-clamp consume so it never exceeds amount - net.
865
- if (net.lt(amount)) {
866
- consume = Decimal.min(consume, amount.minus(net));
867
- }
868
- }
869
- // Spend cap is ADVISORY at settle (work is done): record the strongest
870
- // breaching action, never block (interface plan §7). 'deny' surfaces as a
871
- // non-blocking signal the manager re-emits as credits.cap_reached.
872
- let capWarning = null;
873
- const userCaps = this.spendCaps
874
- .filter((c) => c.userId === userId && (c.model == null || c.model === model))
875
- .sort((a, b) => (a.action === "deny" ? 0 : 1) - (b.action === "deny" ? 0 : 1));
876
- for (const cap of userCaps) {
877
- const windowStart = this.capWindowStart(cap.type);
878
- const spend = this.spendInWindow(userId, windowStart, cap.model);
879
- if (spend.plus(net).gt(cap.limit) &&
880
- (capWarning === null || (capWarning !== "deny" && cap.action === "deny"))) {
881
- capWarning = cap.action;
882
- }
883
- }
884
- // Feature limit is ADVISORY at settle (work is done, never blocks): a
885
- // breach — even a configured 'deny' — only sets featureLimitWarning
886
- // ("prefer deny", mirroring capWarning's resolution above).
887
- let featureLimitWarning = null;
888
- if (feature != null && featureLimit != null && featurePeriodStart != null) {
889
- const featurePeriodEnd = resolveCalendarWindow(featurePeriodStart, featureLimit.period).end;
890
- const count = this.featureUsageCount(userId, feature, featurePeriodStart, featurePeriodEnd);
891
- if (count >= featureLimit.maxCalls) {
892
- featureLimitWarning = featureLimit.action;
893
- }
894
- }
895
- if (consume.gt(0) && planId) {
896
- this.incrementUsageWindowSync(userId, planId, consume, periodStart);
897
- }
898
- this.balances.set(userId, balance.minus(net));
899
- const tierBreakdown = this.walkTiers(userId, net);
900
- const txMeta = metadata ? this.cleanMetadata(metadata) : {};
901
- if (model != null)
902
- txMeta["model"] = model;
903
- if (idempotencyKey)
904
- txMeta["idempotencyKey"] = idempotencyKey;
905
- // Tag metadata.feature whenever `feature` is given — this is what makes
906
- // this call countable by future checks (settle_lease is the ONLY place a
907
- // leased operation's usage transaction is inserted).
908
- if (feature != null)
909
- txMeta["feature"] = feature;
910
- txMeta["allowanceConsumed"] = consume;
911
- txMeta["tierBreakdown"] = tierBreakdown;
912
- const txId = randomUUID();
913
- this.transactions.push({
914
- id: txId,
915
- userId,
916
- amount: net.negated(),
917
- type: "usage",
918
- metadata: txMeta,
919
- createdAt: this.now(),
920
- });
921
- activeLease.status = "settled";
922
- activeLease.settleTxId = txId;
923
- return {
924
- transactionId: txId,
925
- userId,
926
- amount: net,
927
- allowanceConsumed: consume,
928
- balanceAfter: balance.minus(net),
929
- idempotent: false,
930
- capWarning,
931
- featureLimitWarning,
932
- tierBreakdown,
933
- };
934
- }
935
- async releaseLease(userId, leaseId) {
936
- const lease = this.reservations.get(leaseId);
937
- if (!lease || lease.userId !== userId) {
938
- return { leaseId, userId, released: false, reason: "not_found" };
939
- }
940
- if (lease.status === "settled") {
941
- return { leaseId, userId, released: false, reason: "already_settled" };
942
- }
943
- if (lease.status === "released") {
944
- return { leaseId, userId, released: false, reason: "already_released" };
945
- }
946
- lease.status = "released";
947
- return { leaseId, userId, released: true, reason: "released" };
948
- }
949
- async renewLease(userId, leaseId, ttlSeconds) {
950
- const now = this.now();
951
- const lease = this.reservations.get(leaseId);
952
- if (!lease ||
953
- lease.userId !== userId ||
954
- lease.status === "released" ||
955
- lease.status === "settled") {
956
- return {
957
- leaseId,
958
- userId,
959
- amount: ZERO,
960
- available: ZERO,
961
- reservedTotal: ZERO,
962
- billingMode: "strict",
963
- expiresAt: "",
964
- error: "lease_not_found",
965
- };
966
- }
967
- if (lease.status === "expired" || lease.expiresAt <= now) {
968
- lease.status = "expired";
969
- return {
970
- leaseId,
971
- userId,
972
- amount: ZERO,
973
- available: ZERO,
974
- reservedTotal: ZERO,
975
- billingMode: lease.billingMode,
976
- expiresAt: "",
977
- error: "lease_expired",
978
- };
979
- }
980
- lease.expiresAt = new Date(now.getTime() + ttlSeconds * 1000);
981
- let reservedTotal = ZERO;
982
- for (const r of this.activeLeases(userId))
983
- reservedTotal = reservedTotal.plus(r.amount);
984
- const balance = this.balance(userId);
985
- return {
986
- leaseId,
987
- userId,
988
- amount: lease.amount,
989
- available: balance.minus(reservedTotal),
990
- reservedTotal,
991
- billingMode: lease.billingMode,
992
- expiresAt: lease.expiresAt.toISOString(),
993
- };
994
- }
995
- async getAvailable(userId) {
996
- const balance = this.balance(userId);
997
- let reserved = ZERO;
998
- for (const r of this.activeLeases(userId))
999
- reserved = reserved.plus(r.amount);
1000
- return { userId, balance, reserved, available: balance.minus(reserved) };
1001
- }
1002
- async getActivePricing() {
1003
- // LOW hygiene fix: return the stored record id (stable), not a fresh randomUUID()
1004
- // every call. A fresh id breaks any caching keyed on config id.
1005
- const active = [...this.pricingHistory].reverse().find((h) => h.active);
1006
- if (!active)
1007
- return null;
1008
- return { id: active.id, config: active.config, version: active.version };
1009
- }
1010
- async setActivePricing(config, label) {
1011
- // Deactivate all previous versions, then insert a new active entry.
1012
- for (const h of this.pricingHistory)
1013
- h.active = false;
1014
- this.pricingVersion += 1;
1015
- this.pricingLabel = label ?? null;
1016
- const id = randomUUID();
1017
- this.pricingHistory.push({
1018
- id,
1019
- version: this.pricingVersion,
1020
- label: this.pricingLabel,
1021
- active: true,
1022
- config,
1023
- createdAt: new Date().toISOString(),
1024
- });
1025
- // H1 fix: key planDefinitions by the config dict key (plan_key), not plan.id.
1026
- // Python MemoryStore and SQL both resolve setUserPlan("u1","pro") by looking up
1027
- // the dict key "pro"; JS must match or setUserPlan resolves to null/planless.
1028
- if ("plans" in config && config.plans) {
1029
- for (const [planKey, planData] of Object.entries(config.plans)) {
1030
- this.planDefinitions.set(planKey, normalisePlanDefinition(planKey, planData));
1031
- }
1032
- }
1033
- if ("tiers" in config && config.tiers) {
1034
- for (const [tierKey, tierData] of Object.entries(config.tiers)) {
1035
- this.tierDefinitions.set(tierKey, normaliseTierDefinition(tierKey, tierData));
1036
- }
1037
- }
1038
- return id;
1039
- }
1040
- // H8: pricing history / activation — parity with Python base.py:293-312.
1041
- async getPricingHistory() {
1042
- return this.pricingHistory
1043
- .slice()
1044
- .reverse()
1045
- .map((h) => ({
1046
- id: h.id,
1047
- version: h.version,
1048
- label: h.label,
1049
- active: h.active,
1050
- createdAt: h.createdAt,
1051
- }));
1052
- }
1053
- async getPricingConfig(version) {
1054
- const entry = this.pricingHistory.find((h) => h.version === version);
1055
- if (!entry)
1056
- return null;
1057
- return { id: entry.id, config: entry.config, version: entry.version };
1058
- }
1059
- async activatePricing(version) {
1060
- const entry = this.pricingHistory.find((h) => h.version === version);
1061
- if (!entry)
1062
- throw new Error(`pricing version ${version} not found`);
1063
- for (const h of this.pricingHistory)
1064
- h.active = false;
1065
- entry.active = true;
1066
- this.pricingVersion = entry.version;
1067
- if ("plans" in entry.config && entry.config.plans) {
1068
- for (const [planKey, planData] of Object.entries(entry.config.plans)) {
1069
- this.planDefinitions.set(planKey, normalisePlanDefinition(planKey, planData));
1070
- }
1071
- }
1072
- if ("tiers" in entry.config && entry.config.tiers) {
1073
- for (const [tierKey, tierData] of Object.entries(entry.config.tiers)) {
1074
- this.tierDefinitions.set(tierKey, normaliseTierDefinition(tierKey, tierData));
1075
- }
1076
- }
1077
- return entry.id;
1078
- }
1079
- // ── Plan management ────────────────────────────────────────────────
1080
- async getUserPlan(userId) {
1081
- const planId = this.userPlanMap.get(userId) ?? null;
1082
- const planDef = planId ? this.planDefinitions.get(planId) : null;
1083
- return {
1084
- userId,
1085
- planId,
1086
- planName: planDef?.name ?? null,
1087
- freeAllowance: planDef?.freeAllowance ?? ZERO,
1088
- features: planDef?.features ?? {},
1089
- featureLimits: planDef?.featureLimits ?? {},
1090
- defaultBillingMode: planDef?.defaultBillingMode ?? "strict",
1091
- perOperation: planDef?.perOperation ?? {},
1092
- maxConcurrent: planDef?.maxConcurrent ?? null,
1093
- overdraftFloor: planDef?.overdraftFloor ?? null,
1094
- allowancePeriod: planDef?.allowancePeriod ?? "calendar_month",
1095
- planAssignedAt: planId ? (this.userPlanAssignedAt.get(userId) ?? null) : null,
1096
- };
1097
- }
1098
- async checkFeature(userId, feature) {
1099
- const plan = await this.getUserPlan(userId);
1100
- const present = Object.prototype.hasOwnProperty.call(plan.features, feature);
1101
- const value = present ? plan.features[feature] : null;
1102
- return {
1103
- userId,
1104
- feature,
1105
- value,
1106
- // M6: presence-vs-truthiness — numeric 0 / "" count as present.
1107
- hasFeature: present && featurePresent(value),
1108
- };
1109
- }
1110
- async setUserPlan(userId, planId) {
1111
- this.userPlanMap.set(userId, planId);
1112
- // WS9: record the assignment time as the anchor for non-calendar-month
1113
- // allowance periods. Uses the SAME injectable clock as everything else so
1114
- // tests can control it deterministically.
1115
- this.userPlanAssignedAt.set(userId, this.now());
1116
- return { userId, planId };
1117
- }
1118
- async checkAllowance(userId, periodStart) {
1119
- // periodStart is unused here: MemoryStore already has direct access to
1120
- // planAssignedAt and its own (injectable, test-controllable) clock, so it
1121
- // self-resolves the window rather than trusting a caller-supplied date that
1122
- // may have been computed against the manager's wall clock instead.
1123
- void periodStart;
1124
- const planId = this.userPlanMap.get(userId);
1125
- if (!planId) {
1126
- return { planId: "", allowanceRemaining: ZERO, periodStart: "", periodEnd: "" };
1127
- }
1128
- const planDef = this.planDefinitions.get(planId);
1129
- if (!planDef) {
1130
- return { planId: "", allowanceRemaining: ZERO, periodStart: "", periodEnd: "" };
1131
- }
1132
- const now = this.now();
1133
- const allowancePeriod = planDef.allowancePeriod ?? "calendar_month";
1134
- const anchor = this.userPlanAssignedAt.get(userId) ?? null;
1135
- const { start, end: exclusiveEnd } = resolveAllowanceWindow(now, allowancePeriod, anchor);
1136
- // Preserve the pre-WS9 display convention: periodEnd is the LAST DAY of the
1137
- // window (inclusive), i.e. one day before the resolver's exclusive end.
1138
- const periodEnd = new Date(exclusiveEnd.getTime() - 86_400_000);
1139
- const billingPeriod = start.toISOString().slice(0, 10);
1140
- let usage = ZERO;
1141
- for (const w of this.usageWindows) {
1142
- if (w.userId === userId && w.planId === planId && w.billingPeriod === billingPeriod) {
1143
- usage = usage.plus(w.usage);
1144
- }
1145
- }
1146
- return {
1147
- planId,
1148
- allowanceRemaining: Decimal.max(planDef.freeAllowance.minus(usage), ZERO),
1149
- periodStart: start.toISOString(),
1150
- periodEnd: periodEnd.toISOString(),
1151
- };
1152
- }
1153
- incrementUsageWindowSync(userId, planId, amount, periodStart) {
1154
- const billingPeriod = this.billingPeriod(periodStart);
1155
- const existing = this.usageWindows.find((w) => w.userId === userId && w.planId === planId && w.billingPeriod === billingPeriod);
1156
- if (existing) {
1157
- existing.usage = existing.usage.plus(amount);
1158
- }
1159
- else {
1160
- this.usageWindows.push({ userId, planId, billingPeriod, usage: amount });
1161
- }
1162
- }
1163
- async incrementUsageWindow(userId, planId, amount) {
1164
- this.incrementUsageWindowSync(userId, planId, amount);
1165
- }
1166
- // ── Refunds ──────────────────────────────────────────────────────────
1167
- async refundCredits(transactionId, amount, reason, metadata) {
1168
- // ── critical section (synchronous; no awaits) ──
1169
- const origTx = this.transactions.find((t) => t.id === transactionId);
1170
- if (!origTx) {
1171
- return {
1172
- refundTransactionId: "",
1173
- originalTransactionId: transactionId,
1174
- userId: "",
1175
- amount: ZERO,
1176
- newBalance: ZERO,
1177
- error: "not_found",
1178
- };
1179
- }
1180
- // Only a usage/team_usage debit (negative amount) is refundable. Anything
1181
- // else (purchase/refund/adjustment/bonus) has zero refundable amount, so any
1182
- // refund over-refunds (parity with SQL refund RPC).
1183
- if ((origTx.type !== "usage" && origTx.type !== "team_usage") || origTx.amount.gte(0)) {
1184
- return {
1185
- refundTransactionId: "",
1186
- originalTransactionId: transactionId,
1187
- userId: origTx.userId,
1188
- amount: ZERO,
1189
- newBalance: this.balance(origTx.userId),
1190
- error: "over_refund",
1191
- };
1192
- }
1193
- const originalDebit = origTx.amount.abs();
1194
- // Back-compat: an exact duplicate of a prior FULL refund → already_refunded.
1195
- const fullRefundExists = this.transactions.some((t) => t.type === "refund" && t.referenceId === transactionId && t.amount.eq(originalDebit));
1196
- if (fullRefundExists) {
1197
- return {
1198
- refundTransactionId: "",
1199
- originalTransactionId: transactionId,
1200
- userId: origTx.userId,
1201
- amount: ZERO,
1202
- newBalance: this.balance(origTx.userId),
1203
- error: "already_refunded",
1204
- };
1205
- }
1206
- // Sum prior refunds for cumulative-partial over-refund detection.
1207
- let priorRefunded = ZERO;
1208
- for (const t of this.transactions) {
1209
- if (t.type === "refund" && t.referenceId === transactionId) {
1210
- priorRefunded = priorRefunded.plus(t.amount);
1211
- }
1212
- }
1213
- const remaining = originalDebit.minus(priorRefunded);
1214
- const refundAmount = quantizeMoney(amount ?? remaining);
1215
- // Over-refund: non-positive request, or one exceeding what remains.
1216
- if (refundAmount.lte(0) || refundAmount.gt(remaining)) {
1217
- return {
1218
- refundTransactionId: "",
1219
- originalTransactionId: transactionId,
1220
- userId: origTx.userId,
1221
- amount: ZERO,
1222
- newBalance: this.balance(origTx.userId),
1223
- error: "over_refund",
1224
- };
1225
- }
1226
- // Restore balance and append the refund ledger row.
1227
- const current = this.balance(origTx.userId);
1228
- this.balances.set(origTx.userId, current.plus(refundAmount));
1229
- // Credit tiers: LIFO restoration (plan §5). The original debit's per-tier
1230
- // breakdown drives allocation; legacy debits without a stored breakdown
1231
- // (pre-tiers) fall back to the whole amount landing in "default".
1232
- const originalBreakdown = origTx.metadata?.["tierBreakdown"] ?? { default: originalDebit };
1233
- // tierRemaining[t] = original[t] - Σ(all PRIOR refunds' own breakdown[t]) —
1234
- // derived fresh each time so repeated partial refunds compose correctly
1235
- // without a separate running counter.
1236
- const priorBreakdowns = [];
1237
- for (const t of this.transactions) {
1238
- if (t.type === "refund" && t.referenceId === transactionId) {
1239
- const b = t.metadata?.["tierBreakdown"];
1240
- if (b)
1241
- priorBreakdowns.push(b);
1242
- }
1243
- }
1244
- const tierRemaining = {};
1245
- for (const [t, orig] of Object.entries(originalBreakdown)) {
1246
- let consumed = ZERO;
1247
- for (const b of priorBreakdowns)
1248
- consumed = consumed.plus(b[t] ?? ZERO);
1249
- tierRemaining[t] = orig.minus(consumed);
1250
- }
1251
- // Walk tiers in REVERSE priority order (highest-priority-number/last-drained
1252
- // tier first), restoring only the tiers actually present in the original
1253
- // breakdown.
1254
- let toAllocate = refundAmount;
1255
- const newBreakdown = {};
1256
- const reverseOrder = [
1257
- ...this.tierWalkOrder(origTx.userId, Object.keys(originalBreakdown)),
1258
- ].reverse();
1259
- for (const t of reverseOrder) {
1260
- if (toAllocate.lte(0))
1261
- break;
1262
- const give = Decimal.min(tierRemaining[t.tierKey] ?? ZERO, toAllocate);
1263
- if (give.gt(0)) {
1264
- newBreakdown[t.tierKey] = give;
1265
- toAllocate = toAllocate.minus(give);
1266
- this.adjustTierBalance(origTx.userId, t.tierKey, give);
1267
- }
1268
- }
1269
- const txMeta = metadata ? this.cleanMetadata(metadata) : {};
1270
- if (reason)
1271
- txMeta["reason"] = reason;
1272
- txMeta["tierBreakdown"] = newBreakdown;
1273
- const txId = randomUUID();
1274
- this.transactions.push({
1275
- id: txId,
1276
- userId: origTx.userId,
1277
- amount: refundAmount,
1278
- type: "refund",
1279
- referenceType: reason ?? null,
1280
- referenceId: transactionId,
1281
- metadata: txMeta,
1282
- createdAt: this.now(),
1283
- });
1284
- return {
1285
- refundTransactionId: txId,
1286
- originalTransactionId: transactionId,
1287
- userId: origTx.userId,
1288
- amount: refundAmount,
1289
- newBalance: current.plus(refundAmount),
1290
- tierBreakdown: newBreakdown,
1291
- };
1292
- }
1293
- // ── Credit expiry ─────────────────────────────────────────────────────
1294
- async sweepExpiredCredits(dryRun = false, userId) {
1295
- // ── critical section (synchronous; no awaits) ──
1296
- const now = this.now();
1297
- // Credit tiers: re-scoped from per-userId to per-(userId, tierKey), reading
1298
- // `metadata.tier` off each grant (legacy records without it default to
1299
- // "default"). Grouping key: `${userId} ${tierKey}`.
1300
- const expiredByUserTier = new Map();
1301
- const expiredTxsByUserTier = new Map();
1302
- // Find all expired, not-yet-swept grant transactions. When `userId` is
1303
- // given (lazy-on-read expiry), restrict the scan to that user only —
1304
- // omitted preserves the original global-sweep behaviour exactly.
1305
- for (const tx of this.transactions) {
1306
- if (userId !== undefined && tx.userId !== userId)
1307
- continue;
1308
- if (tx.expiresAt &&
1309
- !tx.sweptAt && // H4: never re-sweep a previously swept grant
1310
- (tx.type === "purchase" || tx.type === "adjustment")) {
1311
- if (tx.expiresAt <= now) {
1312
- const tierKey = tx.metadata?.["tier"] ?? "default";
1313
- const key = `${tx.userId} ${tierKey}`;
1314
- expiredByUserTier.set(key, (expiredByUserTier.get(key) ?? ZERO).plus(tx.amount));
1315
- const list = expiredTxsByUserTier.get(key) ?? [];
1316
- list.push(tx);
1317
- expiredTxsByUserTier.set(key, list);
1318
- }
1319
- }
1320
- }
1321
- let expiredCount = 0;
1322
- let expiredAmount = ZERO;
1323
- const expiredByTier = {};
1324
- for (const [key, totalExpired] of expiredByUserTier) {
1325
- const sep = key.indexOf(" ");
1326
- const userId = key.slice(0, sep);
1327
- const tierKey = key.slice(sep + 1);
1328
- // Clamp per-TIER balance (not aggregate) — the existing LEAST(...) clamp,
1329
- // just re-scoped.
1330
- const currentTierBalance = this.getTierBalance(userId, tierKey);
1331
- const toExpire = Decimal.min(totalExpired, currentTierBalance);
1332
- if (toExpire.gt(0)) {
1333
- expiredCount++;
1334
- expiredAmount = expiredAmount.plus(toExpire);
1335
- expiredByTier[tierKey] = (expiredByTier[tierKey] ?? ZERO).plus(toExpire);
1336
- if (!dryRun) {
1337
- this.adjustTierBalance(userId, tierKey, toExpire.negated());
1338
- this.balances.set(userId, this.balance(userId).minus(toExpire));
1339
- // H4: mark swept grants so a second sweep reports zero.
1340
- const txs = expiredTxsByUserTier.get(key) ?? [];
1341
- for (const et of txs) {
1342
- et.sweptAt = now;
1343
- et.expiresAt = null;
1344
- }
1345
- const txId = randomUUID();
1346
- this.transactions.push({
1347
- id: txId,
1348
- userId,
1349
- amount: toExpire.negated(),
1350
- type: "adjustment",
1351
- metadata: { reason: "credit_expired", expiredAmount: toExpire, tier: tierKey },
1352
- createdAt: now,
1353
- });
1354
- }
1355
- }
1356
- }
1357
- return {
1358
- expiredCount,
1359
- expiredAmount,
1360
- dryRun,
1361
- expiredByTier: Object.keys(expiredByTier).length > 0 ? expiredByTier : null,
1362
- };
1363
- }
1364
- // ── Credit tiers ─────────────────────────────────────────────────────
1365
- async getCreditTiers(userId) {
1366
- if (this.tierDefinitions.size === 0) {
1367
- // No tiers configured: synthesize a single "default" entry from the
1368
- // aggregate balance so the API shape is uniform either way.
1369
- return {
1370
- userId,
1371
- tiers: [
1372
- {
1373
- tierKey: "default",
1374
- name: "default",
1375
- priority: 0,
1376
- expires: false,
1377
- balance: this.balance(userId),
1378
- },
1379
- ],
1380
- totalBalance: this.balance(userId),
1381
- };
1382
- }
1383
- const tiers = [...this.tierDefinitions.entries()]
1384
- .map(([tierKey, def]) => ({
1385
- tierKey,
1386
- name: def.name,
1387
- priority: def.priority,
1388
- expires: def.expires,
1389
- balance: this.getTierBalance(userId, tierKey),
1390
- }))
1391
- .sort((a, b) => a.priority - b.priority || a.tierKey.localeCompare(b.tierKey));
1392
- return { userId, tiers, totalBalance: this.balance(userId) };
1393
- }
1394
- // ── Usage analytics ──────────────────────────────────────────────────
1395
- /** Filter transactions to usage records in the time window. */
1396
- _usageInWindow(start, end) {
1397
- return this.transactions.filter((t) => t.type === "usage" && t.amount.lt(0) && t.createdAt >= start && t.createdAt <= end);
1398
- }
1399
- async spendByUser(start, end) {
1400
- const usage = this._usageInWindow(start, end);
1401
- const byUser = new Map();
1402
- for (const t of usage) {
1403
- const entry = byUser.get(t.userId) ?? { total: ZERO, count: 0 };
1404
- entry.total = entry.total.plus(t.amount.abs());
1405
- entry.count++;
1406
- byUser.set(t.userId, entry);
1407
- }
1408
- return Array.from(byUser.entries())
1409
- .sort(([a], [b]) => a.localeCompare(b))
1410
- .map(([userId, { total, count }]) => ({
1411
- userId,
1412
- totalSpend: total,
1413
- transactionCount: count,
1414
- }));
1415
- }
1416
- async spendByModel(start, end) {
1417
- const usage = this._usageInWindow(start, end);
1418
- const byModel = new Map();
1419
- for (const t of usage) {
1420
- const model = t.metadata?.model ?? "unknown";
1421
- const entry = byModel.get(model) ?? { total: ZERO, count: 0 };
1422
- entry.total = entry.total.plus(t.amount.abs());
1423
- entry.count++;
1424
- byModel.set(model, entry);
1425
- }
1426
- return Array.from(byModel.entries())
1427
- .sort(([a], [b]) => a.localeCompare(b))
1428
- .map(([model, { total, count }]) => ({
1429
- model,
1430
- totalSpend: total,
1431
- transactionCount: count,
1432
- }));
1433
- }
1434
- async topUsers(limit, start, end) {
1435
- const byUser = await this.spendByUser(start, end);
1436
- return byUser
1437
- .sort((a, b) => b.totalSpend.comparedTo(a.totalSpend))
1438
- .slice(0, limit)
1439
- .map((r) => ({ userId: r.userId, totalSpend: r.totalSpend }));
1440
- }
1441
- // ── Transaction listing ─────────────────────────────────────────────
1442
- async listUserTransactions(userId, options) {
1443
- const limit = options?.limit ?? 50;
1444
- const offset = options?.offset ?? 0;
1445
- const filtered = this.transactions.filter((t) => {
1446
- if (t.userId !== userId)
1447
- return false;
1448
- if (options?.types && !options.types.includes(t.type))
1449
- return false;
1450
- if (options?.fromDate && t.createdAt < options.fromDate)
1451
- return false;
1452
- if (options?.toDate && t.createdAt > options.toDate)
1453
- return false;
1454
- return true;
1455
- });
1456
- // Sort newest first
1457
- filtered.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
1458
- const total = filtered.length;
1459
- const items = filtered.slice(offset, offset + limit);
1460
- return {
1461
- total,
1462
- items: items.map((t) => ({
1463
- id: t.id,
1464
- userId: t.userId,
1465
- amount: t.amount,
1466
- type: t.type,
1467
- referenceType: t.referenceType ?? null,
1468
- referenceId: t.referenceId ?? null,
1469
- metadata: t.metadata ?? null,
1470
- createdAt: t.createdAt.toISOString(),
1471
- })),
1472
- };
1473
- }
1474
- async listUsageEvents(userId, options) {
1475
- let items = this.transactions.filter((t) => t.userId === userId && t.type === "usage");
1476
- if (options?.fromDate) {
1477
- const from = options.fromDate;
1478
- items = items.filter((t) => t.createdAt >= from);
1479
- }
1480
- if (options?.toDate) {
1481
- const to = options.toDate;
1482
- items = items.filter((t) => t.createdAt <= to);
1483
- }
1484
- const total = items.length;
1485
- const offset = options?.offset ?? 0;
1486
- const limit = options?.limit ?? 50;
1487
- const page = items
1488
- .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())
1489
- .slice(offset, offset + limit);
1490
- return {
1491
- total,
1492
- items: page.map((t) => ({
1493
- id: t.id,
1494
- userId: t.userId,
1495
- amount: t.amount,
1496
- type: t.type,
1497
- referenceType: t.referenceType ?? null,
1498
- referenceId: t.referenceId ?? null,
1499
- metadata: t.metadata ?? null,
1500
- createdAt: t.createdAt.toISOString(),
1501
- })),
1502
- };
1503
- }
1504
- // ── Aggregate stats ──────────────────────────────────────────────────
1505
- async aggregateStats(start, end) {
1506
- const usage = this._usageInWindow(start, end);
1507
- if (usage.length === 0) {
1508
- return {
1509
- totalCreditsConsumed: ZERO,
1510
- activeUsers: 0,
1511
- avgDailySpend: ZERO,
1512
- topModel: "",
1513
- topUser: "",
1514
- };
1515
- }
1516
- let total = ZERO;
1517
- for (const t of usage)
1518
- total = total.plus(t.amount.abs());
1519
- const activeUsers = new Set(usage.map((t) => t.userId)).size;
1520
- const days = new Set(usage.map((t) => t.createdAt.toISOString().slice(0, 10))).size;
1521
- // NUMERIC division (no integer truncation) — quantize to 4dp.
1522
- const avgDailySpend = days > 0 ? quantizeMoney(total.div(days)) : ZERO;
1523
- const byModel = new Map();
1524
- const byUser = new Map();
1525
- for (const t of usage) {
1526
- const model = t.metadata?.model ?? "unknown";
1527
- byModel.set(model, (byModel.get(model) ?? ZERO).plus(t.amount.abs()));
1528
- byUser.set(t.userId, (byUser.get(t.userId) ?? ZERO).plus(t.amount.abs()));
1529
- }
1530
- const topModel = byModel.size > 0
1531
- ? [...byModel.entries()].reduce((best, curr) => (curr[1].gt(best[1]) ? curr : best))[0]
1532
- : "";
1533
- const topUser = byUser.size > 0
1534
- ? [...byUser.entries()].reduce((best, curr) => (curr[1].gt(best[1]) ? curr : best))[0]
1535
- : "";
1536
- return { totalCreditsConsumed: total, activeUsers, avgDailySpend, topModel, topUser };
1537
- }
1538
- // ── Spend caps and rate limiting ─────────────────────────────────────
1539
- /** Configure a spend cap (MemoryStore-only helper for testing). */
1540
- setSpendCap(cap) {
1541
- this.spendCaps.push(cap);
1542
- }
1543
- capWindowStart(type) {
1544
- const now = this.now();
1545
- if (type === "daily") {
1546
- return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
1547
- }
1548
- return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
1549
- }
1550
- /** Monthly team spend for a specific member: sum of team_usage debits this UTC month (H3). */
1551
- teamMonthSpent(teamId, userId) {
1552
- const now = this.now();
1553
- const windowStart = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
1554
- let total = ZERO;
1555
- for (const t of this.transactions) {
1556
- if (t.userId !== userId)
1557
- continue;
1558
- if (t.type !== "team_usage")
1559
- continue;
1560
- if (t.amount.gte(0))
1561
- continue;
1562
- if (t.metadata?.["teamId"] !== teamId)
1563
- continue;
1564
- if (t.createdAt >= windowStart)
1565
- total = total.plus(t.amount.abs());
1566
- }
1567
- return total;
1568
- }
1569
- /** Sum spend (positive magnitude) in a window, optionally restricted to a model. */
1570
- spendInWindow(userId, windowStart, capModel) {
1571
- let total = ZERO;
1572
- for (const t of this.transactions) {
1573
- if (t.userId !== userId)
1574
- continue;
1575
- if (t.type !== "usage" && t.type !== "team_usage")
1576
- continue;
1577
- if (t.amount.gte(0))
1578
- continue;
1579
- if (capModel != null && t.metadata?.model !== capModel)
1580
- continue;
1581
- if (t.createdAt >= windowStart)
1582
- total = total.plus(t.amount.abs());
1583
- }
1584
- return total;
1585
- }
1586
- /**
1587
- * Ledger-derived count of committed `usage` transactions tagged
1588
- * `metadata.feature === feature` in `[periodStart, periodEnd)` — the
1589
- * counting primitive shared by `deductWithAllowance`/`createLease`/
1590
- * `settleLease`'s feature-limit enforcement and `checkFeatureLimit`.
1591
- * Mirrors `spendInWindow`, replacing "sum of amount" with "count of rows".
1592
- *
1593
- * Deliberately does NOT filter on `amount < 0` (unlike `spendInWindow`,
1594
- * which only cares about actual dollars spent): a call fully covered by
1595
- * free allowance nets to `amount === 0` but is still one invocation of the
1596
- * feature and must still count.
1597
- *
1598
- * `release_lease` never inserts a `usage` row (nothing to count) and
1599
- * `refund_credits` never deletes the original row (the count is
1600
- * unaffected) — both intentional, matching the SQL/Python design.
1601
- */
1602
- featureUsageCount(userId, feature, periodStart, periodEnd) {
1603
- let count = 0;
1604
- for (const t of this.transactions) {
1605
- if (t.userId !== userId)
1606
- continue;
1607
- if (t.type !== "usage")
1608
- continue;
1609
- if ((t.metadata ?? {})["feature"] !== feature)
1610
- continue;
1611
- if (t.createdAt >= periodStart && t.createdAt < periodEnd)
1612
- count += 1;
1613
- }
1614
- return count;
1615
- }
1616
- async checkFeatureLimit(userId, feature, maxCalls, periodStart, periodEnd) {
1617
- const used = this.featureUsageCount(userId, feature, periodStart, periodEnd);
1618
- return {
1619
- userId,
1620
- feature,
1621
- limited: true,
1622
- limit: maxCalls,
1623
- used,
1624
- remaining: Math.max(maxCalls - used, 0),
1625
- periodStart: periodStart.toISOString(),
1626
- periodEnd: periodEnd.toISOString(),
1627
- // The manager overwrites `action` with the resolved FeatureLimit.action.
1628
- action: null,
1629
- };
1630
- }
1631
- async checkSpendCap(userId, model, amount) {
1632
- const amt = amount ?? ZERO;
1633
- const userCaps = this.spendCaps.filter((c) => c.userId === userId);
1634
- if (userCaps.length === 0) {
1635
- return { capped: false, currentSpend: ZERO, limit: ZERO, action: null };
1636
- }
1637
- // Check deny caps first — most restrictive
1638
- for (const cap of userCaps) {
1639
- if (cap.model && cap.model !== model)
1640
- continue;
1641
- if (cap.action !== "deny")
1642
- continue;
1643
- const windowStart = this.capWindowStart(cap.type);
1644
- const currentSpend = this.spendInWindow(userId, windowStart, cap.model);
1645
- if (currentSpend.plus(amt).gt(cap.limit)) {
1646
- return {
1647
- capped: true,
1648
- currentSpend,
1649
- limit: cap.limit,
1650
- action: "deny",
1651
- model: cap.model,
1652
- };
1653
- }
1654
- }
1655
- // Check warn/notify caps
1656
- for (const cap of userCaps) {
1657
- if (cap.model && cap.model !== model)
1658
- continue;
1659
- if (cap.action === "deny")
1660
- continue;
1661
- const windowStart = this.capWindowStart(cap.type);
1662
- const currentSpend = this.spendInWindow(userId, windowStart, cap.model);
1663
- if (currentSpend.plus(amt).gt(cap.limit)) {
1664
- return {
1665
- capped: false,
1666
- currentSpend,
1667
- limit: cap.limit,
1668
- action: cap.action,
1669
- model: cap.model,
1670
- };
1671
- }
1672
- }
1673
- return { capped: false, currentSpend: ZERO, limit: ZERO, action: null };
1674
- }
1675
- // ── Team/shared balance pools ────────────────────────────────────────
1676
- async createTeam(name, initialBalance = ZERO) {
1677
- const teamId = randomUUID();
1678
- this.teams.set(teamId, {
1679
- id: teamId,
1680
- name,
1681
- balance: initialBalance,
1682
- memberCount: 0,
1683
- createdAt: this.now(),
1684
- });
1685
- this.teamMembers.set(teamId, new Map());
1686
- return { teamId, name };
1687
- }
1688
- async getTeamBalance(teamId) {
1689
- const team = this.teams.get(teamId);
1690
- if (!team) {
1691
- return { teamId, name: "", balance: ZERO, memberCount: 0 };
1692
- }
1693
- return {
1694
- teamId: team.id,
1695
- name: team.name,
1696
- balance: team.balance,
1697
- memberCount: team.memberCount,
1698
- };
1699
- }
1700
- async addTeamMember(teamId, userId, role = "member", spendCap) {
1701
- const members = this.teamMembers.get(teamId);
1702
- if (!members) {
1703
- return { teamId, userId, role: "" };
1704
- }
1705
- members.set(userId, { userId, role, spendCap: spendCap ?? null, totalSpent: ZERO });
1706
- const team = this.teams.get(teamId);
1707
- if (team) {
1708
- team.memberCount = members.size;
1709
- }
1710
- return { teamId, userId, role };
1711
- }
1712
- async getTeamMembers(teamId) {
1713
- const members = this.teamMembers.get(teamId);
1714
- if (!members)
1715
- return [];
1716
- return Array.from(members.values());
1717
- }
1718
- async deductTeam(teamId, userId, amount, metadata, idempotencyKey) {
1719
- // ── critical section (synchronous; no awaits) ──
1720
- const team = this.teams.get(teamId);
1721
- if (!team) {
1722
- return {
1723
- transactionId: "",
1724
- teamId,
1725
- userId,
1726
- amount: ZERO,
1727
- teamBalanceAfter: ZERO,
1728
- error: "team_not_found",
1729
- };
1730
- }
1731
- // Idempotency-first (user/team-scoped): replay the original team debit.
1732
- if (idempotencyKey) {
1733
- const existing = this.transactions.find((t) => t.type === "team_usage" &&
1734
- t.metadata?.["teamId"] === teamId &&
1735
- t.metadata?.["idempotencyKey"] === idempotencyKey);
1736
- if (existing) {
1737
- return {
1738
- transactionId: existing.id,
1739
- teamId,
1740
- userId: existing.userId,
1741
- amount: existing.amount,
1742
- teamBalanceAfter: team.balance,
1743
- };
1744
- }
1745
- }
1746
- const members = this.teamMembers.get(teamId);
1747
- const member = members?.get(userId);
1748
- if (!member) {
1749
- return {
1750
- transactionId: "",
1751
- teamId,
1752
- userId,
1753
- amount: ZERO,
1754
- teamBalanceAfter: team.balance,
1755
- error: "user_not_in_team",
1756
- };
1757
- }
1758
- if (!amount.isFinite() || amount.lte(0)) {
1759
- return {
1760
- transactionId: "",
1761
- teamId,
1762
- userId,
1763
- amount: ZERO,
1764
- teamBalanceAfter: team.balance,
1765
- error: "invalid_amount",
1766
- };
1767
- }
1768
- // H3 fix: enforce spend cap against the monthly window, not lifetime totalSpent.
1769
- // Python MemoryStore and SQL both use a monthly window (first day of UTC month).
1770
- if (member.spendCap != null) {
1771
- const monthSpent = this.teamMonthSpent(teamId, userId);
1772
- if (monthSpent.plus(amount).gt(member.spendCap)) {
1773
- return {
1774
- transactionId: "",
1775
- teamId,
1776
- userId,
1777
- amount: ZERO,
1778
- teamBalanceAfter: team.balance,
1779
- error: "spend_cap_exceeded",
1780
- };
1781
- }
1782
- }
1783
- if (team.balance.lt(amount)) {
1784
- return {
1785
- transactionId: "",
1786
- teamId,
1787
- userId,
1788
- amount: ZERO,
1789
- teamBalanceAfter: team.balance,
1790
- error: "insufficient_team_balance",
1791
- };
1792
- }
1793
- team.balance = team.balance.minus(amount);
1794
- member.totalSpent = member.totalSpent.plus(amount);
1795
- const txMeta = {
1796
- ...(metadata ? this.cleanMetadata(metadata) : {}),
1797
- teamId,
1798
- };
1799
- if (idempotencyKey)
1800
- txMeta["idempotencyKey"] = idempotencyKey;
1801
- const txId = randomUUID();
1802
- this.transactions.push({
1803
- id: txId,
1804
- userId,
1805
- amount: amount.negated(),
1806
- type: "team_usage",
1807
- metadata: txMeta,
1808
- createdAt: this.now(),
1809
- });
1810
- return {
1811
- transactionId: txId,
1812
- teamId,
1813
- userId,
1814
- amount: amount.negated(),
1815
- teamBalanceAfter: team.balance,
1816
- };
1817
- }
1818
- async dailySpend(start, end) {
1819
- const usage = this._usageInWindow(start, end);
1820
- const byDay = new Map();
1821
- for (const t of usage) {
1822
- const date = t.createdAt.toISOString().slice(0, 10);
1823
- const entry = byDay.get(date) ?? { total: ZERO, count: 0 };
1824
- entry.total = entry.total.plus(t.amount.abs());
1825
- entry.count++;
1826
- byDay.set(date, entry);
1827
- }
1828
- return Array.from(byDay.entries())
1829
- .sort(([a], [b]) => a.localeCompare(b))
1830
- .map(([date, { total, count }]) => ({ date, totalSpend: total, transactionCount: count }));
1831
- }
1832
- }
1833
- //# sourceMappingURL=memory-store.js.map