@zonastery/bursar 2.0.2 → 2.0.4

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 (395) hide show
  1. package/README.md +1 -0
  2. package/dist/billing/auto-recharge-port.d.ts +3 -2
  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 +1 -1
  6. package/dist/billing/auto-recharge-service.d.ts.map +1 -1
  7. package/dist/billing/auto-recharge-service.js +5 -4
  8. package/dist/billing/auto-recharge-service.js.map +1 -1
  9. package/dist/billing/billing-service.d.ts +3 -2
  10. package/dist/billing/billing-service.d.ts.map +1 -1
  11. package/dist/billing/billing-service.js +2 -10
  12. package/dist/billing/billing-service.js.map +1 -1
  13. package/dist/billing/billing-store.d.ts +7 -7
  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 +10 -8
  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 +5 -9
  20. package/dist/billing/event-handlers.d.ts.map +1 -1
  21. package/dist/billing/event-handlers.js +191 -285
  22. package/dist/billing/event-handlers.js.map +1 -1
  23. package/dist/billing/event-processor.d.ts +1 -1
  24. package/dist/billing/event-processor.d.ts.map +1 -1
  25. package/dist/billing/event-processor.js +42 -21
  26. package/dist/billing/event-processor.js.map +1 -1
  27. package/dist/billing/financial-event-handlers.d.ts +3 -9
  28. package/dist/billing/financial-event-handlers.d.ts.map +1 -1
  29. package/dist/billing/financial-event-handlers.js +10 -12
  30. package/dist/billing/financial-event-handlers.js.map +1 -1
  31. package/dist/billing/index.d.ts +1 -1
  32. package/dist/billing/index.d.ts.map +1 -1
  33. package/dist/billing/index.js.map +1 -1
  34. package/dist/billing/management.d.ts +3 -2
  35. package/dist/billing/management.d.ts.map +1 -1
  36. package/dist/billing/management.js.map +1 -1
  37. package/dist/billing/postgres/repositories/auto-recharge.d.ts +2 -1
  38. package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -1
  39. package/dist/billing/postgres/repositories/auto-recharge.js +59 -41
  40. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
  41. package/dist/billing/postgres/repositories/dispute.d.ts +2 -1
  42. package/dist/billing/postgres/repositories/dispute.d.ts.map +1 -1
  43. package/dist/billing/postgres/repositories/dispute.js.map +1 -1
  44. package/dist/billing/postgres/repositories/event.d.ts.map +1 -1
  45. package/dist/billing/postgres/repositories/event.js +33 -1
  46. package/dist/billing/postgres/repositories/event.js.map +1 -1
  47. package/dist/billing/postgres/repositories/invoice.d.ts +2 -1
  48. package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -1
  49. package/dist/billing/postgres/repositories/invoice.js +8 -12
  50. package/dist/billing/postgres/repositories/invoice.js.map +1 -1
  51. package/dist/billing/postgres/repositories/offer.d.ts +1 -1
  52. package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
  53. package/dist/billing/postgres/repositories/offer.js +6 -1
  54. package/dist/billing/postgres/repositories/offer.js.map +1 -1
  55. package/dist/billing/postgres/repositories/payment.d.ts +1 -1
  56. package/dist/billing/postgres/repositories/payment.d.ts.map +1 -1
  57. package/dist/billing/postgres/repositories/payment.js +1 -1
  58. package/dist/billing/postgres/repositories/payment.js.map +1 -1
  59. package/dist/billing/postgres/repositories/subscription-change.d.ts.map +1 -1
  60. package/dist/billing/postgres/repositories/subscription-change.js +1 -9
  61. package/dist/billing/postgres/repositories/subscription-change.js.map +1 -1
  62. package/dist/billing/postgres/repositories/subscription.d.ts +6 -6
  63. package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -1
  64. package/dist/billing/postgres/repositories/subscription.js +29 -30
  65. package/dist/billing/postgres/repositories/subscription.js.map +1 -1
  66. package/dist/billing/postgres/repositories/topup.d.ts +1 -1
  67. package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
  68. package/dist/billing/postgres/repositories/topup.js +1 -1
  69. package/dist/billing/postgres/repositories/topup.js.map +1 -1
  70. package/dist/billing/postgres/store.d.ts +7 -6
  71. package/dist/billing/postgres/store.d.ts.map +1 -1
  72. package/dist/billing/postgres/store.js +31 -19
  73. package/dist/billing/postgres/store.js.map +1 -1
  74. package/dist/billing/types/auto-recharge.d.ts +3 -2
  75. package/dist/billing/types/auto-recharge.d.ts.map +1 -1
  76. package/dist/billing/types/auto-recharge.js.map +1 -1
  77. package/dist/billing/types/catalog.d.ts +1 -1
  78. package/dist/billing/types/catalog.d.ts.map +1 -1
  79. package/dist/billing/types/catalog.js.map +1 -1
  80. package/dist/billing/types/documents.d.ts +3 -2
  81. package/dist/billing/types/documents.d.ts.map +1 -1
  82. package/dist/billing/types/documents.js.map +1 -1
  83. package/dist/billing/types/events.d.ts +11 -2
  84. package/dist/billing/types/events.d.ts.map +1 -1
  85. package/dist/billing/types/events.js +73 -39
  86. package/dist/billing/types/events.js.map +1 -1
  87. package/dist/billing/types/subscriptions.d.ts +4 -1
  88. package/dist/billing/types/subscriptions.d.ts.map +1 -1
  89. package/dist/billing/types/subscriptions.js.map +1 -1
  90. package/dist/breakdown.d.ts +4 -3
  91. package/dist/breakdown.d.ts.map +1 -1
  92. package/dist/breakdown.js +1 -1
  93. package/dist/breakdown.js.map +1 -1
  94. package/dist/bursar.d.ts.map +1 -1
  95. package/dist/bursar.js +4 -3
  96. package/dist/bursar.js.map +1 -1
  97. package/dist/catalog.d.ts.map +1 -1
  98. package/dist/catalog.js +45 -42
  99. package/dist/catalog.js.map +1 -1
  100. package/dist/commerce/provider-registry.d.ts.map +1 -1
  101. package/dist/commerce/provider-registry.js +11 -6
  102. package/dist/commerce/provider-registry.js.map +1 -1
  103. package/dist/commerce/service.d.ts.map +1 -1
  104. package/dist/commerce/service.js +70 -68
  105. package/dist/commerce/service.js.map +1 -1
  106. package/dist/commerce/types.d.ts +1 -1
  107. package/dist/commerce/types.d.ts.map +1 -1
  108. package/dist/commerce/types.js.map +1 -1
  109. package/dist/config/parse-access.d.ts +5 -2
  110. package/dist/config/parse-access.d.ts.map +1 -1
  111. package/dist/config/parse-access.js +60 -41
  112. package/dist/config/parse-access.js.map +1 -1
  113. package/dist/config/parse-commerce.d.ts +2 -1
  114. package/dist/config/parse-commerce.d.ts.map +1 -1
  115. package/dist/config/parse-commerce.js +49 -29
  116. package/dist/config/parse-commerce.js.map +1 -1
  117. package/dist/config/parse-credits.d.ts +2 -1
  118. package/dist/config/parse-credits.d.ts.map +1 -1
  119. package/dist/config/parse-credits.js +39 -23
  120. package/dist/config/parse-credits.js.map +1 -1
  121. package/dist/config/parse-plans.d.ts +7 -2
  122. package/dist/config/parse-plans.d.ts.map +1 -1
  123. package/dist/config/parse-plans.js +49 -22
  124. package/dist/config/parse-plans.js.map +1 -1
  125. package/dist/config/parse-pricing.d.ts +2 -1
  126. package/dist/config/parse-pricing.d.ts.map +1 -1
  127. package/dist/config/parse-pricing.js +41 -31
  128. package/dist/config/parse-pricing.js.map +1 -1
  129. package/dist/config/parse-utils.d.ts +16 -12
  130. package/dist/config/parse-utils.d.ts.map +1 -1
  131. package/dist/config/parse-utils.js +91 -28
  132. package/dist/config/parse-utils.js.map +1 -1
  133. package/dist/config/types.d.ts +1 -1
  134. package/dist/config/types.d.ts.map +1 -1
  135. package/dist/config/types.js.map +1 -1
  136. package/dist/config.d.ts +6 -5
  137. package/dist/config.d.ts.map +1 -1
  138. package/dist/config.js +66 -36
  139. package/dist/config.js.map +1 -1
  140. package/dist/credits/amount.d.ts +2 -2
  141. package/dist/credits/amount.d.ts.map +1 -1
  142. package/dist/credits/amount.js +6 -5
  143. package/dist/credits/amount.js.map +1 -1
  144. package/dist/credits/catalog-runtime.d.ts +1 -1
  145. package/dist/credits/catalog-runtime.d.ts.map +1 -1
  146. package/dist/credits/catalog-runtime.js +3 -4
  147. package/dist/credits/catalog-runtime.js.map +1 -1
  148. package/dist/credits/events.d.ts +12 -1
  149. package/dist/credits/events.d.ts.map +1 -1
  150. package/dist/credits/events.js +35 -21
  151. package/dist/credits/events.js.map +1 -1
  152. package/dist/credits/lease-workflow.d.ts +3 -2
  153. package/dist/credits/lease-workflow.d.ts.map +1 -1
  154. package/dist/credits/lease-workflow.js +4 -3
  155. package/dist/credits/lease-workflow.js.map +1 -1
  156. package/dist/credits/low-balance-monitor.d.ts +3 -2
  157. package/dist/credits/low-balance-monitor.d.ts.map +1 -1
  158. package/dist/credits/low-balance-monitor.js +1 -1
  159. package/dist/credits/low-balance-monitor.js.map +1 -1
  160. package/dist/credits/postgres/repositories/analytics.d.ts +2 -2
  161. package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -1
  162. package/dist/credits/postgres/repositories/analytics.js +14 -6
  163. package/dist/credits/postgres/repositories/analytics.js.map +1 -1
  164. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
  165. package/dist/credits/postgres/repositories/balance.js +7 -7
  166. package/dist/credits/postgres/repositories/balance.js.map +1 -1
  167. package/dist/credits/postgres/repositories/bucket.js +1 -1
  168. package/dist/credits/postgres/repositories/bucket.js.map +1 -1
  169. package/dist/credits/postgres/repositories/catalog.d.ts +4 -3
  170. package/dist/credits/postgres/repositories/catalog.d.ts.map +1 -1
  171. package/dist/credits/postgres/repositories/catalog.js +4 -3
  172. package/dist/credits/postgres/repositories/catalog.js.map +1 -1
  173. package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -1
  174. package/dist/credits/postgres/repositories/deduction.js +2 -2
  175. package/dist/credits/postgres/repositories/deduction.js.map +1 -1
  176. package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
  177. package/dist/credits/postgres/repositories/lease.js +4 -2
  178. package/dist/credits/postgres/repositories/lease.js.map +1 -1
  179. package/dist/credits/postgres/repositories/plan.d.ts +1 -1
  180. package/dist/credits/postgres/repositories/team.d.ts +2 -1
  181. package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
  182. package/dist/credits/postgres/repositories/team.js +19 -5
  183. package/dist/credits/postgres/repositories/team.js.map +1 -1
  184. package/dist/credits/postgres/store.d.ts +6 -5
  185. package/dist/credits/postgres/store.d.ts.map +1 -1
  186. package/dist/credits/postgres/store.js +23 -13
  187. package/dist/credits/postgres/store.js.map +1 -1
  188. package/dist/credits/postgres/value-mappers.d.ts +5 -4
  189. package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
  190. package/dist/credits/postgres/value-mappers.js +11 -12
  191. package/dist/credits/postgres/value-mappers.js.map +1 -1
  192. package/dist/credits/service-errors.d.ts +1 -1
  193. package/dist/credits/service-errors.d.ts.map +1 -1
  194. package/dist/credits/service-errors.js +1 -1
  195. package/dist/credits/service-errors.js.map +1 -1
  196. package/dist/credits/service-types.d.ts +4 -1
  197. package/dist/credits/service-types.d.ts.map +1 -1
  198. package/dist/credits/service-types.js.map +1 -1
  199. package/dist/credits/service.d.ts +5 -0
  200. package/dist/credits/service.d.ts.map +1 -1
  201. package/dist/credits/service.js +30 -10
  202. package/dist/credits/service.js.map +1 -1
  203. package/dist/credits/store.d.ts +15 -5
  204. package/dist/credits/store.d.ts.map +1 -1
  205. package/dist/credits/store.js +1 -1
  206. package/dist/credits/store.js.map +1 -1
  207. package/dist/credits/types/account.d.ts +5 -4
  208. package/dist/credits/types/account.d.ts.map +1 -1
  209. package/dist/credits/types/account.js.map +1 -1
  210. package/dist/credits/types/catalog.d.ts +2 -1
  211. package/dist/credits/types/catalog.d.ts.map +1 -1
  212. package/dist/credits/types/catalog.js.map +1 -1
  213. package/dist/credits/types/grants.d.ts.map +1 -1
  214. package/dist/credits/types/grants.js.map +1 -1
  215. package/dist/credits/types/ledger.d.ts +3 -2
  216. package/dist/credits/types/ledger.d.ts.map +1 -1
  217. package/dist/credits/types/ledger.js.map +1 -1
  218. package/dist/credits/types/teams.d.ts +1 -0
  219. package/dist/credits/types/teams.d.ts.map +1 -1
  220. package/dist/credits/types/teams.js.map +1 -1
  221. package/dist/engine.d.ts +2 -2
  222. package/dist/engine.d.ts.map +1 -1
  223. package/dist/engine.js +40 -11
  224. package/dist/engine.js.map +1 -1
  225. package/dist/errors.d.ts +10 -3
  226. package/dist/errors.d.ts.map +1 -1
  227. package/dist/errors.js +50 -9
  228. package/dist/errors.js.map +1 -1
  229. package/dist/expr/ast.d.ts.map +1 -1
  230. package/dist/expr/ast.js.map +1 -1
  231. package/dist/expr/evaluator.d.ts +1 -1
  232. package/dist/expr/evaluator.d.ts.map +1 -1
  233. package/dist/expr/evaluator.js +1 -1
  234. package/dist/expr/evaluator.js.map +1 -1
  235. package/dist/expr/parser.d.ts.map +1 -1
  236. package/dist/expr/parser.js.map +1 -1
  237. package/dist/expr/tokenizer.d.ts.map +1 -1
  238. package/dist/expr/tokenizer.js +34 -12
  239. package/dist/expr/tokenizer.js.map +1 -1
  240. package/dist/expr.d.ts +1 -1
  241. package/dist/expr.d.ts.map +1 -1
  242. package/dist/expr.js +13 -7
  243. package/dist/expr.js.map +1 -1
  244. package/dist/generated/pricing-config.types.d.ts.map +1 -1
  245. package/dist/generated/pricing-config.types.js.map +1 -1
  246. package/dist/index.d.ts +3 -1
  247. package/dist/index.d.ts.map +1 -1
  248. package/dist/index.js +1 -0
  249. package/dist/index.js.map +1 -1
  250. package/dist/integrations/better-auth.d.ts +4 -1
  251. package/dist/integrations/better-auth.d.ts.map +1 -1
  252. package/dist/integrations/better-auth.js +7 -4
  253. package/dist/integrations/better-auth.js.map +1 -1
  254. package/dist/load-config-file.d.ts +2 -1
  255. package/dist/load-config-file.d.ts.map +1 -1
  256. package/dist/load-config-file.js +19 -13
  257. package/dist/load-config-file.js.map +1 -1
  258. package/dist/metrics.d.ts +3 -2
  259. package/dist/metrics.d.ts.map +1 -1
  260. package/dist/metrics.js.map +1 -1
  261. package/dist/node.d.ts +6 -3
  262. package/dist/node.d.ts.map +1 -1
  263. package/dist/node.js +1 -0
  264. package/dist/node.js.map +1 -1
  265. package/dist/providers/_shared.d.ts +11 -8
  266. package/dist/providers/_shared.d.ts.map +1 -1
  267. package/dist/providers/_shared.js +26 -17
  268. package/dist/providers/_shared.js.map +1 -1
  269. package/dist/providers/dodo/better-auth-core.d.ts +32 -0
  270. package/dist/providers/dodo/better-auth-core.d.ts.map +1 -0
  271. package/dist/providers/dodo/better-auth-core.js +14 -0
  272. package/dist/providers/dodo/better-auth-core.js.map +1 -0
  273. package/dist/providers/dodo/better-auth.d.ts +5 -7
  274. package/dist/providers/dodo/better-auth.d.ts.map +1 -1
  275. package/dist/providers/dodo/better-auth.js +16 -13
  276. package/dist/providers/dodo/better-auth.js.map +1 -1
  277. package/dist/providers/dodo/client-contract.d.ts +16 -22
  278. package/dist/providers/dodo/client-contract.d.ts.map +1 -1
  279. package/dist/providers/dodo/client-contract.js.map +1 -1
  280. package/dist/providers/dodo/event-mapper.d.ts +7 -4
  281. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  282. package/dist/providers/dodo/event-mapper.js +130 -106
  283. package/dist/providers/dodo/event-mapper.js.map +1 -1
  284. package/dist/providers/dodo/nextjs-core.d.ts +22 -0
  285. package/dist/providers/dodo/nextjs-core.d.ts.map +1 -0
  286. package/dist/providers/dodo/nextjs-core.js +14 -0
  287. package/dist/providers/dodo/nextjs-core.js.map +1 -0
  288. package/dist/providers/dodo/nextjs.d.ts +5 -7
  289. package/dist/providers/dodo/nextjs.d.ts.map +1 -1
  290. package/dist/providers/dodo/nextjs.js +11 -10
  291. package/dist/providers/dodo/nextjs.js.map +1 -1
  292. package/dist/providers/dodo/provider.d.ts +3 -3
  293. package/dist/providers/dodo/provider.d.ts.map +1 -1
  294. package/dist/providers/dodo/provider.js +76 -58
  295. package/dist/providers/dodo/provider.js.map +1 -1
  296. package/dist/providers/dodo/react-native-core.d.ts +56 -0
  297. package/dist/providers/dodo/react-native-core.d.ts.map +1 -0
  298. package/dist/providers/dodo/react-native-core.js +56 -0
  299. package/dist/providers/dodo/react-native-core.js.map +1 -0
  300. package/dist/providers/dodo/react-native.d.ts +6 -50
  301. package/dist/providers/dodo/react-native.d.ts.map +1 -1
  302. package/dist/providers/dodo/react-native.js +5 -49
  303. package/dist/providers/dodo/react-native.js.map +1 -1
  304. package/dist/providers/dodo/webhook-bridge.d.ts +4 -2
  305. package/dist/providers/dodo/webhook-bridge.d.ts.map +1 -1
  306. package/dist/providers/dodo/webhook-bridge.js.map +1 -1
  307. package/dist/providers/environment.d.ts +1 -1
  308. package/dist/providers/environment.d.ts.map +1 -1
  309. package/dist/providers/environment.js +4 -2
  310. package/dist/providers/environment.js.map +1 -1
  311. package/dist/providers/mock/provider.d.ts.map +1 -1
  312. package/dist/providers/mock/provider.js +5 -10
  313. package/dist/providers/mock/provider.js.map +1 -1
  314. package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
  315. package/dist/providers/stripe/event-mapper.js +104 -12
  316. package/dist/providers/stripe/event-mapper.js.map +1 -1
  317. package/dist/providers/stripe/provider.d.ts.map +1 -1
  318. package/dist/providers/stripe/provider.js +100 -60
  319. package/dist/providers/stripe/provider.js.map +1 -1
  320. package/dist/providers/types.d.ts +0 -1
  321. package/dist/providers/types.d.ts.map +1 -1
  322. package/dist/providers/types.js.map +1 -1
  323. package/dist/retry.d.ts.map +1 -1
  324. package/dist/retry.js +16 -9
  325. package/dist/retry.js.map +1 -1
  326. package/dist/shared/diagnostics.d.ts +10 -2
  327. package/dist/shared/diagnostics.d.ts.map +1 -1
  328. package/dist/shared/diagnostics.js +65 -6
  329. package/dist/shared/diagnostics.js.map +1 -1
  330. package/dist/shared/idempotency.d.ts +4 -3
  331. package/dist/shared/idempotency.d.ts.map +1 -1
  332. package/dist/shared/idempotency.js +21 -10
  333. package/dist/shared/idempotency.js.map +1 -1
  334. package/dist/shared/json.d.ts +28 -0
  335. package/dist/shared/json.d.ts.map +1 -0
  336. package/dist/shared/json.js +41 -0
  337. package/dist/shared/json.js.map +1 -0
  338. package/dist/shared/logger.d.ts +10 -4
  339. package/dist/shared/logger.d.ts.map +1 -1
  340. package/dist/shared/logger.js.map +1 -1
  341. package/dist/shared/postgres-client.d.ts +10 -5
  342. package/dist/shared/postgres-client.d.ts.map +1 -1
  343. package/dist/shared/postgres-client.js +80 -45
  344. package/dist/shared/postgres-client.js.map +1 -1
  345. package/dist/shared/postgres-errors.d.ts +1 -1
  346. package/dist/shared/postgres-errors.d.ts.map +1 -1
  347. package/dist/shared/postgres-errors.js +32 -31
  348. package/dist/shared/postgres-errors.js.map +1 -1
  349. package/dist/shared/postgres-types.d.ts +3 -2
  350. package/dist/shared/postgres-types.d.ts.map +1 -1
  351. package/dist/shared/postgres-types.js.map +1 -1
  352. package/dist/shared/postgres-validation.d.ts +7 -6
  353. package/dist/shared/postgres-validation.d.ts.map +1 -1
  354. package/dist/shared/postgres-validation.js +17 -10
  355. package/dist/shared/postgres-validation.js.map +1 -1
  356. package/dist/storage/adapters/clickhouse.d.ts +20 -6
  357. package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
  358. package/dist/storage/adapters/clickhouse.js +150 -42
  359. package/dist/storage/adapters/clickhouse.js.map +1 -1
  360. package/dist/storage/adapters/s3.d.ts +67 -6
  361. package/dist/storage/adapters/s3.d.ts.map +1 -1
  362. package/dist/storage/adapters/s3.js +79 -26
  363. package/dist/storage/adapters/s3.js.map +1 -1
  364. package/dist/storage/diagnostics.d.ts +105 -0
  365. package/dist/storage/diagnostics.d.ts.map +1 -0
  366. package/dist/storage/diagnostics.js +228 -0
  367. package/dist/storage/diagnostics.js.map +1 -0
  368. package/dist/storage/maintenance.d.ts +88 -0
  369. package/dist/storage/maintenance.d.ts.map +1 -0
  370. package/dist/storage/maintenance.js +272 -0
  371. package/dist/storage/maintenance.js.map +1 -0
  372. package/dist/storage/outbox-worker.d.ts +21 -1
  373. package/dist/storage/outbox-worker.d.ts.map +1 -1
  374. package/dist/storage/outbox-worker.js +157 -28
  375. package/dist/storage/outbox-worker.js.map +1 -1
  376. package/dist/storage/ports.d.ts +52 -7
  377. package/dist/storage/ports.d.ts.map +1 -1
  378. package/dist/storage/ports.js.map +1 -1
  379. package/dist/storage/postgres-repository.d.ts +9 -2
  380. package/dist/storage/postgres-repository.d.ts.map +1 -1
  381. package/dist/storage/postgres-repository.js +97 -11
  382. package/dist/storage/postgres-repository.js.map +1 -1
  383. package/dist/storage/runtime.d.ts +20 -3
  384. package/dist/storage/runtime.d.ts.map +1 -1
  385. package/dist/storage/runtime.js +326 -156
  386. package/dist/storage/runtime.js.map +1 -1
  387. package/dist/telemetry/index.d.ts +41 -0
  388. package/dist/telemetry/index.d.ts.map +1 -0
  389. package/dist/telemetry/index.js +118 -0
  390. package/dist/telemetry/index.js.map +1 -0
  391. package/dist/telemetry/opentelemetry.d.ts +25 -0
  392. package/dist/telemetry/opentelemetry.d.ts.map +1 -0
  393. package/dist/telemetry/opentelemetry.js +74 -0
  394. package/dist/telemetry/opentelemetry.js.map +1 -0
  395. package/package.json +24 -14
