@zonastery/bursar 1.0.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (404) hide show
  1. package/README.md +189 -62
  2. package/dist/billing/auto-recharge-port.d.ts +3 -3
  3. package/dist/billing/auto-recharge-port.d.ts.map +1 -1
  4. package/dist/billing/auto-recharge-port.js.map +1 -1
  5. package/dist/billing/auto-recharge-service.d.ts +5 -4
  6. package/dist/billing/auto-recharge-service.d.ts.map +1 -1
  7. package/dist/billing/auto-recharge-service.js +64 -34
  8. package/dist/billing/auto-recharge-service.js.map +1 -1
  9. package/dist/billing/billing-service.d.ts +5 -5
  10. package/dist/billing/billing-service.d.ts.map +1 -1
  11. package/dist/billing/billing-service.js +2 -2
  12. package/dist/billing/billing-service.js.map +1 -1
  13. package/dist/billing/billing-store.d.ts +10 -9
  14. package/dist/billing/billing-store.d.ts.map +1 -1
  15. package/dist/billing/billing-store.js.map +1 -1
  16. package/dist/billing/contracts.d.ts +31 -31
  17. package/dist/billing/contracts.d.ts.map +1 -1
  18. package/dist/billing/contracts.js.map +1 -1
  19. package/dist/billing/event-handlers.d.ts.map +1 -1
  20. package/dist/billing/event-handlers.js +49 -10
  21. package/dist/billing/event-handlers.js.map +1 -1
  22. package/dist/billing/event-processor.d.ts +1 -0
  23. package/dist/billing/event-processor.d.ts.map +1 -1
  24. package/dist/billing/event-processor.js +37 -10
  25. package/dist/billing/event-processor.js.map +1 -1
  26. package/dist/billing/financial-event-handlers.d.ts.map +1 -1
  27. package/dist/billing/financial-event-handlers.js +69 -72
  28. package/dist/billing/financial-event-handlers.js.map +1 -1
  29. package/dist/billing/index.d.ts +2 -1
  30. package/dist/billing/index.d.ts.map +1 -1
  31. package/dist/billing/index.js.map +1 -1
  32. package/dist/billing/management.d.ts +5 -5
  33. package/dist/billing/management.d.ts.map +1 -1
  34. package/dist/billing/management.js +2 -2
  35. package/dist/billing/management.js.map +1 -1
  36. package/dist/billing/policy-window.js.map +1 -1
  37. package/dist/billing/postgres/repositories/auto-recharge.d.ts +3 -3
  38. package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -1
  39. package/dist/billing/postgres/repositories/auto-recharge.js +205 -60
  40. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
  41. package/dist/billing/postgres/repositories/customer.d.ts.map +1 -1
  42. package/dist/billing/postgres/repositories/customer.js +19 -11
  43. package/dist/billing/postgres/repositories/customer.js.map +1 -1
  44. package/dist/billing/postgres/repositories/dispute.d.ts.map +1 -1
  45. package/dist/billing/postgres/repositories/dispute.js +3 -1
  46. package/dist/billing/postgres/repositories/dispute.js.map +1 -1
  47. package/dist/billing/postgres/repositories/event.d.ts +14 -7
  48. package/dist/billing/postgres/repositories/event.d.ts.map +1 -1
  49. package/dist/billing/postgres/repositories/event.js +21 -20
  50. package/dist/billing/postgres/repositories/event.js.map +1 -1
  51. package/dist/billing/postgres/repositories/invoice.d.ts +3 -3
  52. package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -1
  53. package/dist/billing/postgres/repositories/invoice.js +53 -11
  54. package/dist/billing/postgres/repositories/invoice.js.map +1 -1
  55. package/dist/billing/postgres/repositories/offer.d.ts +20 -17
  56. package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
  57. package/dist/billing/postgres/repositories/offer.js +123 -57
  58. package/dist/billing/postgres/repositories/offer.js.map +1 -1
  59. package/dist/billing/postgres/repositories/payment.d.ts +23 -20
  60. package/dist/billing/postgres/repositories/payment.d.ts.map +1 -1
  61. package/dist/billing/postgres/repositories/payment.js +43 -37
  62. package/dist/billing/postgres/repositories/payment.js.map +1 -1
  63. package/dist/billing/postgres/repositories/preferences.d.ts +3 -9
  64. package/dist/billing/postgres/repositories/preferences.d.ts.map +1 -1
  65. package/dist/billing/postgres/repositories/preferences.js +45 -7
  66. package/dist/billing/postgres/repositories/preferences.js.map +1 -1
  67. package/dist/billing/postgres/repositories/refund.d.ts +1 -1
  68. package/dist/billing/postgres/repositories/refund.d.ts.map +1 -1
  69. package/dist/billing/postgres/repositories/refund.js +13 -9
  70. package/dist/billing/postgres/repositories/refund.js.map +1 -1
  71. package/dist/billing/postgres/repositories/subscription-change.d.ts +15 -0
  72. package/dist/billing/postgres/repositories/subscription-change.d.ts.map +1 -0
  73. package/dist/billing/postgres/repositories/subscription-change.js +234 -0
  74. package/dist/billing/postgres/repositories/subscription-change.js.map +1 -0
  75. package/dist/billing/postgres/repositories/subscription.d.ts +38 -17
  76. package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -1
  77. package/dist/billing/postgres/repositories/subscription.js +199 -91
  78. package/dist/billing/postgres/repositories/subscription.js.map +1 -1
  79. package/dist/billing/postgres/repositories/topup.d.ts +13 -15
  80. package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
  81. package/dist/billing/postgres/repositories/topup.js +65 -34
  82. package/dist/billing/postgres/repositories/topup.js.map +1 -1
  83. package/dist/billing/postgres/store.d.ts +23 -14
  84. package/dist/billing/postgres/store.d.ts.map +1 -1
  85. package/dist/billing/postgres/store.js +265 -228
  86. package/dist/billing/postgres/store.js.map +1 -1
  87. package/dist/billing/service-types.d.ts +6 -5
  88. package/dist/billing/service-types.d.ts.map +1 -1
  89. package/dist/billing/service-types.js.map +1 -1
  90. package/dist/billing/types/auto-recharge.d.ts +6 -4
  91. package/dist/billing/types/auto-recharge.d.ts.map +1 -1
  92. package/dist/billing/types/auto-recharge.js.map +1 -1
  93. package/dist/billing/types/catalog.d.ts +18 -35
  94. package/dist/billing/types/catalog.d.ts.map +1 -1
  95. package/dist/billing/types/catalog.js.map +1 -1
  96. package/dist/billing/types/common.d.ts +0 -1
  97. package/dist/billing/types/common.d.ts.map +1 -1
  98. package/dist/billing/types/common.js.map +1 -1
  99. package/dist/billing/types/documents.d.ts +38 -12
  100. package/dist/billing/types/documents.d.ts.map +1 -1
  101. package/dist/billing/types/documents.js.map +1 -1
  102. package/dist/billing/types/events.d.ts +2 -0
  103. package/dist/billing/types/events.d.ts.map +1 -1
  104. package/dist/billing/types/events.js +238 -0
  105. package/dist/billing/types/events.js.map +1 -1
  106. package/dist/billing/types/index.js.map +1 -1
  107. package/dist/billing/types/preferences.js.map +1 -1
  108. package/dist/billing/types/subscriptions.d.ts +8 -8
  109. package/dist/billing/types/subscriptions.d.ts.map +1 -1
  110. package/dist/billing/types/subscriptions.js.map +1 -1
  111. package/dist/breakdown.js.map +1 -1
  112. package/dist/browser.js.map +1 -1
  113. package/dist/bursar.d.ts +33 -11
  114. package/dist/bursar.d.ts.map +1 -1
  115. package/dist/bursar.js +58 -22
  116. package/dist/bursar.js.map +1 -1
  117. package/dist/catalog.d.ts +1 -0
  118. package/dist/catalog.d.ts.map +1 -1
  119. package/dist/catalog.js +1 -0
  120. package/dist/catalog.js.map +1 -1
  121. package/dist/commerce/errors.d.ts +4 -14
  122. package/dist/commerce/errors.d.ts.map +1 -1
  123. package/dist/commerce/errors.js +4 -21
  124. package/dist/commerce/errors.js.map +1 -1
  125. package/dist/commerce/index.d.ts +1 -0
  126. package/dist/commerce/index.d.ts.map +1 -1
  127. package/dist/commerce/index.js.map +1 -1
  128. package/dist/commerce/plan-change.js.map +1 -1
  129. package/dist/commerce/provider-registry.d.ts.map +1 -1
  130. package/dist/commerce/provider-registry.js +27 -2
  131. package/dist/commerce/provider-registry.js.map +1 -1
  132. package/dist/commerce/service.d.ts +15 -7
  133. package/dist/commerce/service.d.ts.map +1 -1
  134. package/dist/commerce/service.js +130 -77
  135. package/dist/commerce/service.js.map +1 -1
  136. package/dist/commerce/types.d.ts +33 -13
  137. package/dist/commerce/types.d.ts.map +1 -1
  138. package/dist/commerce/types.js.map +1 -1
  139. package/dist/config/parse-access.js.map +1 -1
  140. package/dist/config/parse-commerce.js.map +1 -1
  141. package/dist/config/parse-credits.js.map +1 -1
  142. package/dist/config/parse-plans.d.ts.map +1 -1
  143. package/dist/config/parse-plans.js +30 -13
  144. package/dist/config/parse-plans.js.map +1 -1
  145. package/dist/config/parse-pricing.d.ts.map +1 -1
  146. package/dist/config/parse-pricing.js +16 -5
  147. package/dist/config/parse-pricing.js.map +1 -1
  148. package/dist/config/parse-utils.js.map +1 -1
  149. package/dist/config/types.d.ts +14 -1
  150. package/dist/config/types.d.ts.map +1 -1
  151. package/dist/config/types.js.map +1 -1
  152. package/dist/config.d.ts +7 -1
  153. package/dist/config.d.ts.map +1 -1
  154. package/dist/config.js +64 -1
  155. package/dist/config.js.map +1 -1
  156. package/dist/credits/{pricing-runtime.d.ts → catalog-runtime.d.ts} +9 -8
  157. package/dist/credits/catalog-runtime.d.ts.map +1 -0
  158. package/dist/credits/{pricing-runtime.js → catalog-runtime.js} +58 -38
  159. package/dist/credits/catalog-runtime.js.map +1 -0
  160. package/dist/credits/events.d.ts +4 -4
  161. package/dist/credits/events.d.ts.map +1 -1
  162. package/dist/credits/events.js +1 -1
  163. package/dist/credits/events.js.map +1 -1
  164. package/dist/credits/lease-workflow.d.ts +14 -14
  165. package/dist/credits/lease-workflow.d.ts.map +1 -1
  166. package/dist/credits/lease-workflow.js +18 -17
  167. package/dist/credits/lease-workflow.js.map +1 -1
  168. package/dist/credits/low-balance-monitor.d.ts +2 -2
  169. package/dist/credits/low-balance-monitor.d.ts.map +1 -1
  170. package/dist/credits/low-balance-monitor.js.map +1 -1
  171. package/dist/credits/postgres/repositories/analytics.d.ts +39 -35
  172. package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -1
  173. package/dist/credits/postgres/repositories/analytics.js +55 -53
  174. package/dist/credits/postgres/repositories/analytics.js.map +1 -1
  175. package/dist/credits/postgres/repositories/balance.d.ts +28 -30
  176. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
  177. package/dist/credits/postgres/repositories/balance.js +100 -59
  178. package/dist/credits/postgres/repositories/balance.js.map +1 -1
  179. package/dist/credits/postgres/repositories/bucket.d.ts +14 -8
  180. package/dist/credits/postgres/repositories/bucket.d.ts.map +1 -1
  181. package/dist/credits/postgres/repositories/bucket.js +22 -21
  182. package/dist/credits/postgres/repositories/bucket.js.map +1 -1
  183. package/dist/credits/postgres/repositories/catalog.d.ts +31 -0
  184. package/dist/credits/postgres/repositories/catalog.d.ts.map +1 -0
  185. package/dist/credits/postgres/repositories/catalog.js +90 -0
  186. package/dist/credits/postgres/repositories/catalog.js.map +1 -0
  187. package/dist/credits/postgres/repositories/deduction.d.ts +32 -21
  188. package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -1
  189. package/dist/credits/postgres/repositories/deduction.js +171 -62
  190. package/dist/credits/postgres/repositories/deduction.js.map +1 -1
  191. package/dist/credits/postgres/repositories/lease.d.ts +21 -18
  192. package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
  193. package/dist/credits/postgres/repositories/lease.js +157 -65
  194. package/dist/credits/postgres/repositories/lease.js.map +1 -1
  195. package/dist/credits/postgres/repositories/plan.d.ts +94 -42
  196. package/dist/credits/postgres/repositories/plan.d.ts.map +1 -1
  197. package/dist/credits/postgres/repositories/plan.js +134 -104
  198. package/dist/credits/postgres/repositories/plan.js.map +1 -1
  199. package/dist/credits/postgres/repositories/team.d.ts +36 -27
  200. package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
  201. package/dist/credits/postgres/repositories/team.js +96 -52
  202. package/dist/credits/postgres/repositories/team.js.map +1 -1
  203. package/dist/credits/postgres/store.d.ts +31 -21
  204. package/dist/credits/postgres/store.d.ts.map +1 -1
  205. package/dist/credits/postgres/store.js +325 -235
  206. package/dist/credits/postgres/store.js.map +1 -1
  207. package/dist/credits/postgres/value-mappers.d.ts +7 -9
  208. package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
  209. package/dist/credits/postgres/value-mappers.js +42 -63
  210. package/dist/credits/postgres/value-mappers.js.map +1 -1
  211. package/dist/credits/queries.d.ts +5 -5
  212. package/dist/credits/queries.d.ts.map +1 -1
  213. package/dist/credits/queries.js +4 -4
  214. package/dist/credits/queries.js.map +1 -1
  215. package/dist/credits/service-errors.js.map +1 -1
  216. package/dist/credits/service-types.d.ts +42 -7
  217. package/dist/credits/service-types.d.ts.map +1 -1
  218. package/dist/credits/service-types.js.map +1 -1
  219. package/dist/credits/service.d.ts +51 -58
  220. package/dist/credits/service.d.ts.map +1 -1
  221. package/dist/credits/service.js +178 -113
  222. package/dist/credits/service.js.map +1 -1
  223. package/dist/credits/store.d.ts +25 -22
  224. package/dist/credits/store.d.ts.map +1 -1
  225. package/dist/credits/store.js +9 -5
  226. package/dist/credits/store.js.map +1 -1
  227. package/dist/credits/types/account.d.ts +50 -12
  228. package/dist/credits/types/account.d.ts.map +1 -1
  229. package/dist/credits/types/account.js.map +1 -1
  230. package/dist/credits/types/admission.d.ts +17 -6
  231. package/dist/credits/types/admission.d.ts.map +1 -1
  232. package/dist/credits/types/admission.js.map +1 -1
  233. package/dist/credits/types/analytics.d.ts +2 -2
  234. package/dist/credits/types/analytics.d.ts.map +1 -1
  235. package/dist/credits/types/analytics.js.map +1 -1
  236. package/dist/credits/types/catalog.d.ts +21 -14
  237. package/dist/credits/types/catalog.d.ts.map +1 -1
  238. package/dist/credits/types/catalog.js.map +1 -1
  239. package/dist/credits/types/grants.d.ts +22 -8
  240. package/dist/credits/types/grants.d.ts.map +1 -1
  241. package/dist/credits/types/grants.js.map +1 -1
  242. package/dist/credits/types/index.js.map +1 -1
  243. package/dist/credits/types/ledger.d.ts +19 -0
  244. package/dist/credits/types/ledger.d.ts.map +1 -1
  245. package/dist/credits/types/ledger.js.map +1 -1
  246. package/dist/credits/types/quotas.js.map +1 -1
  247. package/dist/credits/types/teams.d.ts +18 -6
  248. package/dist/credits/types/teams.d.ts.map +1 -1
  249. package/dist/credits/types/teams.js.map +1 -1
  250. package/dist/engine.d.ts.map +1 -1
  251. package/dist/engine.js +24 -10
  252. package/dist/engine.js.map +1 -1
  253. package/dist/errors.d.ts +105 -8
  254. package/dist/errors.d.ts.map +1 -1
  255. package/dist/errors.js +137 -9
  256. package/dist/errors.js.map +1 -1
  257. package/dist/expr/ast.d.ts.map +1 -1
  258. package/dist/expr/ast.js.map +1 -1
  259. package/dist/expr/evaluator.d.ts.map +1 -1
  260. package/dist/expr/evaluator.js +29 -17
  261. package/dist/expr/evaluator.js.map +1 -1
  262. package/dist/expr/language.js.map +1 -1
  263. package/dist/expr/parser.d.ts.map +1 -1
  264. package/dist/expr/parser.js +11 -4
  265. package/dist/expr/parser.js.map +1 -1
  266. package/dist/expr/tokenizer.d.ts.map +1 -1
  267. package/dist/expr/tokenizer.js +17 -13
  268. package/dist/expr/tokenizer.js.map +1 -1
  269. package/dist/expr.d.ts +2 -2
  270. package/dist/expr.d.ts.map +1 -1
  271. package/dist/expr.js +7 -9
  272. package/dist/expr.js.map +1 -1
  273. package/dist/generated/pricing-config.schema.json +30 -9
  274. package/dist/generated/pricing-config.types.d.ts +14 -3
  275. package/dist/generated/pricing-config.types.d.ts.map +1 -1
  276. package/dist/generated/pricing-config.types.js.map +1 -1
  277. package/dist/index.d.ts +11 -7
  278. package/dist/index.d.ts.map +1 -1
  279. package/dist/index.js +2 -2
  280. package/dist/index.js.map +1 -1
  281. package/dist/integrations/better-auth.d.ts +23 -0
  282. package/dist/integrations/better-auth.d.ts.map +1 -0
  283. package/dist/integrations/better-auth.js +54 -0
  284. package/dist/integrations/better-auth.js.map +1 -0
  285. package/dist/{load-pricing-file.d.ts → load-config-file.d.ts} +4 -4
  286. package/dist/load-config-file.d.ts.map +1 -0
  287. package/dist/{load-pricing-file.js → load-config-file.js} +23 -14
  288. package/dist/load-config-file.js.map +1 -0
  289. package/dist/metrics.js.map +1 -1
  290. package/dist/node.d.ts +3 -3
  291. package/dist/node.d.ts.map +1 -1
  292. package/dist/node.js +2 -2
  293. package/dist/node.js.map +1 -1
  294. package/dist/providers/_shared.d.ts +5 -0
  295. package/dist/providers/_shared.d.ts.map +1 -1
  296. package/dist/providers/_shared.js +77 -14
  297. package/dist/providers/_shared.js.map +1 -1
  298. package/dist/providers/dodo/better-auth.d.ts +29 -0
  299. package/dist/providers/dodo/better-auth.d.ts.map +1 -0
  300. package/dist/providers/dodo/better-auth.js +23 -0
  301. package/dist/providers/dodo/better-auth.js.map +1 -0
  302. package/dist/providers/dodo/client-contract.d.ts +32 -70
  303. package/dist/providers/dodo/client-contract.d.ts.map +1 -1
  304. package/dist/providers/dodo/client-contract.js.map +1 -1
  305. package/dist/providers/dodo/event-mapper.d.ts +3 -1
  306. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  307. package/dist/providers/dodo/event-mapper.js +219 -148
  308. package/dist/providers/dodo/event-mapper.js.map +1 -1
  309. package/dist/providers/dodo/index.d.ts +5 -2
  310. package/dist/providers/dodo/index.d.ts.map +1 -1
  311. package/dist/providers/dodo/index.js +2 -1
  312. package/dist/providers/dodo/index.js.map +1 -1
  313. package/dist/providers/dodo/nextjs.d.ts +16 -0
  314. package/dist/providers/dodo/nextjs.d.ts.map +1 -0
  315. package/dist/providers/dodo/nextjs.js +16 -0
  316. package/dist/providers/dodo/nextjs.js.map +1 -0
  317. package/dist/providers/dodo/provider.d.ts +30 -11
  318. package/dist/providers/dodo/provider.d.ts.map +1 -1
  319. package/dist/providers/dodo/provider.js +192 -122
  320. package/dist/providers/dodo/provider.js.map +1 -1
  321. package/dist/providers/dodo/react-native.d.ts +56 -0
  322. package/dist/providers/dodo/react-native.d.ts.map +1 -0
  323. package/dist/providers/dodo/react-native.js +57 -0
  324. package/dist/providers/dodo/react-native.js.map +1 -0
  325. package/dist/providers/dodo/webhook-bridge.d.ts +17 -0
  326. package/dist/providers/dodo/webhook-bridge.d.ts.map +1 -0
  327. package/dist/providers/dodo/webhook-bridge.js +21 -0
  328. package/dist/providers/dodo/webhook-bridge.js.map +1 -0
  329. package/dist/providers/index.d.ts +1 -1
  330. package/dist/providers/index.d.ts.map +1 -1
  331. package/dist/providers/index.js.map +1 -1
  332. package/dist/providers/mock/index.d.ts +1 -0
  333. package/dist/providers/mock/index.d.ts.map +1 -1
  334. package/dist/providers/mock/index.js.map +1 -1
  335. package/dist/providers/mock/provider.d.ts +8 -8
  336. package/dist/providers/mock/provider.d.ts.map +1 -1
  337. package/dist/providers/mock/provider.js +26 -19
  338. package/dist/providers/mock/provider.js.map +1 -1
  339. package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
  340. package/dist/providers/stripe/event-mapper.js +214 -173
  341. package/dist/providers/stripe/event-mapper.js.map +1 -1
  342. package/dist/providers/stripe/index.d.ts +1 -0
  343. package/dist/providers/stripe/index.d.ts.map +1 -1
  344. package/dist/providers/stripe/index.js.map +1 -1
  345. package/dist/providers/stripe/provider.d.ts +13 -11
  346. package/dist/providers/stripe/provider.d.ts.map +1 -1
  347. package/dist/providers/stripe/provider.js +287 -107
  348. package/dist/providers/stripe/provider.js.map +1 -1
  349. package/dist/providers/types.d.ts +1 -2
  350. package/dist/providers/types.d.ts.map +1 -1
  351. package/dist/providers/types.js.map +1 -1
  352. package/dist/retry.d.ts +26 -4
  353. package/dist/retry.d.ts.map +1 -1
  354. package/dist/retry.js +65 -23
  355. package/dist/retry.js.map +1 -1
  356. package/dist/shared/diagnostics.d.ts +7 -0
  357. package/dist/shared/diagnostics.d.ts.map +1 -0
  358. package/dist/shared/diagnostics.js +18 -0
  359. package/dist/shared/diagnostics.js.map +1 -0
  360. package/dist/shared/logger.js.map +1 -1
  361. package/dist/shared/postgres-client.d.ts +43 -5
  362. package/dist/shared/postgres-client.d.ts.map +1 -1
  363. package/dist/shared/postgres-client.js +282 -30
  364. package/dist/shared/postgres-client.js.map +1 -1
  365. package/dist/shared/postgres-errors.d.ts +11 -0
  366. package/dist/shared/postgres-errors.d.ts.map +1 -0
  367. package/dist/shared/postgres-errors.js +105 -0
  368. package/dist/shared/postgres-errors.js.map +1 -0
  369. package/dist/shared/postgres-types.js.map +1 -1
  370. package/dist/shared/postgres-validation.d.ts +15 -3
  371. package/dist/shared/postgres-validation.d.ts.map +1 -1
  372. package/dist/shared/postgres-validation.js +58 -14
  373. package/dist/shared/postgres-validation.js.map +1 -1
  374. package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
  375. package/dist/storage/adapters/clickhouse.js +18 -3
  376. package/dist/storage/adapters/clickhouse.js.map +1 -1
  377. package/dist/storage/adapters/s3.d.ts +0 -6
  378. package/dist/storage/adapters/s3.d.ts.map +1 -1
  379. package/dist/storage/adapters/s3.js +0 -2
  380. package/dist/storage/adapters/s3.js.map +1 -1
  381. package/dist/storage/outbox-worker.d.ts +2 -1
  382. package/dist/storage/outbox-worker.d.ts.map +1 -1
  383. package/dist/storage/outbox-worker.js +17 -3
  384. package/dist/storage/outbox-worker.js.map +1 -1
  385. package/dist/storage/ports.d.ts +1 -1
  386. package/dist/storage/ports.d.ts.map +1 -1
  387. package/dist/storage/ports.js.map +1 -1
  388. package/dist/storage/postgres-repository.d.ts +1 -1
  389. package/dist/storage/postgres-repository.d.ts.map +1 -1
  390. package/dist/storage/postgres-repository.js +13 -3
  391. package/dist/storage/postgres-repository.js.map +1 -1
  392. package/dist/storage/runtime.d.ts +35 -7
  393. package/dist/storage/runtime.d.ts.map +1 -1
  394. package/dist/storage/runtime.js +166 -53
  395. package/dist/storage/runtime.js.map +1 -1
  396. package/package.json +62 -7
  397. package/dist/credits/postgres/repositories/pricing.d.ts +0 -28
  398. package/dist/credits/postgres/repositories/pricing.d.ts.map +0 -1
  399. package/dist/credits/postgres/repositories/pricing.js +0 -70
  400. package/dist/credits/postgres/repositories/pricing.js.map +0 -1
  401. package/dist/credits/pricing-runtime.d.ts.map +0 -1
  402. package/dist/credits/pricing-runtime.js.map +0 -1
  403. package/dist/load-pricing-file.d.ts.map +0 -1
  404. package/dist/load-pricing-file.js.map +0 -1
