@zonastery/bursar 0.0.2 → 1.0.1

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 (505) hide show
  1. package/README.md +118 -333
  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 +45 -13
  15. package/dist/billing/billing-store.d.ts.map +1 -1
  16. package/dist/billing/billing-store.js.map +1 -1
  17. package/dist/billing/contracts.d.ts +149 -0
  18. package/dist/billing/contracts.d.ts.map +1 -0
  19. package/dist/billing/contracts.js +2 -0
  20. package/dist/billing/contracts.js.map +1 -0
  21. package/dist/billing/event-handlers.d.ts +57 -0
  22. package/dist/billing/event-handlers.d.ts.map +1 -0
  23. package/dist/billing/event-handlers.js +684 -0
  24. package/dist/billing/event-handlers.js.map +1 -0
  25. package/dist/billing/event-processor.d.ts +20 -0
  26. package/dist/billing/event-processor.d.ts.map +1 -0
  27. package/dist/billing/event-processor.js +131 -0
  28. package/dist/billing/event-processor.js.map +1 -0
  29. package/dist/billing/financial-event-handlers.d.ts +26 -0
  30. package/dist/billing/financial-event-handlers.d.ts.map +1 -0
  31. package/dist/billing/financial-event-handlers.js +241 -0
  32. package/dist/billing/financial-event-handlers.js.map +1 -0
  33. package/dist/billing/index.d.ts +9 -5
  34. package/dist/billing/index.d.ts.map +1 -1
  35. package/dist/billing/index.js +4 -4
  36. package/dist/billing/index.js.map +1 -1
  37. package/dist/billing/management.d.ts +59 -0
  38. package/dist/billing/management.d.ts.map +1 -0
  39. package/dist/billing/management.js +113 -0
  40. package/dist/billing/management.js.map +1 -0
  41. package/dist/billing/policy-window.d.ts +24 -0
  42. package/dist/billing/policy-window.d.ts.map +1 -0
  43. package/dist/billing/policy-window.js +88 -0
  44. package/dist/billing/policy-window.js.map +1 -0
  45. package/dist/billing/postgres/repositories/auto-recharge.d.ts +32 -0
  46. package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -0
  47. package/dist/billing/postgres/repositories/auto-recharge.js +180 -0
  48. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -0
  49. package/dist/billing/postgres/repositories/customer.d.ts +12 -0
  50. package/dist/billing/postgres/repositories/customer.d.ts.map +1 -0
  51. package/dist/billing/postgres/repositories/customer.js +33 -0
  52. package/dist/billing/postgres/repositories/customer.js.map +1 -0
  53. package/dist/billing/postgres/repositories/dispute.d.ts +7 -0
  54. package/dist/billing/postgres/repositories/dispute.d.ts.map +1 -0
  55. package/dist/billing/postgres/repositories/dispute.js +18 -0
  56. package/dist/billing/postgres/repositories/dispute.js.map +1 -0
  57. package/dist/billing/postgres/repositories/event.d.ts +21 -0
  58. package/dist/billing/postgres/repositories/event.d.ts.map +1 -0
  59. package/dist/billing/postgres/repositories/event.js +45 -0
  60. package/dist/billing/postgres/repositories/event.js.map +1 -0
  61. package/dist/billing/postgres/repositories/invoice.d.ts +9 -0
  62. package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -0
  63. package/dist/billing/postgres/repositories/invoice.js +36 -0
  64. package/dist/billing/postgres/repositories/invoice.js.map +1 -0
  65. package/dist/billing/postgres/repositories/offer.d.ts +26 -0
  66. package/dist/billing/postgres/repositories/offer.d.ts.map +1 -0
  67. package/dist/billing/postgres/repositories/offer.js +73 -0
  68. package/dist/billing/postgres/repositories/offer.js.map +1 -0
  69. package/dist/billing/postgres/repositories/payment.d.ts +32 -0
  70. package/dist/billing/postgres/repositories/payment.d.ts.map +1 -0
  71. package/dist/billing/postgres/repositories/payment.js +78 -0
  72. package/dist/billing/postgres/repositories/payment.js.map +1 -0
  73. package/dist/billing/postgres/repositories/preferences.d.ts +15 -0
  74. package/dist/billing/postgres/repositories/preferences.d.ts.map +1 -0
  75. package/dist/billing/postgres/repositories/preferences.js +23 -0
  76. package/dist/billing/postgres/repositories/preferences.js.map +1 -0
  77. package/dist/billing/postgres/repositories/refund.d.ts +7 -0
  78. package/dist/billing/postgres/repositories/refund.d.ts.map +1 -0
  79. package/dist/billing/postgres/repositories/refund.js +32 -0
  80. package/dist/billing/postgres/repositories/refund.js.map +1 -0
  81. package/dist/billing/postgres/repositories/subscription.d.ts +46 -0
  82. package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -0
  83. package/dist/billing/postgres/repositories/subscription.js +187 -0
  84. package/dist/billing/postgres/repositories/subscription.js.map +1 -0
  85. package/dist/billing/postgres/repositories/topup.d.ts +27 -0
  86. package/dist/billing/postgres/repositories/topup.d.ts.map +1 -0
  87. package/dist/billing/postgres/repositories/topup.js +51 -0
  88. package/dist/billing/postgres/repositories/topup.js.map +1 -0
  89. package/dist/billing/postgres/store.d.ts +89 -0
  90. package/dist/billing/postgres/store.d.ts.map +1 -0
  91. package/dist/billing/postgres/store.js +542 -0
  92. package/dist/billing/postgres/store.js.map +1 -0
  93. package/dist/billing/service-types.d.ts +37 -0
  94. package/dist/billing/service-types.d.ts.map +1 -0
  95. package/dist/billing/service-types.js +2 -0
  96. package/dist/billing/service-types.js.map +1 -0
  97. package/dist/billing/types/auto-recharge.d.ts +56 -0
  98. package/dist/billing/types/auto-recharge.d.ts.map +1 -0
  99. package/dist/billing/types/auto-recharge.js +2 -0
  100. package/dist/billing/types/auto-recharge.js.map +1 -0
  101. package/dist/billing/types/catalog.d.ts +47 -0
  102. package/dist/billing/types/catalog.d.ts.map +1 -0
  103. package/dist/billing/types/catalog.js +2 -0
  104. package/dist/billing/types/catalog.js.map +1 -0
  105. package/dist/billing/types/common.d.ts +16 -0
  106. package/dist/billing/types/common.d.ts.map +1 -0
  107. package/dist/billing/types/common.js +2 -0
  108. package/dist/billing/types/common.js.map +1 -0
  109. package/dist/billing/types/documents.d.ts +39 -0
  110. package/dist/billing/types/documents.d.ts.map +1 -0
  111. package/dist/billing/types/documents.js +2 -0
  112. package/dist/billing/types/documents.js.map +1 -0
  113. package/dist/billing/types/events.d.ts +75 -0
  114. package/dist/billing/types/events.d.ts.map +1 -0
  115. package/dist/billing/types/events.js +38 -0
  116. package/dist/billing/types/events.js.map +1 -0
  117. package/dist/billing/types/index.d.ts +8 -0
  118. package/dist/billing/types/index.d.ts.map +1 -0
  119. package/dist/billing/types/index.js +8 -0
  120. package/dist/billing/types/index.js.map +1 -0
  121. package/dist/billing/types/preferences.d.ts +13 -0
  122. package/dist/billing/types/preferences.d.ts.map +1 -0
  123. package/dist/billing/types/preferences.js +2 -0
  124. package/dist/billing/types/preferences.js.map +1 -0
  125. package/dist/billing/types/subscriptions.d.ts +97 -0
  126. package/dist/billing/types/subscriptions.d.ts.map +1 -0
  127. package/dist/billing/types/subscriptions.js +12 -0
  128. package/dist/billing/types/subscriptions.js.map +1 -0
  129. package/dist/breakdown.d.ts +3 -1
  130. package/dist/breakdown.d.ts.map +1 -1
  131. package/dist/breakdown.js +4 -1
  132. package/dist/breakdown.js.map +1 -1
  133. package/dist/browser.d.ts +8 -0
  134. package/dist/browser.d.ts.map +1 -0
  135. package/dist/browser.js +7 -0
  136. package/dist/browser.js.map +1 -0
  137. package/dist/bursar.d.ts +84 -0
  138. package/dist/bursar.d.ts.map +1 -0
  139. package/dist/bursar.js +137 -0
  140. package/dist/bursar.js.map +1 -0
  141. package/dist/catalog.d.ts +62 -0
  142. package/dist/catalog.d.ts.map +1 -0
  143. package/dist/catalog.js +96 -0
  144. package/dist/catalog.js.map +1 -0
  145. package/dist/commerce/errors.d.ts +68 -0
  146. package/dist/commerce/errors.d.ts.map +1 -0
  147. package/dist/commerce/errors.js +105 -0
  148. package/dist/commerce/errors.js.map +1 -0
  149. package/dist/commerce/index.d.ts +6 -0
  150. package/dist/commerce/index.d.ts.map +1 -0
  151. package/dist/commerce/index.js +6 -0
  152. package/dist/commerce/index.js.map +1 -0
  153. package/dist/commerce/plan-change.d.ts +10 -0
  154. package/dist/commerce/plan-change.d.ts.map +1 -0
  155. package/dist/commerce/plan-change.js +42 -0
  156. package/dist/commerce/plan-change.js.map +1 -0
  157. package/dist/commerce/provider-registry.d.ts +18 -0
  158. package/dist/commerce/provider-registry.d.ts.map +1 -0
  159. package/dist/commerce/provider-registry.js +70 -0
  160. package/dist/commerce/provider-registry.js.map +1 -0
  161. package/dist/commerce/service.d.ts +73 -0
  162. package/dist/commerce/service.d.ts.map +1 -0
  163. package/dist/commerce/service.js +1016 -0
  164. package/dist/commerce/service.js.map +1 -0
  165. package/dist/commerce/types.d.ts +225 -0
  166. package/dist/commerce/types.d.ts.map +1 -0
  167. package/dist/commerce/types.js.map +1 -0
  168. package/dist/config/parse-access.d.ts +6 -0
  169. package/dist/config/parse-access.d.ts.map +1 -0
  170. package/dist/config/parse-access.js +72 -0
  171. package/dist/config/parse-access.js.map +1 -0
  172. package/dist/config/parse-commerce.d.ts +3 -0
  173. package/dist/config/parse-commerce.d.ts.map +1 -0
  174. package/dist/config/parse-commerce.js +236 -0
  175. package/dist/config/parse-commerce.js.map +1 -0
  176. package/dist/config/parse-credits.d.ts +3 -0
  177. package/dist/config/parse-credits.d.ts.map +1 -0
  178. package/dist/config/parse-credits.js +99 -0
  179. package/dist/config/parse-credits.js.map +1 -0
  180. package/dist/config/parse-plans.d.ts +5 -0
  181. package/dist/config/parse-plans.d.ts.map +1 -0
  182. package/dist/config/parse-plans.js +142 -0
  183. package/dist/config/parse-plans.js.map +1 -0
  184. package/dist/config/parse-pricing.d.ts +4 -0
  185. package/dist/config/parse-pricing.d.ts.map +1 -0
  186. package/dist/config/parse-pricing.js +252 -0
  187. package/dist/config/parse-pricing.js.map +1 -0
  188. package/dist/config/parse-utils.d.ts +18 -0
  189. package/dist/config/parse-utils.d.ts.map +1 -0
  190. package/dist/config/parse-utils.js +118 -0
  191. package/dist/config/parse-utils.js.map +1 -0
  192. package/dist/config/types.d.ts +340 -0
  193. package/dist/config/types.d.ts.map +1 -0
  194. package/dist/config/types.js +2 -0
  195. package/dist/config/types.js.map +1 -0
  196. package/dist/config.d.ts +12 -23
  197. package/dist/config.d.ts.map +1 -1
  198. package/dist/config.js +141 -377
  199. package/dist/config.js.map +1 -1
  200. package/dist/{stores → credits}/events.d.ts +6 -6
  201. package/dist/credits/events.d.ts.map +1 -0
  202. package/dist/{stores → credits}/events.js +5 -5
  203. package/dist/credits/events.js.map +1 -0
  204. package/dist/credits/lease-workflow.d.ts +90 -0
  205. package/dist/credits/lease-workflow.d.ts.map +1 -0
  206. package/dist/credits/lease-workflow.js +378 -0
  207. package/dist/credits/lease-workflow.js.map +1 -0
  208. package/dist/credits/low-balance-monitor.d.ts +26 -0
  209. package/dist/credits/low-balance-monitor.d.ts.map +1 -0
  210. package/dist/credits/low-balance-monitor.js +110 -0
  211. package/dist/credits/low-balance-monitor.js.map +1 -0
  212. package/dist/credits/postgres/repositories/analytics.d.ts +81 -0
  213. package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -0
  214. package/dist/credits/postgres/repositories/analytics.js +153 -0
  215. package/dist/credits/postgres/repositories/analytics.js.map +1 -0
  216. package/dist/credits/postgres/repositories/balance.d.ts +66 -0
  217. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -0
  218. package/dist/credits/postgres/repositories/balance.js +139 -0
  219. package/dist/credits/postgres/repositories/balance.js.map +1 -0
  220. package/dist/credits/postgres/repositories/bucket.d.ts +25 -0
  221. package/dist/credits/postgres/repositories/bucket.d.ts.map +1 -0
  222. package/dist/credits/postgres/repositories/bucket.js +52 -0
  223. package/dist/credits/postgres/repositories/bucket.js.map +1 -0
  224. package/dist/credits/postgres/repositories/deduction.d.ts +64 -0
  225. package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -0
  226. package/dist/credits/postgres/repositories/deduction.js +154 -0
  227. package/dist/credits/postgres/repositories/deduction.js.map +1 -0
  228. package/dist/credits/postgres/repositories/lease.d.ts +69 -0
  229. package/dist/credits/postgres/repositories/lease.d.ts.map +1 -0
  230. package/dist/credits/postgres/repositories/lease.js +148 -0
  231. package/dist/credits/postgres/repositories/lease.js.map +1 -0
  232. package/dist/credits/postgres/repositories/plan.d.ts +110 -0
  233. package/dist/credits/postgres/repositories/plan.d.ts.map +1 -0
  234. package/dist/credits/postgres/repositories/plan.js +194 -0
  235. package/dist/credits/postgres/repositories/plan.js.map +1 -0
  236. package/dist/credits/postgres/repositories/pricing.d.ts +28 -0
  237. package/dist/credits/postgres/repositories/pricing.d.ts.map +1 -0
  238. package/dist/credits/postgres/repositories/pricing.js +76 -0
  239. package/dist/credits/postgres/repositories/pricing.js.map +1 -0
  240. package/dist/credits/postgres/repositories/team.d.ts +63 -0
  241. package/dist/credits/postgres/repositories/team.d.ts.map +1 -0
  242. package/dist/credits/postgres/repositories/team.js +120 -0
  243. package/dist/credits/postgres/repositories/team.js.map +1 -0
  244. package/dist/credits/postgres/store.d.ts +89 -0
  245. package/dist/credits/postgres/store.d.ts.map +1 -0
  246. package/dist/credits/postgres/store.js +838 -0
  247. package/dist/credits/postgres/store.js.map +1 -0
  248. package/dist/credits/postgres/value-mappers.d.ts +17 -0
  249. package/dist/credits/postgres/value-mappers.d.ts.map +1 -0
  250. package/dist/credits/postgres/value-mappers.js +102 -0
  251. package/dist/credits/postgres/value-mappers.js.map +1 -0
  252. package/dist/credits/pricing-runtime.d.ts +35 -0
  253. package/dist/credits/pricing-runtime.d.ts.map +1 -0
  254. package/dist/credits/pricing-runtime.js +141 -0
  255. package/dist/credits/pricing-runtime.js.map +1 -0
  256. package/dist/credits/queries.d.ts +33 -0
  257. package/dist/credits/queries.d.ts.map +1 -0
  258. package/dist/credits/queries.js +71 -0
  259. package/dist/credits/queries.js.map +1 -0
  260. package/dist/credits/service-errors.d.ts +4 -0
  261. package/dist/credits/service-errors.d.ts.map +1 -0
  262. package/dist/credits/service-errors.js +57 -0
  263. package/dist/credits/service-errors.js.map +1 -0
  264. package/dist/credits/service-types.d.ts +122 -0
  265. package/dist/credits/service-types.d.ts.map +1 -0
  266. package/dist/credits/service-types.js +2 -0
  267. package/dist/credits/service-types.js.map +1 -0
  268. package/dist/credits/service.d.ts +220 -0
  269. package/dist/credits/service.d.ts.map +1 -0
  270. package/dist/credits/service.js +640 -0
  271. package/dist/credits/service.js.map +1 -0
  272. package/dist/credits/store.d.ts +172 -0
  273. package/dist/credits/store.d.ts.map +1 -0
  274. package/dist/{stores/credit-store.js → credits/store.js} +27 -43
  275. package/dist/credits/store.js.map +1 -0
  276. package/dist/credits/types/account.d.ts +82 -0
  277. package/dist/credits/types/account.d.ts.map +1 -0
  278. package/dist/credits/types/account.js +2 -0
  279. package/dist/credits/types/account.js.map +1 -0
  280. package/dist/credits/types/admission.d.ts +39 -0
  281. package/dist/credits/types/admission.d.ts.map +1 -0
  282. package/dist/credits/types/admission.js +2 -0
  283. package/dist/credits/types/admission.js.map +1 -0
  284. package/dist/credits/types/analytics.d.ts +52 -0
  285. package/dist/credits/types/analytics.d.ts.map +1 -0
  286. package/dist/credits/types/analytics.js +2 -0
  287. package/dist/credits/types/analytics.js.map +1 -0
  288. package/dist/credits/types/catalog.d.ts +71 -0
  289. package/dist/credits/types/catalog.d.ts.map +1 -0
  290. package/dist/credits/types/catalog.js +2 -0
  291. package/dist/credits/types/catalog.js.map +1 -0
  292. package/dist/credits/types/grants.d.ts +24 -0
  293. package/dist/credits/types/grants.d.ts.map +1 -0
  294. package/dist/credits/types/grants.js +2 -0
  295. package/dist/credits/types/grants.js.map +1 -0
  296. package/dist/credits/types/index.d.ts +9 -0
  297. package/dist/credits/types/index.d.ts.map +1 -0
  298. package/dist/credits/types/index.js +2 -0
  299. package/dist/credits/types/index.js.map +1 -0
  300. package/dist/credits/types/ledger.d.ts +87 -0
  301. package/dist/credits/types/ledger.d.ts.map +1 -0
  302. package/dist/credits/types/ledger.js +2 -0
  303. package/dist/credits/types/ledger.js.map +1 -0
  304. package/dist/credits/types/quotas.d.ts +40 -0
  305. package/dist/credits/types/quotas.d.ts.map +1 -0
  306. package/dist/credits/types/quotas.js +2 -0
  307. package/dist/credits/types/quotas.js.map +1 -0
  308. package/dist/credits/types/teams.d.ts +44 -0
  309. package/dist/credits/types/teams.d.ts.map +1 -0
  310. package/dist/credits/types/teams.js +2 -0
  311. package/dist/credits/types/teams.js.map +1 -0
  312. package/dist/engine.d.ts +18 -39
  313. package/dist/engine.d.ts.map +1 -1
  314. package/dist/engine.js +169 -145
  315. package/dist/engine.js.map +1 -1
  316. package/dist/errors.d.ts +133 -25
  317. package/dist/errors.d.ts.map +1 -1
  318. package/dist/errors.js +173 -24
  319. package/dist/errors.js.map +1 -1
  320. package/dist/expr/ast.d.ts +46 -0
  321. package/dist/expr/ast.d.ts.map +1 -0
  322. package/dist/expr/ast.js +18 -0
  323. package/dist/expr/ast.js.map +1 -0
  324. package/dist/expr/evaluator.d.ts +4 -0
  325. package/dist/expr/evaluator.d.ts.map +1 -0
  326. package/dist/expr/evaluator.js +144 -0
  327. package/dist/expr/evaluator.js.map +1 -0
  328. package/dist/expr/language.d.ts +5 -0
  329. package/dist/expr/language.d.ts.map +1 -0
  330. package/dist/expr/language.js +73 -0
  331. package/dist/expr/language.js.map +1 -0
  332. package/dist/expr/parser.d.ts +24 -0
  333. package/dist/expr/parser.d.ts.map +1 -0
  334. package/dist/expr/parser.js +175 -0
  335. package/dist/expr/parser.js.map +1 -0
  336. package/dist/expr/tokenizer.d.ts +7 -0
  337. package/dist/expr/tokenizer.d.ts.map +1 -0
  338. package/dist/expr/tokenizer.js +85 -0
  339. package/dist/expr/tokenizer.js.map +1 -0
  340. package/dist/expr.d.ts +7 -58
  341. package/dist/expr.d.ts.map +1 -1
  342. package/dist/expr.js +41 -640
  343. package/dist/expr.js.map +1 -1
  344. package/dist/generated/pricing-config.schema.json +2792 -0
  345. package/dist/generated/pricing-config.types.d.ts +685 -0
  346. package/dist/generated/pricing-config.types.d.ts.map +1 -0
  347. package/dist/generated/pricing-config.types.js +8 -0
  348. package/dist/generated/pricing-config.types.js.map +1 -0
  349. package/dist/index.d.ts +23 -17
  350. package/dist/index.d.ts.map +1 -1
  351. package/dist/index.js +12 -10
  352. package/dist/index.js.map +1 -1
  353. package/dist/load-pricing-file.d.ts.map +1 -1
  354. package/dist/load-pricing-file.js +8 -4
  355. package/dist/load-pricing-file.js.map +1 -1
  356. package/dist/metrics.d.ts +6 -16
  357. package/dist/metrics.d.ts.map +1 -1
  358. package/dist/metrics.js.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 +52 -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 +5 -3
  372. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  373. package/dist/providers/dodo/event-mapper.js +213 -38
  374. package/dist/providers/dodo/event-mapper.js.map +1 -1
  375. package/dist/providers/dodo/index.d.ts +1 -0
  376. package/dist/providers/dodo/index.d.ts.map +1 -1
  377. package/dist/providers/dodo/index.js.map +1 -1
  378. package/dist/providers/dodo/provider.d.ts +24 -14
  379. package/dist/providers/dodo/provider.d.ts.map +1 -1
  380. package/dist/providers/dodo/provider.js +249 -31
  381. package/dist/providers/dodo/provider.js.map +1 -1
  382. package/dist/providers/index.d.ts +3 -1
  383. package/dist/providers/index.d.ts.map +1 -1
  384. package/dist/providers/index.js +1 -0
  385. package/dist/providers/index.js.map +1 -1
  386. package/dist/providers/mock/index.js.map +1 -1
  387. package/dist/providers/mock/provider.d.ts +14 -10
  388. package/dist/providers/mock/provider.d.ts.map +1 -1
  389. package/dist/providers/mock/provider.js +78 -10
  390. package/dist/providers/mock/provider.js.map +1 -1
  391. package/dist/providers/stripe/event-mapper.d.ts +3 -3
  392. package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
  393. package/dist/providers/stripe/event-mapper.js +139 -30
  394. package/dist/providers/stripe/event-mapper.js.map +1 -1
  395. package/dist/providers/stripe/index.js.map +1 -1
  396. package/dist/providers/stripe/provider.d.ts +21 -12
  397. package/dist/providers/stripe/provider.d.ts.map +1 -1
  398. package/dist/providers/stripe/provider.js +175 -17
  399. package/dist/providers/stripe/provider.js.map +1 -1
  400. package/dist/providers/types.d.ts +128 -32
  401. package/dist/providers/types.d.ts.map +1 -1
  402. package/dist/providers/types.js +17 -1
  403. package/dist/providers/types.js.map +1 -1
  404. package/dist/retry.d.ts +35 -0
  405. package/dist/retry.d.ts.map +1 -0
  406. package/dist/retry.js +70 -0
  407. package/dist/retry.js.map +1 -0
  408. package/dist/shared/diagnostics.d.ts +7 -0
  409. package/dist/shared/diagnostics.d.ts.map +1 -0
  410. package/dist/shared/diagnostics.js +18 -0
  411. package/dist/shared/diagnostics.js.map +1 -0
  412. package/dist/shared/logger.d.ts +10 -0
  413. package/dist/shared/logger.d.ts.map +1 -0
  414. package/dist/shared/logger.js +15 -0
  415. package/dist/shared/logger.js.map +1 -0
  416. package/dist/shared/postgres-client.d.ts +84 -0
  417. package/dist/shared/postgres-client.d.ts.map +1 -0
  418. package/dist/shared/postgres-client.js +337 -0
  419. package/dist/shared/postgres-client.js.map +1 -0
  420. package/dist/shared/postgres-errors.d.ts +11 -0
  421. package/dist/shared/postgres-errors.d.ts.map +1 -0
  422. package/dist/shared/postgres-errors.js +105 -0
  423. package/dist/shared/postgres-errors.js.map +1 -0
  424. package/dist/shared/postgres-types.d.ts +7 -0
  425. package/dist/shared/postgres-types.d.ts.map +1 -0
  426. package/dist/shared/postgres-types.js +2 -0
  427. package/dist/shared/postgres-types.js.map +1 -0
  428. package/dist/shared/postgres-validation.d.ts +8 -0
  429. package/dist/shared/postgres-validation.d.ts.map +1 -0
  430. package/dist/shared/postgres-validation.js +40 -0
  431. package/dist/shared/postgres-validation.js.map +1 -0
  432. package/dist/storage/adapters/clickhouse.d.ts +61 -0
  433. package/dist/storage/adapters/clickhouse.d.ts.map +1 -0
  434. package/dist/storage/adapters/clickhouse.js +347 -0
  435. package/dist/storage/adapters/clickhouse.js.map +1 -0
  436. package/dist/storage/adapters/s3.d.ts +35 -0
  437. package/dist/storage/adapters/s3.d.ts.map +1 -0
  438. package/dist/storage/adapters/s3.js +100 -0
  439. package/dist/storage/adapters/s3.js.map +1 -0
  440. package/dist/storage/outbox-worker.d.ts +41 -0
  441. package/dist/storage/outbox-worker.d.ts.map +1 -0
  442. package/dist/storage/outbox-worker.js +146 -0
  443. package/dist/storage/outbox-worker.js.map +1 -0
  444. package/dist/storage/ports.d.ts +78 -0
  445. package/dist/storage/ports.d.ts.map +1 -0
  446. package/dist/storage/ports.js +2 -0
  447. package/dist/storage/ports.js.map +1 -0
  448. package/dist/storage/postgres-repository.d.ts +14 -0
  449. package/dist/storage/postgres-repository.d.ts.map +1 -0
  450. package/dist/storage/postgres-repository.js +140 -0
  451. package/dist/storage/postgres-repository.js.map +1 -0
  452. package/dist/storage/runtime.d.ts +77 -0
  453. package/dist/storage/runtime.d.ts.map +1 -0
  454. package/dist/storage/runtime.js +369 -0
  455. package/dist/storage/runtime.js.map +1 -0
  456. package/package.json +43 -21
  457. package/dist/allowance.d.ts +0 -48
  458. package/dist/allowance.d.ts.map +0 -1
  459. package/dist/allowance.js +0 -140
  460. package/dist/allowance.js.map +0 -1
  461. package/dist/billing/billing-manager.d.ts +0 -66
  462. package/dist/billing/billing-manager.d.ts.map +0 -1
  463. package/dist/billing/billing-manager.js +0 -560
  464. package/dist/billing/billing-manager.js.map +0 -1
  465. package/dist/billing/billing-types.d.ts +0 -203
  466. package/dist/billing/billing-types.d.ts.map +0 -1
  467. package/dist/billing/billing-types.js +0 -6
  468. package/dist/billing/billing-types.js.map +0 -1
  469. package/dist/billing/memory-billing-store.d.ts +0 -37
  470. package/dist/billing/memory-billing-store.d.ts.map +0 -1
  471. package/dist/billing/memory-billing-store.js +0 -197
  472. package/dist/billing/memory-billing-store.js.map +0 -1
  473. package/dist/billing/postgres-billing-store.d.ts +0 -35
  474. package/dist/billing/postgres-billing-store.d.ts.map +0 -1
  475. package/dist/billing/postgres-billing-store.js +0 -274
  476. package/dist/billing/postgres-billing-store.js.map +0 -1
  477. package/dist/billing/supabase-billing-store.d.ts +0 -29
  478. package/dist/billing/supabase-billing-store.d.ts.map +0 -1
  479. package/dist/billing/supabase-billing-store.js +0 -250
  480. package/dist/billing/supabase-billing-store.js.map +0 -1
  481. package/dist/manager.d.ts +0 -444
  482. package/dist/manager.d.ts.map +0 -1
  483. package/dist/manager.js +0 -1153
  484. package/dist/manager.js.map +0 -1
  485. package/dist/stores/credit-store.d.ts +0 -198
  486. package/dist/stores/credit-store.d.ts.map +0 -1
  487. package/dist/stores/credit-store.js.map +0 -1
  488. package/dist/stores/events.d.ts.map +0 -1
  489. package/dist/stores/events.js.map +0 -1
  490. package/dist/stores/memory-store.d.ts +0 -187
  491. package/dist/stores/memory-store.d.ts.map +0 -1
  492. package/dist/stores/memory-store.js +0 -1890
  493. package/dist/stores/memory-store.js.map +0 -1
  494. package/dist/stores/postgres-store.d.ts +0 -100
  495. package/dist/stores/postgres-store.d.ts.map +0 -1
  496. package/dist/stores/postgres-store.js +0 -891
  497. package/dist/stores/postgres-store.js.map +0 -1
  498. package/dist/stores/supabase-store.d.ts +0 -87
  499. package/dist/stores/supabase-store.d.ts.map +0 -1
  500. package/dist/stores/supabase-store.js +0 -948
  501. package/dist/stores/supabase-store.js.map +0 -1
  502. package/dist/types.d.ts +0 -463
  503. package/dist/types.d.ts.map +0 -1
  504. package/dist/types.js.map +0 -1
  505. /package/dist/{types.js → commerce/types.js} +0 -0
