@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,73 +1,104 @@
1
1
  import { z } from "zod";
2
2
  import Decimal from "decimal.js";
3
- import { pgBoolean, safeParse } from "../../../shared/postgres-validation.js";
3
+ import { pgBoolean, postgresUuid, requireRow, safeParse, } from "../../../shared/postgres-validation.js";
4
+ const decimal = z.union([z.string().min(1), z.number().finite()]);
4
5
  const BalanceRowSchema = z
5
6
  .object({
6
- user_id: z.string(),
7
- balance: z.union([z.string(), z.number()]).nullable(),
8
- lifetime_purchased: z.union([z.string(), z.number()]).nullable(),
7
+ user_id: z.string().min(1),
8
+ balance: decimal,
9
+ lifetime_purchased: decimal,
9
10
  })
10
- .partial()
11
- .passthrough();
11
+ .strict();
12
12
  const AddCreditsRowSchema = z
13
13
  .object({
14
- entry_id: z.string().nullable().optional(),
15
- user_id: z.string().optional(),
16
- amount: z
17
- .union([z.string(), z.number()])
18
- .nullable()
19
- .optional(),
20
- new_balance: z
21
- .union([z.string(), z.number()])
22
- .nullable()
23
- .optional(),
24
- lifetime_purchased: z
25
- .union([z.string(), z.number()])
26
- .nullable()
27
- .optional(),
28
- bucket: z.string().optional(),
29
- idempotent: pgBoolean.nullable().optional(),
30
- error: z.string().nullable().optional(),
14
+ entry_id: z.string().nullable(),
15
+ user_id: z.string().min(1),
16
+ amount: decimal,
17
+ new_balance: decimal.nullable(),
18
+ lifetime_purchased: decimal.nullable(),
19
+ bucket: z.string().min(1).nullable(),
20
+ idempotent: pgBoolean,
21
+ error: z.string().min(1).nullable(),
31
22
  })
32
- .passthrough();
23
+ .strict()
24
+ .superRefine((row, context) => {
25
+ if (row.error === null &&
26
+ (row.entry_id === null || row.new_balance === null || row.lifetime_purchased === null)) {
27
+ context.addIssue({
28
+ code: "custom",
29
+ message: "successful credit postings require entry and balance fields",
30
+ });
31
+ }
32
+ const amount = new Decimal(row.amount);
33
+ if (row.error === null && amount.isPositive() && row.bucket === null) {
34
+ context.addIssue({
35
+ code: "custom",
36
+ message: "successful positive credit postings require a destination bucket",
37
+ });
38
+ }
39
+ if (row.error === null && !amount.isPositive() && row.bucket !== null) {
40
+ context.addIssue({
41
+ code: "custom",
42
+ message: "debit postings cannot claim a single destination bucket",
43
+ });
44
+ }
45
+ if (row.error !== null &&
46
+ (row.entry_id !== null ||
47
+ row.new_balance !== null ||
48
+ row.lifetime_purchased !== null ||
49
+ row.bucket !== null ||
50
+ row.idempotent)) {
51
+ context.addIssue({
52
+ code: "custom",
53
+ message: "failed credit postings cannot expose committed result fields",
54
+ });
55
+ }
56
+ });
33
57
  const AvailableRowSchema = z
34
58
  .object({
35
- balance: z
36
- .union([z.string(), z.number()])
37
- .nullable()
38
- .optional(),
39
- reserved: z
40
- .union([z.string(), z.number()])
41
- .nullable()
42
- .optional(),
43
- available: z
44
- .union([z.string(), z.number()])
45
- .nullable()
46
- .optional(),
59
+ balance: decimal,
60
+ reserved: decimal,
61
+ available: decimal,
47
62
  })
48
- .passthrough();
63
+ .strict();
49
64
  const GrantProgramAwardRowSchema = z
50
65
  .object({
51
- grant_event_id: z.string().nullable().optional(),
52
- grant_award_id: z.string().nullable().optional(),
53
- recipient_subject_id: z.string().nullable().optional(),
54
- ledger_entry_id: z.string().nullable().optional(),
55
- amount: z
56
- .union([z.string(), z.number()])
57
- .nullable()
58
- .optional(),
59
- replayed: pgBoolean.nullable().optional(),
60
- error_code: z.string().nullable().optional(),
66
+ grant_event_id: postgresUuid.nullable(),
67
+ grant_award_id: postgresUuid.nullable(),
68
+ recipient_subject_id: postgresUuid.nullable(),
69
+ ledger_entry_id: postgresUuid.nullable(),
70
+ amount: decimal.nullable(),
71
+ replayed: z.boolean(),
72
+ error_code: z.string().min(1).nullable(),
61
73
  })
62
- .passthrough();
74
+ .strict()
75
+ .superRefine((row, context) => {
76
+ const award = [
77
+ row.grant_event_id,
78
+ row.grant_award_id,
79
+ row.recipient_subject_id,
80
+ row.ledger_entry_id,
81
+ row.amount,
82
+ ];
83
+ if (row.error_code === null && award.some((value) => value === null)) {
84
+ context.addIssue({
85
+ code: "custom",
86
+ message: "successful grant awards require committed fields",
87
+ });
88
+ }
89
+ if (row.error_code !== null && (award.some((value) => value !== null) || row.replayed)) {
90
+ context.addIssue({
91
+ code: "custom",
92
+ message: "failed grant awards cannot expose committed fields",
93
+ });
94
+ }
95
+ });
63
96
  /** Repository for user credit balance operations.
64
97
  *
65
98
  * All methods call Postgres RPCs via the callproc function.
66
99
  *
67
- * NOTE: getBalance returns null when no row exists (new user), while
68
- * addCredits and getAvailable always return a parsed object (empty object
69
- * fallback). This inconsistency is intentional: balance queries distinguish
70
- * "no data" from "zeroed data" whereas mutation reads always produce a result.
100
+ * Reads may return no row for a new account. Mutations require the database's
101
+ * single-row result envelope and fail closed when that contract is violated.
71
102
  */