@@ -1 +1 @@
1
- {"version":3,"file":"amount.d.ts","sourceRoot":"","sources":["../../src/credits/amount.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AAEjC,OAAO,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAEvE,8EAA8E;AAC9E,wBAAgB,SAAS,CAAC,KAAK,EAAE,WAAW,GAAG,OAAO,CAerD;AAED,wBAAgB,QAAQ,CAAC,KAAK,EAAE,eAAe,GAAG,KAAK,IAAI,WAAW,CAErE;AAED,uEAAuE;AACvE,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI,CAI7D"}
1
+ {"version":3,"file":"amount.d.ts","sourceRoot":"","sources":["../../src/credits/amount.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAGrC,OAAO,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAEvE,8EAA8E;AAC9E,wBAAgB,SAAS,CAAC,KAAK,EAAE,WAAW,GAAG,OAAO,CAerD;AAED,wBAAgB,QAAQ,CAAC,KAAK,EAAE,eAAe,GAAG,KAAK,IAAI,WAAW,CAErE;AAED,uEAAuE;AACvE,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,eAAe,GAAG,IAAI,CAIrE"}
@@ -1,13 +1,14 @@
1
- import Decimal from "decimal.js";
1
+ import { Decimal } from "decimal.js";
2
+ import { z } from "zod";
2
3
  /** Parse an exact public credit amount without accepting IEEE-754 numbers. */
3
4
  export function toDecimal(value) {
4
5
  let amount;
5
6
  if (value instanceof Decimal) {
6
7
  amount = value;
7
8
  }
8
- else if (typeof value === "string" && value.trim().length > 0) {
9
+ else if (z.string().min(1).safeParse(value).success) {
9
10
  try {
10
- amount = new Decimal(value);
11
+ amount = new Decimal(z.string().parse(value));
11
12
  }
12
13
  catch (cause) {
13
14
  throw new TypeError("amount must be a valid decimal string", { cause });
@@ -21,11 +22,11 @@ export function toDecimal(value) {
21
22
  return amount;
22
23
  }
23
24
  export function isAmount(value) {
24
- return value instanceof Decimal || typeof value === "string";
25
+ return value instanceof Decimal || z.string().safeParse(value).success;
25
26
  }
26
27
  /** Enforce the exact-money contract for untyped JavaScript callers. */
27
28
  export function rejectNativeCreditAmount(value) {
28
- if (typeof value === "number") {
29
+ if (z.number().safeParse(value).success) {
29
30
  throw new TypeError("amount must be a Decimal or decimal string");
30
31
  }
31
32
  }
@@ -1 +1 @@
1
- {"version":3,"file":"amount.js","sourceRoot":"","sources":["../../src/credits/amount.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AAIjC,8EAA8E;AAC9E,MAAM,UAAU,SAAS,CAAC,KAAkB;IAC1C,IAAI,MAAe,CAAC;IACpB,IAAI,KAAK,YAAY,OAAO,EAAE,CAAC;QAC7B,MAAM,GAAG,KAAK,CAAC;IACjB,CAAC;SAAM,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAChE,IAAI,CAAC;YACH,MAAM,GAAG,IAAI,OAAO,CAAC,KAAK,CAAC,CAAC;QAC9B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,IAAI,SAAS,CAAC,uCAAuC,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;QAC1E,CAAC;IACH,CAAC;SAAM,CAAC;QACN,MAAM,IAAI,SAAS,CAAC,4CAA4C,CAAC,CAAC;IACpE,CAAC;IACD,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE;QAAE,MAAM,IAAI,UAAU,CAAC,uBAAuB,CAAC,CAAC;IACtE,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,MAAM,UAAU,QAAQ,CAAC,KAAsB;IAC7C,OAAO,KAAK,YAAY,OAAO,IAAI,OAAO,KAAK,KAAK,QAAQ,CAAC;AAC/D,CAAC;AAED,uEAAuE;AACvE,MAAM,UAAU,wBAAwB,CAAC,KAAc;IACrD,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC9B,MAAM,IAAI,SAAS,CAAC,4CAA4C,CAAC,CAAC;IACpE,CAAC;AACH,CAAC","sourcesContent":["import Decimal from \"decimal.js\";\n\nimport type { ExactAmount, MetricsOrAmount } from \"./service-types.js\";\n\n/** Parse an exact public credit amount without accepting IEEE-754 numbers. */\nexport function toDecimal(value: ExactAmount): Decimal {\n let amount: Decimal;\n if (value instanceof Decimal) {\n amount = value;\n } else if (typeof value === \"string\" && value.trim().length > 0) {\n try {\n amount = new Decimal(value);\n } catch (cause) {\n throw new TypeError(\"amount must be a valid decimal string\", { cause });\n }\n } else {\n throw new TypeError(\"amount must be a Decimal or decimal string\");\n }\n if (!amount.isFinite()) throw new RangeError(\"amount must be finite\");\n return amount;\n}\n\nexport function isAmount(value: MetricsOrAmount): value is ExactAmount {\n return value instanceof Decimal || typeof value === \"string\";\n}\n\n/** Enforce the exact-money contract for untyped JavaScript callers. */\nexport function rejectNativeCreditAmount(value: unknown): void {\n if (typeof value === \"number\") {\n throw new TypeError(\"amount must be a Decimal or decimal string\");\n }\n}\n"]}
1
+ {"version":3,"file":"amount.js","sourceRoot":"","sources":["../../src/credits/amount.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAIxB,8EAA8E;AAC9E,MAAM,UAAU,SAAS,CAAC,KAAkB;IAC1C,IAAI,MAAe,CAAC;IACpB,IAAI,KAAK,YAAY,OAAO,EAAE,CAAC;QAC7B,MAAM,GAAG,KAAK,CAAC;IACjB,CAAC;SAAM,IAAI,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,OAAO,EAAE,CAAC;QACtD,IAAI,CAAC;YACH,MAAM,GAAG,IAAI,OAAO,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;QAChD,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,IAAI,SAAS,CAAC,uCAAuC,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;QAC1E,CAAC;IACH,CAAC;SAAM,CAAC;QACN,MAAM,IAAI,SAAS,CAAC,4CAA4C,CAAC,CAAC;IACpE,CAAC;IACD,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE;QAAE,MAAM,IAAI,UAAU,CAAC,uBAAuB,CAAC,CAAC;IACtE,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,MAAM,UAAU,QAAQ,CAAC,KAAsB;IAC7C,OAAO,KAAK,YAAY,OAAO,IAAI,CAAC,CAAC,MAAM,EAAE,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC;AACzE,CAAC;AAED,uEAAuE;AACvE,MAAM,UAAU,wBAAwB,CAAC,KAAsB;IAC7D,IAAI,CAAC,CAAC,MAAM,EAAE,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,OAAO,EAAE,CAAC;QACxC,MAAM,IAAI,SAAS,CAAC,4CAA4C,CAAC,CAAC;IACpE,CAAC;AACH,CAAC","sourcesContent":["import { Decimal } from \"decimal.js\";\nimport { z } from \"zod\";\n\nimport type { ExactAmount, MetricsOrAmount } from \"./service-types.js\";\n\n/** Parse an exact public credit amount without accepting IEEE-754 numbers. */\nexport function toDecimal(value: ExactAmount): Decimal {\n let amount: Decimal;\n if (value instanceof Decimal) {\n amount = value;\n } else if (z.string().min(1).safeParse(value).success) {\n try {\n amount = new Decimal(z.string().parse(value));\n } catch (cause) {\n throw new TypeError(\"amount must be a valid decimal string\", { cause });\n }\n } else {\n throw new TypeError(\"amount must be a Decimal or decimal string\");\n }\n if (!amount.isFinite()) throw new RangeError(\"amount must be finite\");\n return amount;\n}\n\nexport function isAmount(value: MetricsOrAmount): value is ExactAmount {\n return value instanceof Decimal || z.string().safeParse(value).success;\n}\n\n/** Enforce the exact-money contract for untyped JavaScript callers. */\nexport function rejectNativeCreditAmount(value: MetricsOrAmount): void {\n if (z.number().safeParse(value).success) {\n throw new TypeError(\"amount must be a Decimal or decimal string\");\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- import Decimal from "decimal.js";
1
+ import { Decimal } from "decimal.js";
2
2
  import { type BursarConfigData, type CatalogRollout } from "../config.js";
3
3
  import type { PricingEngine } from "../engine.js";
4
4
  import type { NormalizedLogger } from "../shared/logger.js";
@@ -1 +1 @@
1
- {"version":3,"file":"catalog-runtime.d.ts","sourceRoot":"","sources":["../../src/credits/catalog-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AAEjC,OAAO,EAEL,KAAK,gBAAgB,EACrB,KAAK,cAAc,EACpB,MAAM,cAAc,CAAC;AACtB,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAGlD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OA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AK,CAAC,EAAE,MAAM,GAAG,IAAI,EACrB,OAAO,CAAC,EAAE,cAAc,GAAG,IAAI,GAC9B,OAAO,CAAC,MAAM,CAAC;IASZ,YAAY,CAAC,MAAM,EAAE,gBAAgB,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC;IAI9E,gBAAgB,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC;IAMnF,MAAM,CACV,eAAe,EAAE,eAAe,EAChC,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,EACtB,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,GACtB,OAAO,CAAC;QAAE,MAAM,EAAE,OAAO,CAAC;QAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAAA;KAAE,CAAC;IA2BrD,OAAO,CAAC,SAAS;IAMX,aAAa,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,aAAa,CAAC;YAapD,uBAAuB;IAgBrC,OAAO,CAAC,aAAa;CAQtB"}
@@ -1,5 +1,6 @@
1
- import Decimal from "decimal.js";
1
+ import { Decimal } from "decimal.js";
2
2
  import { LRUCache } from "lru-cache";
3
+ import { z } from "zod";
3
4
  import { canonicalBursarConfigDict, } from "../config.js";
4
5
  import { PricingEngine as PricingEngineClass } from "../engine.js";
5
6
  import { LeaseNotFoundError, CatalogNotLoadedError } from "../errors.js";
@@ -109,9 +110,7 @@ export class CatalogRuntime {
109
110
  });
110
111
  return {
111
112
  amount: breakdown.total,
112
- model: typeof metricsOrAmount.dimensions?.model === "string"
113
- ? metricsOrAmount.dimensions.model
114
- : null,
113
+ model: z.string().safeParse(metricsOrAmount.dimensions?.model).data ?? null,
115
114
  };
116
115
  }
117
116
  setEngine(engine) {
@@ -1 +1 @@
1
- {"version":3,"file":"catalog-runtime.js","sourceRoot":"","sources":["../../src/credits/catalog-runtime.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aAAa,EAAE,CAAC;QAEhD,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;QAClD,MAAM,cAAc,GAAG,IAAI,CAAC,cAAc,IAAI,IAAI,CAAC;QACnD,IAAI,cAAc,IAAI,IAAI,EAAE,CAAC;YAC3B,MAAM,IAAI,CAAC,cAAc,EAAE,CAAC;YAC5B,OAAO,IAAI,CAAC,aAAa,EAAE,CAAC;QAC9B,CAAC;QAED,OAAO,IAAI,CAAC,uBAAuB,CAAC,cAAc,CAAC,CAAC;IACtD,CAAC;IAEO,KAAK,CAAC,uBAAuB,CAAC,cAAsB;QAC1D,MAAM,MAAM,GAAG,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;QACvD,IAAI,MAAM;YAAE,OAAO,MAAM,CAAC;QAE1B,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,kBAAkB,CAAC,cAAc,CAAC,CAAC;QACnE,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC;YACpB,MAAM,IAAI,qBAAqB,CAC7B,oBAAoB,cAAc,qCAAqC,CACxE,CAAC;QACJ,CAAC;QAED,MAAM,MAAM,GAAG,kBAAkB,CAAC,QAAQ,CAAC,MAAM,CAAC,MAAiC,CAAC,CAAC;QACrF,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,cAAc,EAAE,MAAM,CAAC,CAAC;QAChD,OAAO,MAAM,CAAC;IAChB,CAAC;IAEO,aAAa;QACnB,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;YACjB,MAAM,IAAI,qBAAqB,CAC7B,kFAAkF,CACnF,CAAC;QACJ,CAAC;QACD,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;CACF","sourcesContent":["import Decimal from \"decimal.js\";\nimport { LRUCache } from \"lru-cache\";\nimport {\n canonicalBursarConfigDict,\n type BursarConfigData,\n type CatalogRollout,\n} from \"../config.js\";\nimport type { PricingEngine } from \"../engine.js\";\nimport { PricingEngine as PricingEngineClass } from \"../engine.js\";\nimport { LeaseNotFoundError, CatalogNotLoadedError } from \"../errors.js\";\nimport type { NormalizedLogger } from \"../shared/logger.js\";\nimport type { CreditStore } from \"./store.js\";\nimport type { ExactAmount, MetricsOrAmount } from \"./service-types.js\";\nimport { isAmount, rejectNativeCreditAmount, toDecimal } from \"./amount.js\";\n\nfunction toNonNegativeAmount(value: ExactAmount): Decimal {\n const amount = toDecimal(value);\n if (!amount.isFinite() || amount.isNegative()) {\n throw new RangeError(\"amount must be finite and non-negative\");\n }\n return amount;\n}\n\n/** Owns catalog publication, cache refresh, and revision-aware pricing engines. */\nexport class CatalogRuntime {\n private engine: PricingEngine | null;\n private readonly cache: LRUCache<string, PricingEngine>;\n private readonly versionEngines = new Map<number, PricingEngine>();\n\n constructor(\n private readonly store: CreditStore,\n engine: PricingEngine | null,\n private readonly logger: NormalizedLogger,\n private readonly cacheTtlMs: number,\n ) {\n this.engine = engine;\n this.cache = new LRUCache<string, PricingEngine>({\n max: 1,\n ttl: cacheTtlMs,\n // Consumers must never proceed against a known-stale catalog. The cache\n // still deduplicates concurrent refreshes, but every caller awaits the\n // same fresh value just like the Python SDK's refresh lock.\n allowStale: false,\n fetchMethod: async () => {\n const engine = await this.fetchEngineFromStore();\n // `lru-cache` installs the returned value when the fetch completes.\n // Calling cache.set() from inside fetchMethod aborts the in-flight\n // refresh with a \"replaced\" error.\n this.engine = engine;\n this.versionEngines.clear();\n return engine;\n },\n });\n if (engine) this.cache.set(\"catalog\", engine);\n }\n\n get currentEngine(): PricingEngine | null {\n return this.engine;\n }\n\n async loadFromStore(): Promise<void> {\n this.setEngine(await this.fetchEngineFromStore());\n }\n\n private async fetchEngineFromStore(): Promise<PricingEngine> {\n this.logger.info(\"[CatalogService] loading active catalog\");\n const active = await this.store.getActiveCatalog();\n if (!active) {\n this.logger.warn(\"[CatalogService] no active catalog revision in store\");\n throw new CatalogNotLoadedError(\"No active catalog revision is available\");\n }\n return PricingEngineClass.fromDict(active.config as Record<string, unknown>);\n }\n\n async refreshIfStale(): Promise<void> {\n if (this.cacheTtlMs === 0) return;\n await this.cache.fetch(\"catalog\");\n }\n\n invalidate(): void {\n this.cache.delete(\"catalog\");\n }\n\n async publishAndActivate(\n config: BursarConfigData,\n label?: string | null,\n rollout?: CatalogRollout | null,\n ): Promise<string> {\n this.logger.info(\"[CatalogService] publishing and activating catalog\", { label });\n const canonical = canonicalBursarConfigDict(config);\n const nextEngine = PricingEngineClass.fromDict(canonical);\n const revisionId = await this.store.publishAndActivateCatalog(canonical, label, rollout);\n this.setEngine(nextEngine);\n return revisionId;\n }\n\n async publishDraft(config: BursarConfigData, label?: string | null): Promise<string> {\n return this.store.publishCatalogDraft(canonicalBursarConfigDict(config), label);\n }\n\n async activateRevision(version: number, rollout?: CatalogRollout | null): Promise<string> {\n const id = await this.store.activateCatalogRevision(version, rollout);\n await this.loadFromStore();\n return id;\n }\n\n async costOf(\n metricsOrAmount: MetricsOrAmount,\n userId?: string | null,\n leaseId?: string | null,\n ): Promise<{ amount: Decimal; model: string | null }> {\n rejectNativeCreditAmount(metricsOrAmount);\n if (isAmount(metricsOrAmount)) {\n return { amount: toNonNegativeAmount(metricsOrAmount), model: null };\n }\n let engine: PricingEngine;\n let rateCard: string | undefined;\n if (leaseId != null) {\n if (userId == null) throw new TypeError(\"userId is required when pricing a lease\");\n const context = await this.store.getLeasePricingContext(userId, leaseId);\n if (!context) throw new LeaseNotFoundError(`Lease not found. User=${userId}`);\n engine = await this.engineForCatalogVersion(context.catalogVersion);\n rateCard = context.rateCard ?? engine.getRateCardForPlan(context.planKey);\n } else {\n engine = await this.engineForUser(userId ?? null);\n const plan = userId == null ? null : await this.store.getUserPlan(userId);\n rateCard = plan?.rateCard ?? undefined;\n }\n const breakdown = engine.calculate(metricsOrAmount, {\n rateCard,\n });\n return {\n amount: breakdown.total,\n model:\n typeof metricsOrAmount.dimensions?.model === \"string\"\n ? metricsOrAmount.dimensions.model\n : null,\n };\n }\n\n private setEngine(engine: PricingEngine): void {\n this.engine = engine;\n this.versionEngines.clear();\n this.cache.set(\"catalog\", engine);\n }\n\n async engineForUser(userId: string | null): Promise<PricingEngine> {\n if (userId == null) return this.requireEngine();\n\n const plan = await this.store.getUserPlan(userId);\n const catalogVersion = plan.catalogVersion ?? null;\n if (catalogVersion == null) {\n await this.refreshIfStale();\n return this.requireEngine();\n }\n\n return this.engineForCatalogVersion(catalogVersion);\n }\n\n private async engineForCatalogVersion(catalogVersion: number): Promise<PricingEngine> {\n const cached = this.versionEngines.get(catalogVersion);\n if (cached) return cached;\n\n const config = await this.store.getCatalogRevision(catalogVersion);\n if (!config?.config) {\n throw new CatalogNotLoadedError(\n `Catalog revision ${catalogVersion} is unavailable for the pinned plan`,\n );\n }\n\n const engine = PricingEngineClass.fromDict(config.config as Record<string, unknown>);\n this.versionEngines.set(catalogVersion, engine);\n return engine;\n }\n\n private requireEngine(): PricingEngine {\n if (!this.engine) {\n throw new CatalogNotLoadedError(\n \"Catalog is not loaded; call catalog.load() or catalog.publishAndActivate() first\",\n );\n }\n return this.engine;\n }\n}\n"]}
1
+ {"version":3,"file":"catalog-runtime.js","sourceRoot":"","sources":["../../src/credits/catalog-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AACrC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EACL,yBAAyB,GAG1B,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,aAAa,IAAI,kBAAkB,EAAE,MAAM,cAAc,CAAC;AACnE,OAAO,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAIzE,OAAO,EAAE,QAAQ,EAAE,wBAAwB,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAE5E,SAAS,mBAAmB,CAA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cAAsB;QAC1D,MAAM,MAAM,GAAG,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;QACvD,IAAI,MAAM;YAAE,OAAO,MAAM,CAAC;QAE1B,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,kBAAkB,CAAC,cAAc,CAAC,CAAC;QACnE,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC;YACpB,MAAM,IAAI,qBAAqB,CAC7B,oBAAoB,cAAc,qCAAqC,CACxE,CAAC;QACJ,CAAC;QAED,MAAM,MAAM,GAAG,kBAAkB,CAAC,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QAC1D,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,cAAc,EAAE,MAAM,CAAC,CAAC;QAChD,OAAO,MAAM,CAAC;IAChB,CAAC;IAEO,aAAa;QACnB,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;YACjB,MAAM,IAAI,qBAAqB,CAC7B,kFAAkF,CACnF,CAAC;QACJ,CAAC;QACD,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;CACF","sourcesContent":["import { Decimal } from \"decimal.js\";\nimport { LRUCache } from \"lru-cache\";\nimport { z } from \"zod\";\nimport {\n canonicalBursarConfigDict,\n type BursarConfigData,\n type CatalogRollout,\n} from \"../config.js\";\nimport type { PricingEngine } from \"../engine.js\";\nimport { PricingEngine as PricingEngineClass } from \"../engine.js\";\nimport { LeaseNotFoundError, CatalogNotLoadedError } from \"../errors.js\";\nimport type { NormalizedLogger } from \"../shared/logger.js\";\nimport type { CreditStore } from \"./store.js\";\nimport type { ExactAmount, MetricsOrAmount } from \"./service-types.js\";\nimport { isAmount, rejectNativeCreditAmount, toDecimal } from \"./amount.js\";\n\nfunction toNonNegativeAmount(value: ExactAmount): Decimal {\n const amount = toDecimal(value);\n if (!amount.isFinite() || amount.isNegative()) {\n throw new RangeError(\"amount must be finite and non-negative\");\n }\n return amount;\n}\n\n/** Owns catalog publication, cache refresh, and revision-aware pricing engines. */\nexport class CatalogRuntime {\n private engine: PricingEngine | null;\n private readonly cache: LRUCache<string, PricingEngine>;\n private readonly versionEngines = new Map<number, PricingEngine>();\n\n constructor(\n private readonly store: CreditStore,\n engine: PricingEngine | null,\n private readonly logger: NormalizedLogger,\n private readonly cacheTtlMs: number,\n ) {\n this.engine = engine;\n this.cache = new LRUCache<string, PricingEngine>({\n max: 1,\n ttl: cacheTtlMs,\n // Consumers must never proceed against a known-stale catalog. The cache\n // still deduplicates concurrent refreshes, but every caller awaits the\n // same fresh value just like the Python SDK's refresh lock.\n allowStale: false,\n fetchMethod: async () => {\n const engine = await this.fetchEngineFromStore();\n // `lru-cache` installs the returned value when the fetch completes.\n // Calling cache.set() from inside fetchMethod aborts the in-flight\n // refresh with a \"replaced\" error.\n this.engine = engine;\n this.versionEngines.clear();\n return engine;\n },\n });\n if (engine) this.cache.set(\"catalog\", engine);\n }\n\n get currentEngine(): PricingEngine | null {\n return this.engine;\n }\n\n async loadFromStore(): Promise<void> {\n this.setEngine(await this.fetchEngineFromStore());\n }\n\n private async fetchEngineFromStore(): Promise<PricingEngine> {\n this.logger.info(\"[CatalogService] loading active catalog\");\n const active = await this.store.getActiveCatalog();\n if (!active) {\n this.logger.warn(\"[CatalogService] no active catalog revision in store\");\n throw new CatalogNotLoadedError(\"No active catalog revision is available\");\n }\n return PricingEngineClass.fromDict(active.config);\n }\n\n async refreshIfStale(): Promise<void> {\n if (this.cacheTtlMs === 0) return;\n await this.cache.fetch(\"catalog\");\n }\n\n invalidate(): void {\n this.cache.delete(\"catalog\");\n }\n\n async publishAndActivate(\n config: BursarConfigData,\n label?: string | null,\n rollout?: CatalogRollout | null,\n ): Promise<string> {\n this.logger.info(\"[CatalogService] publishing and activating catalog\", { label });\n const canonical = canonicalBursarConfigDict(config);\n const nextEngine = PricingEngineClass.fromDict(canonical);\n const revisionId = await this.store.publishAndActivateCatalog(canonical, label, rollout);\n this.setEngine(nextEngine);\n return revisionId;\n }\n\n async publishDraft(config: BursarConfigData, label?: string | null): Promise<string> {\n return this.store.publishCatalogDraft(canonicalBursarConfigDict(config), label);\n }\n\n async activateRevision(version: number, rollout?: CatalogRollout | null): Promise<string> {\n const id = await this.store.activateCatalogRevision(version, rollout);\n await this.loadFromStore();\n return id;\n }\n\n async costOf(\n metricsOrAmount: MetricsOrAmount,\n userId?: string | null,\n leaseId?: string | null,\n ): Promise<{ amount: Decimal; model: string | null }> {\n rejectNativeCreditAmount(metricsOrAmount);\n if (isAmount(metricsOrAmount)) {\n return { amount: toNonNegativeAmount(metricsOrAmount), model: null };\n }\n let engine: PricingEngine;\n let rateCard: string | undefined;\n if (leaseId != null) {\n if (userId == null) throw new TypeError(\"userId is required when pricing a lease\");\n const context = await this.store.getLeasePricingContext(userId, leaseId);\n if (!context) throw new LeaseNotFoundError(`Lease not found. User=${userId}`);\n engine = await this.engineForCatalogVersion(context.catalogVersion);\n rateCard = context.rateCard ?? engine.getRateCardForPlan(context.planKey);\n } else {\n engine = await this.engineForUser(userId ?? null);\n const plan = userId == null ? null : await this.store.getUserPlan(userId);\n rateCard = plan?.rateCard ?? undefined;\n }\n const breakdown = engine.calculate(metricsOrAmount, {\n rateCard,\n });\n return {\n amount: breakdown.total,\n model: z.string().safeParse(metricsOrAmount.dimensions?.model).data ?? null,\n };\n }\n\n private setEngine(engine: PricingEngine): void {\n this.engine = engine;\n this.versionEngines.clear();\n this.cache.set(\"catalog\", engine);\n }\n\n async engineForUser(userId: string | null): Promise<PricingEngine> {\n if (userId == null) return this.requireEngine();\n\n const plan = await this.store.getUserPlan(userId);\n const catalogVersion = plan.catalogVersion ?? null;\n if (catalogVersion == null) {\n await this.refreshIfStale();\n return this.requireEngine();\n }\n\n return this.engineForCatalogVersion(catalogVersion);\n }\n\n private async engineForCatalogVersion(catalogVersion: number): Promise<PricingEngine> {\n const cached = this.versionEngines.get(catalogVersion);\n if (cached) return cached;\n\n const config = await this.store.getCatalogRevision(catalogVersion);\n if (!config?.config) {\n throw new CatalogNotLoadedError(\n `Catalog revision ${catalogVersion} is unavailable for the pinned plan`,\n );\n }\n\n const engine = PricingEngineClass.fromDict(config.config);\n this.versionEngines.set(catalogVersion, engine);\n return engine;\n }\n\n private requireEngine(): PricingEngine {\n if (!this.engine) {\n throw new CatalogNotLoadedError(\n \"Catalog is not loaded; call catalog.load() or catalog.publishAndActivate() first\",\n );\n }\n return this.engine;\n }\n}\n"]}
@@ -1,3 +1,5 @@
1
+ import type { StructuredObject } from "../shared/json.js";
2
+ import { type Logger } from "../shared/logger.js";
1
3
  /**
2
4
  * Typed event emitter for credit lifecycle events.
3
5
  *
@@ -35,12 +37,21 @@ export interface CreditEvent {
35
37
  type: CreditEventType;
36
38
  timestamp: Date;
37
39
  userId: string;
38
- data?: Record<string, unknown>;
40
+ data?: StructuredObject;
39
41
  }
40
42
  type EventHandler = (event: CreditEvent) => void | PromiseLike<void>;
41
43
  /** Typed pub/sub event emitter for credit events. */
42
44
  export declare class CreditEventEmitter {
43
45
  private listeners;
46
+ private readonly logger;
47
+ /**
48
+ * Create an emitter with an optional SDK logger.
49
+ *
50
+ * The argument is optional for compatibility with existing no-argument
51
+ * construction. Missing logger methods are normalized to no-ops.
52
+ */
53
+ constructor(logger?: Logger | null);
54
+ private logHandlerFailure;
44
55
  /** Register a handler for a specific event type. */
45
56
  on(type: CreditEventType, handler: EventHandler): void;
46
57
  /** Remove a previously registered handler. */
@@ -1 +1 @@
1
- {"version":3,"file":"events.d.ts","sourceRoot":"","sources":["../../src/credits/events.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH;;;;;;;;GAQG;AACH,MAAM,MAAM,eAAe,GACvB,kBAAkB,GAClB,uBAAuB,GACvB,eAAe,GACf,kBAAkB,GAClB,uBAAuB,GACvB,iBAAiB,GACjB,qBAAqB,GACrB,sBAAsB,GACtB,kBAAkB,GAClB,8BAA8B,GAC9B,uBAAuB,GACvB,mBAAmB,GACn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B,GACvB,iBAAiB,GACjB,uBAAuB,GACvB,yBAAyB,CAAC;AAE9B;;;;;;GAMG;AACH,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,eAAe,CAAC;IACtB,SAAS,EAAE,IAAI,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,gBAAgB,CAAC;CACzB;AAED,KAAK,YAAY,GAAG,CAAC,KAAK,EAAE,WAAW,KAAK,IAAI,GAAG,WAAW,CAAC,IAAI,CAAC,CAAC;AAErE,qDAAqD;AACrD,qBAAa,kBAAkB;IAC7B,OAAO,CAAC,SAAS,CAAiD;IAClE,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAmB;IAE1C;;;;;OAKG;gBACS,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI;IAIlC,OAAO,CAAC,iBAAiB;IAkBzB,oDAAoD;IACpD,EAAE,CAAC,IAAI,EAAE,eAAe,EAAE,OAAO,EAAE,YAAY,GAAG,IAAI;IAOtD,8CAA8C;IAC9C,GAAG,CAAC,IAAI,EAAE,eAAe,EAAE,OAAO,EAAE,YAAY,GAAG,IAAI;IAIvD;;;;;;;OAOG;IACH,IAAI,CAAC,KAAK,EAAE,WAAW,GAAG,IAAI;IAmB9B,+CAA+C;IAC/C,SAAS,CAAC,IAAI,EAAE,eAAe,GAAG,IAAI;IAItC,yCAAyC;IACzC,QAAQ,IAAI,IAAI;CAGjB"}
@@ -1,22 +1,36 @@
1
- /**
2
- * Typed event emitter for credit lifecycle events.
3
- *
4
- * Events are emitted by ``CreditsService`` after each store operation.
5
- * The emitter is optional — inject into ``CreditsService`` constructor,
6
- * no-op if omitted.
7
- *
8
- * @example
9
- * ```ts
10
- * const emitter = new CreditEventEmitter();
11
- * emitter.on("credits.deducted", (event) => {
12
- * console.log(`Deducted ${event.data?.amount} from ${event.userId}`);
13
- * });
14
- * const manager = new CreditsService(store, engine, emitter);
15
- * ```
16
- */
1
+ import { normalizeLogger } from "../shared/logger.js";
17
2
  /** Typed pub/sub event emitter for credit events. */
18
3
  export class CreditEventEmitter {
19
4
  listeners = new Map();
5
+ logger;
6
+ /**
7
+ * Create an emitter with an optional SDK logger.
8
+ *
9
+ * The argument is optional for compatibility with existing no-argument
10
+ * construction. Missing logger methods are normalized to no-ops.
11
+ */
12
+ constructor(logger) {
13
+ this.logger = normalizeLogger(logger);
14
+ }
15
+ logHandlerFailure(message, eventType, cause) {
16
+ let error;
17
+ try {
18
+ error = cause instanceof Error ? cause : String(cause);
19
+ }
20
+ catch {
21
+ error = "Unknown handler failure";
22
+ }
23
+ try {
24
+ // Logger methods may be synchronous or asynchronous. Normalize the
25
+ // result so a rejecting injected logger cannot escape as an unhandled
26
+ // rejection and weaken listener isolation.
27
+ const loggerResult = this.logger.error(message, { eventType, error });
28
+ void Promise.resolve(loggerResult).catch(() => { });
29
+ }
30
+ catch {
31
+ // Logging must not weaken listener isolation if a caller-supplied logger fails.
32
+ }
33
+ }
20
34
  /** Register a handler for a specific event type. */
21
35
  on(type, handler) {
22
36
  if (!this.listeners.has(type)) {
@@ -45,14 +59,14 @@ export class CreditEventEmitter {
45
59
  try {
46
60
  const out = handler(event);
47
61
  // Swallow rejections from async handlers so they never become unhandled.
48
- if (out != null && typeof out.then === "function") {
49
- void Promise.resolve(out).catch((err) => {
50
- console.error(`[CreditEventEmitter] async handler error for event ${event.type}:`, err);
62
+ if (out != null) {
63
+ void Promise.resolve(out).catch((error) => {
64
+ this.logHandlerFailure("[CreditEventEmitter] async handler failed", event.type, error);
51
65
  });
52
66
  }
53
67
  }
54
- catch (err) {
55
- console.error(`[CreditEventEmitter] handler error for event ${event.type}:`, err);
68
+ catch (error) {
69
+ this.logHandlerFailure("[CreditEventEmitter] handler failed", event.type, error);
56
70
  }
57
71
  }
58
72
  }
@@ -1 +1 @@
1
- {"version":3,"file":"events.js","sourceRoot":"","sources":["../../src/credits/events.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AA6CH,qDAAqD;AACr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AAE,CAAC;gBACb,OAAO,CAAC,KAAK,CAAC,gDAAgD,KAAK,CAAC,IAAI,GAAG,EAAE,GAAG,CAAC,CAAC;YACpF,CAAC;QACH,CAAC;IACH,CAAC;IAED,+CAA+C;IAC/C,SAAS,CAAC,IAAqB;QAC7B,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAC9B,CAAC;IAED,yCAAyC;IACzC,QAAQ;QACN,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,CAAC;IACzB,CAAC;CACF","sourcesContent":["/**\n * Typed event emitter for credit lifecycle events.\n *\n * Events are emitted by ``CreditsService`` after each store operation.\n * The emitter is optional — inject into ``CreditsService`` constructor,\n * no-op if omitted.\n *\n * @example\n * ```ts\n * const emitter = new CreditEventEmitter();\n * emitter.on(\"credits.deducted\", (event) => {\n * console.log(`Deducted ${event.data?.amount} from ${event.userId}`);\n * });\n * const manager = new CreditsService(store, engine, emitter);\n * ```\n */\n\n/**\n * All credit lifecycle event types.\n *\n * Success events (``credits.deducted``/``credits.refunded``/…) are emitted by\n * ``CreditsService`` only after the underlying store operation committed without\n * an ``error``. Failure events (``credits.deduct_failed`` /\n * ``credits.refund_failed``) carry the store's business-error code in\n * ``data.error`` for observability/fraud monitoring.\n */\nexport type CreditEventType =\n | \"credits.deducted\"\n | \"credits.deduct_failed\"\n | \"credits.added\"\n | \"credits.refunded\"\n | \"credits.refund_failed\"\n | \"credits.expired\"\n | \"credits.low_balance\"\n | \"credits.plan_changed\"\n | \"credits.reserved\"\n | \"credits.reservation_released\"\n | \"credits.lease_expired\"\n | \"credits.overdraft\"\n | \"credits.cycle_renewed\"\n | \"credits.revoked\"\n | \"credits.quota_blocked\"\n | \"credits.quota_threshold\";\n\n/**\n * A typed credit lifecycle event.\n *\n * Money values inside ``data`` (``amount``, ``balanceAfter``,\n * ``allowanceConsumed``, ``threshold``, …) are exact `Decimal` instances\n * and never binary `number`.\n */\nexport interface CreditEvent {\n type: CreditEventType;\n timestamp: Date;\n userId: string;\n data?: Record<string, unknown>;\n}\n\ntype EventHandler = (event: CreditEvent) => void | PromiseLike<void>;\n\n/** Typed pub/sub event emitter for credit events. */\nexport class CreditEventEmitter {\n private listeners = new Map<CreditEventType, Set<EventHandler>>();\n\n /** Register a handler for a specific event type. */\n on(type: CreditEventType, handler: EventHandler): void {\n if (!this.listeners.has(type)) {\n this.listeners.set(type, new Set());\n }\n this.listeners.get(type)!.add(handler);\n }\n\n /** Remove a previously registered handler. */\n off(type: CreditEventType, handler: EventHandler): void {\n this.listeners.get(type)?.delete(handler);\n }\n\n /**\n * Emit an event to all registered handlers. No-op if no handlers exist.\n *\n * Each handler is isolated: a synchronous throw (or a rejected promise from an\n * async handler) is caught and logged, never propagated. This guarantees a\n * misbehaving listener can never break the manager's main flow and never\n * produces an unhandled promise rejection.\n */\n emit(event: CreditEvent): void {\n const handlers = this.listeners.get(event.type);\n if (!handlers) return;\n // Iterate a snapshot so a handler that mutates the set during emit is safe.\n for (const handler of [...handlers]) {\n try {\n const out = handler(event);\n // Swallow rejections from async handlers so they never become unhandled.\n if (out != null && typeof out.then === \"function\") {\n void Promise.resolve(out).catch((err: unknown) => {\n console.error(`[CreditEventEmitter] async handler error for event ${event.type}:`, err);\n });\n }\n } catch (err) {\n console.error(`[CreditEventEmitter] handler error for event ${event.type}:`, err);\n }\n }\n }\n\n /** Remove all handlers for a specific type. */\n clearType(type: CreditEventType): void {\n this.listeners.delete(type);\n }\n\n /** Remove all handlers for all types. */\n clearAll(): void {\n this.listeners.clear();\n }\n}\n"]}
1
+ {"version":3,"file":"events.js","sourceRoot":"","sources":["../../src/credits/events.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAsC,MAAM,qBAAqB,CAAC;AA8D1F,qDAAqD;AACrD,MAAM,OAAO,kBAAkB;IACrB,SAAS,GAAG,IAAI,GAAG,EAAsC,CAAC;IACjD,MAAM,CAAmB;IAE1C;;;;;OAKG;IACH,YAAY,MAAsB;QAChC,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,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAChD,IAAI,CAAC,QAAQ;YAAE,OAAO;QACtB,4EAA4E;QAC5E,KAAK,MAAM,OAAO,IAAI,CAAC,GAAG,QAAQ,CAAC,EAAE,CAAC;YACpC,IAAI,CAAC;gBACH,MAAM,GAAG,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC;gBAC3B,yEAAyE;gBACzE,IAAI,GAAG,IAAI,IAAI,EAAE,CAAC;oBAChB,KAAK,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;wBACjD,IAAI,CAAC,iBAAiB,CAAC,2CAA2C,EAAE,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;oBACzF,CAAC,CAAC,CAAC;gBACL,CAAC;YACH,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,IAAI,CAAC,iBAAiB,CAAC,qCAAqC,EAAE,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;YACnF,CAAC;QACH,CAAC;IACH,CAAC;IAED,+CAA+C;IAC/C,SAAS,CAAC,IAAqB;QAC7B,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAC9B,CAAC;IAED,yCAAyC;IACzC,QAAQ;QACN,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,CAAC;IACzB,CAAC;CACF","sourcesContent":["import type { StructuredObject } from \"../shared/json.js\";\nimport { normalizeLogger, type Logger, type NormalizedLogger } from \"../shared/logger.js\";\n\n/**\n * Typed event emitter for credit lifecycle events.\n *\n * Events are emitted by ``CreditsService`` after each store operation.\n * The emitter is optional — inject into ``CreditsService`` constructor,\n * no-op if omitted.\n *\n * @example\n * ```ts\n * const emitter = new CreditEventEmitter();\n * emitter.on(\"credits.deducted\", (event) => {\n * console.log(`Deducted ${event.data?.amount} from ${event.userId}`);\n * });\n * const manager = new CreditsService(store, engine, emitter);\n * ```\n */\n\n/**\n * All credit lifecycle event types.\n *\n * Success events (``credits.deducted``/``credits.refunded``/…) are emitted by\n * ``CreditsService`` only after the underlying store operation committed without\n * an ``error``. Failure events (``credits.deduct_failed`` /\n * ``credits.refund_failed``) carry the store's business-error code in\n * ``data.error`` for observability/fraud monitoring.\n */\nexport type CreditEventType =\n | \"credits.deducted\"\n | \"credits.deduct_failed\"\n | \"credits.added\"\n | \"credits.refunded\"\n | \"credits.refund_failed\"\n | \"credits.expired\"\n | \"credits.low_balance\"\n | \"credits.plan_changed\"\n | \"credits.reserved\"\n | \"credits.reservation_released\"\n | \"credits.lease_expired\"\n | \"credits.overdraft\"\n | \"credits.cycle_renewed\"\n | \"credits.revoked\"\n | \"credits.quota_blocked\"\n | \"credits.quota_threshold\";\n\n/**\n * A typed credit lifecycle event.\n *\n * Money values inside ``data`` (``amount``, ``balanceAfter``,\n * ``allowanceConsumed``, ``threshold``, …) are exact `Decimal` instances\n * and never binary `number`.\n */\nexport interface CreditEvent {\n type: CreditEventType;\n timestamp: Date;\n userId: string;\n data?: StructuredObject;\n}\n\ntype EventHandler = (event: CreditEvent) => void | PromiseLike<void>;\n\n/** Typed pub/sub event emitter for credit events. */\nexport class CreditEventEmitter {\n private listeners = new Map<CreditEventType, Set<EventHandler>>();\n private readonly logger: NormalizedLogger;\n\n /**\n * Create an emitter with an optional SDK logger.\n *\n * The argument is optional for compatibility with existing no-argument\n * construction. Missing logger methods are normalized to no-ops.\n */\n constructor(logger?: Logger | null) {\n this.logger = normalizeLogger(logger);\n }\n\n private logHandlerFailure(message: string, eventType: CreditEventType, cause: unknown): void {\n let error: Error | string;\n try {\n error = cause instanceof Error ? cause : String(cause);\n } catch {\n error = \"Unknown handler failure\";\n }\n try {\n // Logger methods may be synchronous or asynchronous. Normalize the\n // result so a rejecting injected logger cannot escape as an unhandled\n // rejection and weaken listener isolation.\n const loggerResult = this.logger.error(message, { eventType, error });\n void Promise.resolve(loggerResult).catch(() => {});\n } catch {\n // Logging must not weaken listener isolation if a caller-supplied logger fails.\n }\n }\n\n /** Register a handler for a specific event type. */\n on(type: CreditEventType, handler: EventHandler): void {\n if (!this.listeners.has(type)) {\n this.listeners.set(type, new Set());\n }\n this.listeners.get(type)!.add(handler);\n }\n\n /** Remove a previously registered handler. */\n off(type: CreditEventType, handler: EventHandler): void {\n this.listeners.get(type)?.delete(handler);\n }\n\n /**\n * Emit an event to all registered handlers. No-op if no handlers exist.\n *\n * Each handler is isolated: a synchronous throw (or a rejected promise from an\n * async handler) is caught and logged, never propagated. This guarantees a\n * misbehaving listener can never break the manager's main flow and never\n * produces an unhandled promise rejection.\n */\n emit(event: CreditEvent): void {\n const handlers = this.listeners.get(event.type);\n if (!handlers) return;\n // Iterate a snapshot so a handler that mutates the set during emit is safe.\n for (const handler of [...handlers]) {\n try {\n const out = handler(event);\n // Swallow rejections from async handlers so they never become unhandled.\n if (out != null) {\n void Promise.resolve(out).catch((error: unknown) => {\n this.logHandlerFailure(\"[CreditEventEmitter] async handler failed\", event.type, error);\n });\n }\n } catch (error) {\n this.logHandlerFailure(\"[CreditEventEmitter] handler failed\", event.type, error);\n }\n }\n }\n\n /** Remove all handlers for a specific type. */\n clearType(type: CreditEventType): void {\n this.listeners.delete(type);\n }\n\n /** Remove all handlers for all types. */\n clearAll(): void {\n this.listeners.clear();\n }\n}\n"]}
@@ -1,10 +1,11 @@
1
- import Decimal from "decimal.js";
1
+ import { Decimal } from "decimal.js";
2
2
  import type { NormalizedLogger } from "../shared/logger.js";
3
3
  import type { CreditEventType } from "./events.js";
4
4
  import { LowBalanceMonitor } from "./low-balance-monitor.js";
5
5
  import { CatalogRuntime } from "./catalog-runtime.js";
6
6
  import type { CanAffordOptions, BeginBilledOperationOptions, BilledOperation, MetricsOrAmount, PolicyPreset, ReserveOptions, RunBilledOptions, SettleOptions } from "./service-types.js";
7
7
  import type { CreditStore } from "./store.js";
8
+ import type { StructuredObject } from "../shared/json.js";
8
9
  import type { AllowanceResult, BucketBalancesResult, CanAffordResult, DeductionResult, DeductionSuccess, LeaseSuccess, ReleaseResult } from "./types/index.js";
9
10
  export declare class CreditLeaseWorkflow {
10
11
  private readonly store;
@@ -19,7 +20,7 @@ export declare class CreditLeaseWorkflow {
19
20
  private readonly emitQuotaEvents;
20
21
  private readonly maybeLazyExpire;
21
22
  private readonly afterDeduction;
22
- constructor(store: CreditStore, catalogRuntime: CatalogRuntime, logger: NormalizedLogger, balanceMonitor: LowBalanceMonitor, policy: PolicyPreset, overdraftFloor: Decimal | null, defaultMaxConcurrent: number | null, defaultTtl: number, emit: (type: CreditEventType, userId: string, data?: Record<string, unknown>) => void, emitQuotaEvents: (userId: string, idempotencyKey: string) => Promise<void>, maybeLazyExpire: (userId: string) => Promise<void>, afterDeduction: (userId: string, result: DeductionSuccess) => Promise<void>);
23
+ constructor(store: CreditStore, catalogRuntime: CatalogRuntime, logger: NormalizedLogger, balanceMonitor: LowBalanceMonitor, policy: PolicyPreset, overdraftFloor: Decimal | null, defaultMaxConcurrent: number | null, defaultTtl: number, emit: (type: CreditEventType, userId: string, data?: StructuredObject) => void, emitQuotaEvents: (userId: string, idempotencyKey: string) => Promise<void>, maybeLazyExpire: (userId: string) => Promise<void>, afterDeduction: (userId: string, result: DeductionSuccess) => Promise<void>);
23
24
  private expectedAdmissionPolicy;
24
25
  /**
25
26
  * Compute the credit cost and model from metrics, or pass a raw amount through.
@@ -1 +1 @@
1
- {"version":3,"file":"lease-workflow.d.ts","sourceRoot":"","sources":["../../src/credits/lease-workflow.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AAEjC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;A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CAAC,aAAa,CAAC;IAatE,4EAA4E;IACtE,KAAK,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,YAAY,CAAC;IAaxF;;;;OAIG;IACG,SAAS,CACb,MAAM,EAAE,MAAM,EACd,eAAe,EAAE,eAAe,EAChC,OAAO,CAAC,EAAE,gBAAgB,GACzB,OAAO,CAAC,eAAe,CAAC;IAiD3B,sGAAsG;IAChG,iBAAiB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,CAAC;IAKtE;;;;;;;;;OASG;IACG,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC;IAIrE;;;;;;;;OAQG;IACG,SAAS,CAAC,CAAC,EACf,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,gBAAgB,CAAC,CAAC,CAAC,GAC3B,OAAO,CAAC;QAAE,MAAM,EAAE,CAAC,CAAC;QAAC,SAAS,EAAE,eAAe,CAAA;KAAE,CAAC;IA6BrD;;;;;OAKG;IACG,oBAAoB,CACxB,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,2BAA2B,GACnC,OAAO,CAAC,eAAe,CAAC;CA2B5B"}
@@ -1,4 +1,5 @@
1
- import Decimal from "decimal.js";
1
+ import { Decimal } from "decimal.js";
2
+ import { z } from "zod";
2
3
  import { retryBursarOperation } from "../retry.js";
3
4
  import { LowBalanceMonitor } from "./low-balance-monitor.js";
4
5
  import { CatalogRuntime } from "./catalog-runtime.js";
@@ -87,7 +88,7 @@ export class CreditLeaseWorkflow {
87
88
  const feature = options.feature ?? null;
88
89
  const measures = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.measures ?? {}) };
89
90
  const dimensions = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.dimensions ?? {}) };
90
- const region = typeof dimensions.region === "string" ? dimensions.region : null;
91
+ const region = z.string().safeParse(dimensions.region).data ?? null;
91
92
  const result = await this.store.createLease(userId, amount, operationType, {
92
93
  idempotencyKey: leaseIdempotencyKey,
93
94
  billingMode: expectedPolicy.billingMode,
@@ -147,7 +148,7 @@ export class CreditLeaseWorkflow {
147
148
  const { amount, model } = await this.costOf(metricsOrAmount, userId, leaseId);
148
149
  const measures = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.measures ?? {}) };
149
150
  const dimensions = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.dimensions ?? {}) };
150
- const region = typeof dimensions.region === "string" ? dimensions.region : null;
151
+ const region = z.string().safeParse(dimensions.region).data ?? null;
151
152
  // Build ledger metadata with caller fields first and protected system fields last.
152
153
  const txMeta = {};
153
154
  if (isAmount(metricsOrAmount)) {
@@ -1 +1 @@
1
- {"version":3,"file":"lease-workflow.js","sourceRoot":"","sources":["../../src/credits/lease-workflow.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AACjC,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAGnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,QAAQ,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AACjE,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAwB7E,MAAM,OAAO,mBAAmB;IAEX;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IAKA;IACA;IACA;IAhBnB,YACmB,KAAkB,EAClB,cAA8B,EAC9B,MAAwB,EACxB,cAAiC,EACjC,MAAoB,EACpB,cAA8B,EAC9B,oBAAmC,EACnC,UAAkB,EAClB,IAIR,EACQ,eAA0E,EAC1E,eAAkD,EAClD,cAA2E;QAf3E,UAAK,GAAL,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EAAE;gBACzC,cAAc,EAAE,eAAe,CAAC,YAAY,EAAE,QAAQ,CAAC;gBACvD,OAAO,EAAE,OAAO,CAAC,OAAO;gBACxB,QAAQ,EAAE,QAAQ,IAAI,OAAO,CAAC,QAAQ;aACvC,CAAC;YACJ,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,EAAE;gBACnB,MAAM,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;YAC/C,CAAC;YACD,OAAO,EAAE,KAAK,IAAI,EAAE;gBAClB,MAAM,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;YAC5C,CAAC;SACF,CAAC;IACJ,CAAC;CACF","sourcesContent":["import Decimal from \"decimal.js\";\nimport { retryBursarOperation } from \"../retry.js\";\nimport type { NormalizedLogger } from \"../shared/logger.js\";\nimport type { CreditEventType } from \"./events.js\";\nimport { LowBalanceMonitor } from \"./low-balance-monitor.js\";\nimport { CatalogRuntime } from \"./catalog-runtime.js\";\nimport { isAmount, rejectNativeCreditAmount } from \"./amount.js\";\nimport { raiseLeaseError } from \"./service-errors.js\";\nimport { requireStableKey, scopedStableKey } from \"../shared/idempotency.js\";\nimport type {\n CanAffordOptions,\n BeginBilledOperationOptions,\n BilledOperation,\n MetricsOrAmount,\n PolicyPreset,\n ReserveOptions,\n RunBilledOptions,\n SettleOptions,\n} from \"./service-types.js\";\nimport type { CreditStore } from \"./store.js\";\nimport type {\n AllowanceResult,\n BillingMode,\n BucketBalancesResult,\n CanAffordResult,\n CreditMetadata,\n DeductionResult,\n DeductionSuccess,\n LeaseSuccess,\n ReleaseResult,\n} from \"./types/index.js\";\n\nexport class CreditLeaseWorkflow {\n constructor(\n private readonly store: CreditStore,\n private readonly catalogRuntime: CatalogRuntime,\n private readonly logger: NormalizedLogger,\n private readonly balanceMonitor: LowBalanceMonitor,\n private readonly policy: PolicyPreset,\n private readonly overdraftFloor: Decimal | null,\n private readonly defaultMaxConcurrent: number | null,\n private readonly defaultTtl: number,\n private readonly emit: (\n type: CreditEventType,\n userId: string,\n data?: Record<string, unknown>,\n ) => void,\n private readonly emitQuotaEvents: (userId: string, idempotencyKey: string) => Promise<void>,\n private readonly maybeLazyExpire: (userId: string) => Promise<void>,\n private readonly afterDeduction: (userId: string, result: DeductionSuccess) => Promise<void>,\n ) {}\n\n private async expectedAdmissionPolicy(\n userId: string,\n operationType: string,\n billingModeOverride?: BillingMode | null,\n ): Promise<{\n billingMode: BillingMode;\n floor: Decimal;\n maxConcurrent: number | null;\n }> {\n const plan = await this.store.getUserPlan(userId);\n const creditPolicy = plan.planId == null ? null : plan.creditPolicy;\n const planMode: BillingMode =\n plan.planId == null\n ? this.policy === \"overdraft\"\n ? \"overdraft\"\n : \"strict\"\n : creditPolicy?.type === \"credit_line\"\n ? \"overdraft\"\n : \"strict\";\n const operationAdmission =\n plan.planId == null ? null : (plan.admission?.operations[operationType] ?? null);\n const billingMode = billingModeOverride ?? planMode;\n const floor =\n billingMode === \"overdraft\"\n ? (creditPolicy?.creditLimit?.negated() ?? this.overdraftFloor ?? new Decimal(0))\n : new Decimal(0);\n return {\n billingMode,\n floor,\n maxConcurrent:\n plan.planId == null\n ? this.defaultMaxConcurrent\n : (operationAdmission?.maxInFlight ?? plan.admission?.maxInFlight ?? null),\n };\n }\n\n /**\n * Compute the credit cost and model from metrics, or pass a raw amount through.\n *\n * For {@link UsageMetrics} the cost is ``engine.calculate(...).total`` (exact\n * `Decimal`, no truncation); a raw amount is used as-is with no model.\n */\n private async costOf(\n metricsOrAmount: MetricsOrAmount,\n userId?: string | null,\n leaseId?: string | null,\n ): Promise<{ amount: Decimal; model: string | null }> {\n return this.catalogRuntime.costOf(metricsOrAmount, userId, leaseId);\n }\n\n /**\n * Atomically acquire a lease — the only authoritative admission control.\n *\n * Prices the estimate and delegates entitlement, quota, allowance, credit\n * policy, and concurrency enforcement to the database in one atomic call.\n */\n async reserve(\n userId: string,\n metricsOrAmount: MetricsOrAmount,\n options: ReserveOptions,\n ): Promise<LeaseSuccess> {\n rejectNativeCreditAmount(metricsOrAmount);\n const leaseIdempotencyKey = requireStableKey(options?.idempotencyKey);\n await this.maybeLazyExpire(userId);\n this.logger.debug(\"[CreditsService] reserve\", {\n feature: options.feature,\n operationType: options.operationType,\n });\n const operationType =\n options.operationType ?? (isAmount(metricsOrAmount) ? \"usage\" : metricsOrAmount.operation);\n const expectedPolicy = await this.expectedAdmissionPolicy(\n userId,\n operationType,\n options.billingMode,\n );\n const priced = await this.costOf(metricsOrAmount, userId);\n const amount = priced.amount;\n const model = priced.model ?? options.model ?? null;\n const ttlSeconds = options.ttl != null ? options.ttl : this.defaultTtl;\n const feature = options.feature ?? null;\n const measures = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.measures ?? {}) };\n const dimensions = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.dimensions ?? {}) };\n const region = typeof dimensions.region === \"string\" ? dimensions.region : null;\n\n const result = await this.store.createLease(userId, amount, operationType, {\n idempotencyKey: leaseIdempotencyKey,\n billingMode: expectedPolicy.billingMode,\n floor: expectedPolicy.floor,\n maxConcurrent: expectedPolicy.maxConcurrent,\n ttlSeconds,\n model,\n metadata: options.metadata,\n feature,\n region,\n measures,\n dimensions,\n });\n\n if (result.error !== null) {\n if (result.error === \"quota_exceeded\") {\n await this.emitQuotaEvents(userId, leaseIdempotencyKey);\n }\n this.emit(\"credits.deduct_failed\", userId, {\n error: result.error,\n amount,\n stage: \"reserve\",\n operationType,\n });\n raiseLeaseError(result.error, userId, amount);\n }\n\n this.logger.info(\"[CreditsService] reservation acquired\", {\n leaseId: result.leaseId,\n amount: result.amount,\n minimumBalance: result.minimumBalance,\n });\n this.emit(\"credits.reserved\", userId, {\n leaseId: result.leaseId,\n amount: result.amount,\n available: result.available,\n minimumBalance: result.minimumBalance,\n operationType,\n expiresAt: result.expiresAt,\n });\n await this.emitQuotaEvents(userId, leaseIdempotencyKey);\n return result;\n }\n\n /**\n * Charge the actual cost against a lease and finalize it.\n *\n * De-clamped: bills the full actual cost even if it exceeds the lease hold\n * (overdraft). Emits ``credits.deducted``, then low-balance and overdraft\n * signals as applicable.\n */\n async settle(\n userId: string,\n leaseId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: SettleOptions,\n ): Promise<DeductionResult> {\n rejectNativeCreditAmount(metricsOrAmount);\n await this.maybeLazyExpire(userId);\n this.logger.debug(\"[CreditsService] settle\", { leaseId });\n const idempotencyKey =\n options?.idempotencyKey === undefined\n ? `lease:${leaseId}:settle`\n : requireStableKey(options.idempotencyKey);\n const feature = options?.feature ?? null;\n const { amount, model } = await this.costOf(metricsOrAmount, userId, leaseId);\n const measures = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.measures ?? {}) };\n const dimensions = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.dimensions ?? {}) };\n const region = typeof dimensions.region === \"string\" ? dimensions.region : null;\n\n // Build ledger metadata with caller fields first and protected system fields last.\n const txMeta: Record<string, unknown> = {};\n if (isAmount(metricsOrAmount)) {\n if (options?.metadata) {\n for (const [k, v] of Object.entries(options.metadata)) {\n if (v != null) txMeta[k] = v;\n }\n }\n if (idempotencyKey) txMeta[\"idempotencyKey\"] = idempotencyKey;\n } else {\n if (options?.metadata) {\n for (const [k, v] of Object.entries(options.metadata)) {\n if (v != null) txMeta[k] = v;\n }\n }\n txMeta[\"operation\"] = metricsOrAmount.operation;\n txMeta[\"measures\"] = { ...(metricsOrAmount.measures ?? {}) };\n txMeta[\"dimensions\"] = { ...(metricsOrAmount.dimensions ?? {}) };\n txMeta[\"breakdownTotal\"] = amount.toString();\n if (idempotencyKey) txMeta[\"idempotencyKey\"] = idempotencyKey;\n }\n\n const result = await this.store.settleLease(userId, leaseId, amount, {\n idempotencyKey,\n feature,\n model,\n region,\n measures,\n dimensions,\n metadata: txMeta as CreditMetadata,\n });\n\n if (result.error !== null) {\n this.emit(\"credits.deduct_failed\", userId, {\n error: result.error,\n amount,\n stage: \"settle\",\n leaseId,\n });\n if (result.error === \"expired_lease\") {\n this.emit(\"credits.lease_expired\", userId, { leaseId });\n }\n raiseLeaseError(result.error, userId, amount);\n }\n\n this.logger.info(\"[CreditsService] settled\", {\n leaseId,\n amount: result.amount,\n balanceAfter: result.balanceAfter,\n idempotent: result.idempotent,\n });\n this.emit(\"credits.deducted\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n allowanceConsumed: result.allowanceConsumed,\n balanceAfter: result.balanceAfter,\n model,\n leaseId,\n idempotent: result.idempotent,\n });\n\n await this.balanceMonitor.afterCharge(userId, result);\n if (!result.idempotent) {\n await this.emitQuotaEvents(userId, idempotencyKey);\n await this.afterDeduction(userId, result);\n }\n return result;\n }\n\n /** Release a lease without charging; safe to repeat after failed or aborted work. */\n async release(userId: string, leaseId: string): Promise<ReleaseResult> {\n this.logger.debug(\"[CreditsService] release\", { leaseId });\n const result = await this.store.releaseLease(userId, leaseId);\n if (result.released) {\n this.logger.info(\"[CreditsService] lease released\", { leaseId, reason: result.reason });\n this.emit(\"credits.reservation_released\", userId, {\n leaseId,\n reason: result.reason,\n });\n }\n return result;\n }\n\n /** Extend an active lease's expiry without changing its captured policy. */\n async renew(userId: string, leaseId: string, ttl?: number | null): Promise<LeaseSuccess> {\n const ttlSeconds = ttl ?? this.defaultTtl;\n this.logger.debug(\"[CreditsService] renew\", { leaseId, ttlSeconds });\n const result = await this.store.renewLease(userId, leaseId, ttlSeconds);\n if (result.error !== null) {\n if (result.error === \"expired_lease\") {\n this.emit(\"credits.lease_expired\", userId, { leaseId });\n }\n raiseLeaseError(result.error, userId, new Decimal(0));\n }\n return result;\n }\n\n /**\n * Advisory affordability check — UI only, non-locking, and potentially stale.\n *\n * Never use this as an admission gate; only ``reserve`` is authoritative.\n */\n async canAfford(\n userId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: CanAffordOptions,\n ): Promise<CanAffordResult> {\n rejectNativeCreditAmount(metricsOrAmount);\n await this.maybeLazyExpire(userId);\n const feature = options?.feature ?? null;\n const { amount: worstCase } = await this.costOf(metricsOrAmount, userId);\n const avail = await this.store.getAvailable(userId);\n let expectedPolicy;\n try {\n expectedPolicy = await this.expectedAdmissionPolicy(\n userId,\n options?.operationType ?? \"usage\",\n options?.billingMode,\n );\n } catch {\n return {\n affordable: false,\n spendable: avail.available,\n worstCase,\n reason: \"policy_unavailable\",\n };\n }\n let allowanceRemaining = new Decimal(0);\n try {\n allowanceRemaining =\n (await this.store.checkAllowance(userId))?.allowanceRemaining ?? new Decimal(0);\n } catch (error) {\n this.logger.debug(\"[CreditsService] allowance fetch failed in canAfford\", {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n const spendable = avail.available.plus(allowanceRemaining).minus(expectedPolicy.floor);\n\n let affordable = true;\n let reason: string | null = null;\n if (feature != null) {\n const check = await this.store.checkFeature(userId, feature);\n if (!check.hasFeature) {\n affordable = false;\n reason = \"feature_not_entitled\";\n }\n }\n if (affordable && spendable.lt(worstCase)) {\n affordable = false;\n reason = \"insufficient_credits\";\n }\n\n return { affordable, spendable, worstCase, reason };\n }\n\n /** Get a user's per-bucket credit balances (credit buckets). Thin pass-through, no event emission. */\n async getBucketBalances(userId: string): Promise<BucketBalancesResult> {\n await this.maybeLazyExpire(userId);\n return await this.store.getBucketBalances(userId);\n }\n\n /**\n * Get remaining free allowance for the current billing period.\n *\n * Convenience wrapper that routes through the manager so callers never need\n * to reach past it into the raw store. Returns `null` when the subject has no\n * active allowance policy.\n *\n * Window calculation is database-owned and supports the full normalized\n * policy tuple, including timezone and arbitrary interval counts.\n */\n async checkAllowance(userId: string): Promise<AllowanceResult | null> {\n return await this.store.checkAllowance(userId);\n }\n\n /**\n * One-call shortcut wiring reserve → doWork → settle.\n *\n * ``doWork`` runs the operation and returns ``{ result, actual }`` where\n * ``actual`` is the real usage metrics (or amount) to settle. On any exception\n * from ``doWork`` the lease is released and the error re-raised. For long jobs\n * ``doWork`` may call the configured lease TTL. A crash between reserve and settle is\n * covered by the lease TTL (and the store's reaper).\n */\n async runBilled<T>(\n userId: string,\n options: RunBilledOptions<T>,\n ): Promise<{ result: T; deduction: DeductionResult }> {\n const operationKey = requireStableKey(options.operationKey, \"operationKey\");\n const operation = await this.beginBilledOperation(userId, {\n estimate: options.estimate,\n operationKey,\n operationType: options.operationType,\n billingMode: options.billingMode,\n ttl: options.ttl,\n feature: options.feature,\n metadata: options.metadata,\n });\n\n let workResult: T;\n let actual: MetricsOrAmount;\n try {\n ({ result: workResult, actual } = await options.doWork());\n } catch (err) {\n await operation.release();\n throw err;\n }\n\n // Never release after work succeeds. A settlement failure may be a\n // transient/unknown-commit outcome and is safe to replay with operationKey.\n const deduction = await retryBursarOperation(() => operation.settle(actual), {\n maxAttempts: options.settlementAttempts,\n });\n return { result: workResult, deduction };\n }\n\n /**\n * Begin a replay-safe billable operation that can span framework callbacks.\n *\n * The operation key is namespaced into distinct reserve and settle keys, so\n * replaying the whole lifecycle cannot acquire a second hold.\n */\n async beginBilledOperation(\n userId: string,\n options: BeginBilledOperationOptions,\n ): Promise<BilledOperation> {\n const operationKey = requireStableKey(options.operationKey, \"operationKey\");\n const lease = await this.reserve(userId, options.estimate, {\n operationType: options.operationType,\n billingMode: options.billingMode,\n ttl: options.ttl,\n feature: options.feature,\n metadata: options.metadata,\n idempotencyKey: scopedStableKey(operationKey, \"reserve\"),\n });\n return {\n leaseId: lease.leaseId,\n operationKey,\n settle: async (actual, metadata) =>\n this.settle(userId, lease.leaseId, actual, {\n idempotencyKey: scopedStableKey(operationKey, \"settle\"),\n feature: options.feature,\n metadata: metadata ?? options.metadata,\n }),\n renew: async (ttl) => {\n await this.renew(userId, lease.leaseId, ttl);\n },\n release: async () => {\n await this.release(userId, lease.leaseId);\n },\n };\n }\n}\n"]}
1
+ {"version":3,"file":"lease-workflow.js","sourceRoot":"","sources":["../../src/credits/lease-workflow.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,C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AAoB,CACxB,MAAc,EACd,OAAoC;QAEpC,MAAM,YAAY,GAAG,gBAAgB,CAAC,OAAO,CAAC,YAAY,EAAE,cAAc,CAAC,CAAC;QAC5E,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,CAAC,QAAQ,EAAE;YACzD,aAAa,EAAE,OAAO,CAAC,aAAa;YACpC,WAAW,EAAE,OAAO,CAAC,WAAW;YAChC,GAAG,EAAE,OAAO,CAAC,GAAG;YAChB,OAAO,EAAE,OAAO,CAAC,OAAO;YACxB,QAAQ,EAAE,OAAO,CAAC,QAAQ;YAC1B,cAAc,EAAE,eAAe,CAAC,YAAY,EAAE,SAAS,CAAC;SACzD,CAAC,CAAC;QACH,OAAO;YACL,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,YAAY;YACZ,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,CACjC,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE;gBACzC,cAAc,EAAE,eAAe,CAAC,YAAY,EAAE,QAAQ,CAAC;gBACvD,OAAO,EAAE,OAAO,CAAC,OAAO;gBACxB,QAAQ,EAAE,QAAQ,IAAI,OAAO,CAAC,QAAQ;aACvC,CAAC;YACJ,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,EAAE;gBACnB,MAAM,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;YAC/C,CAAC;YACD,OAAO,EAAE,KAAK,IAAI,EAAE;gBAClB,MAAM,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;YAC5C,CAAC;SACF,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { Decimal } from \"decimal.js\";\nimport { z } from \"zod\";\nimport { retryBursarOperation } from \"../retry.js\";\nimport type { NormalizedLogger } from \"../shared/logger.js\";\nimport type { CreditEventType } from \"./events.js\";\nimport { LowBalanceMonitor } from \"./low-balance-monitor.js\";\nimport { CatalogRuntime } from \"./catalog-runtime.js\";\nimport { isAmount, rejectNativeCreditAmount } from \"./amount.js\";\nimport { raiseLeaseError } from \"./service-errors.js\";\nimport { requireStableKey, scopedStableKey } from \"../shared/idempotency.js\";\nimport type {\n CanAffordOptions,\n BeginBilledOperationOptions,\n BilledOperation,\n MetricsOrAmount,\n PolicyPreset,\n ReserveOptions,\n RunBilledOptions,\n SettleOptions,\n} from \"./service-types.js\";\nimport type { CreditStore } from \"./store.js\";\nimport type { StructuredObject } from \"../shared/json.js\";\nimport type {\n AllowanceResult,\n BillingMode,\n BucketBalancesResult,\n CanAffordResult,\n CreditMetadata,\n DeductionResult,\n DeductionSuccess,\n LeaseSuccess,\n ReleaseResult,\n} from \"./types/index.js\";\n\nexport class CreditLeaseWorkflow {\n constructor(\n private readonly store: CreditStore,\n private readonly catalogRuntime: CatalogRuntime,\n private readonly logger: NormalizedLogger,\n private readonly balanceMonitor: LowBalanceMonitor,\n private readonly policy: PolicyPreset,\n private readonly overdraftFloor: Decimal | null,\n private readonly defaultMaxConcurrent: number | null,\n private readonly defaultTtl: number,\n private readonly emit: (type: CreditEventType, userId: string, data?: StructuredObject) => void,\n private readonly emitQuotaEvents: (userId: string, idempotencyKey: string) => Promise<void>,\n private readonly maybeLazyExpire: (userId: string) => Promise<void>,\n private readonly afterDeduction: (userId: string, result: DeductionSuccess) => Promise<void>,\n ) {}\n\n private async expectedAdmissionPolicy(\n userId: string,\n operationType: string,\n billingModeOverride?: BillingMode | null,\n ): Promise<{\n billingMode: BillingMode;\n floor: Decimal;\n maxConcurrent: number | null;\n }> {\n const plan = await this.store.getUserPlan(userId);\n const creditPolicy = plan.planId == null ? null : plan.creditPolicy;\n const planMode: BillingMode =\n plan.planId == null\n ? this.policy === \"overdraft\"\n ? \"overdraft\"\n : \"strict\"\n : creditPolicy?.type === \"credit_line\"\n ? \"overdraft\"\n : \"strict\";\n const operationAdmission =\n plan.planId == null ? null : (plan.admission?.operations[operationType] ?? null);\n const billingMode = billingModeOverride ?? planMode;\n const floor =\n billingMode === \"overdraft\"\n ? (creditPolicy?.creditLimit?.negated() ?? this.overdraftFloor ?? new Decimal(0))\n : new Decimal(0);\n return {\n billingMode,\n floor,\n maxConcurrent:\n plan.planId == null\n ? this.defaultMaxConcurrent\n : (operationAdmission?.maxInFlight ?? plan.admission?.maxInFlight ?? null),\n };\n }\n\n /**\n * Compute the credit cost and model from metrics, or pass a raw amount through.\n *\n * For {@link UsageMetrics} the cost is ``engine.calculate(...).total`` (exact\n * `Decimal`, no truncation); a raw amount is used as-is with no model.\n */\n private async costOf(\n metricsOrAmount: MetricsOrAmount,\n userId?: string | null,\n leaseId?: string | null,\n ): Promise<{ amount: Decimal; model: string | null }> {\n return this.catalogRuntime.costOf(metricsOrAmount, userId, leaseId);\n }\n\n /**\n * Atomically acquire a lease — the only authoritative admission control.\n *\n * Prices the estimate and delegates entitlement, quota, allowance, credit\n * policy, and concurrency enforcement to the database in one atomic call.\n */\n async reserve(\n userId: string,\n metricsOrAmount: MetricsOrAmount,\n options: ReserveOptions,\n ): Promise<LeaseSuccess> {\n rejectNativeCreditAmount(metricsOrAmount);\n const leaseIdempotencyKey = requireStableKey(options?.idempotencyKey);\n await this.maybeLazyExpire(userId);\n this.logger.debug(\"[CreditsService] reserve\", {\n feature: options.feature,\n operationType: options.operationType,\n });\n const operationType =\n options.operationType ?? (isAmount(metricsOrAmount) ? \"usage\" : metricsOrAmount.operation);\n const expectedPolicy = await this.expectedAdmissionPolicy(\n userId,\n operationType,\n options.billingMode,\n );\n const priced = await this.costOf(metricsOrAmount, userId);\n const amount = priced.amount;\n const model = priced.model ?? options.model ?? null;\n const ttlSeconds = options.ttl != null ? options.ttl : this.defaultTtl;\n const feature = options.feature ?? null;\n const measures = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.measures ?? {}) };\n const dimensions = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.dimensions ?? {}) };\n const region = z.string().safeParse(dimensions.region).data ?? null;\n\n const result = await this.store.createLease(userId, amount, operationType, {\n idempotencyKey: leaseIdempotencyKey,\n billingMode: expectedPolicy.billingMode,\n floor: expectedPolicy.floor,\n maxConcurrent: expectedPolicy.maxConcurrent,\n ttlSeconds,\n model,\n metadata: options.metadata,\n feature,\n region,\n measures,\n dimensions,\n });\n\n if (result.error !== null) {\n if (result.error === \"quota_exceeded\") {\n await this.emitQuotaEvents(userId, leaseIdempotencyKey);\n }\n this.emit(\"credits.deduct_failed\", userId, {\n error: result.error,\n amount,\n stage: \"reserve\",\n operationType,\n });\n raiseLeaseError(result.error, userId, amount);\n }\n\n this.logger.info(\"[CreditsService] reservation acquired\", {\n leaseId: result.leaseId,\n amount: result.amount,\n minimumBalance: result.minimumBalance,\n });\n this.emit(\"credits.reserved\", userId, {\n leaseId: result.leaseId,\n amount: result.amount,\n available: result.available,\n minimumBalance: result.minimumBalance,\n operationType,\n expiresAt: result.expiresAt,\n });\n await this.emitQuotaEvents(userId, leaseIdempotencyKey);\n return result;\n }\n\n /**\n * Charge the actual cost against a lease and finalize it.\n *\n * De-clamped: bills the full actual cost even if it exceeds the lease hold\n * (overdraft). Emits ``credits.deducted``, then low-balance and overdraft\n * signals as applicable.\n */\n async settle(\n userId: string,\n leaseId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: SettleOptions,\n ): Promise<DeductionResult> {\n rejectNativeCreditAmount(metricsOrAmount);\n await this.maybeLazyExpire(userId);\n this.logger.debug(\"[CreditsService] settle\", { leaseId });\n const idempotencyKey =\n options?.idempotencyKey === undefined\n ? `lease:${leaseId}:settle`\n : requireStableKey(options.idempotencyKey);\n const feature = options?.feature ?? null;\n const { amount, model } = await this.costOf(metricsOrAmount, userId, leaseId);\n const measures = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.measures ?? {}) };\n const dimensions = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.dimensions ?? {}) };\n const region = z.string().safeParse(dimensions.region).data ?? null;\n\n // Build ledger metadata with caller fields first and protected system fields last.\n const txMeta: CreditMetadata = {};\n if (isAmount(metricsOrAmount)) {\n if (options?.metadata) {\n for (const [k, v] of Object.entries(options.metadata)) {\n if (v != null) txMeta[k] = v;\n }\n }\n if (idempotencyKey) txMeta[\"idempotencyKey\"] = idempotencyKey;\n } else {\n if (options?.metadata) {\n for (const [k, v] of Object.entries(options.metadata)) {\n if (v != null) txMeta[k] = v;\n }\n }\n txMeta[\"operation\"] = metricsOrAmount.operation;\n txMeta[\"measures\"] = { ...(metricsOrAmount.measures ?? {}) };\n txMeta[\"dimensions\"] = { ...(metricsOrAmount.dimensions ?? {}) };\n txMeta[\"breakdownTotal\"] = amount.toString();\n if (idempotencyKey) txMeta[\"idempotencyKey\"] = idempotencyKey;\n }\n\n const result = await this.store.settleLease(userId, leaseId, amount, {\n idempotencyKey,\n feature,\n model,\n region,\n measures,\n dimensions,\n metadata: txMeta,\n });\n\n if (result.error !== null) {\n this.emit(\"credits.deduct_failed\", userId, {\n error: result.error,\n amount,\n stage: \"settle\",\n leaseId,\n });\n if (result.error === \"expired_lease\") {\n this.emit(\"credits.lease_expired\", userId, { leaseId });\n }\n raiseLeaseError(result.error, userId, amount);\n }\n\n this.logger.info(\"[CreditsService] settled\", {\n leaseId,\n amount: result.amount,\n balanceAfter: result.balanceAfter,\n idempotent: result.idempotent,\n });\n this.emit(\"credits.deducted\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n allowanceConsumed: result.allowanceConsumed,\n balanceAfter: result.balanceAfter,\n model,\n leaseId,\n idempotent: result.idempotent,\n });\n\n await this.balanceMonitor.afterCharge(userId, result);\n if (!result.idempotent) {\n await this.emitQuotaEvents(userId, idempotencyKey);\n await this.afterDeduction(userId, result);\n }\n return result;\n }\n\n /** Release a lease without charging; safe to repeat after failed or aborted work. */\n async release(userId: string, leaseId: string): Promise<ReleaseResult> {\n this.logger.debug(\"[CreditsService] release\", { leaseId });\n const result = await this.store.releaseLease(userId, leaseId);\n if (result.released) {\n this.logger.info(\"[CreditsService] lease released\", { leaseId, reason: result.reason });\n this.emit(\"credits.reservation_released\", userId, {\n leaseId,\n reason: result.reason,\n });\n }\n return result;\n }\n\n /** Extend an active lease's expiry without changing its captured policy. */\n async renew(userId: string, leaseId: string, ttl?: number | null): Promise<LeaseSuccess> {\n const ttlSeconds = ttl ?? this.defaultTtl;\n this.logger.debug(\"[CreditsService] renew\", { leaseId, ttlSeconds });\n const result = await this.store.renewLease(userId, leaseId, ttlSeconds);\n if (result.error !== null) {\n if (result.error === \"expired_lease\") {\n this.emit(\"credits.lease_expired\", userId, { leaseId });\n }\n raiseLeaseError(result.error, userId, new Decimal(0));\n }\n return result;\n }\n\n /**\n * Advisory affordability check — UI only, non-locking, and potentially stale.\n *\n * Never use this as an admission gate; only ``reserve`` is authoritative.\n */\n async canAfford(\n userId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: CanAffordOptions,\n ): Promise<CanAffordResult> {\n rejectNativeCreditAmount(metricsOrAmount);\n await this.maybeLazyExpire(userId);\n const feature = options?.feature ?? null;\n const { amount: worstCase } = await this.costOf(metricsOrAmount, userId);\n const avail = await this.store.getAvailable(userId);\n let expectedPolicy;\n try {\n expectedPolicy = await this.expectedAdmissionPolicy(\n userId,\n options?.operationType ?? \"usage\",\n options?.billingMode,\n );\n } catch {\n return {\n affordable: false,\n spendable: avail.available,\n worstCase,\n reason: \"policy_unavailable\",\n };\n }\n let allowanceRemaining = new Decimal(0);\n try {\n allowanceRemaining =\n (await this.store.checkAllowance(userId))?.allowanceRemaining ?? new Decimal(0);\n } catch (error) {\n this.logger.debug(\"[CreditsService] allowance fetch failed in canAfford\", {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n const spendable = avail.available.plus(allowanceRemaining).minus(expectedPolicy.floor);\n\n let affordable = true;\n let reason: string | null = null;\n if (feature != null) {\n const check = await this.store.checkFeature(userId, feature);\n if (!check.hasFeature) {\n affordable = false;\n reason = \"feature_not_entitled\";\n }\n }\n if (affordable && spendable.lt(worstCase)) {\n affordable = false;\n reason = \"insufficient_credits\";\n }\n\n return { affordable, spendable, worstCase, reason };\n }\n\n /** Get a user's per-bucket credit balances (credit buckets). Thin pass-through, no event emission. */\n async getBucketBalances(userId: string): Promise<BucketBalancesResult> {\n await this.maybeLazyExpire(userId);\n return await this.store.getBucketBalances(userId);\n }\n\n /**\n * Get remaining free allowance for the current billing period.\n *\n * Convenience wrapper that routes through the manager so callers never need\n * to reach past it into the raw store. Returns `null` when the subject has no\n * active allowance policy.\n *\n * Window calculation is database-owned and supports the full normalized\n * policy tuple, including timezone and arbitrary interval counts.\n */\n async checkAllowance(userId: string): Promise<AllowanceResult | null> {\n return await this.store.checkAllowance(userId);\n }\n\n /**\n * One-call shortcut wiring reserve → doWork → settle.\n *\n * ``doWork`` runs the operation and returns ``{ result, actual }`` where\n * ``actual`` is the real usage metrics (or amount) to settle. On any exception\n * from ``doWork`` the lease is released and the error re-raised. For long jobs\n * ``doWork`` may call the configured lease TTL. A crash between reserve and settle is\n * covered by the lease TTL (and the store's reaper).\n */\n async runBilled<T>(\n userId: string,\n options: RunBilledOptions<T>,\n ): Promise<{ result: T; deduction: DeductionResult }> {\n const operationKey = requireStableKey(options.operationKey, \"operationKey\");\n const operation = await this.beginBilledOperation(userId, {\n estimate: options.estimate,\n operationKey,\n operationType: options.operationType,\n billingMode: options.billingMode,\n ttl: options.ttl,\n feature: options.feature,\n metadata: options.metadata,\n });\n\n let workResult: T;\n let actual: MetricsOrAmount;\n try {\n ({ result: workResult, actual } = await options.doWork());\n } catch (err) {\n await operation.release();\n throw err;\n }\n\n // Never release after work succeeds. A settlement failure may be a\n // transient/unknown-commit outcome and is safe to replay with operationKey.\n const deduction = await retryBursarOperation(() => operation.settle(actual), {\n maxAttempts: options.settlementAttempts,\n });\n return { result: workResult, deduction };\n }\n\n /**\n * Begin a replay-safe billable operation that can span framework callbacks.\n *\n * The operation key is namespaced into distinct reserve and settle keys, so\n * replaying the whole lifecycle cannot acquire a second hold.\n */\n async beginBilledOperation(\n userId: string,\n options: BeginBilledOperationOptions,\n ): Promise<BilledOperation> {\n const operationKey = requireStableKey(options.operationKey, \"operationKey\");\n const lease = await this.reserve(userId, options.estimate, {\n operationType: options.operationType,\n billingMode: options.billingMode,\n ttl: options.ttl,\n feature: options.feature,\n metadata: options.metadata,\n idempotencyKey: scopedStableKey(operationKey, \"reserve\"),\n });\n return {\n leaseId: lease.leaseId,\n operationKey,\n settle: async (actual, metadata) =>\n this.settle(userId, lease.leaseId, actual, {\n idempotencyKey: scopedStableKey(operationKey, \"settle\"),\n feature: options.feature,\n metadata: metadata ?? options.metadata,\n }),\n renew: async (ttl) => {\n await this.renew(userId, lease.leaseId, ttl);\n },\n release: async () => {\n await this.release(userId, lease.leaseId);\n },\n };\n }\n}\n"]}
@@ -1,9 +1,10 @@
1
- import Decimal from "decimal.js";
1
+ import { Decimal } from "decimal.js";
2
2
  import type { NormalizedLogger } from "../shared/logger.js";
3
+ import type { StructuredObject } from "../shared/json.js";
3
4
  import type { CreditEventType } from "./events.js";
4
5
  import type { DeductionSuccess } from "./types/index.js";
5
6
  import type { LowBalanceConfig } from "./service-types.js";
6
- type EmitCreditEvent = (type: CreditEventType, userId: string, data?: Record<string, unknown>) => void;
7
+ type EmitCreditEvent = (type: CreditEventType, userId: string, data?: StructuredObject) => void;
7
8
  /**
8
9
  * Owns edge-trigger state for low-balance and overdraft notifications.
9
10
  *
@@ -1 +1 @@
1
- {"version":3,"file":"low-balance-monitor.d.ts","sourceRoot":"","sources":["../../src/credits/low-balance-monitor.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AAGjC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OAAO,KAAK,EAAe,eAAe,EAAE,MAAM,aAAa,CAAC;AAChE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,kBAAkB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,kBAAkB,CAAC;AACzD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAK3D,KAAK,eAAe,GAAG,CAAC,IAAI,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,gBAAgB,KAAK,IAAI,CAAC;AAEhG;;;;;GAKG;AACH,qBAAa,iBAAiB;IAO1B,OAAO,CAAC,QAAQ,CAAC,IAAI;IACrB,OAAO,CAAC,QAAQ,CAAC,MAAM;IAPzB,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAmB;IAC9C,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAwD;IAChF,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAgC;gBAG7D,MAAM,EAAE,gBAAgB,GAAG,IAAI,GAAG,SAAS,EAC1B,IAAI,EAAE,eAAe,EACrB,MAAM,EAAE,gBAAgB;IAa3C,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,IAAI;IAalD,WAAW,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC;IAWpE,cAAc,CAClB,MAAM,EAAE,MAAM,EACd,aAAa,EAAE,OAAO,EACtB,YAAY,EAAE,OAAO,GACpB,OAAO,CAAC,IAAI,CAAC;YAkCF,IAAI;CAmBnB"}
@@ -1,4 +1,4 @@
1
- import Decimal from "decimal.js";
1
+ import { Decimal } from "decimal.js";
2
2
  import { LRUCache } from "lru-cache";
3
3
  import { toDecimal } from "./amount.js";
4
4
  const DEFAULT_MAX_TRACKED_USERS = 100_000;
@@ -1 +1 @@
1
- {"version":3,"file":"low-balance-monitor.js","sourceRoot":"","sources":["../../src/credits/low-balance-monitor.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AACjC,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAMrC,OAAO,EAAE,SAAS,EAAE,MA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pC,IAAI,CAAC,IAAI,CAAC,qBAAqB,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;QAC/C,IAAI,CAAC,IAAI,CAAC,OAAO;YAAE,OAAO;QAE1B,IAAI,CAAC;YACH,MAAM,IAAI,CAAC,OAAO,CAAC;gBACjB,IAAI,EAAE,qBAAqB;gBAC3B,SAAS,EAAE,IAAI,IAAI,EAAE;gBACrB,MAAM;gBACN,IAAI;aACL,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,8CAA8C,EAAE;gBAChE,MAAM;gBACN,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;aAC9D,CAAC,CAAC;QACL,CAAC;IACH,CAAC;CACF","sourcesContent":["import Decimal from \"decimal.js\";\nimport { LRUCache } from \"lru-cache\";\n\nimport type { NormalizedLogger } from \"../shared/logger.js\";\nimport type { CreditEvent, CreditEventType } from \"./events.js\";\nimport type { DeductionSuccess } from \"./types/index.js\";\nimport type { LowBalanceConfig } from \"./service-types.js\";\nimport { toDecimal } from \"./amount.js\";\n\nconst DEFAULT_MAX_TRACKED_USERS = 100_000;\n\ntype EmitCreditEvent = (\n type: CreditEventType,\n userId: string,\n data?: Record<string, unknown>,\n) => void;\n\n/**\n * Owns edge-trigger state for low-balance and overdraft notifications.\n *\n * Keeping this state outside CreditsService makes the event semantics\n * independently testable and keeps the service focused on orchestration.\n */\nexport class LowBalanceMonitor {\n private readonly thresholds: Decimal[] | null;\n private readonly handler: ((event: CreditEvent) => void | Promise<void>) | null;\n private readonly breachedByUser: LRUCache<string, Set<string>>;\n\n constructor(\n config: LowBalanceConfig | null | undefined,\n private readonly emit: EmitCreditEvent,\n private readonly logger: NormalizedLogger,\n ) {\n this.thresholds = config?.thresholds?.length\n ? config.thresholds.map(toDecimal).sort((left, right) => right.comparedTo(left))\n : null;\n this.handler = config?.onTrigger ?? null;\n const maxTrackedUsers = config?.maxTrackedUsers ?? DEFAULT_MAX_TRACKED_USERS;\n if (!Number.isSafeInteger(maxTrackedUsers) || maxTrackedUsers < 1) {\n throw new RangeError(\"lowBalance.maxTrackedUsers must be a positive safe integer\");\n }\n this.breachedByUser = new LRUCache({ max: maxTrackedUsers });\n }\n\n rearmAfterCredit(userId: string, balance: Decimal): void {\n if (!this.thresholds) return;\n const breached = this.breachedByUser.get(userId) ?? new Set<string>();\n for (const threshold of this.thresholds) {\n if (balance.gt(threshold)) breached.delete(threshold.toString());\n }\n if (breached.size === 0) {\n this.breachedByUser.delete(userId);\n } else {\n this.breachedByUser.set(userId, breached);\n }\n }\n\n async afterCharge(userId: string, result: DeductionSuccess): Promise<void> {\n if (result.idempotent) return;\n if (result.balanceAfter.lt(0)) {\n this.emit(\"credits.overdraft\", userId, {\n balance: result.balanceAfter,\n amount: result.amount,\n });\n }\n await this.signalCrossing(userId, result.balanceAfter.plus(result.amount), result.balanceAfter);\n }\n\n async signalCrossing(\n userId: string,\n balanceBefore: Decimal,\n balanceAfter: Decimal,\n ): Promise<void> {\n if (!this.thresholds) {\n const threshold = new Decimal(0);\n if (balanceBefore.gt(threshold) && balanceAfter.lte(threshold)) {\n await this.fire(userId, balanceAfter, threshold);\n }\n return;\n }\n\n const breached = this.breachedByUser.get(userId) ?? new Set<string>();\n const newlyCrossed: Decimal[] = [];\n for (const threshold of this.thresholds) {\n if (balanceAfter.lte(threshold)) {\n if (!breached.has(threshold.toString())) {\n breached.add(threshold.toString());\n newlyCrossed.push(threshold);\n }\n } else {\n breached.delete(threshold.toString());\n }\n }\n if (breached.size === 0) {\n this.breachedByUser.delete(userId);\n } else {\n this.breachedByUser.set(userId, breached);\n }\n if (newlyCrossed.length > 0) {\n const lowest = newlyCrossed.reduce((minimum, threshold) =>\n threshold.lt(minimum) ? threshold : minimum,\n );\n await this.fire(userId, balanceAfter, lowest);\n }\n }\n\n private async fire(userId: string, balance: Decimal, threshold: Decimal): Promise<void> {\n const data = { balance, threshold };\n this.emit(\"credits.low_balance\", userId, data);\n if (!this.handler) return;\n\n try {\n await this.handler({\n type: \"credits.low_balance\",\n timestamp: new Date(),\n userId,\n data,\n });\n } catch (error) {\n this.logger.error(\"[CreditsService] onLowBalance handler failed\", {\n userId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n}\n"]}
1
+ {"version":3,"file":"low-balance-monitor.js","sourceRoot":"","sources":["../../src/credits/low-balance-monitor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAOrC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,MAAM,yBAAyB,GAAG,OAAO,CAAC;AAI1C;;;;;GAKG;AACH,MAAM,OAAO,iBAAiB;IAOT;IACA;IAPF,UAAU,CAAmB;IAC7B,OAAO,CAAwD;IAC/D,cAAc,CAAgC;IAE/D,YACE,MAA2C,EAC1B,IAAqB,EACrB,MAAwB;QADxB,SAAI,GAAJ,IAAI,CAAiB;QACrB,WAAM,GAAN,MAAM,CAAkB;QAEzC,IAAI,CAAC,UAAU,GAAG,MAAM,EAAE,UAAU,EAAE,MAAM;YAC1C,CAAC,CAAC,MAAM,CAAC,UAAU,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;YAChF,CAAC,CAAC,IAAI,CAAC;QACT,IAAI,CAAC,OAAO,GAAG,MAAM,EAAE,SAAS,IAAI,IAAI,CAAC;QACzC,MAAM,eAAe,GAAG,MAAM,EAAE,eAAe,IAAI,yBAAyB,CAAC;QAC7E,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,eAAe,CAAC,IAAI,eAAe,GAAG,CAAC,EAAE,CA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C,CAAC;QACD,IAAI,YAAY,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YAC5B,MAAM,MAAM,GAAG,YAAY,CAAC,MAAM,CAAC,CAAC,OAAO,EAAE,SAAS,EAAE,EAAE,CACxD,SAAS,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,OAAO,CAC5C,CAAC;YACF,MAAM,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,CAAC,CAAC;QAChD,CAAC;IACH,CAAC;IAEO,KAAK,CAAC,IAAI,CAAC,MAAc,EAAE,OAAgB,EAAE,SAAkB;QACrE,MAAM,IAAI,GAAG,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC;QACpC,IAAI,CAAC,IAAI,CAAC,qBAAqB,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;QAC/C,IAAI,CAAC,IAAI,CAAC,OAAO;YAAE,OAAO;QAE1B,IAAI,CAAC;YACH,MAAM,IAAI,CAAC,OAAO,CAAC;gBACjB,IAAI,EAAE,qBAAqB;gBAC3B,SAAS,EAAE,IAAI,IAAI,EAAE;gBACrB,MAAM;gBACN,IAAI;aACL,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,8CAA8C,EAAE;gBAChE,MAAM;gBACN,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;aAC9D,CAAC,CAAC;QACL,CAAC;IACH,CAAC;CACF","sourcesContent":["import { Decimal } from \"decimal.js\";\nimport { LRUCache } from \"lru-cache\";\n\nimport type { NormalizedLogger } from \"../shared/logger.js\";\nimport type { StructuredObject } from \"../shared/json.js\";\nimport type { CreditEvent, CreditEventType } from \"./events.js\";\nimport type { DeductionSuccess } from \"./types/index.js\";\nimport type { LowBalanceConfig } from \"./service-types.js\";\nimport { toDecimal } from \"./amount.js\";\n\nconst DEFAULT_MAX_TRACKED_USERS = 100_000;\n\ntype EmitCreditEvent = (type: CreditEventType, userId: string, data?: StructuredObject) => void;\n\n/**\n * Owns edge-trigger state for low-balance and overdraft notifications.\n *\n * Keeping this state outside CreditsService makes the event semantics\n * independently testable and keeps the service focused on orchestration.\n */\nexport class LowBalanceMonitor {\n private readonly thresholds: Decimal[] | null;\n private readonly handler: ((event: CreditEvent) => void | Promise<void>) | null;\n private readonly breachedByUser: LRUCache<string, Set<string>>;\n\n constructor(\n config: LowBalanceConfig | null | undefined,\n private readonly emit: EmitCreditEvent,\n private readonly logger: NormalizedLogger,\n ) {\n this.thresholds = config?.thresholds?.length\n ? config.thresholds.map(toDecimal).sort((left, right) => right.comparedTo(left))\n : null;\n this.handler = config?.onTrigger ?? null;\n const maxTrackedUsers = config?.maxTrackedUsers ?? DEFAULT_MAX_TRACKED_USERS;\n if (!Number.isSafeInteger(maxTrackedUsers) || maxTrackedUsers < 1) {\n throw new RangeError(\"lowBalance.maxTrackedUsers must be a positive safe integer\");\n }\n this.breachedByUser = new LRUCache({ max: maxTrackedUsers });\n }\n\n rearmAfterCredit(userId: string, balance: Decimal): void {\n if (!this.thresholds) return;\n const breached = this.breachedByUser.get(userId) ?? new Set<string>();\n for (const threshold of this.thresholds) {\n if (balance.gt(threshold)) breached.delete(threshold.toString());\n }\n if (breached.size === 0) {\n this.breachedByUser.delete(userId);\n } else {\n this.breachedByUser.set(userId, breached);\n }\n }\n\n async afterCharge(userId: string, result: DeductionSuccess): Promise<void> {\n if (result.idempotent) return;\n if (result.balanceAfter.lt(0)) {\n this.emit(\"credits.overdraft\", userId, {\n balance: result.balanceAfter,\n amount: result.amount,\n });\n }\n await this.signalCrossing(userId, result.balanceAfter.plus(result.amount), result.balanceAfter);\n }\n\n async signalCrossing(\n userId: string,\n balanceBefore: Decimal,\n balanceAfter: Decimal,\n ): Promise<void> {\n if (!this.thresholds) {\n const threshold = new Decimal(0);\n if (balanceBefore.gt(threshold) && balanceAfter.lte(threshold)) {\n await this.fire(userId, balanceAfter, threshold);\n }\n return;\n }\n\n const breached = this.breachedByUser.get(userId) ?? new Set<string>();\n const newlyCrossed: Decimal[] = [];\n for (const threshold of this.thresholds) {\n if (balanceAfter.lte(threshold)) {\n if (!breached.has(threshold.toString())) {\n breached.add(threshold.toString());\n newlyCrossed.push(threshold);\n }\n } else {\n breached.delete(threshold.toString());\n }\n }\n if (breached.size === 0) {\n this.breachedByUser.delete(userId);\n } else {\n this.breachedByUser.set(userId, breached);\n }\n if (newlyCrossed.length > 0) {\n const lowest = newlyCrossed.reduce((minimum, threshold) =>\n threshold.lt(minimum) ? threshold : minimum,\n );\n await this.fire(userId, balanceAfter, lowest);\n }\n }\n\n private async fire(userId: string, balance: Decimal, threshold: Decimal): Promise<void> {\n const data = { balance, threshold };\n this.emit(\"credits.low_balance\", userId, data);\n if (!this.handler) return;\n\n try {\n await this.handler({\n type: \"credits.low_balance\",\n timestamp: new Date(),\n userId,\n data,\n });\n } catch (error) {\n this.logger.error(\"[CreditsService] onLowBalance handler failed\", {\n userId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n}\n"]}
@@ -35,7 +35,7 @@ declare const LedgerEntryRowSchema: z.ZodObject<{
35
35
  operation: z.ZodString;
36
36
  reference_entry_id: z.ZodNullable<z.ZodString>;
37
37
  idempotency_key: z.ZodNullable<z.ZodString>;
38
- metadata: z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
38
+ metadata: z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodJSONSchema>>;
39
39
  created_at: z.ZodUnion<readonly [z.ZodString, z.ZodPipe<z.ZodDate, z.ZodTransform<string, Date>>]>;
40
40
  }, z.core.$strict>;
41
41
  declare const UsageChargeRowSchema: z.ZodObject<{
@@ -55,7 +55,7 @@ declare const UsageChargeRowSchema: z.ZodObject<{
55
55
  region: z.ZodNullable<z.ZodString>;
56
56
  event_at: z.ZodUnion<readonly [z.ZodString, z.ZodPipe<z.ZodDate, z.ZodTransform<string, Date>>]>;
57
57
  idempotency_key: z.ZodString;
58
- metadata: z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
58
+ metadata: z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodJSONSchema>>;
59
59
  created_at: z.ZodUnion<readonly [z.ZodString, z.ZodPipe<z.ZodDate, z.ZodTransform<string, Date>>]>;
60
60
  }, z.core.$strict>;
61
61
  export type SpendByUserRow = z.infer<typeof SpendByUserRowSchema>;