package/README.md CHANGED
@@ -1,375 +1,160 @@
1
- # @zonastery/bursar
2
-
3
- [![CI](https://github.com/Zonastery/bursar/actions/workflows/ci.yml/badge.svg)](https://github.com/Zonastery/bursar/actions/workflows/ci.yml)
4
- [![npm](https://img.shields.io/npm/v/@zonastery/bursar)](https://www.npmjs.com/package/@zonastery/bursar)
5
- [![License: AGPL-3.0](https://img.shields.io/badge/license-AGPL--3.0-blue)](https://github.com/Zonastery/bursar/blob/main/LICENSE)
6
-
7
- Add usage-based credits to your AI SaaS in minutes — not weeks.
8
-
9
- bursar is a drop-in credit calculation engine. Define pricing as math expressions
10
- (per-model, per-tool, search/RAG, cache, fixed jobs), connect a database, and
11
- start deducting credits. Pricing lives in your DB — update it live without redeploys.
12
-
13
- ```typescript
14
- import { CreditManager } from "@zonastery/bursar";
15
- import { MemoryStore } from "@zonastery/bursar/node"; // Node-only (uses `crypto`)
16
-
17
- const store = new MemoryStore();
18
- const manager = new CreditManager(store);
19
-
20
- await manager.publishPricingFromDict({
21
- version: 1,
22
- models: { "_default": "input_tokens * (0.01 / 1000) + output_tokens * (0.03 / 1000)" },
23
- plans: {
24
- free: { id: "free", name: "Free Tier", freeAllowance: 50000 },
25
- pro: { id: "pro", name: "Pro Plan", freeAllowance: 500000 },
26
- },
27
- });
28
-
29
- await manager.addCredits("user_abc", 1000); // number or decimal.js Decimal
30
- ```
31
-
32
- Works in Node.js 18+, Bun, and Deno. ESM-only.
33
-
34
- ## Features
35
-
36
- - **Safe expression engine** — Recursive descent parser with strict allowlist. `min`, `max`, `if`, `tier`, `clamp`, `ceil`, `floor`, `round`, `percentile`. No eval/Function().
37
- - **Plan-based pricing** — Subscription plans with free monthly allowances and rate overrides. Allowance consumed before balance.
38
- - **Refunds** — Full and partial credit reversals with duplicate detection.
39
- - **Credit expiry / TTL** — Time-bound credits with `expiresAt` on `addCredits`. Sweep with dry-run mode.
40
- - **Team / shared balances** — Separate team credit pools with per-member spend caps.
41
- - **Spend caps** — Per-user daily/monthly limits with `deny`, `warn`, `notify` actions. Per-model caps supported.
42
- - **Usage analytics** — `spendByUser`, `spendByModel`, `topUsers`, `dailySpend`, `aggregateStats` across time windows.
43
- - **Event hooks** — Typed pub/sub for `credits.deducted`, `credits.added`, `credits.refunded`, `credits.expired`, `credits.cap_reached`, `credits.cap_warning`, `credits.low_balance`.
44
- - **Database-backed pricing** — Live updates without redeploys. Dict loading for testing.
45
- - **Multi-dimensional** — Per-model (with `_default` fallback), per-tool overrides, search/RAG, cache discounts, fixed-cost jobs.
46
- - **Pluggable storage** — One atomic, idempotency-keyed `deductWithAllowance` per `CreditStore`: Supabase (native fetch, zero deps), PostgreSQL (`pg`), or in-memory. The two-phase reserve-then-deduct API is also available.
47
- - **Safe defaults** — `minBalance` floor, idempotent deductions, concurrent-deduction protection.
48
- - **Exact decimal money** — All credit amounts are [`decimal.js`](https://github.com/MikeMcl/decimal.js) `Decimal` values, quantized to 4 dp (`ROUND_HALF_UP`). No binary-float rounding or truncation of sub-credit costs.
49
- - **Auditable** — Structured `CostBreakdown` with per-dimension costs.
1
+ # Bursar for JavaScript
2
+
3
+ [![npm](https://img.shields.io/npm/v/@zonastery/bursar.svg)](https://www.npmjs.com/package/@zonastery/bursar)
4
+ [![npm downloads](https://img.shields.io/npm/dm/@zonastery/bursar.svg)](https://www.npmjs.com/package/@zonastery/bursar)
5
+
6
+ <p align="center">
7
+ <img
8
+ src="https://raw.githubusercontent.com/zonastery/bursar/main/docs/static/img/logo.png"
9
+ alt="Bursar logo"
10
+ width="192"
11
+ height="192"
12
+ />
13
+ </p>
14
+
15
+ The TypeScript SDK for [Bursar](https://github.com/Zonastery/bursar) — a
16
+ behavioral mirror of the Python SDK. It meters usage, prices operations, and
17
+ manages balances against the shared canonical PostgreSQL schema and the same
18
+ versioned configuration document, with identical rounding. `@zonastery/bursar`
19
+ is ESM-only and requires Node.js 22 or newer.
50
20
 
51
21
  ## Installation
52
22
 
53
23
  ```bash
54
24
  npm install @zonastery/bursar
55
-
56
- # PostgreSQL store (optional)
57
- npm install pg
58
-
59
- # YAML pricing loading (optional)
60
- npm install js-yaml
61
25
  ```
62
26
 
63
- Requires Node.js 18+ (native `fetch` for Supabase store).
64
-
65
- ## Full docs
66
-
67
- **[zonastery.github.io/bursar](https://zonastery.github.io/bursar/)** — JS API reference, expressions, configuration, examples.
27
+ Optional peer dependencies: `pg` (PostgresStore), `stripe` and `dodopayments`
28
+ (provider billing), `js-yaml` (YAML config loading). No peer is required for
29
+ core credits.
68
30
 
69
- ## Quick Start
31
+ ## Database setup
70
32
 
71
- ### Calculation only (no database)
33
+ Database installation belongs to the SQL baseline, not to the SDK. Apply it
34
+ with the Python migration CLI:
72
35
 
73
- ```typescript
74
- import { PricingEngine } from "@zonastery/bursar";
75
-
76
- const engine = PricingEngine.fromDict({
77
- version: 1,
78
- models: {
79
- "gpt-4": "input_tokens * (0.01 / 1000) + output_tokens * (0.03 / 1000)",
80
- "_default": "input_tokens * (0.001 / 1000) + output_tokens * (0.003 / 1000)",
81
- },
82
- });
83
-
84
- const cost = engine.calculate({
85
- model: "gpt-4",
86
- inputTokens: 500,
87
- outputTokens: 200,
88
- });
89
- // cost.total is a decimal.js `Decimal` (quantized to 4 dp, ROUND_HALF_UP)
90
- console.log(`Total: ${cost.total.toString()}`); // 0.0110
36
+ ```bash
37
+ pip install bursar[postgres]
38
+ export DATABASE_URL=postgresql://...
39
+ bursar migrate
91
40
  ```
92
41
 
93
- ### Full credit lifecycle (in-memory)
94
-
95
- ```typescript
96
- import { CreditManager } from "@zonastery/bursar";
97
- import { MemoryStore } from "@zonastery/bursar/node"; // Node-only (uses `crypto`)
98
- import Decimal from "decimal.js";
42
+ ## Usage
99
43
 
100
- const store = new MemoryStore();
101
- const manager = new CreditManager(store);
44
+ ```ts
45
+ import { Bursar, PostgresStore } from "@zonastery/bursar";
102
46
 
103
- // publishPricingFromDict is async — it syncs the config to the store.
104
- await manager.publishPricingFromDict({
105
- version: 1,
106
- models: { "_default": "input_tokens * (0.01 / 1000) + output_tokens * (0.03 / 1000)" },
107
- plans: {
108
- free: { id: "free", name: "Free Tier", freeAllowance: 50000 },
109
- pro: { id: "pro", name: "Pro Plan", freeAllowance: 500000 },
110
- },
47
+ const store = new PostgresStore(process.env.DATABASE_URL!, tenantId, {
48
+ connectionTimeoutMs: 10_000,
49
+ statementTimeoutMs: 30_000,
50
+ onPoolError: (error) => console.error("Bursar PostgreSQL pool error", error),
111
51
  });
52
+ const bursar = new Bursar({ creditStore: store });
112
53
 
113
- // Money amounts accept a plain `number` or a `decimal.js` Decimal.
114
- await manager.addCredits("user_abc", new Decimal(1000));
115
- const result = await manager.deduct(
116
- "user_abc",
117
- { model: "gpt-4", inputTokens: 500, outputTokens: 200 },
118
- "idempotency-key-123",
119
- );
120
- console.log(`Charged: ${result.amount.toString()}`); // Decimal
121
- console.log(`Remaining balance: ${(await manager.getBalance("user_abc")).balance.toString()}`);
122
- ```
123
-
124
- ### Production with Supabase
125
-
126
- ```typescript
127
- import { CreditManager } from "@zonastery/bursar";
128
- import { HttpxSupabaseStore } from "@zonastery/bursar";
129
-
130
- const store = new HttpxSupabaseStore(
131
- "https://your-project.supabase.co",
132
- "service_role_key"
133
- );
134
- const manager = new CreditManager(store);
135
- await manager.loadPricingFromStore();
136
- await manager.addCredits("user_abc", 5000);
137
- ```
138
-
139
- ### Plan-based pricing
140
-
141
- ```typescript
142
- import { CreditManager } from "@zonastery/bursar";
143
- import { MemoryStore } from "@zonastery/bursar/node"; // Node-only (uses `crypto`)
144
-
145
- const store = new MemoryStore();
146
- const manager = new CreditManager(store);
147
-
148
- await manager.publishPricingFromDict({
149
- version: 1,
150
- models: { "_default": "input_tokens * 1" },
151
- plans: {
152
- free: { id: "free", name: "Free Tier", freeAllowance: 50000 },
153
- },
54
+ const grant = await bursar.credits.addCredits(userId, 500, {
55
+ type: "purchase",
56
+ idempotencyKey: "checkout:42",
154
57
  });
155
- await store.setUserPlan("user-1", "free");
156
- await manager.addCredits("user-1", 10);
157
-
158
- // First 50000 credits are free — no balance deduction
159
- const result = await manager.deduct("user-1", { inputTokens: 5 });
160
- console.log(result.amount.toString()); // "0" — covered by allowance
161
- ```
162
-
163
- ## Feature Examples
164
-
165
- ### Refunds
166
-
167
- ```typescript
168
- const tx = await manager.deduct("user-1", { model: "gpt-4", inputTokens: 100 });
169
- const refund = await manager.refundCredits(tx.transactionId); // full refund
170
- const partial = await manager.refundCredits(tx.transactionId, 5); // partial
171
- ```
172
-
173
- ### Credit expiry
174
-
175
- ```typescript
176
- await manager.addCredits("user-1", 100, "purchase", null, new Date("2025-01-01"));
177
- const result = await manager.sweepExpiredCredits(); // sweep
178
- const report = await manager.sweepExpiredCredits(true); // preview only
179
- ```
180
-
181
- ### Team / shared balances
182
-
183
- ```typescript
184
- const team = await store.createTeam("Engineering", 5000);
185
- await store.addTeamMember(team.teamId, "user-1", "admin", 1000);
186
- const result = await manager.deductTeam(team.teamId, "user-1", { model: "gpt-4", inputTokens: 500 });
58
+ const charge = await bursar.credits.deductCredits(userId, 20, {
59
+ idempotencyKey: "job:42",
60
+ });
61
+ const refund = await bursar.credits.refundCredits(charge.entryId);
62
+
63
+ let page = await bursar.credits.listLedgerEntries(userId, { limit: 25 });
64
+ while (page.nextCursor) {
65
+ page = await bursar.credits.listLedgerEntries(userId, {
66
+ limit: 25,
67
+ cursor: page.nextCursor,
68
+ });
69
+ }
187
70
  ```
188
71
 
189
- ### Spend caps
72
+ `LedgerEntry`, `LedgerCursor`, and `LedgerPage` are the public history
73
+ contract; pagination is cursor-only. Publish one versioned configuration
74
+ document through the facade — billing and auto-recharge read the same active
75
+ document:
190
76
 
191
- ```typescript
192
- store.setSpendCap({ userId: "user-1", type: "daily", limit: 100, action: "deny" });
77
+ ```ts
78
+ await bursar.catalog.publishAndActivate(config);
193
79
  ```
194
80
 
195
- ### Financial safety (leases)
81
+ ## Errors, deadlines, and retries
196
82
 
197
- Because bursar charges *after* the AI call, the safe pattern is an atomic **lease** taken *before* the work: `reserve` a worst-case hold against `available = balance − Σ(active holds)`, do the work, then `settle` the **actual** cost (de-clamped) or `release` to cancel. `reserve` is the only admission gate. Two presets: `strict_prepaid` (default; floor ≥ 0, structurally zero debt) and `overdraft` (negative floor; bills full actual; for paid users with auto-reload).
83
+ All Bursar-classified failures extend `BursarError` and carry stable `code`,
84
+ `category`, and `retryable` fields. Native `cause` chains retain the underlying
85
+ driver error without exposing it from
86
+ `bursarErrorPublicMessage()` or the serialized `toJSON()` shape. PostgreSQL
87
+ failures are classified primarily from SQLSTATE and network error codes, with
88
+ narrow fallbacks for the stable timeout messages emitted by `pg` itself.
198
89
 
199
- ```typescript
200
- import Decimal from "decimal.js";
90
+ `PostgresStore` and `PostgresBillingStore` use a 10-second connection deadline,
91
+ a 30-second server-side statement deadline, and a 30-second idle-transaction
92
+ deadline by default. All are configurable. An SDK-owned pool also installs an
93
+ idle-client error listener so a network partition cannot become an uncaught
94
+ EventEmitter error.
201
95
 
202
- const manager = new CreditManager(store, null, null, { policy: "strict_prepaid" }); // or { policy: "overdraft", overdraftFloor: new Decimal(-50) }
203
- const lease = await manager.reserve("user-1", new Decimal(40)); // worst-case hold
204
- const deduction = await manager.settle("user-1", lease.leaseId, new Decimal(11)); // actual cost; de-clamped
205
- // on failure: await manager.release("user-1", lease.leaseId); // idempotent
206
- ```
96
+ Use `retryBursarOperation()` only for reads or idempotent mutations. It uses
97
+ bounded exponential backoff with jitter, an elapsed-time budget, and optional
98
+ `AbortSignal` cancellation:
207
99
 
208
- ### Usage analytics
100
+ ```ts
101
+ import { isBursarError, retryBursarOperation } from "@zonastery/bursar";
209
102
 
210
- ```typescript
211
- const now = new Date();
212
- const start = new Date(now.getTime() - 30 * 86400000);
213
- await manager.spendByUser(start, now); // per-user totals
214
- await manager.spendByModel(start, now); // per-model spend
215
- await manager.topUsers(10, start, now); // top 10 users
216
- await manager.dailySpend(start, now); // daily buckets
217
- await manager.aggregateStats(start, now); // aggregate summary
218
- ```
219
-
220
- ### Events
221
-
222
- ```typescript
223
- import { CreditEventEmitter } from "@zonastery/bursar";
224
- const emitter = new CreditEventEmitter();
225
- const manager = new CreditManager(store, null, emitter);
226
- emitter.on("credits.deducted", (e) => console.log(`User ${e.userId} spent credits`));
227
- emitter.on("credits.low_balance", (e) => sendAlert(e.userId, e.data?.balance));
228
- ```
229
-
230
- ## Pricing Configuration
231
-
232
- Basic example:
233
-
234
- ```json
235
- {
236
- "version": 1,
237
- "models": {
238
- "gpt-4": "input_tokens * (0.01 / 1000) + output_tokens * (0.03 / 1000)",
239
- "_default": "input_tokens * (0.001 / 1000) + output_tokens * (0.003 / 1000)"
240
- },
241
- "tools": { "_default": "tool_calls * 5 / 1000" },
242
- "search": { "costs": "search_queries * 0.5 + search_results * 0.05" },
243
- "cache": { "discount": "-cache_read_tokens * (0.001 / 1000)" },
244
- "fixed": { "batch_train": 100 },
245
- "minBalance": 5
103
+ try {
104
+ const balance = await retryBursarOperation(() => bursar.credits.getBalance(userId), {
105
+ maxAttempts: 3,
106
+ signal: request.signal,
107
+ });
108
+ } catch (error) {
109
+ if (isBursarError(error)) {
110
+ console.error("Bursar request failed", error.toJSON());
111
+ }
112
+ throw error;
246
113
  }
247
114
  ```
248
115
 
249
- ### Expression syntax
116
+ `StoreError.indeterminate` means a transport failure occurred when a mutation
117
+ may have reached PostgreSQL. Retry only with the same idempotency key. A plain
118
+ `StoreError` is deliberately non-retryable; custom stores should throw
119
+ `StoreUnavailableError` or `StoreTimeoutError` only for classified transient
120
+ failures.
250
121
 
251
- | Feature | Example |
252
- |---------|---------|
253
- | Arithmetic | `+`, `-`, `*`, `/`, `//`, `%` |
254
- | Comparisons | `==`, `!=`, `<`, `<=`, `>`, `>=`, `in`, `not in` |
255
- | Boolean | `and`, `or`, `not` |
256
- | Ternary | `X if cond else Y` |
257
- | Functions | `ceil`, `floor`, `round`, `min`, `max`, `if(cond,t,f)`, `tier(v,t1,r1,t2,r2,...)`, `clamp(x,lo,hi)`, `percentile(p,v1,v2,...)` |
122
+ ## Optional S3 and ClickHouse storage
258
123
 
259
- > Exponentiation (`**`) is **not allowed** in pricing expressions — it is rejected
260
- > at config-load time (`ExpressionError`) as a sandbox-safety measure. Division and
261
- > modulo by zero, and any non-finite result, are rejected the same way.
124
+ PostgreSQL remains authoritative. S3 and ClickHouse are optional delivery
125
+ targets, managed by `createBursarRuntime` from `@zonastery/bursar/node`:
262
126
 
263
- ### Loading from file
127
+ ```ts
128
+ import { createBursarRuntime } from "@zonastery/bursar/node";
264
129
 
265
- `loadPricingFile` reads Node's filesystem, so it ships from the `@zonastery/bursar/node`
266
- subpath (not the root entry point). YAML files require the optional `js-yaml` peer
267
- dependency; if it is missing, an `ImportError` is thrown.
130
+ const runtime = await createBursarRuntime({
131
+ postgres: process.env.DATABASE_URL!,
132
+ tenantId: process.env.BURSAR_TENANT_ID!,
133
+ });
134
+ await runtime.start();
135
+ const bursar = runtime.bursar;
136
+ ```
268
137
 
269
- ```typescript
270
- import { PricingEngine } from "@zonastery/bursar";
271
- import { loadPricingFile } from "@zonastery/bursar/node";
138
+ With no S3/ClickHouse configuration the runtime creates no background worker
139
+ and analytics query PostgreSQL directly. See the
140
+ [storage guide](https://zonastery.github.io/bursar/docs/guides/storage-backends)
141
+ for the full S3 and ClickHouse setup.
272
142
 
273
- const data = await loadPricingFile("./pricing.yaml");
274
- const engine = PricingEngine.fromDict(data);
275
- ```
143
+ ## Development
276
144
 
277
- ### Available metrics
278
-
279
- | Variable | Source | Type |
280
- |----------|--------|------|
281
- | `input_tokens` | `metrics.inputTokens` | `number` |
282
- | `output_tokens` | `metrics.outputTokens` | `number` |
283
- | `cache_read_tokens` | `metrics.cacheReadTokens` | `number` |
284
- | `cache_write_tokens` | `metrics.cacheWriteTokens` | `number` |
285
- | `tool_calls` | `metrics.toolCalls.length` | `number` |
286
- | `search_queries` | `metrics.searchQueries` | `number` |
287
- | `search_results` | `metrics.searchResults` | `number` |
288
- | `web_search_calls` | `metrics.webSearchCalls` | `number` |
289
- | `code_exec_calls` | `metrics.codeExecCalls` | `number` |
290
-
291
- ## Store adapters
292
-
293
- | Store | Import | Deps | Use case |
294
- |-------|--------|------|----------|
295
- | `MemoryStore` | `@zonastery/bursar/node` | None (uses Node `crypto`) | Testing, development |
296
- | `HttpxSupabaseStore` | `@zonastery/bursar` | Node 18+ (`fetch`) | Supabase production |
297
- | `PostgresStore` | `@zonastery/bursar` | `pg` (optional peer) | Direct PostgreSQL |
298
-
299
- `PostgresStore` requires the optional `pg` peer dependency (`npm install pg`); it
300
- is dynamically imported and throws if missing.
301
-
302
- ## API
303
-
304
- ### `PricingEngine`
305
-
306
- ```typescript
307
- PricingEngine.fromDict(data): PricingEngine
308
- engine.calculate(metrics: UsageMetrics): CostBreakdown // CostBreakdown.total is a Decimal
309
- engine.calculateBatch(metrics: UsageMetrics[]): CostBreakdown[]
310
- engine.resolveModel(modelVersion: string): string | null
311
- engine.hasModel(modelName: string): boolean
312
- engine.getFixedCost(jobName: string): Decimal | null
313
- engine.pricingSchema(): PricingConfigData
314
- engine.knownVariables: Set<string>
315
- engine.minBalance: number
145
+ ```bash
146
+ cd javascript
147
+ bun ci # Bun 1.3.14; installs the committed bun.lock
148
+ bun run typecheck
149
+ bun run test # integration tests need Postgres (DATABASE_URL or testcontainer)
150
+ bun run lint
151
+ bun run build
316
152
  ```
317
153
 
318
- ### `CreditManager`
319
-
320
- All money parameters (`amount`, `minBalance`) accept a plain `number` or a
321
- `decimal.js` `Decimal`. All money fields on returned results (`amount`,
322
- `balance`, `balanceAfter`, `newBalance`, `allowanceConsumed`, …) are `Decimal`.
323
-
324
- ```typescript
325
- new CreditManager(store: CreditStore, engine?, emitter?, options?: CreditManagerOptions)
326
-
327
- // Setup / pricing
328
- manager.setup(): Promise<SetupResult>
329
- manager.publishPricingFromDict(data): Promise<void>
330
- manager.loadPricingFromStore(): Promise<void>
331
- manager.publishPricing(config, label?): Promise<void>
332
-
333
- // Balance ops
334
- manager.getBalance(userId): Promise<BalanceResult>
335
- manager.addCredits(userId, amount: Decimal | number, type?, metadata?, expiresAt?): Promise<AddCreditsResult>
336
- manager.reserveCredits(userId, amount: Decimal | number, opType?, metadata?, minBalance?): Promise<ReserveResult>
337
- manager.deduct(userId, metrics, idempotencyKey?, metadata?): Promise<DeductionResult>
338
- manager.deductFixed(userId, jobName, idempotencyKey?, metadata?): Promise<DeductionResult> // throws ConfigError on unknown job
339
-
340
- // Plans
341
- manager.getUserPlan(userId): Promise<GetUserPlanResult>
342
- manager.checkFeature(userId, feature): Promise<CheckFeatureResult>
343
-
344
- // Refunds
345
- manager.refundCredits(transactionId, amount?: Decimal | number, reason?, metadata?): Promise<RefundResult>
346
-
347
- // Expiry
348
- manager.sweepExpiredCredits(dryRun?): Promise<SweepResult>
349
-
350
- // Teams
351
- manager.deductTeam(teamId, userId, metrics, idempotencyKey?, metadata?): Promise<TeamDeductionResult>
352
-
353
- // Analytics
354
- manager.spendByUser(start, end): Promise<SpendByUserRow[]>
355
- manager.spendByModel(start, end): Promise<SpendByModelRow[]>
356
- manager.topUsers(limit, start, end): Promise<TopUserRow[]>
357
- manager.dailySpend(start, end): Promise<DailySpendRow[]>
358
- manager.aggregateStats(start, end): Promise<AggregateStats>
359
- manager.listUserTransactions(userId, options?): Promise<PaginatedTransactions>
360
- manager.listUsageEvents(userId, options?): Promise<PaginatedTransactions>
361
-
362
- // Events
363
- const emitter = new CreditEventEmitter();
364
- emitter.on("credits.deducted", handler);
365
- emitter.on("credits.low_balance", handler);
366
- // ... credits.added, credits.refunded, credits.expired, credits.cap_reached,
367
- // credits.cap_warning, credits.deduct_failed, credits.refund_failed
368
-
369
- // Properties
370
- manager.pricingEngine: PricingEngine | null
371
- ```
154
+ Bun manages development dependencies and scripts; consumers of the published
155
+ package do not need it. See
156
+ [CONTRIBUTING.md](https://github.com/Zonastery/bursar/blob/main/CONTRIBUTING.md).
372
157
 
373
158
  ## License
374
159
 
375
- MIT
160
+ AGPL-3.0.
@@ -0,0 +1,27 @@
1
+ import type { BillingAutoRechargeAttempt, BillingAutoRechargeProfile, BillingCustomerRecord, BillingTopupResult } from "./types/index.js";
2
+ /** Narrow billing capability required by AutoRechargeService. */
3
+ export interface AutoRechargeBillingPort {
4
+ getActiveBursarConfig(): Promise<Record<string, unknown> | null>;
5
+ resolveTopup(provider: string, productId?: string | null, priceId?: string | null): Promise<BillingTopupResult | null>;
6
+ resolveTopupByLookup(provider: string, lookupKey: string): Promise<BillingTopupResult | null>;
7
+ getCustomerByUserId(userId: string, provider?: string | null): Promise<BillingCustomerRecord | null>;
8
+ getAutoRechargeProfile(userId: string): Promise<BillingAutoRechargeProfile | null>;
9
+ upsertAutoRechargeProfile(profile: BillingAutoRechargeProfile, options?: {
10
+ resetCooldown?: boolean;
11
+ }): Promise<void>;
12
+ claimAutoRechargeAttempt(input: {
13
+ userId: string;
14
+ idempotencyKey: string;
15
+ }): Promise<BillingAutoRechargeAttempt | null>;
16
+ updateAutoRechargeAttempt(input: {
17
+ id: string;
18
+ state: string;
19
+ providerAttemptId?: string | null;
20
+ failureCode?: string | null;
21
+ failureMessage?: string | null;
22
+ metadata?: Record<string, unknown>;
23
+ }): Promise<void>;
24
+ /** Count attempts since an exact instant. */
25
+ countAutoRechargeAttempts(userId: string, since: string | Date): Promise<number>;
26
+ }
27
+ //# sourceMappingURL=auto-recharge-port.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auto-recharge-port.d.ts","sourceRoot":"","sources":["../../src/billing/auto-recharge-port.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,0BAA0B,EAC1B,0BAA0B,EAC1B,qBAAqB,EACrB,kBAAkB,EACnB,MAAM,kBAAkB,CAAC;AAE1B,iEAAiE;AACjE,MAAM,WAAW,uBAAuB;IACtC,qBAAqB,IAAI,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC;IACjE,YAAY,CACV,QAAQ,EAAE,MAAM,EAChB,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,EACzB,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,GACtB,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC,CAAC;IACtC,oBAAoB,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC,CAAC;IAC9F,mBAAmB,CACjB,MAAM,EAAE,MAAM,EACd,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,GACvB,OAAO,CAAC,qBAAqB,GAAG,IAAI,CAAC,CAAC;IACzC,sBAAsB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,0BAA0B,GAAG,IAAI,CAAC,CAAC;IACnF,yBAAyB,CACvB,OAAO,EAAE,0BAA0B,EACnC,OAAO,CAAC,EAAE;QAAE,aAAa,CAAC,EAAE,OAAO,CAAA;KAAE,GACpC,OAAO,CAAC,IAAI,CAAC,CAAC;IACjB,wBAAwB,CAAC,KAAK,EAAE;QAC9B,MAAM,EAAE,MAAM,CAAC;QACf,cAAc,EAAE,MAAM,CAAC;KACxB,GAAG,OAAO,CAAC,0BAA0B,GAAG,IAAI,CAAC,CAAC;IAC/C,yBAAyB,CAAC,KAAK,EAAE;QAC/B,EAAE,EAAE,MAAM,CAAC;QACX,KAAK,EAAE,MAAM,CAAC;QACd,iBAAiB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;QAClC,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;QAC5B,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;QAC/B,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;KACpC,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAClB,6CAA6C;IAC7C,yBAAyB,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;CAClF"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=auto-recharge-port.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auto-recharge-port.js","sourceRoot":"","sources":["../../src/billing/auto-recharge-port.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n BillingAutoRechargeAttempt,\n BillingAutoRechargeProfile,\n BillingCustomerRecord,\n BillingTopupResult,\n} from \"./types/index.js\";\n\n/** Narrow billing capability required by AutoRechargeService. */\nexport interface AutoRechargeBillingPort {\n getActiveBursarConfig(): Promise<Record<string, unknown> | null>;\n resolveTopup(\n provider: string,\n productId?: string | null,\n priceId?: string | null,\n ): Promise<BillingTopupResult | null>;\n resolveTopupByLookup(provider: string, lookupKey: string): Promise<BillingTopupResult | null>;\n getCustomerByUserId(\n userId: string,\n provider?: string | null,\n ): Promise<BillingCustomerRecord | null>;\n getAutoRechargeProfile(userId: string): Promise<BillingAutoRechargeProfile | null>;\n upsertAutoRechargeProfile(\n profile: BillingAutoRechargeProfile,\n options?: { resetCooldown?: boolean },\n ): Promise<void>;\n claimAutoRechargeAttempt(input: {\n userId: string;\n idempotencyKey: string;\n }): Promise<BillingAutoRechargeAttempt | null>;\n updateAutoRechargeAttempt(input: {\n id: string;\n state: string;\n providerAttemptId?: string | null;\n failureCode?: string | null;\n failureMessage?: string | null;\n metadata?: Record<string, unknown>;\n }): Promise<void>;\n /** Count attempts since an exact instant. */\n countAutoRechargeAttempts(userId: string, since: string | Date): Promise<number>;\n}\n"]}
@@ -0,0 +1,43 @@
1
+ import type { BillingAutoRechargeStatus } from "./types/index.js";
2
+ import type { PaymentProvider, SavedPaymentChargeQuote, SavedPaymentChargeResult } from "../providers/types.js";
3
+ import type { AutoRechargeBillingPort } from "./auto-recharge-port.js";
4
+ export type AutoRechargeOutcome = "not_configured" | "disabled" | "above_threshold" | "already_processing" | "limit_reached" | "submitted" | "action_required" | "failed";
5
+ export interface AutoRechargeProcessResult {
6
+ outcome: AutoRechargeOutcome;
7
+ charge?: SavedPaymentChargeResult | null;
8
+ }
9
+ export declare class AutoRechargeService {
10
+ private readonly billing;
11
+ constructor(billing: AutoRechargeBillingPort);
12
+ private policy;
13
+ private paymentMethod;
14
+ quote(input: {
15
+ userId: string;
16
+ provider: PaymentProvider;
17
+ }): Promise<SavedPaymentChargeQuote | null>;
18
+ getStatus(input: {
19
+ userId: string;
20
+ provider: PaymentProvider;
21
+ }): Promise<BillingAutoRechargeStatus | null>;
22
+ enable(input: {
23
+ userId: string;
24
+ provider: PaymentProvider;
25
+ balance: number;
26
+ returnUrl?: string;
27
+ consentReference?: string;
28
+ }): Promise<BillingAutoRechargeStatus | null>;
29
+ disable(userId: string): Promise<void>;
30
+ retry(input: {
31
+ userId: string;
32
+ provider: PaymentProvider;
33
+ balance: number;
34
+ returnUrl?: string;
35
+ }): Promise<AutoRechargeProcessResult>;
36
+ processIfNeeded(input: {
37
+ userId: string;
38
+ provider: PaymentProvider;
39
+ balance: number;
40
+ returnUrl?: string;
41
+ }): Promise<AutoRechargeProcessResult>;
42
+ }
43
+ //# sourceMappingURL=auto-recharge-service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auto-recharge-service.d.ts","sourceRoot":"","sources":["../../src/billing/auto-recharge-service.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAA8B,yBAAyB,EAAE,MAAM,kBAAkB,CAAC;AAC9F,OAAO,KAAK,EAEV,eAAe,EACf,uBAAuB,EACvB,wBAAwB,EACzB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAGvE,MAAM,MAAM,mBAAmB,GAC3B,gBAAgB,GAChB,UAAU,GACV,iBAAiB,GACjB,oBAAoB,GACpB,eAAe,GACf,WAAW,GACX,iBAAiB,GACjB,QAAQ,CAAC;AAEb,MAAM,WAAW,yBAAyB;IACxC,OAAO,EAAE,mBAAmB,CAAC;IAC7B,MAAM,CAAC,EAAE,wBAAwB,GAAG,IAAI,CAAC;CAC1C;AAkBD,qBAAa,mBAAmB;IAClB,OAAO,CAAC,QAAQ,CAAC,OAAO;gBAAP,OAAO,EAAE,uBAAuB;YAE/C,MAAM;YA6CN,aAAa;IAiBrB,KAAK,CAAC,KAAK,EAAE;QACjB,MAAM,EAAE,MAAM,CAAC;QACf,QAAQ,EAAE,eAAe,CAAC;KAC3B,GAAG,OAAO,CAAC,uBAAuB,GAAG,IAAI,CAAC;IAerC,SAAS,CAAC,KAAK,EAAE;QACrB,MAAM,EAAE,MAAM,CAAC;QACf,QAAQ,EAAE,eAAe,CAAC;KAC3B,GAAG,OAAO,CAAC,yBAAyB,GAAG,IAAI,CAAC;IA+BvC,MAAM,CAAC,KAAK,EAAE;QAClB,MAAM,EAAE,MAAM,CAAC;QACf,QAAQ,EAAE,eAAe,CAAC;QAC1B,OAAO,EAAE,MAAM,CAAC;QAChB,SAAS,CAAC,EAAE,MAAM,CAAC;QACnB,gBAAgB,CAAC,EAAE,MAAM,CAAC;KAC3B,GAAG,OAAO,CAAC,yBAAyB,GAAG,IAAI,CAAC;IA0BvC,OAAO,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAWtC,KAAK,CAAC,KAAK,EAAE;QACjB,MAAM,EAAE,MAAM,CAAC;QACf,QAAQ,EAAE,eAAe,CAAC;QAC1B,OAAO,EAAE,MAAM,CAAC;QAChB,SAAS,CAAC,EAAE,MAAM,CAAC;KACpB,GAAG,OAAO,CAAC,yBAAyB,CAAC;IAchC,eAAe,CAAC,KAAK,EAAE;QAC3B,MAAM,EAAE,MAAM,CAAC;QACf,QAAQ,EAAE,eAAe,CAAC;QAC1B,OAAO,EAAE,MAAM,CAAC;QAChB,SAAS,CAAC,EAAE,MAAM,CAAC;KACpB,GAAG,OAAO,CAAC,yBAAyB,CAAC;CA4DvC"}