72
103
  export class BalanceRepository {
73
104
  callproc;
@@ -79,9 +110,11 @@ export class BalanceRepository {
79
110
  const rows = await this.callproc("get_credit_state", [userId]);
80
111
  if (!rows || rows.length === 0)
81
112
  return null;
113
+ const row = requireRow(rows, "BalanceRepository.getBalance");
82
114
  return safeParse(BalanceRowSchema, {
83
115
  user_id: userId,
84
- ...rows[0],
116
+ balance: row.balance,
117
+ lifetime_purchased: row.lifetime_purchased,
85
118
  }, "BalanceRepository.getBalance");
86
119
  }
87
120
  /** Add credits to a user's account. */
@@ -99,7 +132,7 @@ export class BalanceRepository {
99
132
  expiresAt,
100
133
  "0",
101
134
  ]);
102
- const row = (rows?.[0] ?? {});
135
+ const row = requireRow(rows, "BalanceRepository.addCredits");
103
136
  const state = row.error_code == null
104
137
  ? (await this.callproc("get_credit_state", [userId]))[0]
105
138
  : undefined;
@@ -107,12 +140,12 @@ export class BalanceRepository {
107
140
  ? (await this.callproc("get_credit_grant_details", [userId, row.entry_id]))[0]
108
141
  : undefined;
109
142
  return safeParse(AddCreditsRowSchema, {
110
- ...row,
143
+ entry_id: row.entry_id ?? null,
111
144
  user_id: userId,
112
145
  amount,
113
- new_balance: row.balance_after,
114
- lifetime_purchased: state?.lifetime_purchased,
115
- bucket: grant?.bucket_key ?? bucket ?? "default",
146
+ new_balance: row.balance_after ?? null,
147
+ lifetime_purchased: state?.lifetime_purchased ?? null,
148
+ bucket: decimalAmount.isPositive() ? (grant?.bucket_key ?? null) : null,
116
149
  idempotent: row.replayed,
117
150
  error: row.error_code,
118
151
  }, "BalanceRepository.addCredits");
@@ -120,7 +153,15 @@ export class BalanceRepository {
120
153
  /** Fetch available balance (balance minus reserved holds). */
121
154
  async getAvailable(userId) {
122
155
  const rows = await this.callproc("get_credit_state", [userId]);
123
- return safeParse(AvailableRowSchema, rows?.[0] ?? {}, "BalanceRepository.getAvailable");
156
+ if (!rows || rows.length === 0) {
157
+ return null;
158
+ }
159
+ const row = requireRow(rows, "BalanceRepository.getAvailable");
160
+ return safeParse(AvailableRowSchema, {
161
+ balance: row.balance,
162
+ reserved: row.reserved,
163
+ available: row.available,
164
+ }, "BalanceRepository.getAvailable");
124
165
  }
125
166
  /** Execute a configured grant-program event and return every award row. */
126
167
  async executeGrantProgram(params) {
@@ -1 +1 @@
1
- {"version":3,"file":"balance.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/balance.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,OAAO,MAAM,YAAY,CAAC;AAEjC,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,wCAAwC,CAAC;AAE9E,MAAM,gBAAgB,GAAG,CAAC;KACvB,MAAM,CAAC;IACN,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE;IACnB,OAAO,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAU,CAAC,CAAC,QAAQ,EAAE;IAC9D,kBAAkB,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAU,CAAC,CAAC,QAAQ,EAAE;CAC1E,CAAC;KACD,OAAO,EAAE;KACT,WAAW,EAAE,CAAC;AAEjB,MAAM,mBAAmB,GAAG,CAAC;KAC1B,MAAM,CAAC;IACN,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,CAAC,QAAQ,EAAE;IAC1C,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAC9B,MAAM,EAAE,CAAC;SAC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AAC,MAQzB;QACC,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,uBAAuB,EAAE;YACxD,MAAM,CAAC,OAAO;YACd,MAAM,CAAC,UAAU;YACjB,MAAM,CAAC,SAAS;YAChB,MAAM,CAAC,QAAQ;YACf,MAAM,CAAC,iBAAiB;YACxB,MAAM,CAAC,MAAM;YACb,MAAM,CAAC,QAAQ;SAChB,CAAC,CAAC;QACH,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAC9B,SAAS,CAAC,0BAA0B,EAAE,GAAG,EAAE,uCAAuC,CAAC,CACpF,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport Decimal from \"decimal.js\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport {\n pgBoolean,\n postgresUuid,\n requireRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\n\nconst BalanceRowSchema = z\n .object({\n user_id: z.string().min(1),\n balance: decimal,\n lifetime_purchased: decimal,\n })\n .strict();\n\nconst AddCreditsRowSchema = z\n .object({\n entry_id: z.string().nullable(),\n user_id: z.string().min(1),\n amount: decimal,\n new_balance: decimal.nullable(),\n lifetime_purchased: decimal.nullable(),\n bucket: z.string().min(1).nullable(),\n idempotent: pgBoolean,\n error: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (\n row.error === null &&\n (row.entry_id === null || row.new_balance === null || row.lifetime_purchased === null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"successful credit postings require entry and balance fields\",\n });\n }\n const amount = new Decimal(row.amount);\n if (row.error === null && amount.isPositive() && row.bucket === null) {\n context.addIssue({\n code: \"custom\",\n message: \"successful positive credit postings require a destination bucket\",\n });\n }\n if (row.error === null && !amount.isPositive() && row.bucket !== null) {\n context.addIssue({\n code: \"custom\",\n message: \"debit postings cannot claim a single destination bucket\",\n });\n }\n if (\n row.error !== null &&\n (row.entry_id !== null ||\n row.new_balance !== null ||\n row.lifetime_purchased !== null ||\n row.bucket !== null ||\n row.idempotent)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed credit postings cannot expose committed result fields\",\n });\n }\n });\n\nconst AvailableRowSchema = z\n .object({\n balance: decimal,\n reserved: decimal,\n available: decimal,\n })\n .strict();\n\nconst GrantProgramAwardRowSchema = z\n .object({\n grant_event_id: postgresUuid.nullable(),\n grant_award_id: postgresUuid.nullable(),\n recipient_subject_id: postgresUuid.nullable(),\n ledger_entry_id: postgresUuid.nullable(),\n amount: decimal.nullable(),\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n const award = [\n row.grant_event_id,\n row.grant_award_id,\n row.recipient_subject_id,\n row.ledger_entry_id,\n row.amount,\n ];\n if (row.error_code === null && award.some((value) => value === null)) {\n context.addIssue({\n code: \"custom\",\n message: \"successful grant awards require committed fields\",\n });\n }\n if (row.error_code !== null && (award.some((value) => value !== null) || row.replayed)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed grant awards cannot expose committed fields\",\n });\n }\n });\n\nexport type BalanceRow = z.infer<typeof BalanceRowSchema>;\nexport type AddCreditsRow = z.infer<typeof AddCreditsRowSchema>;\nexport type AvailableRow = z.infer<typeof AvailableRowSchema>;\nexport type GrantProgramAwardRow = z.infer<typeof GrantProgramAwardRowSchema>;\n\n/** Repository for user credit balance operations.\n *\n * All methods call Postgres RPCs via the callproc function.\n *\n * Reads may return no row for a new account. Mutations require the database's\n * single-row result envelope and fail closed when that contract is violated.\n */\nexport class BalanceRepository {\n constructor(private callproc: CallProc) {}\n\n /** Fetch a user's credit balance. Returns null for new users with no balance row. */\n async getBalance(userId: string): Promise<BalanceRow | null> {\n const rows = await this.callproc(\"get_credit_state\", [userId]);\n if (!rows || rows.length === 0) return null;\n const row = requireRow(rows, \"BalanceRepository.getBalance\") as Record<string, unknown>;\n return safeParse(\n BalanceRowSchema,\n {\n user_id: userId,\n balance: row.balance,\n lifetime_purchased: row.lifetime_purchased,\n },\n \"BalanceRepository.getBalance\",\n );\n }\n\n /** Add credits to a user's account. */\n async addCredits(\n userId: string,\n amount: string,\n type: string,\n metadata: string,\n expiresAt: string | null,\n bucket: string | null,\n idempotencyKey: string | null,\n ): Promise<AddCreditsRow> {\n const decimalAmount = new Decimal(amount);\n const rows = await this.callproc(\"post_credit\", [\n userId,\n decimalAmount.isNegative() ? \"adjustment\" : type === \"purchase\" ? \"purchase\" : \"grant\",\n amount,\n type,\n idempotencyKey,\n metadata,\n bucket,\n null,\n expiresAt,\n \"0\",\n ]);\n const row = requireRow(rows, \"BalanceRepository.addCredits\") as Record<string, unknown>;\n const state =\n row.error_code == null\n ? ((await this.callproc(\"get_credit_state\", [userId]))[0] as\n | Record<string, unknown>\n | undefined)\n : undefined;\n const grant =\n row.error_code == null && decimalAmount.isPositive() && row.entry_id != null\n ? ((await this.callproc(\"get_credit_grant_details\", [userId, row.entry_id]))[0] as\n | Record<string, unknown>\n | undefined)\n : undefined;\n return safeParse(\n AddCreditsRowSchema,\n {\n entry_id: row.entry_id ?? null,\n user_id: userId,\n amount,\n new_balance: row.balance_after ?? null,\n lifetime_purchased: state?.lifetime_purchased ?? null,\n bucket: decimalAmount.isPositive() ? (grant?.bucket_key ?? null) : null,\n idempotent: row.replayed,\n error: row.error_code,\n },\n \"BalanceRepository.addCredits\",\n );\n }\n\n /** Fetch available balance (balance minus reserved holds). */\n async getAvailable(userId: string): Promise<AvailableRow | null> {\n const rows = await this.callproc(\"get_credit_state\", [userId]);\n if (!rows || rows.length === 0) {\n return null;\n }\n const row = requireRow(rows, \"BalanceRepository.getAvailable\") as Record<string, unknown>;\n return safeParse(\n AvailableRowSchema,\n {\n balance: row.balance,\n reserved: row.reserved,\n available: row.available,\n },\n \"BalanceRepository.getAvailable\",\n );\n }\n\n /** Execute a configured grant-program event and return every award row. */\n async executeGrantProgram(params: {\n trigger: string;\n programKey: string;\n subjectId: string;\n eventKey: string;\n referrerSubjectId: string | null;\n region: string | null;\n metadata: string;\n }): Promise<GrantProgramAwardRow[]> {\n const rows = await this.callproc(\"execute_grant_program\", [\n params.trigger,\n params.programKey,\n params.subjectId,\n params.eventKey,\n params.referrerSubjectId,\n params.region,\n params.metadata,\n ]);\n return (rows ?? []).map((row) =>\n safeParse(GrantProgramAwardRowSchema, row, \"BalanceRepository.executeGrantProgram\"),\n );\n }\n}\n"]}
@@ -1,15 +1,21 @@
1
1
  import { z } from "zod";
2
2
  import type { CallProc } from "../../../shared/postgres-types.js";
3
3
  declare const BucketEnvelopeRowSchema: z.ZodObject<{
4
- user_id: z.ZodOptional<z.ZodString>;
5
- buckets: z.ZodOptional<z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
6
- total_balance: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
7
- }, z.core.$loose>;
4
+ user_id: z.ZodString;
5
+ buckets: z.ZodArray<z.ZodObject<{
6
+ bucket_key: z.ZodString;
7
+ label: z.ZodString;
8
+ priority: z.ZodNumber;
9
+ expires: z.ZodBoolean;
10
+ balance: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
11
+ }, z.core.$strict>>;
12
+ total_balance: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
13
+ }, z.core.$strict>;
8
14
  declare const SweepRowSchema: z.ZodObject<{
9
- expired_count: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
10
- expired_amount: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
11
- expired_by_bucket: z.ZodOptional<z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>>;
12
- }, z.core.$loose>;
15
+ expired_count: z.ZodNumber;
16
+ expired_amount: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
17
+ expired_by_bucket: z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
18
+ }, z.core.$strict>;
13
19
  export type BucketEnvelopeRow = z.infer<typeof BucketEnvelopeRowSchema>;