@@ -1,27 +1,33 @@
1
1
  import Decimal from "decimal.js";
2
2
  import { randomUUID } from "node:crypto";
3
- import { StoreError } from "../../errors.js";
4
- import { canonicalBursarConfigDict } from "../../config.js";
3
+ import { StoreClosedError, StoreError } from "../../errors.js";
4
+ import { canonicalBursarConfigDict, canonicalCatalogRolloutDict, loadCatalogRollout, loadConfigFromDict, validateCatalogRollout, } from "../../config.js";
5
5
  import { PostgresClient, } from "../../shared/postgres-client.js";
6
6
  import { CreditStore } from "../store.js";
7
7
  import { BalanceRepository } from "./repositories/balance.js";
8
8
  import { DeductionRepository } from "./repositories/deduction.js";
9
9
  import { LeaseRepository } from "./repositories/lease.js";
10
- import { PricingRepository } from "./repositories/pricing.js";
10
+ import { CatalogRepository } from "./repositories/catalog.js";
11
11
  import { PlanRepository } from "./repositories/plan.js";
12
12
  import { AnalyticsRepository } from "./repositories/analytics.js";
13
13
  import { TeamRepository } from "./repositories/team.js";
14
14
  import { BucketRepository } from "./repositories/bucket.js";
15
- import { ZERO, decimalParameter as decParam, decimalRecord as decRecord, decimalValue as dec, mapLedgerEntry, mapUsageCharge, normalizeBursarConfig, parseAdmissionOperations, parseEntitlements, } from "./value-mappers.js";
15
+ import { ZERO, decimalParameter as decParam, decimalRecord as decRecord, decimalValue as dec, mapLedgerEntry, mapUsageCharge, normalizeCatalogRevision, } from "./value-mappers.js";
16
16
  const DEFAULT_LEASE_TTL_SECONDS = 600;
