@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
@@ -1,891 +0,0 @@
1
- import Decimal from "decimal.js";
2
- import { StoreError } from "../errors.js";
3
- import { resolveCalendarWindow } from "../allowance.js";
4
- import { CreditStore } from "./credit-store.js";
5
- const ZERO = new Decimal(0);
6
- /**
7
- * Parse a Postgres NUMERIC column into an exact `Decimal`. Postgres returns
8
- * NUMERIC as a *string* via `pg`, so this preserves full precision (contract
9
- * §1). `null`/`undefined` become the supplied fallback.
10
- */
11
- function dec(value, fallback = ZERO) {
12
- if (value === null || value === undefined)
13
- return fallback;
14
- if (value instanceof Decimal)
15
- return value;
16
- try {
17
- return new Decimal(typeof value === "string" ? value : String(value));
18
- }
19
- catch {
20
- return fallback;
21
- }
22
- }
23
- /** A money serialized for an SQL parameter: send as a decimal string. */
24
- function decParam(value) {
25
- return value.toString();
26
- }
27
- /**
28
- * Derive the feature-limit window END from its (already calendar-aligned)
29
- * START — the manager only resolves/threads the start (mirrors Python
30
- * `base.py`); the RPC needs an explicit end for its `WHERE` clause, so this
31
- * store computes it via `resolveCalendarWindow` (idempotent on an aligned
32
- * start — re-resolving it yields the identical window).
33
- */
34
- function featureWindowEnd(start, period) {
35
- return resolveCalendarWindow(start, period).end;
36
- }
37
- /**
38
- * Parse a JSON `{tier_key: "3.0000", ...}` object (e.g. `tier_breakdown`,
39
- * `expired_by_tier`) into `Record<string, Decimal>`, converting every value
40
- * the same way scalar money fields are (never left as a raw string/number).
41
- * Returns `null` when `raw` is not an object (absent/error responses).
42
- */
43
- function decRecord(raw) {
44
- if (!raw || typeof raw !== "object" || Array.isArray(raw))
45
- return null;
46
- const out = {};
47
- for (const [k, v] of Object.entries(raw)) {
48
- out[k] = dec(v);
49
- }
50
- return out;
51
- }
52
- /** Parse the ``feature_limits`` JSONB map into typed `FeatureLimit` records. */
53
- function parseFeatureLimits(raw) {
54
- if (!raw || typeof raw !== "object")
55
- return {};
56
- const out = {};
57
- for (const [k, v] of Object.entries(raw)) {
58
- const fl = (v ?? {});
59
- out[k] = {
60
- maxCalls: Number(fl.max_calls ?? fl.maxCalls ?? 0),
61
- period: String(fl.period ?? "monthly") ?? "monthly",
62
- action: String(fl.action ?? "deny") ?? "deny",
63
- };
64
- }
65
- return out;
66
- }
67
- /** Parse the ``per_operation`` JSONB map into typed `OperationPolicy` records. */
68
- function parsePerOperation(raw) {
69
- if (!raw || typeof raw !== "object")
70
- return {};
71
- const out = {};
72
- for (const [k, v] of Object.entries(raw)) {
73
- const op = (v ?? {});
74
- out[k] = {
75
- billingMode: String(op.billing_mode ?? op.billingMode ?? "strict") ?? "strict",
76
- maxConcurrent: op.max_concurrent != null
77
- ? Number(op.max_concurrent)
78
- : op.maxConcurrent != null
79
- ? Number(op.maxConcurrent)
80
- : null,
81
- overdraftFloor: op.overdraft_floor != null
82
- ? dec(op.overdraft_floor)
83
- : op.overdraftFloor != null
84
- ? dec(op.overdraftFloor)
85
- : null,
86
- };
87
- }
88
- return out;
89
- }
90
- /**
91
- * Credit store backed by a raw Postgres connection.
92
- *
93
- * Uses dependency injection for the PG pool — supply a real ``pg.Pool`` class
94
- * for production, a mock constructor for tests, or a pre-created pool instance
95
- * to share across stores (avoids exhausting Postgres connections).
96
- *
97
- * Args:
98
- * databaseUrl: Postgres connection string.
99
- * poolOrCtor: A pre-created PgPool instance, a PgPoolConstructor, or omitted
100
- * (loads ``pg`` on first use).
101
- */
102
- export class PostgresStore extends CreditStore {
103
- databaseUrl;
104
- poolCtor = null;
105
- pool = null;
106
- ownsPool;
107
- constructor(databaseUrl, poolOrCtor, pricingCacheTtl = 300) {
108
- super(pricingCacheTtl);
109
- this.databaseUrl = databaseUrl;
110
- if (poolOrCtor && typeof poolOrCtor.query === "function") {
111
- // Pre-created pool instance — share, don't own.
112
- this.pool = poolOrCtor;
113
- this.ownsPool = false;
114
- }
115
- else {
116
- this.poolCtor = poolOrCtor ?? null;
117
- this.ownsPool = true;
118
- }
119
- }
120
- async getPool() {
121
- if (!this.pool) {
122
- const Pool = await this.getPoolCtor();
123
- this.pool = new Pool({ connectionString: this.databaseUrl });
124
- }
125
- return this.pool;
126
- }
127
- async getPoolCtor() {
128
- if (this.poolCtor)
129
- return this.poolCtor;
130
- const mod = await import("pg");
131
- this.poolCtor = mod.Pool;
132
- return this.poolCtor;
133
- }
134
- async query(text, params) {
135
- const pool = await this.getPool();
136
- const res = await pool.query(text, params);
137
- return res.rows;
138
- }
139
- async close() {
140
- if (this.pool && this.ownsPool) {
141
- await this.pool.end();
142
- this.pool = null;
143
- }
144
- }
145
- /**
146
- * Call a SQL function and return its result rows.
147
- *
148
- * bursar's RPCs come in two shapes:
149
- * 1. **Scalar JSONB** (`RETURNS JSONB`) — `pg` returns one row whose single
150
- * column holds the parsed object. We unwrap that to `[object]`.
151
- * 2. **Set-returning** (`RETURNS TABLE/SETOF`) — many rows of named columns.
152
- * We return them as-is.
153
- *
154
- * The previous `rows[0]` heuristic was fragile: a single-row set-returning
155
- * function whose first column happened to be an object would be misread. We
156
- * instead detect the JSONB-scalar case precisely: exactly one row with exactly
157
- * one column whose value is a non-array object. Lists therefore always return
158
- * all their rows.
159
- */
160
- async callproc(name, params) {
161
- const placeholders = params.map((_, i) => `$${i + 1}`).join(", ");
162
- const rows = await this.query(`SELECT * FROM ${name}(${placeholders})`, params);
163
- if (rows.length === 1) {
164
- const row = rows[0];
165
- const keys = Object.keys(row);
166
- if (keys.length === 1) {
167
- const v = row[keys[0]];
168
- if (v !== null && typeof v === "object" && !Array.isArray(v)) {
169
- // Scalar JSONB result: unwrap to the parsed object.
170
- return [v];
171
- }
172
- }
173
- }
174
- return rows;
175
- }
176
- async setup(_databaseUrl) {
177
- // H17: do NOT silently report success for a no-op. bursar's schema is managed
178
- // as a set of ordered SQL migrations bundled with the Python package; this
179
- // store does not embed them. Surface that clearly instead of green-lighting
180
- // a missing schema (which would only fail later as missing-RPC errors).
181
- throw new StoreError("PostgresStore.setup() does not run migrations. Apply the bundled SQL " +
182
- "migrations first — run `bursar migrate` via the Python CLI, or execute the " +
183
- "files in `python/src/bursar/sql/*.sql` (in filename order) against your " +
184
- "database. This store assumes the schema already exists.");
185
- }
186
- async getBalance(userId) {
187
- const rows = await this.callproc("get_credits_balance", [userId]);
188
- if (!rows || rows.length === 0) {
189
- return { userId, balance: ZERO, lifetimePurchased: ZERO };
190
- }
191
- const row = rows[0];
192
- return {
193
- userId: String(row.user_id ?? userId),
194
- balance: dec(row.balance),
195
- lifetimePurchased: dec(row.lifetime_purchased),
196
- };
197
- }
198
- async addCredits(userId, amount, type = "adjustment", metadata, expiresAt, tier,
199
- // NOTE: threaded through defensively as a trailing positional param to the
200
- // `credits_add` RPC. Confirm the SQL migration adds a `p_idempotency_key`
201
- // parameter (with a default, so existing 5-arg call sites keep working)
202
- // before relying on this against a real database (see 011_lazy_expiry.sql).
203
- idempotencyKey) {
204
- const meta = { ...(metadata ?? {}) };
205
- if (expiresAt) {
206
- meta.expires_at = expiresAt instanceof Date ? expiresAt.toISOString() : String(expiresAt);
207
- }
208
- const rows = await this.callproc("credits_add", [
209
- userId,
210
- decParam(amount),
211
- type,
212
- JSON.stringify(meta),
213
- tier ?? null,
214
- idempotencyKey ?? null,
215
- ]);
216
- const row = (rows?.[0] ?? {});
217
- if ("error" in row && row.error) {
218
- throw new StoreError(`credits_add: ${String(row.error)}`);
219
- }
220
- return {
221
- transactionId: String(row.id ?? ""),
222
- userId: String(row.user_id ?? userId),
223
- amount: dec(row.amount, amount),
224
- newBalance: dec(row.new_balance),
225
- lifetimePurchased: dec(row.lifetime_purchased),
226
- tier: String(row.tier ?? tier ?? "default"),
227
- idempotent: Boolean(row.idempotent),
228
- };
229
- }
230
- async deductWithAllowance(userId, amount, options) {
231
- const idempotencyKey = options?.idempotencyKey ?? null;
232
- const minBalance = options?.minBalance ?? ZERO;
233
- const model = options?.model ?? null;
234
- const metadata = options?.metadata ?? {};
235
- const periodStart = options?.periodStart ?? null;
236
- const feature = options?.feature ?? null;
237
- const featureLimit = options?.featureLimit ?? null;
238
- const featurePeriodStart = options?.featurePeriodStart ?? null;
239
- const featurePeriodEnd = featureLimit != null && featurePeriodStart != null
240
- ? featureWindowEnd(featurePeriodStart, featureLimit.period)
241
- : null;
242
- const rows = await this.callproc("deduct_with_allowance", [
243
- userId,
244
- decParam(amount),
245
- idempotencyKey,
246
- decParam(minBalance),
247
- model,
248
- JSON.stringify(metadata ?? {}),
249
- false, // p_skip_allowance: not yet exposed as a JS option; keep the SQL default
250
- periodStart != null ? periodStart.toISOString().slice(0, 10) : null,
251
- feature,
252
- featureLimit != null ? featureLimit.maxCalls : null,
253
- featureLimit != null ? featureLimit.action : null,
254
- featurePeriodStart != null ? featurePeriodStart.toISOString().slice(0, 10) : null,
255
- featurePeriodEnd != null ? featurePeriodEnd.toISOString().slice(0, 10) : null,
256
- ]);
257
- const row = (rows?.[0] ?? {});
258
- if ("error" in row && row.error) {
259
- // Map the SQL error envelope to DeductionResult.error (the manager maps
260
- // codes to typed exceptions). cap_reached / insufficient_credits /
261
- // invalid_amount / feature_limit_reached all flow through here without
262
- // throwing.
263
- return {
264
- transactionId: "",
265
- userId,
266
- amount: ZERO,
267
- allowanceConsumed: ZERO,
268
- balanceAfter: dec(row.balance_after),
269
- idempotent: false,
270
- capWarning: null,
271
- featureLimitWarning: null,
272
- error: String(row.error),
273
- };
274
- }
275
- return {
276
- transactionId: String(row.transaction_id ?? ""),
277
- userId,
278
- amount: dec(row.amount),
279
- allowanceConsumed: dec(row.allowance_consumed),
280
- balanceAfter: dec(row.balance_after),
281
- idempotent: Boolean(row.idempotent),
282
- capWarning: row.cap_warning != null ? String(row.cap_warning) : null,
283
- featureLimitWarning: row.feature_limit_warning != null ? String(row.feature_limit_warning) : null,
284
- tierBreakdown: decRecord(row.tier_breakdown),
285
- };
286
- }
287
- // ── Lease lifecycle (atomic admission) ─────────────────────────────
288
- async createLease(userId, amount, operationType, options) {
289
- const billingMode = options?.billingMode ?? "strict";
290
- const floor = options?.floor ?? ZERO;
291
- const overdraftFloor = options?.overdraftFloor ?? null;
292
- const periodStart = options?.periodStart ?? null;
293
- const feature = options?.feature ?? null;
294
- const featureLimit = options?.featureLimit ?? null;
295
- const featurePeriodStart = options?.featurePeriodStart ?? null;
296
- const featurePeriodEnd = featureLimit != null && featurePeriodStart != null
297
- ? featureWindowEnd(featurePeriodStart, featureLimit.period)
298
- : null;
299
- const rows = await this.callproc("create_lease", [
300
- userId,
301
- decParam(amount),
302
- operationType,
303
- billingMode,
304
- decParam(floor),
305
- options?.maxConcurrent ?? null,
306
- options?.ttlSeconds ?? 600,
307
- options?.model ?? null,
308
- overdraftFloor != null ? decParam(overdraftFloor) : null,
309
- JSON.stringify(options?.metadata ?? {}),
310
- periodStart != null ? periodStart.toISOString().slice(0, 10) : null,
311
- feature,
312
- featureLimit != null ? featureLimit.maxCalls : null,
313
- featureLimit != null ? featureLimit.action : null,
314
- featurePeriodStart != null ? featurePeriodStart.toISOString().slice(0, 10) : null,
315
- featurePeriodEnd != null ? featurePeriodEnd.toISOString().slice(0, 10) : null,
316
- ]);
317
- const row = (rows?.[0] ?? {});
318
- if (!row || Object.keys(row).length === 0) {
319
- return {
320
- leaseId: "",
321
- userId,
322
- amount: ZERO,
323
- available: ZERO,
324
- reservedTotal: ZERO,
325
- billingMode,
326
- expiresAt: "",
327
- error: "no result",
328
- };
329
- }
330
- if ("error" in row && row.error) {
331
- return {
332
- leaseId: "",
333
- userId,
334
- amount: ZERO,
335
- available: dec(row.available),
336
- reservedTotal: dec(row.reserved),
337
- billingMode,
338
- expiresAt: "",
339
- error: String(row.error),
340
- };
341
- }
342
- return {
343
- leaseId: String(row.lease_id ?? ""),
344
- userId: String(row.user_id ?? userId),
345
- amount: dec(row.amount),
346
- available: dec(row.available),
347
- reservedTotal: dec(row.reserved),
348
- billingMode: String(row.billing_mode ?? billingMode) ?? billingMode,
349
- expiresAt: String(row.expires_at ?? ""),
350
- };
351
- }
352
- async settleLease(userId, leaseId, amount, options) {
353
- const minBalance = options?.minBalance ?? ZERO;
354
- const periodStart = options?.periodStart ?? null;
355
- const feature = options?.feature ?? null;
356
- const featureLimit = options?.featureLimit ?? null;
357
- const featurePeriodStart = options?.featurePeriodStart ?? null;
358
- const featurePeriodEnd = featureLimit != null && featurePeriodStart != null
359
- ? featureWindowEnd(featurePeriodStart, featureLimit.period)
360
- : null;
361
- const rows = await this.callproc("settle_lease", [
362
- userId,
363
- leaseId,
364
- decParam(amount),
365
- options?.idempotencyKey ?? null,
366
- decParam(minBalance),
367
- options?.model ?? null,
368
- JSON.stringify(options?.metadata ?? {}),
369
- false, // p_skip_allowance: not yet exposed as a JS option; keep the SQL default
370
- periodStart != null ? periodStart.toISOString().slice(0, 10) : null,
371
- feature,
372
- featureLimit != null ? featureLimit.maxCalls : null,
373
- featureLimit != null ? featureLimit.action : null,
374
- featurePeriodStart != null ? featurePeriodStart.toISOString().slice(0, 10) : null,
375
- featurePeriodEnd != null ? featurePeriodEnd.toISOString().slice(0, 10) : null,
376
- ]);
377
- const row = (rows?.[0] ?? {});
378
- if (!row || Object.keys(row).length === 0) {
379
- return {
380
- transactionId: "",
381
- userId,
382
- amount: ZERO,
383
- allowanceConsumed: ZERO,
384
- balanceAfter: ZERO,
385
- idempotent: false,
386
- capWarning: null,
387
- featureLimitWarning: null,
388
- error: "no result",
389
- };
390
- }
391
- if ("error" in row && row.error) {
392
- return {
393
- transactionId: "",
394
- userId,
395
- amount: ZERO,
396
- allowanceConsumed: ZERO,
397
- balanceAfter: dec(row.balance_after),
398
- idempotent: false,
399
- capWarning: null,
400
- featureLimitWarning: null,
401
- error: String(row.error),
402
- };
403
- }
404
- return {
405
- transactionId: String(row.transaction_id ?? ""),
406
- userId,
407
- amount: dec(row.amount),
408
- allowanceConsumed: dec(row.allowance_consumed),
409
- balanceAfter: dec(row.balance_after),
410
- idempotent: Boolean(row.idempotent),
411
- capWarning: row.cap_warning != null ? String(row.cap_warning) : null,
412
- featureLimitWarning: row.feature_limit_warning != null ? String(row.feature_limit_warning) : null,
413
- tierBreakdown: decRecord(row.tier_breakdown),
414
- };
415
- }
416
- async releaseLease(userId, leaseId) {
417
- const rows = await this.callproc("release_lease", [userId, leaseId]);
418
- const row = (rows?.[0] ?? {});
419
- return {
420
- leaseId,
421
- userId,
422
- released: Boolean(row.released),
423
- reason: row.reason != null ? String(row.reason) : null,
424
- };
425
- }
426
- async renewLease(userId, leaseId, ttlSeconds) {
427
- const rows = await this.callproc("renew_lease", [userId, leaseId, ttlSeconds]);
428
- const row = (rows?.[0] ?? {});
429
- if ("error" in row && row.error) {
430
- return {
431
- leaseId,
432
- userId,
433
- amount: ZERO,
434
- available: ZERO,
435
- reservedTotal: ZERO,
436
- billingMode: "strict",
437
- expiresAt: "",
438
- error: String(row.error),
439
- };
440
- }
441
- return {
442
- leaseId: String(row.lease_id ?? leaseId),
443
- userId,
444
- amount: dec(row.amount),
445
- available: dec(row.available),
446
- reservedTotal: dec(row.reserved),
447
- billingMode: String(row.billing_mode ?? "strict"),
448
- expiresAt: String(row.expires_at ?? ""),
449
- };
450
- }
451
- async getAvailable(userId) {
452
- const rows = await this.callproc("get_available_credits", [userId]);
453
- const row = (rows?.[0] ?? {});
454
- return {
455
- userId,
456
- balance: dec(row.balance),
457
- reserved: dec(row.reserved),
458
- available: dec(row.available),
459
- };
460
- }
461
- async getActivePricing() {
462
- return this._getCachedPricing(() => this._loadActivePricing());
463
- }
464
- async _loadActivePricing() {
465
- const rows = await this.callproc("get_active_pricing_config", []);
466
- if (!rows || rows.length === 0)
467
- return null;
468
- const row = rows[0];
469
- if (!row || !row.config)
470
- return null;
471
- return row;
472
- }
473
- async setActivePricing(config, label) {
474
- const rows = await this.callproc("set_active_pricing_config", [
475
- JSON.stringify(config),
476
- label ?? null,
477
- ]);
478
- const row = (rows?.[0] ?? {});
479
- this.invalidatePricingCache();
480
- return String(row.id ?? "");
481
- }
482
- // H8: pricing history / activation — mirrors Python base.py:293-312.
483
- async getPricingHistory() {
484
- const rows = await this.callproc("get_pricing_history", []);
485
- if (!rows)
486
- return [];
487
- return rows.map((r) => ({
488
- id: String(r.id ?? ""),
489
- version: Number(r.version ?? 0),
490
- label: r.label ?? null,
491
- active: Boolean(r.active ?? false),
492
- createdAt: String(r.created_at ?? ""),
493
- }));
494
- }
495
- async getPricingConfig(version) {
496
- const rows = await this.callproc("get_pricing_config", [version]);
497
- if (!rows || rows.length === 0)
498
- return null;
499
- const row = rows[0];
500
- if (!row.config)
501
- return null;
502
- return {
503
- id: String(row.id ?? ""),
504
- config: row.config,
505
- version: Number(row.version ?? version),
506
- };
507
- }
508
- async activatePricing(version) {
509
- const rows = await this.callproc("activate_pricing", [version]);
510
- const row = (rows?.[0] ?? {});
511
- this.invalidatePricingCache();
512
- return String(row.id ?? "");
513
- }
514
- // ── Plan management ────────────────────────────────────────────────
515
- async getUserPlan(userId) {
516
- const rows = await this.callproc("get_user_plan", [userId]);
517
- if (!rows || rows.length === 0) {
518
- return { userId, planId: null, planName: null, freeAllowance: ZERO, features: {} };
519
- }
520
- const row = rows[0];
521
- return {
522
- userId: String(row.user_id ?? userId),
523
- planId: row.plan_id ?? null,
524
- planName: row.plan_name ?? null,
525
- freeAllowance: dec(row.free_allowance),
526
- features: row.features ?? {},
527
- featureLimits: parseFeatureLimits(row.feature_limits),
528
- defaultBillingMode: String(row.default_billing_mode ?? "strict") ?? "strict",
529
- perOperation: parsePerOperation(row.per_operation),
530
- maxConcurrent: row.max_concurrent != null ? Number(row.max_concurrent) : null,
531
- overdraftFloor: row.overdraft_floor != null ? dec(row.overdraft_floor) : null,
532
- allowancePeriod: row.allowance_period ?? "calendar_month",
533
- planAssignedAt: row.plan_assigned_at != null ? new Date(String(row.plan_assigned_at)) : null,
534
- };
535
- }
536
- async checkFeature(userId, feature) {
537
- const plan = await this.getUserPlan(userId);
538
- const present = Object.prototype.hasOwnProperty.call(plan.features, feature);
539
- const value = present ? plan.features[feature] : null;
540
- return {
541
- userId,
542
- feature,
543
- value,
544
- // M6: presence-vs-truthiness — numeric 0 / "" count as present.
545
- hasFeature: present && value !== null && value !== undefined && value !== false,
546
- };
547
- }
548
- async setUserPlan(userId, planId, planAssignedAt) {
549
- const params = planAssignedAt
550
- ? [userId, planId, planAssignedAt.toISOString()]
551
- : [userId, planId];
552
- const rows = await this.callproc("set_user_plan", params);
553
- const row = (rows?.[0] ?? {});
554
- return {
555
- userId: String(row.user_id ?? userId),
556
- planId: String(row.plan_id ?? planId),
557
- planAssignedAt: row.plan_assigned_at != null ? String(row.plan_assigned_at) : null,
558
- };
559
- }
560
- async unsetUserPlan(userId) {
561
- const rows = await this.callproc("unset_user_plan", [userId]);
562
- const row = (rows?.[0] ?? {});
563
- return { userId: String(row.user_id ?? userId) };
564
- }
565
- async checkAllowance(userId, periodStart) {
566
- const rows = await this.callproc("check_plan_allowance", [
567
- userId,
568
- periodStart != null ? periodStart.toISOString().slice(0, 10) : null,
569
- ]);
570
- if (!rows || rows.length === 0) {
571
- return { planId: "", allowanceRemaining: ZERO, periodStart: "", periodEnd: "" };
572
- }
573
- const row = rows[0];
574
- return {
575
- planId: String(row.plan_id ?? ""),
576
- allowanceRemaining: dec(row.allowance_remaining),
577
- periodStart: String(row.period_start ?? ""),
578
- periodEnd: String(row.period_end ?? ""),
579
- };
580
- }
581
- async incrementUsageWindow(userId, planId, amount) {
582
- await this.callproc("increment_usage_window", [userId, planId, decParam(amount)]);
583
- }
584
- /** Advisory, non-locking read of invocation-count usage (UI only). Mirrors `checkSpendCap`. */
585
- async checkFeatureLimit(userId, feature, maxCalls, periodStart, periodEnd) {
586
- const rows = await this.callproc("check_feature_limit", [
587
- userId,
588
- feature,
589
- maxCalls,
590
- periodStart.toISOString().slice(0, 10),
591
- periodEnd.toISOString().slice(0, 10),
592
- ]);
593
- if (!rows || rows.length === 0) {
594
- return {
595
- userId,
596
- feature,
597
- limited: false,
598
- limit: 0,
599
- used: 0,
600
- remaining: 0,
601
- periodStart: "",
602
- periodEnd: "",
603
- action: null,
604
- };
605
- }
606
- const row = rows[0];
607
- return {
608
- userId: String(row.user_id ?? userId),
609
- feature: String(row.feature ?? feature),
610
- limited: Boolean(row.limited ?? true),
611
- limit: Number(row.limit ?? maxCalls),
612
- used: Number(row.used ?? 0),
613
- remaining: Number(row.remaining ?? Math.max(maxCalls - Number(row.used ?? 0), 0)),
614
- periodStart: String(row.period_start ?? ""),
615
- periodEnd: String(row.period_end ?? ""),
616
- action: row.action ?? null,
617
- };
618
- }
619
- // ── Spend caps and rate limiting ──────────────────────────────────────
620
- async checkSpendCap(userId, model, amount) {
621
- const rows = await this.callproc("check_spend_cap", [
622
- userId,
623
- model ?? null,
624
- decParam(amount ?? ZERO),
625
- ]);
626
- if (!rows || rows.length === 0) {
627
- return { capped: false, currentSpend: ZERO, limit: ZERO, action: null };
628
- }
629
- const row = rows[0];
630
- return {
631
- capped: Boolean(row.capped),
632
- currentSpend: dec(row.current_spend),
633
- limit: dec(row.cap_limit),
634
- action: row.action ?? null,
635
- model: row.model ? String(row.model) : undefined,
636
- };
637
- }
638
- // ── Revoke credits by tx type ──────────────────────────────────────────
639
- async revokeCreditsByTxType(userId, txType) {
640
- const rows = await this.callproc("revoke_credits_by_tx_type", [userId, txType]);
641
- return (rows?.[0] ?? {});
642
- }
643
- // ── Refunds ──────────────────────────────────────────────────────────
644
- async refundCredits(transactionId, amount, reason, metadata) {
645
- const rows = await this.callproc("refund_credits", [
646
- transactionId,
647
- amount != null ? decParam(amount) : null,
648
- reason ?? null,
649
- JSON.stringify(metadata ?? {}),
650
- ]);
651
- const row = (rows?.[0] ?? {});
652
- if ("error" in row && row.error) {
653
- return {
654
- refundTransactionId: "",
655
- originalTransactionId: transactionId,
656
- userId: String(row.user_id ?? ""),
657
- amount: ZERO,
658
- newBalance: dec(row.new_balance),
659
- error: String(row.error),
660
- };
661
- }
662
- return {
663
- refundTransactionId: String(row.refund_transaction_id ?? ""),
664
- originalTransactionId: transactionId,
665
- userId: String(row.user_id ?? ""),
666
- amount: dec(row.amount),
667
- newBalance: dec(row.new_balance),
668
- tierBreakdown: decRecord(row.tier_breakdown),
669
- };
670
- }
671
- // ── Usage analytics ──────────────────────────────────────────────────
672
- async spendByUser(start, end) {
673
- const rows = await this.callproc("spend_by_user", [start.toISOString(), end.toISOString()]);
674
- return (rows ?? []).map((r) => {
675
- const row = r;
676
- return {
677
- userId: String(row.user_id ?? ""),
678
- totalSpend: dec(row.total_spend),
679
- transactionCount: Number(row.transaction_count ?? 0),
680
- };
681
- });
682
- }
683
- async spendByModel(start, end) {
684
- const rows = await this.callproc("spend_by_model", [start.toISOString(), end.toISOString()]);
685
- return (rows ?? []).map((r) => {
686
- const row = r;
687
- return {
688
- model: String(row.model ?? ""),
689
- totalSpend: dec(row.total_spend),
690
- transactionCount: Number(row.transaction_count ?? 0),
691
- };
692
- });
693
- }
694
- async topUsers(limit, start, end) {
695
- const rows = await this.callproc("top_users", [limit, start.toISOString(), end.toISOString()]);
696
- return (rows ?? []).map((r) => {
697
- const row = r;
698
- return {
699
- userId: String(row.user_id ?? ""),
700
- totalSpend: dec(row.total_spend),
701
- };
702
- });
703
- }
704
- async dailySpend(start, end) {
705
- const rows = await this.callproc("daily_spend", [start.toISOString(), end.toISOString()]);
706
- return (rows ?? []).map((r) => {
707
- const row = r;
708
- return {
709
- date: String(row.date ?? ""),
710
- totalSpend: dec(row.total_spend),
711
- transactionCount: Number(row.transaction_count ?? 0),
712
- };
713
- });
714
- }
715
- // ── Transaction listing ─────────────────────────────────────────────
716
- async listUserTransactions(userId, options) {
717
- const rows = await this.callproc("list_user_transactions", [
718
- userId,
719
- options?.types ?? null,
720
- options?.fromDate?.toISOString() ?? null,
721
- options?.toDate?.toISOString() ?? null,
722
- options?.limit ?? 50,
723
- options?.offset ?? 0,
724
- ]);
725
- const items = (rows ?? []).map((r) => {
726
- const row = r;
727
- return {
728
- id: String(row.id ?? ""),
729
- userId: String(row.user_id ?? ""),
730
- amount: dec(row.amount),
731
- type: String(row.type ?? ""),
732
- referenceType: row.reference_type != null ? String(row.reference_type) : null,
733
- referenceId: row.reference_id != null ? String(row.reference_id) : null,
734
- metadata: row.metadata ?? null,
735
- createdAt: String(row.created_at ?? ""),
736
- };
737
- });
738
- const total = rows.length > 0 ? Number(rows[0].total_count ?? 0) : 0;
739
- return { items, total };
740
- }
741
- async listUsageEvents(userId, options) {
742
- const rows = await this.callproc("list_usage_events", [
743
- userId,
744
- options?.fromDate?.toISOString() ?? null,
745
- options?.toDate?.toISOString() ?? null,
746
- options?.limit ?? 50,
747
- options?.offset ?? 0,
748
- ]);
749
- const items = (rows ?? []).map((r) => {
750
- const row = r;
751
- return {
752
- id: String(row.id ?? ""),
753
- userId: String(row.user_id ?? ""),
754
- amount: dec(row.amount),
755
- type: String(row.type ?? ""),
756
- referenceType: row.reference_type != null ? String(row.reference_type) : null,
757
- referenceId: row.reference_id != null ? String(row.reference_id) : null,
758
- metadata: row.metadata ?? null,
759
- createdAt: String(row.created_at ?? ""),
760
- };
761
- });
762
- const total = rows.length > 0 ? Number(rows[0].total_count ?? 0) : 0;
763
- return { items, total };
764
- }
765
- // ── Aggregate stats ────────────────────────────────────────────────
766
- async aggregateStats(start, end) {
767
- const rows = await this.callproc("aggregate_stats", [start.toISOString(), end.toISOString()]);
768
- const row = (rows?.[0] ?? {});
769
- return {
770
- totalCreditsConsumed: dec(row.total_credits_consumed),
771
- activeUsers: Number(row.active_users ?? 0),
772
- avgDailySpend: dec(row.avg_daily_spend),
773
- topModel: String(row.top_model ?? ""),
774
- topUser: String(row.top_user ?? ""),
775
- };
776
- }
777
- // ── Team/shared balance pools ────────────────────────────────────────
778
- async createTeam(name, initialBalance = ZERO) {
779
- const rows = await this.callproc("create_team", [name, decParam(initialBalance)]);
780
- const row = (rows?.[0] ?? {});
781
- return {
782
- teamId: String(row.team_id ?? ""),
783
- name: String(row.name ?? name),
784
- };
785
- }
786
- async getTeamBalance(teamId) {
787
- const rows = await this.callproc("get_team_balance", [teamId]);
788
- if (!rows || rows.length === 0) {
789
- return { teamId, name: "", balance: ZERO, memberCount: 0 };
790
- }
791
- const row = rows[0];
792
- if ("error" in row && row.error) {
793
- return { teamId, name: "", balance: ZERO, memberCount: 0 };
794
- }
795
- return {
796
- teamId: String(row.team_id ?? teamId),
797
- name: String(row.name ?? ""),
798
- balance: dec(row.balance),
799
- memberCount: Number(row.member_count ?? 0),
800
- };
801
- }
802
- async addTeamMember(teamId, userId, role = "member", spendCap) {
803
- const rows = await this.callproc("add_team_member", [
804
- teamId,
805
- userId,
806
- role,
807
- spendCap != null ? decParam(spendCap) : null,
808
- ]);
809
- const row = (rows?.[0] ?? {});
810
- return {
811
- teamId: String(row.team_id ?? teamId),
812
- userId: String(row.user_id ?? userId),
813
- role: String(row.role ?? role),
814
- };
815
- }
816
- async getTeamMembers(teamId) {
817
- const rows = await this.callproc("get_team_members", [teamId]);
818
- return (rows ?? []).map((r) => {
819
- const row = r;
820
- return {
821
- userId: String(row.user_id ?? ""),
822
- role: String(row.role ?? "member"),
823
- spendCap: row.spend_cap != null ? dec(row.spend_cap) : null,
824
- totalSpent: dec(row.total_spent),
825
- };
826
- });
827
- }
828
- async deductTeam(teamId, userId, amount, metadata, idempotencyKey) {
829
- const meta = { ...(metadata ?? {}) };
830
- if (idempotencyKey)
831
- meta.idempotency_key = idempotencyKey;
832
- const rows = await this.callproc("deduct_team", [
833
- teamId,
834
- userId,
835
- decParam(amount),
836
- JSON.stringify(meta),
837
- ]);
838
- const row = (rows?.[0] ?? {});
839
- if ("error" in row && row.error) {
840
- return {
841
- transactionId: "",
842
- teamId,
843
- userId,
844
- amount: ZERO,
845
- teamBalanceAfter: dec(row.team_balance_after),
846
- error: String(row.error),
847
- };
848
- }
849
- return {
850
- transactionId: String(row.transaction_id ?? ""),
851
- teamId: String(row.team_id ?? teamId),
852
- userId: String(row.user_id ?? userId),
853
- amount: dec(row.amount, amount.negated()),
854
- teamBalanceAfter: dec(row.team_balance_after),
855
- };
856
- }
857
- // ── Credit expiry ────────────────────────────────────────────────────
858
- async sweepExpiredCredits(dryRun = false, userId) {
859
- // NOTE: `userId` is threaded through defensively as a trailing positional
860
- // param to `expire_credits`. Confirm the SQL migration adds a `p_user_id`
861
- // parameter (with a `DEFAULT NULL`, so the existing 1-arg call sites keep
862
- // meaning "global sweep") before relying on this against a real database
863
- // (see 011_lazy_expiry.sql).
864
- const rows = await this.callproc("expire_credits", [dryRun, userId ?? null]);
865
- const row = (rows?.[0] ?? {});
866
- return {
867
- expiredCount: Number(row.expired_count ?? 0),
868
- expiredAmount: dec(row.expired_amount),
869
- dryRun,
870
- expiredByTier: decRecord(row.expired_by_tier),
871
- };
872
- }
873
- // ── Credit tiers ─────────────────────────────────────────────────────
874
- async getCreditTiers(userId) {
875
- // get_user_credit_tiers returns one JSONB envelope object (not a rowset):
876
- // {user_id, tiers: [...], total_balance}. callproc's scalar-JSONB
877
- // unwrapping surfaces it as a single-element array.
878
- const rows = await this.callproc("get_user_credit_tiers", [userId]);
879
- const envelope = (rows?.[0] ?? {});
880
- const tierRows = envelope.tiers ?? [];
881
- const tiers = tierRows.map((row) => ({
882
- tierKey: String(row.tier_key ?? ""),
883
- name: String(row.name ?? ""),
884
- priority: Number(row.priority ?? 0),
885
- expires: Boolean(row.expires ?? false),
886
- balance: dec(row.balance),
887
- }));
888
- return { userId, tiers, totalBalance: dec(envelope.total_balance) };
889
- }
890
- }
891
- //# sourceMappingURL=postgres-store.js.map