14
20
  export type SweepRow = z.infer<typeof SweepRowSchema>;
15
21
  /** Repository for credit bucket operations. */
@@ -1 +1 @@
1
- {"version":3,"file":"bucket.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/bucket.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;AAGlE,QAAA,MAAM,uBAAuB;;;;iBASb,CAAC;AAEjB,QAAA,MAAM,cAAc;;;;iBAYJ,CAAC;AAEjB,MAAM,MAAM,iBAAiB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,uBAAuB,CAAC,CAAC;AACxE,MAAM,MAAM,QAAQ,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,cAAc,CAAC,CAAC;AAEtD,+CAA+C;AAC/C,qBAAa,gBAAgB;IACf,OAAO,CAAC,QAAQ;gBAAR,QAAQ,EAAE,QAAQ;IAEtC,mDAAmD;IAC7C,iBAAiB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC;IAoBnE,mCAAmC;IAC7B,mBAAmB,CAAC,MAAM,UAAQ,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,KAAK,SAAM,GAAG,OAAO,CAAC,QAAQ,CAAC;CAI3F"}
1
+ {"version":3,"file":"bucket.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/bucket.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;AAelE,QAAA,MAAM,uBAAuB;;;;;;;;;;kBAMlB,CAAC;AAEZ,QAAA,MAAM,cAAc;;;;kBAMT,CAAC;AAEZ,MAAM,MAAM,iBAAiB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,uBAAuB,CAAC,CAAC;AACxE,MAAM,MAAM,QAAQ,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,cAAc,CAAC,CAAC;AAEtD,+CAA+C;AAC/C,qBAAa,gBAAgB;IACf,OAAO,CAAC,QAAQ;gBAAR,QAAQ,EAAE,QAAQ;IAEtC,mDAAmD;IAC7C,iBAAiB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC;IAmBnE,mCAAmC;IAC7B,mBAAmB,CAAC,MAAM,UAAQ,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,KAAK,SAAM,GAAG,OAAO,CAAC,QAAQ,CAAC;CAQ3F"}
@@ -1,29 +1,30 @@
1
1
  import { z } from "zod";