17
17
  const DEFAULT_PAGE_SIZE = 50;
18
18
  const MAX_PAGE_SIZE = 200;
19
+ function requireText(value, context) {
20
+ if (typeof value !== "string" || value.length === 0) {
21
+ throw new StoreError(`${context} returned a missing or invalid identifier`);
22
+ }
23
+ return value;
24
+ }
19
25
  export class PostgresStore extends CreditStore {
20
26
  postgres;
21
27
  _balanceRepo = null;
22
28
  _deductionRepo = null;
23
29
  _leaseRepo = null;
24
- _pricingRepo = null;
30
+ _catalogRepo = null;
25
31
  _planRepo = null;
26
32
  _analyticsRepo = null;
27
33
  _teamRepo = null;
@@ -44,11 +50,11 @@ export class PostgresStore extends CreditStore {
44
50
  }
45
51
  return this._leaseRepo;
46
52
  }
47
- get pricingRepo() {
48
- if (!this._pricingRepo) {
49
- this._pricingRepo = new PricingRepository(this.callproc.bind(this));
53
+ get catalogRepo() {
54
+ if (!this._catalogRepo) {
55
+ this._catalogRepo = new CatalogRepository(this.callproc.bind(this));
50
56
  }
51
- return this._pricingRepo;
57
+ return this._catalogRepo;
52
58
  }
53
59
  get planRepo() {
54
60
  if (!this._planRepo) {
@@ -74,23 +80,27 @@ export class PostgresStore extends CreditStore {
74
80
  }
75
81
  return this._bucketRepo;
76
82
  }
77
- constructor(databaseUrl, tenantId, poolOrCtor, storageOptions) {
83
+ constructor(options) {
78
84
  super();
79
- if (poolOrCtor && typeof poolOrCtor.query === "function") {
80
- this.postgres = new PostgresClient(poolOrCtor, {
81
- tenantId,
82
- usageBackend: storageOptions?.usageBackend,
83
- closedError: () => new StoreError("Store has been closed"),
84
- });
85
- }
86
- else {
87
- this.postgres = new PostgresClient(databaseUrl, {
88
- tenantId,
89
- usageBackend: storageOptions?.usageBackend,
90
- poolConstructor: poolOrCtor,
91
- closedError: () => new StoreError("Store has been closed"),
92
- });
93
- }
85
+ if (typeof options !== "object" || options === null) {
86
+ throw new TypeError("PostgresStore options are required");
87
+ }
88
+ if (typeof options.postgres !== "string" && options.poolConstructor !== undefined) {
89
+ throw new TypeError("poolConstructor cannot be used with an existing PostgreSQL pool");
90
+ }
91
+ this.postgres = new PostgresClient(options.postgres, {
92
+ tenantId: options.tenantId,
93
+ usageBackend: options.usageBackend,
94
+ poolConstructor: options.poolConstructor,
95
+ connectionTimeoutMs: options.connectionTimeoutMs,
96
+ statementTimeoutMs: options.statementTimeoutMs,
97
+ idleTransactionTimeoutMs: options.idleTransactionTimeoutMs,
98
+ idleTimeoutMs: options.idleTimeoutMs,
99
+ maxConnections: options.maxConnections,
100
+ applicationName: options.applicationName,
101
+ onPoolError: options.onPoolError,
102
+ closedError: () => new StoreClosedError("Credit store has been closed"),
103
+ });
94
104
  }
95
105
  async query(text, params) {
96
106
  return this.postgres.query(text, params);
@@ -100,9 +110,10 @@ export class PostgresStore extends CreditStore {
100
110
  }
101
111
  static RPC_NAME_RE = /^[a-z_][a-z0-9_]*$/;
102
112
  static SCALAR_RPC_NAMES = new Set([
103
- "assign_plan",
113
+ "apply_due_plan_assignment_changes",
104
114
  "release_lease",
105
115
  "remove_team_member",
116
+ "set_plan_revision_pin",
106
117
  "set_team_member",
107
118
  "start_plan_migration",
108
119
  "unassign_plan",
@@ -116,8 +127,9 @@ export class PostgresStore extends CreditStore {
116
127
  if (PostgresStore.SCALAR_RPC_NAMES.has(name) && rows.length === 1) {
117
128
  const row = rows[0];
118
129
  const keys = Object.keys(row);
119
- if (keys.length === 1) {
120
- return [row[keys[0]]];
130
+ const key = keys[0];
131
+ if (keys.length === 1 && key !== undefined) {
132
+ return [row[key]];
121
133
  }
122
134
  }
123
135
  return rows;
@@ -128,7 +140,7 @@ export class PostgresStore extends CreditStore {
128
140
  return { userId, balance: ZERO, lifetimePurchased: ZERO };
129
141
  }
130
142
  return {
131
- userId: String(row.user_id ?? userId),
143
+ userId: row.user_id,
132
144
  balance: dec(row.balance),
133
145
  lifetimePurchased: dec(row.lifetime_purchased),
134
146
  };
@@ -139,17 +151,17 @@ export class PostgresStore extends CreditStore {
139
151
  meta.expires_at = expiresAt instanceof Date ? expiresAt.toISOString() : String(expiresAt);
140
152
  }
141
153
  const row = await this.balanceRepo.addCredits(userId, decParam(amount), type, JSON.stringify(meta), expiresAt ? expiresAt.toISOString() : null, bucket ?? null, idempotencyKey ?? `credit:${randomUUID()}`);
142
- if ("error" in row && row.error) {
143
- throw new StoreError(`post_credit: ${String(row.error)}`);
154
+ if (row.error !== null) {
155
+ throw new StoreError(`post_credit: ${row.error}`);
144
156
  }
145
157
  return {
146
- entryId: String(row.entry_id ?? ""),
147
- userId: String(row.user_id ?? userId),
148
- amount: dec(row.amount, amount),
158
+ entryId: requireText(row.entry_id, "post_credit"),
159
+ userId: row.user_id,
160
+ amount: dec(row.amount),
149
161
  newBalance: dec(row.new_balance),
150
162
  lifetimePurchased: dec(row.lifetime_purchased),
151
- bucket: String(row.bucket ?? "default"),
152
- idempotent: Boolean(row.idempotent),
163
+ bucket: row.bucket,
164
+ idempotent: row.idempotent,
153
165
  };
154
166
  }
155
167
  async deductWithAllowance(userId, amount, options) {
@@ -174,27 +186,62 @@ export class PostgresStore extends CreditStore {
174
186
  dimensions: JSON.stringify(dimensions),
175
187
  metadata: JSON.stringify(metadata ?? {}),
176
188
  });
177
- if ("error" in row && row.error) {
189
+ if (row.error !== null) {
178
190
  return {
179
- entryId: "",
191
+ entryId: null,
192
+ usageChargeId: row.charge_id != null ? String(row.charge_id) : null,
180
193
  userId,
181
- amount: ZERO,
182
- allowanceConsumed: ZERO,
183
- balanceAfter: dec(row.balance_after),
194
+ amount: dec(row.amount),
195
+ allowanceConsumed: dec(row.allowance_consumed),
196
+ balanceAfter: row.balance_after == null ? null : dec(row.balance_after),
184
197
  idempotent: false,
185
- error: String(row.error),
198
+ error: row.error,
199
+ bucketBreakdown: null,
186
200
  };
187
201
  }
188
202
  return {
189
- entryId: String(row.entry_id ?? ""),
203
+ entryId: row.entry_id == null ? null : requireText(row.entry_id, "charge_usage_for_operation"),
204
+ usageChargeId: requireText(row.charge_id, "charge_usage_for_operation"),
190
205
  userId,
191
206
  amount: dec(row.amount),
192
207
  allowanceConsumed: dec(row.allowance_consumed),
193
208
  balanceAfter: dec(row.balance_after),
194
- idempotent: Boolean(row.idempotent),
209
+ idempotent: row.idempotent,
210
+ error: null,
195
211
  bucketBreakdown: decRecord(row.bucket_breakdown),
196
212
  };
197
213
  }
214
+ async recordUsage(userId, operation, amount, options) {
215
+ const idempotencyKey = options?.idempotencyKey ?? `usage-record:${randomUUID()}`;
216
+ const row = await this.deductionRepo.recordUsage({
217
+ userId,
218
+ operation,
219
+ amount: decParam(amount),
220
+ idempotencyKey,
221
+ feature: options?.feature ?? null,
222
+ model: options?.model ?? null,
223
+ region: options?.region ?? null,
224
+ measures: JSON.stringify(options?.measures ?? {}),
225
+ dimensions: JSON.stringify(options?.dimensions ?? {}),
226
+ metadata: JSON.stringify(options?.metadata ?? {}),
227
+ });
228
+ if (row.error_code !== null) {
229
+ return {
230
+ usageId: null,
231
+ userId,
232
+ requested: dec(row.requested),
233
+ idempotent: false,
234
+ error: row.error_code,
235
+ };
236
+ }
237
+ return {
238
+ usageId: requireText(row.charge_id, "record_usage"),
239
+ userId,
240
+ requested: dec(row.requested),
241
+ idempotent: row.replayed,
242
+ error: null,
243
+ };
244
+ }
198
245
  async createLease(userId, amount, operationType, options) {
199
246
  const row = await this.leaseRepo.createLease({
200
247
  userId,
@@ -209,42 +256,30 @@ export class PostgresStore extends CreditStore {
209
256
  minimumBalance: options?.floor == null ? null : decParam(options.floor),
210
257
  maxConcurrent: options?.maxConcurrent ?? null,
211
258
  });
212
- if (!row || Object.keys(row).length === 0) {
213
- return {
214
- leaseId: "",
215
- userId,
216
- amount: ZERO,
217
- available: ZERO,
218
- reservedTotal: ZERO,
219
- minimumBalance: ZERO,
220
- billingMode: options?.billingMode ?? "strict",
221
- expiresAt: "",
222
- error: "no result",
223
- };
224
- }
225
259
  const availability = await this.getAvailable(userId);
226
- if ("error" in row && row.error) {
260
+ if (row.error !== null) {
227
261
  return {
228
- leaseId: "",
262
+ leaseId: null,
229
263
  userId,
230
- amount: ZERO,
264
+ amount: row.amount == null ? null : dec(row.amount),
231
265
  available: availability.available,
232
266
  reservedTotal: availability.reserved,
233
- minimumBalance: ZERO,
267
+ minimumBalance: row.minimum_balance == null ? null : dec(row.minimum_balance),
234
268
  billingMode: options?.billingMode ?? "strict",
235
- expiresAt: "",
236
- error: String(row.error),
269
+ expiresAt: null,
270
+ error: row.error,
237
271
  };
238
272
  }
239
273
  return {
240
- leaseId: String(row.lease_id ?? ""),
241
- userId: String(row.user_id ?? userId),
274
+ leaseId: requireText(row.lease_id, "create_lease_for_operation"),
275
+ userId: row.user_id,
242
276
  amount: dec(row.amount),
243
277
  available: availability.available,
244
278
  reservedTotal: availability.reserved,
245
279
  minimumBalance: dec(row.minimum_balance),
246
280
  billingMode: dec(row.minimum_balance).lt(0) ? "overdraft" : "strict",
247
- expiresAt: String(row.expires_at ?? ""),
281
+ expiresAt: requireText(row.expires_at, "create_lease_for_operation"),
282
+ error: null,
248
283
  };
249
284
  }
250
285
  async settleLease(userId, leaseId, amount, options) {
@@ -260,35 +295,28 @@ export class PostgresStore extends CreditStore {
260
295
  dimensions: JSON.stringify(options?.dimensions ?? {}),
261
296
  metadata: JSON.stringify(options?.metadata ?? {}),
262
297
  });
263
- if (!row || Object.keys(row).length === 0) {
298
+ if (row.error !== null) {
264
299
  return {
265
- entryId: "",
300
+ entryId: null,
301
+ usageChargeId: row.charge_id != null ? String(row.charge_id) : null,
266
302
  userId,
267
- amount: ZERO,
268
- allowanceConsumed: ZERO,
269
- balanceAfter: ZERO,
303
+ amount: dec(row.amount),
304
+ allowanceConsumed: dec(row.allowance_consumed),
305
+ balanceAfter: row.balance_after == null ? null : dec(row.balance_after),
270
306
  idempotent: false,
271
- error: "no result",
272
- };
273
- }
274
- if ("error" in row && row.error) {
275
- return {
276
- entryId: "",
277
- userId,
278
- amount: ZERO,
279
- allowanceConsumed: ZERO,
280
- balanceAfter: dec(row.balance_after),
281
- idempotent: false,
282
- error: String(row.error),
307
+ error: row.error,
308
+ bucketBreakdown: null,
283
309
  };
284
310
  }
285
311
  return {
286
- entryId: String(row.entry_id ?? ""),
312
+ entryId: row.entry_id == null ? null : requireText(row.entry_id, "settle_lease"),
313
+ usageChargeId: requireText(row.charge_id, "settle_lease"),
287
314
  userId,
288
315
  amount: dec(row.amount),
289
316
  allowanceConsumed: dec(row.allowance_consumed),
290
317
  balanceAfter: dec(row.balance_after),
291
- idempotent: Boolean(row.idempotent),
318
+ idempotent: row.idempotent,
319
+ error: null,
292
320
  bucketBreakdown: decRecord(row.bucket_breakdown),
293
321
  };
294
322
  }
@@ -308,8 +336,8 @@ export class PostgresStore extends CreditStore {
308
336
  return {
309
337
  leaseId,
310
338
  userId,
311
- released: Boolean(row.released),
312
- reason: row.reason != null ? String(row.reason) : null,
339
+ released: row.released,
340
+ reason: row.reason,
313
341
  };
314
342
  }
315
343
  async renewLease(userId, leaseId, ttlSeconds) {
@@ -318,17 +346,30 @@ export class PostgresStore extends CreditStore {
318
346
  }
319
347
  const row = await this.leaseRepo.renewLease(userId, leaseId, ttlSeconds);
320
348
  const availability = await this.getAvailable(userId);
349
+ if (row.error !== null) {
350
+ return {
351
+ leaseId: null,
352
+ userId,
353
+ amount: row.amount == null ? null : dec(row.amount),
354
+ available: availability.available,
355
+ reservedTotal: availability.reserved,
356
+ minimumBalance: row.minimum_balance == null ? null : dec(row.minimum_balance),
357
+ billingMode: row.minimum_balance != null && dec(row.minimum_balance).lt(0) ? "overdraft" : "strict",
358
+ expiresAt: null,
359
+ error: row.error,
360
+ };
361
+ }
321
362
  const minimumBalance = dec(row.minimum_balance);
322
363
  return {
323
- leaseId: String(row.lease_id ?? leaseId),
364
+ leaseId: requireText(row.lease_id, "renew_lease"),
324
365
  userId,
325
366
  amount: dec(row.amount),
326
367
  available: availability.available,
327
368
  reservedTotal: availability.reserved,
328
369
  minimumBalance,
329
370
  billingMode: minimumBalance.lt(0) ? "overdraft" : "strict",
330
- expiresAt: String(row.expires_at ?? ""),
331
- error: row.error != null ? String(row.error) : null,
371
+ expiresAt: requireText(row.expires_at, "renew_lease"),
372
+ error: null,
332
373
  };
333
374
  }
334
375
  async expireLeases(limit = 100) {
@@ -339,6 +380,9 @@ export class PostgresStore extends CreditStore {
339
380
  }
340
381
  async getAvailable(userId) {
341
382
  const row = await this.balanceRepo.getAvailable(userId);
383
+ if (row === null) {
384
+ return { userId, balance: ZERO, reserved: ZERO, available: ZERO };
385
+ }
342
386
  return {
343
387
  userId,
344
388
  balance: dec(row.balance),
@@ -346,46 +390,47 @@ export class PostgresStore extends CreditStore {
346
390
  available: dec(row.available),
347
391
  };
348
392
  }
349
- async getActivePricing() {
350
- return this._loadActivePricing();
393
+ async getActiveCatalog() {
394
+ return this.loadActiveCatalog();
351
395
  }
352
- async _loadActivePricing() {
353
- const row = await this.pricingRepo.getActivePricing();
354
- if (!row || !row.config)
355
- return null;
356
- return normalizeBursarConfig(row, 0);
396
+ async loadActiveCatalog() {
397
+ const row = await this.catalogRepo.getActiveCatalog();
398
+ return row === null ? null : normalizeCatalogRevision(row);
357
399
  }
358
- async setActivePricing(config, label) {
400
+ async publishAndActivateCatalog(config, label, rollout) {
359
401
  const canonical = canonicalBursarConfigDict(config);
360
- const row = await this.pricingRepo.setActivePricing(JSON.stringify(canonical), label ?? null);
361
- return String(row.id ?? "");
402
+ const parsed = loadConfigFromDict(canonical);
403
+ const rolloutDocument = canonicalCatalogRolloutDict(validateCatalogRollout(parsed, loadCatalogRollout(rollout ?? {})));
404
+ const row = await this.catalogRepo.publishAndActivateCatalog(JSON.stringify(canonical), label ?? null, rolloutDocument);
405
+ return row.id;
362
406
  }
363
- async publishPricing(config, label) {
407
+ async publishCatalogDraft(config, label) {
364
408
  const canonical = canonicalBursarConfigDict(config);
365
- const row = await this.pricingRepo.publishPricing(JSON.stringify(canonical), label ?? null);
366
- return String(row.id ?? "");
409
+ const row = await this.catalogRepo.publishCatalogDraft(JSON.stringify(canonical), label ?? null);
410
+ return row.id;
367
411
  }
368
- async getPricingHistory() {
369
- const rows = await this.pricingRepo.getPricingHistory();
370
- if (!rows)
371
- return [];
412
+ async getCatalogHistory() {
413
+ const rows = await this.catalogRepo.getCatalogHistory();
372
414
  return rows.map((r) => ({
373
- id: String(r.id ?? ""),
374
- version: Number(r.version ?? 0),
375
- label: r.label ?? null,
376
- active: Boolean(r.active ?? false),
377
- createdAt: String(r.created_at ?? ""),
415
+ id: r.id,
416
+ version: r.version,
417
+ label: r.label,
418
+ active: r.active,
419
+ createdAt: r.created_at,
378
420
  }));
379
421
  }
380
- async getBursarConfig(version) {
381
- const row = await this.pricingRepo.getBursarConfig(version);
382
- if (!row || !row.config)
383
- return null;
384
- return normalizeBursarConfig(row, version);
422
+ async getCatalogRevision(version) {
423
+ const row = await this.catalogRepo.getCatalogRevision(version);
424
+ return row === null ? null : normalizeCatalogRevision(row);
385
425
  }
386
- async activatePricing(version) {
387
- const row = await this.pricingRepo.activatePricing(version);
388
- return String(row.id ?? "");
426
+ async activateCatalogRevision(version, rollout) {
427
+ const target = await this.getCatalogRevision(version);
428
+ const parsedRollout = loadCatalogRollout(rollout ?? {});
429
+ if (target != null) {
430
+ validateCatalogRollout(loadConfigFromDict(target.config), parsedRollout);
431
+ }
432
+ const row = await this.catalogRepo.activateCatalogRevision(version, canonicalCatalogRolloutDict(parsedRollout));
433
+ return row.id;
389
434
  }
390
435
  async getUserPlan(userId) {
391
436
  const row = await this.planRepo.getUserPlan(userId);
@@ -397,57 +442,72 @@ export class PostgresStore extends CreditStore {
397
442
  planLabel: null,
398
443
  allowance: null,
399
444
  entitlements: {},
445
+ rateCard: null,
400
446
  creditPolicy: null,
401
447
  admission: null,
402
448
  allowedOperations: [],
449
+ planAssignedAt: null,
450
+ planAssignmentEndsAt: null,
451
+ assignmentSourceType: null,
452
+ assignmentSourceId: null,
453
+ catalogRevisionPinned: false,
454
+ catalogVersion: null,
455
+ };
456
+ }
457
+ let allowance = null;
458
+ if (row.credit_allowance_amount != null) {
459
+ const priority = row.credit_allowance_priority;
460
+ const resetUnit = row.credit_allowance_reset_unit;
461
+ const resetCount = row.credit_allowance_reset_count;
462
+ const resetAnchor = row.credit_allowance_reset_anchor;
463
+ const resetTimezone = row.credit_allowance_reset_timezone;
464
+ if (priority == null ||
465
+ resetUnit == null ||
466
+ resetCount == null ||
467
+ resetAnchor == null ||
468
+ resetTimezone == null) {
469
+ throw new StoreError("get_user_plan returned an incomplete allowance policy");
470
+ }
471
+ allowance = {
472
+ amount: dec(row.credit_allowance_amount),
473
+ priority,
474
+ resetUnit,
475
+ resetCount,
476
+ resetAnchor,
477
+ resetTimezone,
403
478
  };
404
479
  }
405
- const allowanceAmount = dec(row.credit_allowance_amount);
406
- const admissionOperations = parseAdmissionOperations(row.operation_admission);
480
+ const admissionOperations = Object.fromEntries(Object.entries(row.operation_admission).map(([operation, policy]) => [
481
+ operation,
482
+ { maxInFlight: policy.max_in_flight },
483
+ ]));
407
484
  return {
408
- userId: String(row.user_id ?? userId),
409
- planId: row.plan_id ?? null,
410
- planKey: row.plan_key ?? null,
411
- planLabel: row.plan_label ?? null,
412
- allowance: row.credit_allowance_amount == null
413
- ? null
414
- : {
415
- amount: allowanceAmount,
416
- resetUnit: row.credit_allowance_reset_unit == null
417
- ? null
418
- : String(row.credit_allowance_reset_unit),
419
- resetCount: row.credit_allowance_reset_count == null
420
- ? null
421
- : Number(row.credit_allowance_reset_count),
422
- resetAnchor: row.credit_allowance_reset_anchor == null
423
- ? null
424
- : String(row.credit_allowance_reset_anchor),
425
- resetTimezone: row.credit_allowance_reset_timezone == null
426
- ? null
427
- : String(row.credit_allowance_reset_timezone),
428
- },
429
- entitlements: parseEntitlements(row.entitlements),
430
- rateCard: row.rate_card != null ? String(row.rate_card) : null,
485
+ userId: row.user_id,
486
+ planId: row.plan_id,
487
+ planKey: row.plan_key,
488
+ planLabel: row.plan_label,
489
+ allowance,
490
+ entitlements: row.entitlements,
491
+ rateCard: row.rate_card,
431
492
  creditPolicy: row.credit_policy_type == null
432
493
  ? null
433
494
  : {
434
- type: String(row.credit_policy_type),
495
+ type: row.credit_policy_type,
435
496
  creditLimit: row.credit_limit == null ? null : dec(row.credit_limit),
436
497
  },
437
498
  admission: row.admission_max_in_flight == null && Object.keys(admissionOperations).length === 0
438
499
  ? null
439
500
  : {
440
- maxInFlight: row.admission_max_in_flight == null ? null : Number(row.admission_max_in_flight),
501
+ maxInFlight: row.admission_max_in_flight,
441
502
  operations: admissionOperations,
442
503
  },
443
- allowedOperations: Array.isArray(row.allowed_operations)
444
- ? row.allowed_operations.map(String)
445
- : [],
446
- planAssignedAt: row.plan_assigned_at != null ? new Date(String(row.plan_assigned_at)) : null,
447
- assignmentSourceType: row.assignment_source_type == null ? null : String(row.assignment_source_type),
448
- assignmentSourceId: row.assignment_source_id == null ? null : String(row.assignment_source_id),
449
- revisionPolicy: row.revision_policy == null ? null : String(row.revision_policy),
450
- catalogVersion: row.catalog_revision_no != null ? Number(row.catalog_revision_no) : null,
504
+ allowedOperations: row.allowed_operations,
505
+ planAssignedAt: row.plan_assigned_at,
506
+ planAssignmentEndsAt: row.plan_assignment_ends_at,
507
+ assignmentSourceType: row.assignment_source_type,
508
+ assignmentSourceId: row.assignment_source_id,
509
+ catalogRevisionPinned: row.catalog_revision_pinned,
510
+ catalogVersion: row.catalog_revision_no,
451
511
  };
452
512
  }
453
513
  async checkFeature(userId, feature) {
@@ -463,27 +523,36 @@ export class PostgresStore extends CreditStore {
463
523
  async setUserPlan(userId, planKey, planAssignedAt) {
464
524
  const row = await this.planRepo.setUserPlan(userId, planKey, planAssignedAt?.toISOString() ?? null);
465
525
  return {
466
- userId: String(row.user_id ?? userId),
467
- planId: String(row.plan_id),
468
- planAssignedAt: row.plan_assigned_at != null ? String(row.plan_assigned_at) : null,
526
+ userId: row.user_id,
527
+ planId: requireText(row.plan_id, "set_subject_plan"),
528
+ planKey: row.plan_key,
529
+ planAssignedAt: row.plan_assigned_at,
530
+ assignmentState: row.assignment_state,
469
531
  };
470
532
  }
471
533
  async unsetUserPlan(userId) {
472
534
  const row = await this.planRepo.unsetUserPlan(userId);
473
- return { userId: String(row.user_id ?? userId) };
535
+ return { userId: row.user_id };
536
+ }
537
+ async setPlanRevisionPin(userId, pinned) {
538
+ return this.planRepo.setPlanRevisionPin(userId, pinned);
539
+ }
540
+ async applyDuePlanChanges(limit = 100) {
541
+ if (!Number.isInteger(limit) || limit < 1 || limit > 1000) {
542
+ throw new RangeError("plan change limit must be an integer between 1 and 1000");
543
+ }
544
+ return this.planRepo.applyDuePlanChanges(limit);
474
545
  }
475
546
  async startPlanMigration(fromPlanId, toPlanId) {
476
547
  const migrationId = await this.planRepo.startPlanMigration(fromPlanId, toPlanId);
477
- if (!migrationId)
478
- throw new StoreError("start_plan_migration returned no migration id");
479
548
  return { migrationId };
480
549
  }
481
550
  async migratePlanBatch(migrationId, batchSize) {
482
551
  const row = await this.planRepo.migratePlanBatch(migrationId, batchSize);
483
552
  return {
484
- migrated: Number(row.migrated ?? 0),
485
- done: Boolean(row.done),
486
- nextCursor: row.next_cursor != null ? String(row.next_cursor) : null,
553
+ migrated: row.migrated,
554
+ done: row.done,
555
+ nextCursor: row.next_cursor,
487
556
  };
488
557
  }
489
558
  async getQuotaState(userId, quotaKey) {
@@ -527,37 +596,47 @@ export class PostgresStore extends CreditStore {
527
596
  }
528
597
  async checkAllowance(userId) {
529
598
  const row = await this.planRepo.checkAllowance(userId);
530
- if (!row) {
531
- return { planId: "", allowanceRemaining: ZERO, periodStart: "", periodEnd: "" };
532
- }
599
+ if (!row)
600
+ return null;
533
601
  return {
534
- planId: String(row.plan_id ?? ""),
602
+ planId: row.plan_id,
535
603
  allowanceRemaining: dec(row.allowance_remaining),
536
- periodStart: String(row.period_start ?? ""),
537
- periodEnd: String(row.period_end ?? ""),
604
+ periodStart: row.period_start,
605
+ periodEnd: row.period_end,
538
606
  };
539
607
  }
540
608
  async revokeCreditsByEntryType(userId, entryType) {
541
- return this.deductionRepo.revokeCreditsByEntryType(userId, entryType);
609
+ const row = await this.deductionRepo.revokeCreditsByEntryType(userId, entryType);
610
+ if (row.error_code !== null) {
611
+ throw new StoreError(`revoke_subject_credits_by_operation failed: ${row.error_code}`);
612
+ }
613
+ return {
614
+ userId: row.user_id,
615
+ entryType: row.entry_type,
616
+ revoked: dec(row.revoked),
617
+ balanceAfter: dec(row.balance_after),
618
+ };
542
619
  }
543
620
  async refundCredits(entryId, amount, reason, metadata, idempotencyKey) {
544
621
  const row = await this.deductionRepo.refundCredits(entryId, amount != null ? decParam(amount) : null, idempotencyKey ?? `refund:${entryId}:${amount != null ? decParam(amount) : "remaining"}`, reason ?? null, JSON.stringify(metadata ?? {}));
545
- if ("error" in row && row.error) {
622
+ if (row.error !== null) {
546
623
  return {
547
- refundEntryId: "",
624
+ refundEntryId: null,
548
625
  originalEntryId: entryId,
549
- userId: String(row.user_id ?? ""),
550
- amount: ZERO,
551
- newBalance: dec(row.new_balance),
552
- error: String(row.error),
626
+ userId: row.user_id ?? null,
627
+ amount: row.amount == null ? null : dec(row.amount),
628
+ newBalance: row.new_balance == null ? null : dec(row.new_balance),
629
+ error: row.error,
630
+ bucketBreakdown: null,
553
631
  };
554
632
  }
555
633
  return {
556
- refundEntryId: String(row.refund_entry_id ?? ""),
634
+ refundEntryId: requireText(row.refund_entry_id, "refund_credit_by_entry"),
557
635
  originalEntryId: entryId,
558
- userId: String(row.user_id ?? ""),
636
+ userId: requireText(row.user_id, "refund_credit_by_entry"),
559
637
  amount: dec(row.amount),
560
638
  newBalance: dec(row.new_balance),
639
+ error: null,
561
640
  bucketBreakdown: decRecord(row.bucket_breakdown),
562
641
  };
563
642
  }
@@ -568,41 +647,41 @@ export class PostgresStore extends CreditStore {
568
647
  const row = await this.analyticsRepo.aggregateStats(start.toISOString(), end.toISOString());
569
648
  return {
570
649
  totalCreditsConsumed: dec(row.total_credits_consumed),
571
- activeUsers: Number(row.active_users ?? 0),
650
+ activeUsers: row.active_users,
572
651
  avgDailySpend: dec(row.avg_daily_spend),
573
- topModel: String(row.top_model ?? ""),
574
- topUser: String(row.top_user ?? ""),
652
+ topModel: row.top_model,
653
+ topUser: row.top_user,
575
654
  };
576
655
  }
577
656
  async spendByUser(start, end) {
578
657
  const rows = await this.analyticsRepo.spendByUser(start.toISOString(), end.toISOString());
579
658
  return (rows ?? []).map((r) => ({
580
- userId: String(r.user_id ?? ""),
659
+ userId: r.user_id,
581
660
  totalSpend: dec(r.total_spend),
582
- entryCount: Number(r.entry_count ?? 0),
661
+ entryCount: r.entry_count,
583
662
  }));
584
663
  }
585
664
  async spendByModel(start, end) {
586
665
  const rows = await this.analyticsRepo.spendByModel(start.toISOString(), end.toISOString());
587
666
  return (rows ?? []).map((r) => ({
588
- model: String(r.model ?? ""),
667
+ model: r.model,
589
668
  totalSpend: dec(r.total_spend),
590
- entryCount: Number(r.entry_count ?? 0),
669
+ entryCount: r.entry_count,
591
670
  }));
592
671
  }
593
672
  async topUsers(limit, start, end) {
594
673
  const rows = await this.analyticsRepo.topUsers(limit, start.toISOString(), end.toISOString());
595
674
  return (rows ?? []).map((r) => ({
596
- userId: String(r.user_id ?? ""),
675
+ userId: r.user_id,
597
676
  totalSpend: dec(r.total_spend),
598
677
  }));
599
678
  }
600
679
  async dailySpend(start, end) {
601
680
  const rows = await this.analyticsRepo.dailySpend(start.toISOString(), end.toISOString());
602
681
  return (rows ?? []).map((r) => ({
603
- date: String(r.date ?? ""),
682
+ date: r.date,
604
683
  totalSpend: dec(r.total_spend),
605
- entryCount: Number(r.entry_count ?? 0),
684
+ entryCount: r.entry_count,
606
685
  }));
607
686
  }
608
687
  async getLedgerEntry(userId, entryId) {
@@ -641,7 +720,7 @@ export class PostgresStore extends CreditStore {
641
720
  throw new RangeError(`limit must be an integer between 1 and ${MAX_PAGE_SIZE}`);
642
721
  }
643
722
  const cursor = options?.cursor ?? null;
644
- const rows = await this.analyticsRepo.listUsageCharges(userId, options?.fromDate?.toISOString() ?? null, options?.toDate?.toISOString() ?? null, limit + 1, cursor?.eventAt ?? null, cursor?.usageId ?? null);
723
+ const rows = await this.analyticsRepo.listUsageCharges(userId, options?.fromDate?.toISOString() ?? null, options?.toDate?.toISOString() ?? null, limit + 1, cursor?.eventAt ?? null, cursor?.usageId ?? null, options?.includeRecordOnly ?? true);
645
724
  const hasMore = rows.length > limit;
646
725
  const items = rows.slice(0, limit).map(mapUsageCharge);
647
726
  const last = items.at(-1);
@@ -652,41 +731,37 @@ export class PostgresStore extends CreditStore {
652
731
  }
653
732
  async createTeam(ownerSubjectId, name, initialBalance = ZERO) {
654
733
  const row = await this.teamRepo.createTeam(ownerSubjectId, name, decParam(initialBalance));
655
- if (row.error_code)
656
- throw new StoreError(String(row.error_code));
734
+ if (row.error_code !== null)
735
+ throw new StoreError(row.error_code);
657
736
  return {
658
- teamId: String(row.team_id ?? ""),
659
- name: String(row.name ?? name),
737
+ teamId: requireText(row.team_id, "create_team"),
738
+ name: requireText(row.name, "create_team"),
660
739
  };
661
740
  }
662
741
  async getTeamBalance(teamId) {
663
742
  const row = await this.teamRepo.getTeamBalance(teamId);
664
- if (!row) {
665
- return { teamId, name: "", balance: ZERO, memberCount: 0 };
666
- }
667
- if ("error" in row && row.error) {
668
- return { teamId, name: "", balance: ZERO, memberCount: 0 };
669
- }
743
+ if (!row)
744
+ return null;
670
745
  return {
671
- teamId: String(row.team_id ?? teamId),
672
- name: String(row.name ?? ""),
746
+ teamId: row.team_id,
747
+ name: row.name,
673
748
  balance: dec(row.balance),
674
- memberCount: Number(row.member_count ?? 0),
749
+ memberCount: row.member_count,
675
750
  };
676
751
  }
677
752
  async addTeamMember(teamId, userId, role = "member", spendCap) {
678
753
  const row = await this.teamRepo.addTeamMember(teamId, userId, role, spendCap != null ? decParam(spendCap) : null);
679
754
  return {
680
- teamId: String(row.team_id ?? teamId),
681
- userId: String(row.user_id ?? userId),
682
- role: String(row.role ?? role),
755
+ teamId: row.team_id,
756
+ userId: row.user_id,
757
+ role: row.role,
683
758
  };
684
759
  }
685
760
  async getTeamMembers(teamId) {
686
761
  const rows = await this.teamRepo.getTeamMembers(teamId);
687
- return (rows ?? []).map((r) => ({
688
- userId: String(r.user_id ?? ""),
689
- role: String(r.role ?? "member"),
762
+ return rows.map((r) => ({
763
+ userId: r.user_id,
764
+ role: r.role,
690
765
  spendCap: r.spend_cap != null ? dec(r.spend_cap) : null,
691
766
  totalSpent: dec(r.total_spent),
692
767
  }));
@@ -702,41 +777,43 @@ export class PostgresStore extends CreditStore {
702
777
  ? meta.operation
703
778
  : "team_usage";
704
779
  const row = await this.teamRepo.deductTeam(teamId, userId, decParam(amount), effectiveIdempotencyKey, operation, JSON.stringify(meta));
705
- if ("error" in row && row.error) {
780
+ if (row.error !== null) {
706
781
  return {
707
- entryId: "",
782
+ entryId: null,
708
783
  teamId,
709
784
  userId,
710
- amount: ZERO,
711
- teamBalanceAfter: dec(row.team_balance_after),
712
- error: String(row.error),
785
+ amount: dec(row.amount),
786
+ teamBalanceAfter: row.team_balance_after == null ? null : dec(row.team_balance_after),
787
+ idempotent: false,
788
+ error: row.error,
713
789
  };
714
790
  }
715
791
  return {
716
- entryId: String(row.entry_id ?? ""),
717
- teamId: String(row.team_id ?? teamId),
718
- userId: String(row.user_id ?? userId),
719
- amount: dec(row.amount, amount),
792
+ entryId: requireText(row.entry_id, "deduct_team"),
793
+ teamId: row.team_id,
794
+ userId: row.user_id,
795
+ amount: dec(row.amount),
720
796
  teamBalanceAfter: dec(row.team_balance_after),
797
+ idempotent: row.replayed,
798
+ error: null,
721
799
  };
722
800
  }
723
801
  async sweepExpiredCredits(dryRun = false, userId, limit = 100) {
724
802
  const row = await this.bucketRepo.sweepExpiredCredits(dryRun, userId, limit);
725
803
  return {
726
- expiredCount: Number(row.expired_count ?? 0),
804
+ expiredCount: row.expired_count,
727
805
  expiredAmount: dec(row.expired_amount),
728
806
  dryRun,
729
- expiredByBucket: decRecord(row.expired_by_bucket),
807
+ expiredByBucket: Object.fromEntries(Object.entries(row.expired_by_bucket).map(([key, value]) => [key, dec(value)])),
730
808
  };
731
809
  }
732
810
  async getBucketBalances(userId) {
733
811
  const envelope = await this.bucketRepo.getBucketBalances(userId);
734
- const bucketRows = envelope.buckets ?? [];
735
- const buckets = bucketRows.map((row) => ({
736
- bucketKey: String(row.bucket_key ?? ""),
737
- label: String(row.label ?? ""),
738
- priority: Number(row.priority ?? 0),
739
- expires: Boolean(row.expires ?? false),
812
+ const buckets = envelope.buckets.map((row) => ({
813
+ bucketKey: row.bucket_key,
814
+ label: row.label,
815
+ priority: row.priority,
816
+ expires: row.expires,
740
817
  balance: dec(row.balance),
741
818
  }));
742
819
  return { userId, buckets, totalBalance: dec(envelope.total_balance) };
@@ -751,15 +828,28 @@ export class PostgresStore extends CreditStore {
751
828
  region: request.region ?? null,
752
829
  metadata: JSON.stringify(request.metadata ?? {}),
753
830
  });
754
- return rows.map((row) => ({
755
- grantEventId: row.grant_event_id ?? null,
756
- grantAwardId: row.grant_award_id ?? null,
757
- recipientSubjectId: row.recipient_subject_id ?? null,
758
- ledgerEntryId: row.ledger_entry_id ?? null,
759
- amount: dec(row.amount),
760
- replayed: Boolean(row.replayed),
761
- error: row.error_code ?? null,
762
- }));
831
+ return rows.map((row) => {
832
+ if (row.error_code !== null) {
833
+ return {
834
+ grantEventId: null,
835
+ grantAwardId: null,
836
+ recipientSubjectId: null,
837
+ ledgerEntryId: null,
838
+ amount: null,
839
+ replayed: false,
840
+ error: row.error_code,
841
+ };
842
+ }
843
+ return {
844
+ grantEventId: requireText(row.grant_event_id, "execute_grant_program"),
845
+ grantAwardId: requireText(row.grant_award_id, "execute_grant_program"),
846
+ recipientSubjectId: requireText(row.recipient_subject_id, "execute_grant_program"),
847
+ ledgerEntryId: requireText(row.ledger_entry_id, "execute_grant_program"),
848
+ amount: dec(row.amount),
849
+ replayed: row.replayed,
850
+ error: null,
851
+ };
852
+ });
763
853
  }
764
854
  }
765
855
  //# sourceMappingURL=store.js.map