2
2
  import Decimal from "decimal.js";
3
- import { safeParse } from "../../../shared/postgres-validation.js";
3
+ import { postgresUuid, requireRow, safeParse } from "../../../shared/postgres-validation.js";
4
+ const decimal = z.union([z.string().min(1), z.number().finite()]);
5
+ const BucketRowSchema = z
6
+ .object({
7
+ bucket_key: z.string().min(1),
8
+ label: z.string().min(1),
9
+ priority: z.number().int().nonnegative(),
10
+ expires: z.boolean(),
11
+ balance: decimal,
12
+ })
13
+ .strict();
4
14
  const BucketEnvelopeRowSchema = z
5
15
  .object({
6
- user_id: z.string().optional(),
7
- buckets: z.array(z.record(z.string(), z.unknown())).optional(),
8
- total_balance: z
9
- .union([z.string(), z.number()])
10
- .nullable()
11
- .optional(),
16
+ user_id: postgresUuid,
17
+ buckets: z.array(BucketRowSchema),
18
+ total_balance: decimal,
12
19
  })
13
- .passthrough();
20
+ .strict();
14
21
  const SweepRowSchema = z
15
22
  .object({
16
- expired_count: z.coerce.number().optional(),
17
- expired_amount: z
18
- .union([z.string(), z.number()])
19
- .nullable()
20
- .optional(),
21
- expired_by_bucket: z
22
- .record(z.string(), z.union([z.string(), z.number()]))
23
- .nullable()
24
- .optional(),
23
+ expired_count: z.number().int().nonnegative(),
24
+ expired_amount: decimal,
25
+ expired_by_bucket: z.record(z.string().min(1), decimal),
25
26
  })
26
- .passthrough();
27
+ .strict();
27
28
  /** Repository for credit bucket operations. */
28
29
  export class BucketRepository {
29
30
  callproc;
@@ -33,9 +34,9 @@ export class BucketRepository {
33
34
  /** Fetch per-bucket credit balances for a user. */
34
35
  async getBucketBalances(userId) {
35
36
  const rows = await this.callproc("get_credit_bucket_balances", [userId]);
36
- const buckets = (rows ?? []).filter((row) => row != null && typeof row === "object" && !Array.isArray(row));
37
+ const buckets = (rows ?? []).map((row) => safeParse(BucketRowSchema, row, "BucketRepository.getBucketBalances"));
37
38
  const totalBalance = buckets
38
- .reduce((total, row) => total.plus(String(row.balance ?? 0)), new Decimal(0))
39
+ .reduce((total, row) => total.plus(row.balance), new Decimal(0))
39
40
  .toString();
40
41
  return safeParse(BucketEnvelopeRowSchema, {
41
42
  user_id: userId,
@@ -46,7 +47,7 @@ export class BucketRepository {
46
47
  /** Sweep expired credit grants. */
47
48
  async sweepExpiredCredits(dryRun = false, userId, limit = 100) {
48
49
  const rows = await this.callproc("sweep_expired_lots", [limit, userId ?? null, dryRun]);
49
- return safeParse(SweepRowSchema, rows?.[0] ?? {}, "BucketRepository.sweepExpiredCredits");
50
+ return safeParse(SweepRowSchema, requireRow(rows, "BucketRepository.sweepExpiredCredits"), "BucketRepository.sweepExpiredCredits");
50
51
  }
51
52
  }
52
53
  //# sourceMappingURL=bucket.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"bucket.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/bucket.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,OAAO,MAAM,YAAY,CAAC;AAEjC,OAAO,EAAE,SAAS,EAAE,MAAM,wCAAwC,CAAC;AAEnE,MAAM,uBAAuB,GAAG,CAAC;KAC9B,MAAM,CAAC;I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M,OAAO,GAAG,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CACvC,SAAS,CAAC,eAAe,EAAE,GAAG,EAAE,oCAAoC,CAAC,CACtE,CAAC;QACF,MAAM,YAAY,GAAG,OAAO;aACzB,MAAM,CAAC,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC;aAC/D,QAAQ,EAAE,CAAC;QACd,OAAO,SAAS,CACd,uBAAuB,EACvB;YACE,OAAO,EAAE,MAAM;YACf,OAAO;YACP,aAAa,EAAE,YAAY;SAC5B,EACD,oCAAoC,CACrC,CAAC;IACJ,CAAC;IAED,mCAAmC;IACnC,KAAK,CAAC,mBAAmB,CAAC,MAAM,GAAG,KAAK,EAAE,MAAe,EAAE,KAAK,GAAG,GAAG;QACpE,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,oBAAoB,EAAE,CAAC,KAAK,EAAE,MAAM,IAAI,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC;QACxF,OAAO,SAAS,CACd,cAAc,EACd,UAAU,CAAC,IAAI,EAAE,sCAAsC,CAAC,EACxD,sCAAsC,CACvC,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport Decimal from \"decimal.js\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport { postgresUuid, requireRow, safeParse } from \"../../../shared/postgres-validation.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\n\nconst BucketRowSchema = z\n .object({\n bucket_key: z.string().min(1),\n label: z.string().min(1),\n priority: z.number().int().nonnegative(),\n expires: z.boolean(),\n balance: decimal,\n })\n .strict();\n\nconst BucketEnvelopeRowSchema = z\n .object({\n user_id: postgresUuid,\n buckets: z.array(BucketRowSchema),\n total_balance: decimal,\n })\n .strict();\n\nconst SweepRowSchema = z\n .object({\n expired_count: z.number().int().nonnegative(),\n expired_amount: decimal,\n expired_by_bucket: z.record(z.string().min(1), decimal),\n })\n .strict();\n\nexport type BucketEnvelopeRow = z.infer<typeof BucketEnvelopeRowSchema>;\nexport type SweepRow = z.infer<typeof SweepRowSchema>;\n\n/** Repository for credit bucket operations. */\nexport class BucketRepository {\n constructor(private callproc: CallProc) {}\n\n /** Fetch per-bucket credit balances for a user. */\n async getBucketBalances(userId: string): Promise<BucketEnvelopeRow> {\n const rows = await this.callproc(\"get_credit_bucket_balances\", [userId]);\n const buckets = (rows ?? []).map((row) =>\n safeParse(BucketRowSchema, row, \"BucketRepository.getBucketBalances\"),\n );\n const totalBalance = buckets\n .reduce((total, row) => total.plus(row.balance), new Decimal(0))\n .toString();\n return safeParse(\n BucketEnvelopeRowSchema,\n {\n user_id: userId,\n buckets,\n total_balance: totalBalance,\n },\n \"BucketRepository.getBucketBalances\",\n );\n }\n\n /** Sweep expired credit grants. */\n async sweepExpiredCredits(dryRun = false, userId?: string, limit = 100): Promise<SweepRow> {\n const rows = await this.callproc(\"sweep_expired_lots\", [limit, userId ?? null, dryRun]);\n return safeParse(\n SweepRowSchema,\n requireRow(rows, \"BucketRepository.sweepExpiredCredits\"),\n \"BucketRepository.sweepExpiredCredits\",\n );\n }\n}\n"]}
@@ -0,0 +1,31 @@
1
+ import { z } from "zod";
2
+ import type { CallProc } from "../../../shared/postgres-types.js";
3
+ declare const CatalogRevisionRowSchema: z.ZodObject<{
4
+ id: z.ZodString;
5
+ config: z.ZodRecord<z.ZodString, z.ZodUnknown>;
6
+ version: z.ZodCoercedNumber<unknown>;
7
+ label: z.ZodNullable<z.ZodString>;
8
+ active: z.ZodBoolean;
9
+ status: z.ZodEnum<{
10
+ draft: "draft";
11
+ active: "active";
12
+ published: "published";
13
+ retired: "retired";
14
+ }>;
15
+ created_at: z.ZodUnion<readonly [z.ZodString, z.ZodPipe<z.ZodDate, z.ZodTransform<string, Date>>]>;
16
+ }, z.core.$strict>;
17
+ export type CatalogRevisionRow = z.infer<typeof CatalogRevisionRowSchema>;
18
+ export declare class CatalogRepository {
19
+ private readonly callproc;
20
+ constructor(callproc: CallProc);
21
+ private parseRevision;
22
+ getActiveCatalog(): Promise<CatalogRevisionRow | null>;
23
+ publishAndActivateCatalog(config: string, label: string | null, rollout: Record<string, unknown>): Promise<CatalogRevisionRow>;
24
+ publishCatalogDraft(config: string, label: string | null): Promise<CatalogRevisionRow>;
25
+ private publishRevision;
26
+ getCatalogHistory(): Promise<CatalogRevisionRow[]>;
27
+ getCatalogRevision(version: number): Promise<CatalogRevisionRow | null>;
28
+ activateCatalogRevision(version: number, rollout: Record<string, unknown>): Promise<CatalogRevisionRow>;
29
+ }
30
+ export {};
31
+ //# sourceMappingURL=catalog.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"catalog.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/catalog.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;AAQlE,QAAA,MAAM,wBAAwB;;;;;;;;;;;;;kBAUnB,CAAC;AAQZ,MAAM,MAAM,kBAAkB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,wBAAwB,CAAC,CAAC;AAE1E,qBAAa,iBAAiB;IAChB,OAAO,CAAC,QAAQ,CAAC,QAAQ;gBAAR,QAAQ,EAAE,QAAQ;IAE/C,OAAO,CAAC,aAAa;IAgBf,gBAAgB,IAAI,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC;IAOtD,yBAAyB,CAC7B,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,GAAG,IAAI,EACpB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC/B,OAAO,CAAC,kBAAkB,CAAC;IAIxB,mBAAmB,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,kBAAkB,CAAC;YAI9E,eAAe;IA6BvB,iBAAiB,IAAI,OAAO,CAAC,kBAAkB,EAAE,CAAC;IAalD,kBAAkB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC;IAOvE,uBAAuB,CAC3B,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC/B,OAAO,CAAC,kBAAkB,CAAC;CAQ/B"}
@@ -0,0 +1,90 @@
1
+ import { z } from "zod";
2
+ import { StoreError } from "../../../errors.js";
3
+ import { optionalRecordRow, pgBoolean, requireRecordRow, safeParse, } from "../../../shared/postgres-validation.js";
4
+ const CatalogRevisionRowSchema = z
5
+ .object({
6
+ id: z.string().min(1),
7
+ config: z.record(z.string(), z.unknown()),
8
+ version: z.coerce.number().int().positive(),
9
+ label: z.string().nullable(),
10
+ active: pgBoolean,
11
+ status: z.enum(["draft", "published", "active", "retired"]),
12
+ created_at: z.union([z.string(), z.date().transform((v) => v.toISOString())]),
13
+ })
14
+ .strict();
15
+ const PublishedRevisionSchema = z
16
+ .object({
17
+ revision_id: z.string().min(1),
18
+ revision_no: z.coerce.number().int().positive(),
19
+ status: z.enum(["published", "active"]),
20
+ })
21
+ .strict();
22
+ export class CatalogRepository {
23
+ callproc;
24
+ constructor(callproc) {
25
+ this.callproc = callproc;
26
+ }
27
+ parseRevision(row, context) {
28
+ return safeParse(CatalogRevisionRowSchema, {
29
+ id: row.id,
30
+ config: row.source_document,
31
+ version: row.revision_no,
32
+ label: row.label,
33
+ active: row.status === "active",
34
+ status: row.status,
35
+ created_at: row.created_at,
36
+ }, context);
37
+ }
38
+ async getActiveCatalog() {
39
+ const rows = await this.callproc("active_catalog_revision", []);
40
+ const row = optionalRecordRow(rows, "CatalogRepository.getActiveCatalog");
41
+ if (row === null || Object.values(row).every((value) => value === null))
42
+ return null;
43
+ return this.parseRevision(row, "CatalogRepository.getActiveCatalog");
44
+ }
45
+ async publishAndActivateCatalog(config, label, rollout) {
46
+ return this.publishRevision(config, label, true, rollout);
47
+ }
48
+ async publishCatalogDraft(config, label) {
49
+ return this.publishRevision(config, label, false, { plans: {} });
50
+ }
51
+ async publishRevision(config, label, activate = false, rollout = { plans: {} }) {
52
+ const published = safeParse(PublishedRevisionSchema, requireRecordRow(await this.callproc("publish_and_activate_catalog", [
53
+ 1,
54
+ JSON.parse(config),
55
+ label,
56
+ activate,
57
+ rollout,
58
+ ]), "CatalogRepository.publishRevision"), "CatalogRepository.publishRevision");
59
+ const revision = await this.getCatalogRevision(published.revision_no);
60
+ if (!revision) {
61
+ throw new StoreError(`Catalog revision ${published.revision_no} disappeared after publication`);
62
+ }
63
+ return revision;
64
+ }
65
+ async getCatalogHistory() {
66
+ const rows = await this.callproc("list_catalog_revisions", [500]);
67
+ return (rows ?? []).map((row) => {
68
+ if (typeof row !== "object" || row === null || Array.isArray(row)) {
69
+ throw new StoreError("CatalogRepository.getCatalogHistory returned a non-object row");
70
+ }
71
+ return this.parseRevision(row, "CatalogRepository.getCatalogHistory");
72
+ });
73
+ }
74
+ async getCatalogRevision(version) {
75
+ const rows = await this.callproc("catalog_revision_by_number", [version]);
76
+ const row = optionalRecordRow(rows, "CatalogRepository.getCatalogRevision");
77
+ if (row === null || Object.values(row).every((value) => value === null))
78
+ return null;
79
+ return this.parseRevision(row, "CatalogRepository.getCatalogRevision");
80
+ }
81
+ async activateCatalogRevision(version, rollout) {
82
+ const rows = await this.callproc("activate_catalog_revision", [version, rollout]);
83
+ const row = optionalRecordRow(rows, "CatalogRepository.activateCatalogRevision");
84
+ if (row === null || Object.values(row).every((value) => value === null)) {
85
+ throw new StoreError(`Catalog revision ${version} was not found`);
86
+ }
87
+ return this.parseRevision(row, "CatalogRepository.activateCatalogRevision");
88
+ }
89
+ }
90
+ //# sourceMappingURL=catalog.js.map
@@ -0,0 +1 @@
1
+ {"version":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C;IACL,CAAC;IAED,KAAK,CAAC,kBAAkB,CAAC,OAAe;QACtC,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,4BAA4B,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC;QAC1E,MAAM,GAAG,GAAG,iBAAiB,CAAC,IAAI,EAAE,sCAAsC,CAAC,CAAC;QAC5E,IAAI,GAAG,KAAK,IAAI,IAAI,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,KAAK,IAAI,CAAC;YAAE,OAAO,IAAI,CAAC;QACrF,OAAO,IAAI,CAAC,aAAa,CAAC,GAAG,EAAE,sCAAsC,CAAC,CAAC;IACzE,CAAC;IAED,KAAK,CAAC,uBAAuB,CAC3B,OAAe,EACf,OAAgC;QAEhC,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,2BAA2B,EAAE,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC;QAClF,MAAM,GAAG,GAAG,iBAAiB,CAAC,IAAI,EAAE,2CAA2C,CAAC,CAAC;QACjF,IAAI,GAAG,KAAK,IAAI,IAAI,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,KAAK,IAAI,CAAC,EAAE,CAAC;YACxE,MAAM,IAAI,UAAU,CAAC,oBAAoB,OAAO,gBAAgB,CAAC,CAAC;QACpE,CAAC;QACD,OAAO,IAAI,CAAC,aAAa,CAAC,GAAG,EAAE,2CAA2C,CAAC,CAAC;IAC9E,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport { StoreError } from \"../../../errors.js\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport {\n optionalRecordRow,\n pgBoolean,\n requireRecordRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\n\nconst CatalogRevisionRowSchema = z\n .object({\n id: z.string().min(1),\n config: z.record(z.string(), z.unknown()),\n version: z.coerce.number().int().positive(),\n label: z.string().nullable(),\n active: pgBoolean,\n status: z.enum([\"draft\", \"published\", \"active\", \"retired\"]),\n created_at: z.union([z.string(), z.date().transform((v) => v.toISOString())]),\n })\n .strict();\nconst PublishedRevisionSchema = z\n .object({\n revision_id: z.string().min(1),\n revision_no: z.coerce.number().int().positive(),\n status: z.enum([\"published\", \"active\"]),\n })\n .strict();\nexport type CatalogRevisionRow = z.infer<typeof CatalogRevisionRowSchema>;\n\nexport class CatalogRepository {\n constructor(private readonly callproc: CallProc) {}\n\n private parseRevision(row: Record<string, unknown>, context: string): CatalogRevisionRow {\n return safeParse(\n CatalogRevisionRowSchema,\n {\n id: row.id,\n config: row.source_document,\n version: row.revision_no,\n label: row.label,\n active: row.status === \"active\",\n status: row.status,\n created_at: row.created_at,\n },\n context,\n );\n }\n\n async getActiveCatalog(): Promise<CatalogRevisionRow | null> {\n const rows = await this.callproc(\"active_catalog_revision\", []);\n const row = optionalRecordRow(rows, \"CatalogRepository.getActiveCatalog\");\n if (row === null || Object.values(row).every((value) => value === null)) return null;\n return this.parseRevision(row, \"CatalogRepository.getActiveCatalog\");\n }\n\n async publishAndActivateCatalog(\n config: string,\n label: string | null,\n rollout: Record<string, unknown>,\n ): Promise<CatalogRevisionRow> {\n return this.publishRevision(config, label, true, rollout);\n }\n\n async publishCatalogDraft(config: string, label: string | null): Promise<CatalogRevisionRow> {\n return this.publishRevision(config, label, false, { plans: {} });\n }\n\n private async publishRevision(\n config: string,\n label: string | null,\n activate = false,\n rollout: Record<string, unknown> = { plans: {} },\n ): Promise<CatalogRevisionRow> {\n const published = safeParse(\n PublishedRevisionSchema,\n requireRecordRow(\n await this.callproc(\"publish_and_activate_catalog\", [\n 1,\n JSON.parse(config),\n label,\n activate,\n rollout,\n ]),\n \"CatalogRepository.publishRevision\",\n ),\n \"CatalogRepository.publishRevision\",\n );\n const revision = await this.getCatalogRevision(published.revision_no);\n if (!revision) {\n throw new StoreError(\n `Catalog revision ${published.revision_no} disappeared after publication`,\n );\n }\n return revision;\n }\n\n async getCatalogHistory(): Promise<CatalogRevisionRow[]> {\n const rows = await this.callproc(\"list_catalog_revisions\", [500]);\n return (rows ?? []).map((row) => {\n if (typeof row !== \"object\" || row === null || Array.isArray(row)) {\n throw new StoreError(\"CatalogRepository.getCatalogHistory returned a non-object row\");\n }\n return this.parseRevision(\n row as Record<string, unknown>,\n \"CatalogRepository.getCatalogHistory\",\n );\n });\n }\n\n async getCatalogRevision(version: number): Promise<CatalogRevisionRow | null> {\n const rows = await this.callproc(\"catalog_revision_by_number\", [version]);\n const row = optionalRecordRow(rows, \"CatalogRepository.getCatalogRevision\");\n if (row === null || Object.values(row).every((value) => value === null)) return null;\n return this.parseRevision(row, \"CatalogRepository.getCatalogRevision\");\n }\n\n async activateCatalogRevision(\n version: number,\n rollout: Record<string, unknown>,\n ): Promise<CatalogRevisionRow> {\n const rows = await this.callproc(\"activate_catalog_revision\", [version, rollout]);\n const row = optionalRecordRow(rows, \"CatalogRepository.activateCatalogRevision\");\n if (row === null || Object.values(row).every((value) => value === null)) {\n throw new StoreError(`Catalog revision ${version} was not found`);\n }\n return this.parseRevision(row, \"CatalogRepository.activateCatalogRevision\");\n }\n}\n"]}
@@ -1,32 +1,41 @@
1
1
  import { z } from "zod";
2
2
  import type { CallProc } from "../../../shared/postgres-types.js";
3
3
  export declare const DeductionRowSchema: z.ZodObject<{
4
- entry_id: z.ZodOptional<z.ZodNullable<z.ZodString>>;
5
- amount: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
6
- balance_after: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
7
- allowance_consumed: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
8
- idempotent: z.ZodOptional<z.ZodNullable<z.ZodPipe<z.ZodUnion<readonly [z.ZodBoolean, z.ZodString, z.ZodNumber]>, z.ZodTransform<boolean, string | number | boolean>>>>;
9
- bucket_breakdown: z.ZodOptional<z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>>;
10
- error: z.ZodOptional<z.ZodNullable<z.ZodString>>;
11
- user_id: z.ZodOptional<z.ZodString>;
12
- }, z.core.$loose>;
4
+ charge_id: z.ZodNullable<z.ZodString>;
5
+ entry_id: z.ZodNullable<z.ZodString>;
6
+ amount: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
7
+ balance_after: z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
8
+ allowance_consumed: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
9
+ idempotent: z.ZodBoolean;
10
+ bucket_breakdown: z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
11
+ error: z.ZodNullable<z.ZodString>;
12
+ user_id: z.ZodString;
13
+ }, z.core.$strict>;
13
14
  declare const RefundRowSchema: z.ZodObject<{
14
- refund_entry_id: z.ZodOptional<z.ZodString>;
15
- user_id: z.ZodOptional<z.ZodString>;
16
- amount: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
17
- new_balance: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
18
- bucket_breakdown: z.ZodOptional<z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>>;
19
- error: z.ZodOptional<z.ZodNullable<z.ZodString>>;
20
- }, z.core.$loose>;
15
+ refund_entry_id: z.ZodNullable<z.ZodString>;
16
+ user_id: z.ZodNullable<z.ZodString>;
17
+ amount: z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
18
+ new_balance: z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
19
+ bucket_breakdown: z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
20
+ error: z.ZodNullable<z.ZodString>;
21
+ }, z.core.$strict>;
21
22
  declare const RevokeRowSchema: z.ZodObject<{
22
- user_id: z.ZodOptional<z.ZodString>;
23
- amount: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
24
- new_balance: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
25
- bucket: z.ZodOptional<z.ZodNullable<z.ZodString>>;
26
- }, z.core.$loose>;
23
+ user_id: z.ZodString;
24
+ entry_type: z.ZodString;
25
+ revoked: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
26
+ balance_after: z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
27
+ error_code: z.ZodNullable<z.ZodString>;
28
+ }, z.core.$strict>;
27
29
  export type DeductionRow = z.infer<typeof DeductionRowSchema>;
28
30
  export type RefundRow = z.infer<typeof RefundRowSchema>;
29
31
  export type RevokeRow = z.infer<typeof RevokeRowSchema>;
32
+ declare const UsageRecordRowSchema: z.ZodObject<{
33
+ charge_id: z.ZodNullable<z.ZodString>;
34
+ requested: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
35
+ replayed: z.ZodBoolean;
36
+ error_code: z.ZodNullable<z.ZodString>;
37
+ }, z.core.$strict>;
38
+ export type UsageRecordRow = z.infer<typeof UsageRecordRowSchema>;
30
39
  /** Typed input for the plan-aware operation charge RPC. */
31
40
  export interface DeductParams {
32
41
  userId: string;
@@ -46,6 +55,8 @@ export declare class DeductionRepository {
46
55
  constructor(callproc: CallProc);
47
56
  /** Atomically deduct credits with allowance, entitlement, quota, and credit-policy enforcement. */
48
57
  deductWithAllowance(params: DeductParams): Promise<DeductionRow>;
58
+ /** Append a priced usage event without creating another balance debit. */
59
+ recordUsage(params: DeductParams): Promise<UsageRecordRow>;
49
60
  /** Refund a previous credit deduction. */
50
61
  refundCredits(entryId: string, amount: string | null, idempotencyKey: string, reason: string | null, metadata: string): Promise<RefundRow>;
51
62
  /** Revoke credits by transaction type. */
@@ -1 +1 @@
1
- {"version":3,"file":"deduction.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/deduction.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;AAGlE,eAAO,MAAM,kBAAkB;;;;;;;;;iBAuBf,CAAC;AAEjB,QAAA,MAAM,eAAe;;;;;;;iBAkBL,CAAC;AAEjB,QAAA,MAAM,eAAe;;;;;iBAaL,CAAC;AAEjB,MAAM,MAAM,YAAY,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,kBAAkB,CAAC,CAAC;AAC9D,MAAM,MAAM,SAAS,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,eAAe,CAAC,CAAC;AACxD,MAAM,MAAM,SAAS,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,eAAe,CAAC,CAAC;AAExD,2DAA2D;AAC3D,MAAM,WAAW,YAAY;IAC3B,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,cAAc,EAAE,MAAM,CAAC;IACvB,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,kDAAkD;AAClD,qBAAa,mBAAmB;IAClB,OAAO,CAAC,QAAQ;gBAAR,QAAQ,EAAE,QAAQ;IAEtC,mGAAmG;IAC7F,mBAAmB,CAAC,MAAM,EAAE,YAAY,GAAG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