@zonastery/bursar 2.0.3 → 2.0.5

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 (376) hide show
  1. package/README.md +1 -1
  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.map +1 -1
  6. package/dist/billing/auto-recharge-service.js +3 -3
  7. package/dist/billing/auto-recharge-service.js.map +1 -1
  8. package/dist/billing/billing-service.d.ts +3 -2
  9. package/dist/billing/billing-service.d.ts.map +1 -1
  10. package/dist/billing/billing-service.js +2 -10
  11. package/dist/billing/billing-service.js.map +1 -1
  12. package/dist/billing/billing-store.d.ts +6 -6
  13. package/dist/billing/billing-store.d.ts.map +1 -1
  14. package/dist/billing/billing-store.js.map +1 -1
  15. package/dist/billing/contracts.d.ts +8 -7
  16. package/dist/billing/contracts.d.ts.map +1 -1
  17. package/dist/billing/contracts.js.map +1 -1
  18. package/dist/billing/event-handlers.d.ts +5 -9
  19. package/dist/billing/event-handlers.d.ts.map +1 -1
  20. package/dist/billing/event-handlers.js +191 -285
  21. package/dist/billing/event-handlers.js.map +1 -1
  22. package/dist/billing/event-processor.d.ts +1 -1
  23. package/dist/billing/event-processor.d.ts.map +1 -1
  24. package/dist/billing/event-processor.js +32 -23
  25. package/dist/billing/event-processor.js.map +1 -1
  26. package/dist/billing/financial-event-handlers.d.ts +3 -9
  27. package/dist/billing/financial-event-handlers.d.ts.map +1 -1
  28. package/dist/billing/financial-event-handlers.js +10 -12
  29. package/dist/billing/financial-event-handlers.js.map +1 -1
  30. package/dist/billing/index.d.ts +1 -1
  31. package/dist/billing/index.d.ts.map +1 -1
  32. package/dist/billing/index.js.map +1 -1
  33. package/dist/billing/management.d.ts +3 -2
  34. package/dist/billing/management.d.ts.map +1 -1
  35. package/dist/billing/management.js.map +1 -1
  36. package/dist/billing/policy-window.js.map +1 -1
  37. package/dist/billing/postgres/repositories/auto-recharge.d.ts +2 -1
  38. package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -1
  39. package/dist/billing/postgres/repositories/auto-recharge.js +58 -40
  40. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
  41. package/dist/billing/postgres/repositories/customer.d.ts.map +1 -1
  42. package/dist/billing/postgres/repositories/customer.js.map +1 -1
  43. package/dist/billing/postgres/repositories/dispute.d.ts +2 -1
  44. package/dist/billing/postgres/repositories/dispute.d.ts.map +1 -1
  45. package/dist/billing/postgres/repositories/dispute.js.map +1 -1
  46. package/dist/billing/postgres/repositories/event.d.ts +2 -2
  47. package/dist/billing/postgres/repositories/event.d.ts.map +1 -1
  48. package/dist/billing/postgres/repositories/event.js.map +1 -1
  49. package/dist/billing/postgres/repositories/invoice.d.ts +2 -1
  50. package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -1
  51. package/dist/billing/postgres/repositories/invoice.js +8 -12
  52. package/dist/billing/postgres/repositories/invoice.js.map +1 -1
  53. package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
  54. package/dist/billing/postgres/repositories/offer.js +5 -0
  55. package/dist/billing/postgres/repositories/offer.js.map +1 -1
  56. package/dist/billing/postgres/repositories/payment.d.ts +4 -4
  57. package/dist/billing/postgres/repositories/payment.d.ts.map +1 -1
  58. package/dist/billing/postgres/repositories/payment.js +1 -1
  59. package/dist/billing/postgres/repositories/payment.js.map +1 -1
  60. package/dist/billing/postgres/repositories/preferences.d.ts.map +1 -1
  61. package/dist/billing/postgres/repositories/preferences.js.map +1 -1
  62. package/dist/billing/postgres/repositories/refund.d.ts.map +1 -1
  63. package/dist/billing/postgres/repositories/refund.js.map +1 -1
  64. package/dist/billing/postgres/repositories/subscription-change.d.ts.map +1 -1
  65. package/dist/billing/postgres/repositories/subscription-change.js +1 -9
  66. package/dist/billing/postgres/repositories/subscription-change.js.map +1 -1
  67. package/dist/billing/postgres/repositories/subscription.d.ts +11 -11
  68. package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -1
  69. package/dist/billing/postgres/repositories/subscription.js +29 -30
  70. package/dist/billing/postgres/repositories/subscription.js.map +1 -1
  71. package/dist/billing/postgres/repositories/topup.d.ts +1 -1
  72. package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
  73. package/dist/billing/postgres/repositories/topup.js.map +1 -1
  74. package/dist/billing/postgres/store.d.ts +6 -5
  75. package/dist/billing/postgres/store.d.ts.map +1 -1
  76. package/dist/billing/postgres/store.js +15 -13
  77. package/dist/billing/postgres/store.js.map +1 -1
  78. package/dist/billing/types/auto-recharge.d.ts +2 -1
  79. package/dist/billing/types/auto-recharge.d.ts.map +1 -1
  80. package/dist/billing/types/auto-recharge.js.map +1 -1
  81. package/dist/billing/types/documents.d.ts +2 -1
  82. package/dist/billing/types/documents.d.ts.map +1 -1
  83. package/dist/billing/types/documents.js.map +1 -1
  84. package/dist/billing/types/events.d.ts +3 -2
  85. package/dist/billing/types/events.d.ts.map +1 -1
  86. package/dist/billing/types/events.js +73 -39
  87. package/dist/billing/types/events.js.map +1 -1
  88. package/dist/billing/types/subscriptions.d.ts +4 -1
  89. package/dist/billing/types/subscriptions.d.ts.map +1 -1
  90. package/dist/billing/types/subscriptions.js.map +1 -1
  91. package/dist/breakdown.d.ts +3 -2
  92. package/dist/breakdown.d.ts.map +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/errors.d.ts.map +1 -1
  101. package/dist/commerce/errors.js.map +1 -1
  102. package/dist/commerce/provider-registry.d.ts.map +1 -1
  103. package/dist/commerce/provider-registry.js +11 -6
  104. package/dist/commerce/provider-registry.js.map +1 -1
  105. package/dist/commerce/service.d.ts +1 -1
  106. package/dist/commerce/service.d.ts.map +1 -1
  107. package/dist/commerce/service.js +16 -22
  108. package/dist/commerce/service.js.map +1 -1
  109. package/dist/commerce/types.d.ts.map +1 -1
  110. package/dist/commerce/types.js.map +1 -1
  111. package/dist/config/parse-access.d.ts +5 -2
  112. package/dist/config/parse-access.d.ts.map +1 -1
  113. package/dist/config/parse-access.js +60 -41
  114. package/dist/config/parse-access.js.map +1 -1
  115. package/dist/config/parse-commerce.d.ts +2 -1
  116. package/dist/config/parse-commerce.d.ts.map +1 -1
  117. package/dist/config/parse-commerce.js +49 -29
  118. package/dist/config/parse-commerce.js.map +1 -1
  119. package/dist/config/parse-credits.d.ts +2 -1
  120. package/dist/config/parse-credits.d.ts.map +1 -1
  121. package/dist/config/parse-credits.js +39 -23
  122. package/dist/config/parse-credits.js.map +1 -1
  123. package/dist/config/parse-plans.d.ts +7 -2
  124. package/dist/config/parse-plans.d.ts.map +1 -1
  125. package/dist/config/parse-plans.js +49 -22
  126. package/dist/config/parse-plans.js.map +1 -1
  127. package/dist/config/parse-pricing.d.ts +2 -1
  128. package/dist/config/parse-pricing.d.ts.map +1 -1
  129. package/dist/config/parse-pricing.js +41 -31
  130. package/dist/config/parse-pricing.js.map +1 -1
  131. package/dist/config/parse-utils.d.ts +15 -11
  132. package/dist/config/parse-utils.d.ts.map +1 -1
  133. package/dist/config/parse-utils.js +90 -27
  134. package/dist/config/parse-utils.js.map +1 -1
  135. package/dist/config/types.d.ts.map +1 -1
  136. package/dist/config/types.js.map +1 -1
  137. package/dist/config.d.ts +6 -5
  138. package/dist/config.d.ts.map +1 -1
  139. package/dist/config.js +65 -35
  140. package/dist/config.js.map +1 -1
  141. package/dist/credits/amount.d.ts +1 -1
  142. package/dist/credits/amount.d.ts.map +1 -1
  143. package/dist/credits/amount.js +5 -4
  144. package/dist/credits/amount.js.map +1 -1
  145. package/dist/credits/catalog-runtime.d.ts.map +1 -1
  146. package/dist/credits/catalog-runtime.js +2 -3
  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 +2 -1
  153. package/dist/credits/lease-workflow.d.ts.map +1 -1
  154. package/dist/credits/lease-workflow.js +3 -2
  155. package/dist/credits/lease-workflow.js.map +1 -1
  156. package/dist/credits/low-balance-monitor.d.ts +2 -1
  157. package/dist/credits/low-balance-monitor.d.ts.map +1 -1
  158. package/dist/credits/low-balance-monitor.js.map +1 -1
  159. package/dist/credits/postgres/repositories/analytics.d.ts +2 -2
  160. package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -1
  161. package/dist/credits/postgres/repositories/analytics.js +14 -6
  162. package/dist/credits/postgres/repositories/analytics.js.map +1 -1
  163. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
  164. package/dist/credits/postgres/repositories/balance.js +6 -6
  165. package/dist/credits/postgres/repositories/balance.js.map +1 -1
  166. package/dist/credits/postgres/repositories/bucket.d.ts.map +1 -1
  167. package/dist/credits/postgres/repositories/bucket.js.map +1 -1
  168. package/dist/credits/postgres/repositories/catalog.d.ts +5 -4
  169. package/dist/credits/postgres/repositories/catalog.d.ts.map +1 -1
  170. package/dist/credits/postgres/repositories/catalog.js +4 -3
  171. package/dist/credits/postgres/repositories/catalog.js.map +1 -1
  172. package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -1
  173. package/dist/credits/postgres/repositories/deduction.js +2 -2
  174. package/dist/credits/postgres/repositories/deduction.js.map +1 -1
  175. package/dist/credits/postgres/repositories/lease.d.ts +2 -2
  176. package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
  177. package/dist/credits/postgres/repositories/lease.js.map +1 -1
  178. package/dist/credits/postgres/repositories/plan.d.ts +11 -11
  179. package/dist/credits/postgres/repositories/plan.d.ts.map +1 -1
  180. package/dist/credits/postgres/repositories/plan.js.map +1 -1
  181. package/dist/credits/postgres/repositories/team.d.ts +2 -2
  182. package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
  183. package/dist/credits/postgres/repositories/team.js.map +1 -1
  184. package/dist/credits/postgres/store.d.ts +3 -2
  185. package/dist/credits/postgres/store.d.ts.map +1 -1
  186. package/dist/credits/postgres/store.js +17 -10
  187. package/dist/credits/postgres/store.js.map +1 -1
  188. package/dist/credits/postgres/value-mappers.d.ts +4 -3
  189. package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
  190. package/dist/credits/postgres/value-mappers.js +10 -11
  191. package/dist/credits/postgres/value-mappers.js.map +1 -1
  192. package/dist/credits/queries.d.ts.map +1 -1
  193. package/dist/credits/queries.js.map +1 -1
  194. package/dist/credits/service.d.ts.map +1 -1
  195. package/dist/credits/service.js +10 -5
  196. package/dist/credits/service.js.map +1 -1
  197. package/dist/credits/store.d.ts +5 -4
  198. package/dist/credits/store.d.ts.map +1 -1
  199. package/dist/credits/store.js.map +1 -1
  200. package/dist/credits/types/account.d.ts +5 -4
  201. package/dist/credits/types/account.d.ts.map +1 -1
  202. package/dist/credits/types/account.js.map +1 -1
  203. package/dist/credits/types/catalog.d.ts +2 -1
  204. package/dist/credits/types/catalog.d.ts.map +1 -1
  205. package/dist/credits/types/catalog.js.map +1 -1
  206. package/dist/credits/types/grants.d.ts.map +1 -1
  207. package/dist/credits/types/grants.js.map +1 -1
  208. package/dist/credits/types/ledger.d.ts +3 -2
  209. package/dist/credits/types/ledger.d.ts.map +1 -1
  210. package/dist/credits/types/ledger.js.map +1 -1
  211. package/dist/engine.d.ts +2 -2
  212. package/dist/engine.d.ts.map +1 -1
  213. package/dist/engine.js +39 -10
  214. package/dist/engine.js.map +1 -1
  215. package/dist/errors.d.ts +7 -4
  216. package/dist/errors.d.ts.map +1 -1
  217. package/dist/errors.js +18 -11
  218. package/dist/errors.js.map +1 -1
  219. package/dist/expr/ast.d.ts.map +1 -1
  220. package/dist/expr/ast.js.map +1 -1
  221. package/dist/expr/evaluator.js.map +1 -1
  222. package/dist/expr/parser.d.ts.map +1 -1
  223. package/dist/expr/parser.js.map +1 -1
  224. package/dist/expr/tokenizer.d.ts.map +1 -1
  225. package/dist/expr/tokenizer.js +34 -12
  226. package/dist/expr/tokenizer.js.map +1 -1
  227. package/dist/expr.d.ts.map +1 -1
  228. package/dist/expr.js +12 -6
  229. package/dist/expr.js.map +1 -1
  230. package/dist/generated/pricing-config.schema.json +0 -12
  231. package/dist/generated/pricing-config.types.d.ts +2 -8
  232. package/dist/generated/pricing-config.types.d.ts.map +1 -1
  233. package/dist/generated/pricing-config.types.js.map +1 -1
  234. package/dist/integrations/better-auth.d.ts +4 -1
  235. package/dist/integrations/better-auth.d.ts.map +1 -1
  236. package/dist/integrations/better-auth.js +7 -4
  237. package/dist/integrations/better-auth.js.map +1 -1
  238. package/dist/load-config-file.d.ts +2 -1
  239. package/dist/load-config-file.d.ts.map +1 -1
  240. package/dist/load-config-file.js +19 -13
  241. package/dist/load-config-file.js.map +1 -1
  242. package/dist/metrics.d.ts +2 -1
  243. package/dist/metrics.d.ts.map +1 -1
  244. package/dist/metrics.js.map +1 -1
  245. package/dist/node.d.ts +1 -1
  246. package/dist/node.d.ts.map +1 -1
  247. package/dist/node.js.map +1 -1
  248. package/dist/providers/_shared.d.ts +8 -5
  249. package/dist/providers/_shared.d.ts.map +1 -1
  250. package/dist/providers/_shared.js +15 -11
  251. package/dist/providers/_shared.js.map +1 -1
  252. package/dist/providers/dodo/better-auth-core.d.ts +30 -0
  253. package/dist/providers/dodo/better-auth-core.d.ts.map +1 -0
  254. package/dist/providers/dodo/better-auth-core.js +14 -0
  255. package/dist/providers/dodo/better-auth-core.js.map +1 -0
  256. package/dist/providers/dodo/better-auth.d.ts +5 -9
  257. package/dist/providers/dodo/better-auth.d.ts.map +1 -1
  258. package/dist/providers/dodo/better-auth.js +16 -13
  259. package/dist/providers/dodo/better-auth.js.map +1 -1
  260. package/dist/providers/dodo/client-contract.d.ts +12 -10
  261. package/dist/providers/dodo/client-contract.d.ts.map +1 -1
  262. package/dist/providers/dodo/client-contract.js.map +1 -1
  263. package/dist/providers/dodo/event-mapper.d.ts +7 -4
  264. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  265. package/dist/providers/dodo/event-mapper.js +121 -113
  266. package/dist/providers/dodo/event-mapper.js.map +1 -1
  267. package/dist/providers/dodo/nextjs-core.d.ts +22 -0
  268. package/dist/providers/dodo/nextjs-core.d.ts.map +1 -0
  269. package/dist/providers/dodo/nextjs-core.js +14 -0
  270. package/dist/providers/dodo/nextjs-core.js.map +1 -0
  271. package/dist/providers/dodo/nextjs.d.ts +5 -7
  272. package/dist/providers/dodo/nextjs.d.ts.map +1 -1
  273. package/dist/providers/dodo/nextjs.js +11 -10
  274. package/dist/providers/dodo/nextjs.js.map +1 -1
  275. package/dist/providers/dodo/provider.d.ts +3 -3
  276. package/dist/providers/dodo/provider.d.ts.map +1 -1
  277. package/dist/providers/dodo/provider.js +42 -35
  278. package/dist/providers/dodo/provider.js.map +1 -1
  279. package/dist/providers/dodo/react-native-core.d.ts +56 -0
  280. package/dist/providers/dodo/react-native-core.d.ts.map +1 -0
  281. package/dist/providers/dodo/react-native-core.js +56 -0
  282. package/dist/providers/dodo/react-native-core.js.map +1 -0
  283. package/dist/providers/dodo/react-native.d.ts +6 -50
  284. package/dist/providers/dodo/react-native.d.ts.map +1 -1
  285. package/dist/providers/dodo/react-native.js +5 -49
  286. package/dist/providers/dodo/react-native.js.map +1 -1
  287. package/dist/providers/dodo/webhook-bridge.d.ts +4 -2
  288. package/dist/providers/dodo/webhook-bridge.d.ts.map +1 -1
  289. package/dist/providers/dodo/webhook-bridge.js.map +1 -1
  290. package/dist/providers/environment.d.ts +1 -1
  291. package/dist/providers/environment.d.ts.map +1 -1
  292. package/dist/providers/environment.js +4 -2
  293. package/dist/providers/environment.js.map +1 -1
  294. package/dist/providers/mock/provider.d.ts.map +1 -1
  295. package/dist/providers/mock/provider.js +5 -10
  296. package/dist/providers/mock/provider.js.map +1 -1
  297. package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
  298. package/dist/providers/stripe/event-mapper.js +33 -9
  299. package/dist/providers/stripe/event-mapper.js.map +1 -1
  300. package/dist/providers/stripe/provider.d.ts.map +1 -1
  301. package/dist/providers/stripe/provider.js +101 -61
  302. package/dist/providers/stripe/provider.js.map +1 -1
  303. package/dist/providers/types.d.ts.map +1 -1
  304. package/dist/providers/types.js.map +1 -1
  305. package/dist/retry.d.ts.map +1 -1
  306. package/dist/retry.js +16 -9
  307. package/dist/retry.js.map +1 -1
  308. package/dist/shared/diagnostics.d.ts +5 -5
  309. package/dist/shared/diagnostics.d.ts.map +1 -1
  310. package/dist/shared/diagnostics.js +32 -22
  311. package/dist/shared/diagnostics.js.map +1 -1
  312. package/dist/shared/idempotency.d.ts +4 -3
  313. package/dist/shared/idempotency.d.ts.map +1 -1
  314. package/dist/shared/idempotency.js +21 -10
  315. package/dist/shared/idempotency.js.map +1 -1
  316. package/dist/shared/json.d.ts +28 -0
  317. package/dist/shared/json.d.ts.map +1 -0
  318. package/dist/shared/json.js +41 -0
  319. package/dist/shared/json.js.map +1 -0
  320. package/dist/shared/logger.d.ts +10 -4
  321. package/dist/shared/logger.d.ts.map +1 -1
  322. package/dist/shared/logger.js +28 -4
  323. package/dist/shared/logger.js.map +1 -1
  324. package/dist/shared/postgres-client.d.ts +8 -6
  325. package/dist/shared/postgres-client.d.ts.map +1 -1
  326. package/dist/shared/postgres-client.js +69 -47
  327. package/dist/shared/postgres-client.js.map +1 -1
  328. package/dist/shared/postgres-errors.d.ts +1 -1
  329. package/dist/shared/postgres-errors.d.ts.map +1 -1
  330. package/dist/shared/postgres-errors.js +32 -31
  331. package/dist/shared/postgres-errors.js.map +1 -1
  332. package/dist/shared/postgres-types.d.ts +3 -2
  333. package/dist/shared/postgres-types.d.ts.map +1 -1
  334. package/dist/shared/postgres-types.js.map +1 -1
  335. package/dist/shared/postgres-validation.d.ts +7 -6
  336. package/dist/shared/postgres-validation.d.ts.map +1 -1
  337. package/dist/shared/postgres-validation.js +17 -10
  338. package/dist/shared/postgres-validation.js.map +1 -1
  339. package/dist/storage/adapters/clickhouse.d.ts +11 -4
  340. package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
  341. package/dist/storage/adapters/clickhouse.js +8 -6
  342. package/dist/storage/adapters/clickhouse.js.map +1 -1
  343. package/dist/storage/adapters/s3.d.ts +28 -5
  344. package/dist/storage/adapters/s3.d.ts.map +1 -1
  345. package/dist/storage/adapters/s3.js +48 -33
  346. package/dist/storage/adapters/s3.js.map +1 -1
  347. package/dist/storage/diagnostics.d.ts +1 -1
  348. package/dist/storage/diagnostics.d.ts.map +1 -1
  349. package/dist/storage/diagnostics.js +13 -12
  350. package/dist/storage/diagnostics.js.map +1 -1
  351. package/dist/storage/maintenance.d.ts.map +1 -1
  352. package/dist/storage/maintenance.js +31 -25
  353. package/dist/storage/maintenance.js.map +1 -1
  354. package/dist/storage/outbox-worker.d.ts +1 -1
  355. package/dist/storage/outbox-worker.d.ts.map +1 -1
  356. package/dist/storage/outbox-worker.js +18 -18
  357. package/dist/storage/outbox-worker.js.map +1 -1
  358. package/dist/storage/ports.d.ts +10 -7
  359. package/dist/storage/ports.d.ts.map +1 -1
  360. package/dist/storage/ports.js.map +1 -1
  361. package/dist/storage/postgres-repository.d.ts +3 -1
  362. package/dist/storage/postgres-repository.d.ts.map +1 -1
  363. package/dist/storage/postgres-repository.js +10 -4
  364. package/dist/storage/postgres-repository.js.map +1 -1
  365. package/dist/storage/runtime.d.ts +1 -1
  366. package/dist/storage/runtime.d.ts.map +1 -1
  367. package/dist/storage/runtime.js +165 -182
  368. package/dist/storage/runtime.js.map +1 -1
  369. package/dist/telemetry/index.d.ts +10 -6
  370. package/dist/telemetry/index.d.ts.map +1 -1
  371. package/dist/telemetry/index.js +26 -23
  372. package/dist/telemetry/index.js.map +1 -1
  373. package/dist/telemetry/opentelemetry.d.ts.map +1 -1
  374. package/dist/telemetry/opentelemetry.js +3 -3
  375. package/dist/telemetry/opentelemetry.js.map +1 -1
  376. package/package.json +40 -40
@@ -1 +1 @@
1
- {"version":3,"file":"lease.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/lease.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAEpD,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,UAAU,EACV,SAAS,GACV,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAEjD,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,CAAU,CAAC,CAAC;AAC3E,MAAM,SAAS,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,EAAE,CAAU,CAAC,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE;IAC7F,MAAM,MAAM,GAAG,KAAK,YAAY,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC;IAC/D,IAAI,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC,EAAE,CAAC;QACnC,OAAO,CAAC,QAAQ,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,4BAA4B,EAAE,CAAC,CAAC;QAC5E,OAAO,CAAC,CAAC,KAAK,CAAC;IACjB,CAAC;IACD,OAA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AG,iBAAiB,CAC7B,MAAM,IAAI,CAAC,QAAQ,CAAC,kBAAkB,EAAE,CAAC,MAAM,EAAE,GAAG,CAAC,QAAQ,CAAC,CAAC,EAC/D,oCAAoC,CACrC,CAAC;QACF,OAAO,SAAS,CACd,cAAc,EACd;YACE,QAAQ,EAAE,GAAG,CAAC,QAAQ;YACtB,OAAO,EAAE,MAAM;YACf,MAAM,EAAE,GAAG,CAAC,eAAe;YAC3B,UAAU,EAAE,KAAK,EAAE,UAAU;YAC7B,eAAe,EAAE,KAAK,EAAE,eAAe;YACvC,KAAK,EAAE,IAAI;SACZ,EACD,4BAA4B,CAC7B,CAAC;IACJ,CAAC;IAED,uEAAuE;IACvE,KAAK,CAAC,YAAY,CAAC,KAAa;QAC9B,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,eAAe,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;QAC3D,MAAM,GAAG,GAAG,SAAS,CACnB,CAAC,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,EAC9D,UAAU,CAAC,IAAI,EAAE,8BAA8B,CAAC,EAChD,8BAA8B,CAC/B,CAAC;QACF,OAAO,GAAG,CAAC,OAAO,CAAC;IACrB,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport { DeductionRowSchema } from \"./deduction.js\";\nimport type { DeductionRow } from \"./deduction.js\";\nimport {\n optionalRecordRow,\n postgresUuid,\n requireRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\nimport { StoreError } from \"../../../errors.js\";\nimport { Decimal } from \"decimal.js\";\nimport { quantizeMoney } from \"../../../expr.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\nconst timestamp = z.union([z.string().min(1), z.date()] as const).transform((value, context) => {\n const parsed = value instanceof Date ? value : new Date(value);\n if (Number.isNaN(parsed.getTime())) {\n context.addIssue({ code: \"custom\", message: \"expected a valid timestamp\" });\n return z.NEVER;\n }\n return parsed.toISOString();\n});\nconst safeInteger = z\n .union([z.number().int(), z.string().regex(/^\\d+$/)] as const)\n .transform(Number)\n .refine(Number.isSafeInteger, \"expected a safe integer\");\nconst leaseStatus = z.enum([\"active\", \"settling\", \"settled\", \"released\", \"expired\"]);\n\nconst LeaseMutationRpcRowSchema = z\n .object({\n lease_id: postgresUuid.nullable(),\n status: leaseStatus,\n reserved_amount: decimal,\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error_code === null && (row.lease_id === null || row.status !== \"active\")) {\n context.addIssue({\n code: \"custom\",\n message: \"successful lease mutations require an active lease\",\n });\n }\n });\n\nconst SettleLeaseRpcRowSchema = z\n .object({\n ledger_entry_id: postgresUuid.nullable(),\n charge_id: postgresUuid.nullable(),\n settled_amount: decimal,\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error_code === null && row.charge_id === null) {\n context.addIssue({\n code: \"custom\",\n message: \"successful lease settlement requires a charge receipt\",\n });\n }\n if (\n row.error_code !== null &&\n (row.ledger_entry_id !== null || row.charge_id !== null || row.replayed)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed lease settlement cannot expose committed fields\",\n });\n }\n });\n\nconst LeaseRowSchema = z\n .object({\n lease_id: postgresUuid.nullable(),\n user_id: postgresUuid,\n amount: decimal.nullable(),\n minimum_balance: decimal.nullable(),\n expires_at: timestamp.nullable(),\n error: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (\n row.error === null &&\n (row.lease_id === null ||\n row.amount === null ||\n row.minimum_balance === null ||\n row.expires_at === null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"successful lease acquisition requires lease and policy fields\",\n });\n }\n if (\n row.error !== null &&\n (row.lease_id !== null ||\n row.amount !== null ||\n row.minimum_balance !== null ||\n row.expires_at !== null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed lease mutations cannot expose committed fields\",\n });\n }\n });\n\nconst ReleaseRowSchema = z\n .object({\n released: z.boolean(),\n reason: leaseStatus.or(z.literal(\"missing_lease\")).nullable(),\n })\n .strict();\n\nconst LeasePricingContextRowSchema = z\n .object({\n catalog_revision_no: safeInteger,\n plan_id: postgresUuid.nullable(),\n plan_key: z.string().min(1).nullable(),\n rate_card: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if ((row.plan_id === null) !== (row.plan_key === null)) {\n context.addIssue({ code: \"custom\", message: \"lease plan identity fields are inconsistent\" });\n }\n });\n\nexport type LeaseRow = z.infer<typeof LeaseRowSchema>;\nexport type ReleaseRow = z.infer<typeof ReleaseRowSchema>;\nexport type LeasePricingContextRow = z.infer<typeof LeasePricingContextRowSchema>;\n\n/** Repository for lease lifecycle operations (admission control). */\nexport class LeaseRepository {\n constructor(private callproc: CallProc) {}\n\n /** Atomically acquire a lease (hold) — admission control. */\n async createLease(params: {\n userId: string;\n amount: string;\n operationType: string;\n idempotencyKey: string;\n ttlSeconds: number;\n metadata: string;\n feature: string | null;\n measures: string;\n dimensions: string;\n minimumBalance: string | null;\n maxConcurrent: number | null;\n }): Promise<LeaseRow> {\n const rows = await this.callproc(\"create_lease_for_operation\", [\n params.userId,\n params.operationType,\n params.amount,\n params.idempotencyKey,\n `${params.ttlSeconds} seconds`,\n params.metadata,\n params.feature,\n params.measures,\n params.dimensions,\n params.minimumBalance,\n params.maxConcurrent,\n ]);\n const row = safeParse(\n LeaseMutationRpcRowSchema,\n requireRow(rows, \"LeaseRepository.createLease\"),\n \"LeaseRepository.createLease\",\n );\n if (row.error_code !== null) {\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: null,\n user_id: params.userId,\n amount: null,\n expires_at: null,\n minimum_balance: null,\n error: row.error_code,\n },\n \"LeaseRepository.createLease\",\n );\n }\n const lease = optionalRecordRow(\n await this.callproc(\"get_credit_lease\", [params.userId, row.lease_id]),\n \"LeaseRepository.createLease.details\",\n );\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: row.lease_id,\n user_id: params.userId,\n amount: row.reserved_amount,\n expires_at: lease?.expires_at,\n minimum_balance: lease?.minimum_balance,\n error: null,\n },\n \"LeaseRepository.createLease\",\n );\n }\n\n /** Charge the actual cost against a lease and mark it settled. */\n async settleLease(params: {\n userId: string;\n leaseId: string;\n amount: string;\n idempotencyKey: string;\n feature: string | null;\n model: string | null;\n region: string | null;\n measures: string;\n dimensions: string;\n metadata: string;\n }): Promise<DeductionRow> {\n const rows = await this.callproc(\"settle_lease\", [\n params.userId,\n params.leaseId,\n params.amount,\n params.idempotencyKey,\n params.feature,\n params.model,\n params.region,\n params.measures,\n params.dimensions,\n params.metadata,\n ]);\n const row = safeParse(\n SettleLeaseRpcRowSchema,\n requireRow(rows, \"LeaseRepository.settleLease\"),\n \"LeaseRepository.settleLease\",\n );\n if (\n row.error_code === null &&\n !new Decimal(row.settled_amount).equals(quantizeMoney(new Decimal(params.amount)))\n ) {\n throw new StoreError(\n \"LeaseRepository.settleLease: committed amount differs from the request\",\n {\n indeterminate: true,\n },\n );\n }\n const charge =\n row.error_code == null\n ? optionalRecordRow(\n await this.callproc(\"get_credit_operation_details\", [\n params.userId,\n row.ledger_entry_id ?? null,\n params.idempotencyKey,\n ]),\n \"LeaseRepository.settleLease.details\",\n )\n : null;\n return safeParse(\n DeductionRowSchema,\n {\n charge_id: row.charge_id,\n user_id: params.userId,\n entry_id: row.ledger_entry_id,\n amount: row.error_code === null ? row.settled_amount : params.amount,\n allowance_consumed: row.error_code === null ? charge?.allowance_covered : \"0\",\n balance_after: row.error_code === null ? charge?.balance_after : null,\n bucket_breakdown: row.error_code === null ? charge?.bucket_breakdown : null,\n idempotent: row.replayed,\n error: row.error_code,\n },\n \"LeaseRepository.settleLease\",\n );\n }\n\n /** Return the immutable pricing context captured at lease admission. */\n async getPricingContext(userId: string, leaseId: string): Promise<LeasePricingContextRow | null> {\n const rows = await this.callproc(\"get_credit_lease_pricing_context\", [userId, leaseId]);\n const row = optionalRecordRow(rows, \"LeaseRepository.getPricingContext\");\n return row === null\n ? null\n : safeParse(LeasePricingContextRowSchema, row, \"LeaseRepository.getPricingContext\");\n }\n\n /** Release a lease without charging — idempotent. */\n async releaseLease(userId: string, leaseId: string): Promise<ReleaseRow> {\n const rows = await this.callproc(\"release_lease\", [userId, leaseId]);\n const status = safeParse(\n leaseStatus.or(z.literal(\"missing_lease\")),\n requireRow(rows, \"LeaseRepository.releaseLease\"),\n \"LeaseRepository.releaseLease\",\n );\n return safeParse(\n ReleaseRowSchema,\n {\n released: status === \"released\",\n reason: status === \"released\" ? null : status,\n },\n \"LeaseRepository.releaseLease\",\n );\n }\n\n /** Extend an active lease without changing its captured policy snapshot. */\n async renewLease(userId: string, leaseId: string, ttlSeconds: number): Promise<LeaseRow> {\n const rows = await this.callproc(\"renew_lease\", [userId, leaseId, `${ttlSeconds} seconds`]);\n const row = safeParse(\n LeaseMutationRpcRowSchema,\n requireRow(rows, \"LeaseRepository.renewLease\"),\n \"LeaseRepository.renewLease\",\n );\n if (row.error_code !== null) {\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: null,\n user_id: userId,\n amount: null,\n expires_at: null,\n minimum_balance: null,\n error: row.error_code,\n },\n \"LeaseRepository.renewLease\",\n );\n }\n const lease = optionalRecordRow(\n await this.callproc(\"get_credit_lease\", [userId, row.lease_id]),\n \"LeaseRepository.renewLease.details\",\n );\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: row.lease_id,\n user_id: userId,\n amount: row.reserved_amount,\n expires_at: lease?.expires_at,\n minimum_balance: lease?.minimum_balance,\n error: null,\n },\n \"LeaseRepository.renewLease\",\n );\n }\n\n /** Expire a bounded batch of leases and release their reservations. */\n async expireLeases(limit: number): Promise<number> {\n const rows = await this.callproc(\"expire_leases\", [limit]);\n const row = safeParse(\n z.object({ expired: z.number().int().nonnegative() }).strict(),\n requireRow(rows, \"LeaseRepository.expireLeases\"),\n \"LeaseRepository.expireLeases\",\n );\n return row.expired;\n }\n}\n"]}
1
+ {"version":3,"file":"lease.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/lease.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAEpD,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,UAAU,EACV,SAAS,GACV,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAEjD,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,CAAU,CAAC,CAAC;AAC3E,MAAM,SAAS,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,EAAE,CAAU,CAAC,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE;IAC7F,MAAM,MAAM,GAAG,KAAK,YAAY,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC;IAC/D,IAAI,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC,EAAE,CAAC;QACnC,OAAO,CAAC,QAAQ,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,4BAA4B,EAAE,CAAC,CAAC;QAC5E,OAAO,CAAC,CAAC,KAAK,CA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MAAM,KAAK,GAAG,iBAAiB,CAC7B,MAAM,IAAI,CAAC,QAAQ,CAAC,kBAAkB,EAAE,CAAC,MAAM,EAAE,GAAG,CAAC,QAAQ,CAAC,CAAC,EAC/D,oCAAoC,CACrC,CAAC;QACF,OAAO,SAAS,CACd,cAAc,EACd;YACE,QAAQ,EAAE,GAAG,CAAC,QAAQ;YACtB,OAAO,EAAE,MAAM;YACf,MAAM,EAAE,GAAG,CAAC,eAAe;YAC3B,UAAU,EAAE,KAAK,EAAE,UAAU;YAC7B,eAAe,EAAE,KAAK,EAAE,eAAe;YACvC,KAAK,EAAE,IAAI;SACZ,EACD,4BAA4B,CAC7B,CAAC;IACJ,CAAC;IAED,uEAAuE;IACvE,KAAK,CAAC,YAAY,CAAC,KAAa;QAC9B,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,eAAe,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;QAC3D,MAAM,GAAG,GAAG,SAAS,CACnB,CAAC,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,EAC9D,UAAU,CAAC,IAAI,EAAE,8BAA8B,CAAC,EAChD,8BAA8B,CAC/B,CAAC;QACF,OAAO,GAAG,CAAC,OAAO,CAAC;IACrB,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport { DeductionRowSchema } from \"./deduction.js\";\nimport type { DeductionRow } from \"./deduction.js\";\nimport {\n optionalRecordRow,\n postgresUuid,\n requireRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\nimport { StoreError } from \"../../../errors.js\";\nimport { Decimal } from \"decimal.js\";\nimport { quantizeMoney } from \"../../../expr.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\nconst timestamp = z.union([z.string().min(1), z.date()] as const).transform((value, context) => {\n const parsed = value instanceof Date ? value : new Date(value);\n if (Number.isNaN(parsed.getTime())) {\n context.addIssue({ code: \"custom\", message: \"expected a valid timestamp\" });\n return z.NEVER;\n }\n return parsed.toISOString();\n});\nconst safeInteger = z\n .union([z.number().int(), z.string().regex(/^\\d+$/)] as const)\n .transform(Number)\n .refine(Number.isSafeInteger, \"expected a safe integer\");\nconst leaseStatus = z.enum([\"active\", \"settling\", \"settled\", \"released\", \"expired\"]);\n\nconst LeaseMutationRpcRowSchema = z\n .object({\n lease_id: postgresUuid.nullable(),\n status: leaseStatus,\n reserved_amount: decimal,\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error_code === null && (row.lease_id === null || row.status !== \"active\")) {\n context.addIssue({\n code: \"custom\",\n message: \"successful lease mutations require an active lease\",\n });\n }\n });\n\nconst SettleLeaseRpcRowSchema = z\n .object({\n ledger_entry_id: postgresUuid.nullable(),\n charge_id: postgresUuid.nullable(),\n settled_amount: decimal,\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error_code === null && row.charge_id === null) {\n context.addIssue({\n code: \"custom\",\n message: \"successful lease settlement requires a charge receipt\",\n });\n }\n if (\n row.error_code !== null &&\n (row.ledger_entry_id !== null || row.charge_id !== null || row.replayed)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed lease settlement cannot expose committed fields\",\n });\n }\n });\n\nconst LeaseRowSchema = z\n .object({\n lease_id: postgresUuid.nullable(),\n user_id: postgresUuid,\n amount: decimal.nullable(),\n minimum_balance: decimal.nullable(),\n expires_at: timestamp.nullable(),\n error: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if (\n row.error === null &&\n (row.lease_id === null ||\n row.amount === null ||\n row.minimum_balance === null ||\n row.expires_at === null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"successful lease acquisition requires lease and policy fields\",\n });\n }\n if (\n row.error !== null &&\n (row.lease_id !== null ||\n row.amount !== null ||\n row.minimum_balance !== null ||\n row.expires_at !== null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"failed lease mutations cannot expose committed fields\",\n });\n }\n });\n\nconst ReleaseRowSchema = z\n .object({\n released: z.boolean(),\n reason: leaseStatus.or(z.literal(\"missing_lease\")).nullable(),\n })\n .strict();\n\nconst LeasePricingContextRowSchema = z\n .object({\n catalog_revision_no: safeInteger,\n plan_id: postgresUuid.nullable(),\n plan_key: z.string().min(1).nullable(),\n rate_card: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n if ((row.plan_id === null) !== (row.plan_key === null)) {\n context.addIssue({ code: \"custom\", message: \"lease plan identity fields are inconsistent\" });\n }\n });\n\nexport type LeaseRow = z.infer<typeof LeaseRowSchema>;\nexport type ReleaseRow = z.infer<typeof ReleaseRowSchema>;\nexport type LeasePricingContextRow = z.infer<typeof LeasePricingContextRowSchema>;\n\n/** Repository for lease lifecycle operations (admission control). */\nexport class LeaseRepository {\n constructor(private callproc: CallProc) {}\n\n /** Atomically acquire a lease (hold) — admission control. */\n async createLease(params: {\n userId: string;\n amount: string;\n operationType: string;\n idempotencyKey: string;\n ttlSeconds: number;\n metadata: string;\n feature: string | null;\n measures: string;\n dimensions: string;\n minimumBalance: string | null;\n maxConcurrent: number | null;\n }): Promise<LeaseRow> {\n const rows = await this.callproc(\"create_lease_for_operation\", [\n params.userId,\n params.operationType,\n params.amount,\n params.idempotencyKey,\n `${params.ttlSeconds} seconds`,\n params.metadata,\n params.feature,\n params.measures,\n params.dimensions,\n params.minimumBalance,\n params.maxConcurrent,\n ]);\n const row = safeParse(\n LeaseMutationRpcRowSchema,\n requireRow(rows, \"LeaseRepository.createLease\"),\n \"LeaseRepository.createLease\",\n );\n if (row.error_code !== null) {\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: null,\n user_id: params.userId,\n amount: null,\n expires_at: null,\n minimum_balance: null,\n error: row.error_code,\n },\n \"LeaseRepository.createLease\",\n );\n }\n const lease = optionalRecordRow(\n await this.callproc(\"get_credit_lease\", [params.userId, row.lease_id]),\n \"LeaseRepository.createLease.details\",\n );\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: row.lease_id,\n user_id: params.userId,\n amount: row.reserved_amount,\n expires_at: lease?.expires_at,\n minimum_balance: lease?.minimum_balance,\n error: null,\n },\n \"LeaseRepository.createLease\",\n );\n }\n\n /** Charge the actual cost against a lease and mark it settled. */\n async settleLease(params: {\n userId: string;\n leaseId: string;\n amount: string;\n idempotencyKey: string;\n feature: string | null;\n model: string | null;\n region: string | null;\n measures: string;\n dimensions: string;\n metadata: string;\n }): Promise<DeductionRow> {\n const rows = await this.callproc(\"settle_lease\", [\n params.userId,\n params.leaseId,\n params.amount,\n params.idempotencyKey,\n params.feature,\n params.model,\n params.region,\n params.measures,\n params.dimensions,\n params.metadata,\n ]);\n const row = safeParse(\n SettleLeaseRpcRowSchema,\n requireRow(rows, \"LeaseRepository.settleLease\"),\n \"LeaseRepository.settleLease\",\n );\n if (\n row.error_code === null &&\n !new Decimal(row.settled_amount).equals(quantizeMoney(new Decimal(params.amount)))\n ) {\n throw new StoreError(\n \"LeaseRepository.settleLease: committed amount differs from the request\",\n {\n indeterminate: true,\n },\n );\n }\n const charge =\n row.error_code == null\n ? optionalRecordRow(\n await this.callproc(\"get_credit_operation_details\", [\n params.userId,\n row.ledger_entry_id ?? null,\n params.idempotencyKey,\n ]),\n \"LeaseRepository.settleLease.details\",\n )\n : null;\n return safeParse(\n DeductionRowSchema,\n {\n charge_id: row.charge_id,\n user_id: params.userId,\n entry_id: row.ledger_entry_id,\n amount: row.error_code === null ? row.settled_amount : params.amount,\n allowance_consumed: row.error_code === null ? charge?.allowance_covered : \"0\",\n balance_after: row.error_code === null ? charge?.balance_after : null,\n bucket_breakdown: row.error_code === null ? charge?.bucket_breakdown : null,\n idempotent: row.replayed,\n error: row.error_code,\n },\n \"LeaseRepository.settleLease\",\n );\n }\n\n /** Return the immutable pricing context captured at lease admission. */\n async getPricingContext(userId: string, leaseId: string): Promise<LeasePricingContextRow | null> {\n const rows = await this.callproc(\"get_credit_lease_pricing_context\", [userId, leaseId]);\n const row = optionalRecordRow(rows, \"LeaseRepository.getPricingContext\");\n return row === null\n ? null\n : safeParse(LeasePricingContextRowSchema, row, \"LeaseRepository.getPricingContext\");\n }\n\n /** Release a lease without charging — idempotent. */\n async releaseLease(userId: string, leaseId: string): Promise<ReleaseRow> {\n const rows = await this.callproc(\"release_lease\", [userId, leaseId]);\n const status = safeParse(\n leaseStatus.or(z.literal(\"missing_lease\")),\n requireRow(rows, \"LeaseRepository.releaseLease\"),\n \"LeaseRepository.releaseLease\",\n );\n return safeParse(\n ReleaseRowSchema,\n {\n released: status === \"released\",\n reason: status === \"released\" ? null : status,\n },\n \"LeaseRepository.releaseLease\",\n );\n }\n\n /** Extend an active lease without changing its captured policy snapshot. */\n async renewLease(userId: string, leaseId: string, ttlSeconds: number): Promise<LeaseRow> {\n const rows = await this.callproc(\"renew_lease\", [userId, leaseId, `${ttlSeconds} seconds`]);\n const row = safeParse(\n LeaseMutationRpcRowSchema,\n requireRow(rows, \"LeaseRepository.renewLease\"),\n \"LeaseRepository.renewLease\",\n );\n if (row.error_code !== null) {\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: null,\n user_id: userId,\n amount: null,\n expires_at: null,\n minimum_balance: null,\n error: row.error_code,\n },\n \"LeaseRepository.renewLease\",\n );\n }\n const lease = optionalRecordRow(\n await this.callproc(\"get_credit_lease\", [userId, row.lease_id]),\n \"LeaseRepository.renewLease.details\",\n );\n return safeParse(\n LeaseRowSchema,\n {\n lease_id: row.lease_id,\n user_id: userId,\n amount: row.reserved_amount,\n expires_at: lease?.expires_at,\n minimum_balance: lease?.minimum_balance,\n error: null,\n },\n \"LeaseRepository.renewLease\",\n );\n }\n\n /** Expire a bounded batch of leases and release their reservations. */\n async expireLeases(limit: number): Promise<number> {\n const rows = await this.callproc(\"expire_leases\", [limit]);\n const row = safeParse(\n z.object({ expired: z.number().int().nonnegative() }).strict(),\n requireRow(rows, \"LeaseRepository.expireLeases\"),\n \"LeaseRepository.expireLeases\",\n );\n return row.expired;\n }\n}\n"]}
@@ -5,9 +5,9 @@ declare const UserPlanRowSchema: z.ZodObject<{
5
5
  plan_assigned_at: z.ZodPipe<z.ZodUnion<readonly [z.ZodString, z.ZodDate]>, z.ZodTransform<Date, string | Date>>;
6
6
  plan_assignment_ends_at: z.ZodNullable<z.ZodPipe<z.ZodUnion<readonly [z.ZodString, z.ZodDate]>, z.ZodTransform<Date, string | Date>>>;
7
7
  assignment_source_type: z.ZodEnum<{
8
- subscription: "subscription";
9
8
  manual: "manual";
10
9
  migration: "migration";
10
+ subscription: "subscription";
11
11
  system: "system";
12
12
  }>;
13
13
  assignment_source_id: z.ZodNullable<z.ZodString>;
@@ -21,26 +21,26 @@ declare const UserPlanRowSchema: z.ZodObject<{
21
21
  credit_allowance_priority: z.ZodNullable<z.ZodNumber>;
22
22
  credit_allowance_reset_unit: z.ZodNullable<z.ZodEnum<{
23
23
  day: "day";
24
- week: "week";
24
+ hour: "hour";
25
+ minute: "minute";
25
26
  month: "month";
26
- year: "year";
27
27
  second: "second";
28
- minute: "minute";
29
- hour: "hour";
28
+ week: "week";
29
+ year: "year";
30
30
  }>>;
31
31
  credit_allowance_reset_count: z.ZodNullable<z.ZodNumber>;
32
32
  credit_allowance_reset_anchor: z.ZodNullable<z.ZodEnum<{
33
33
  calendar: "calendar";
34
- rolling: "rolling";
35
34
  plan_assignment: "plan_assignment";
35
+ rolling: "rolling";
36
36
  }>>;
37
37
  credit_allowance_reset_timezone: z.ZodNullable<z.ZodString>;
38
38
  entitlements: z.ZodRecord<z.ZodString, z.ZodObject<{
39
39
  value: z.ZodJSONSchema;
40
40
  }, z.core.$strict>>;
41
41
  credit_policy_type: z.ZodNullable<z.ZodEnum<{
42
- prepaid: "prepaid";
43
42
  credit_line: "credit_line";
43
+ prepaid: "prepaid";
44
44
  }>>;
45
45
  credit_limit: z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
46
46
  admission_max_in_flight: z.ZodNullable<z.ZodNumber>;
@@ -55,17 +55,17 @@ declare const SetUserPlanRowSchema: z.ZodObject<{
55
55
  plan_key: z.ZodString;
56
56
  plan_assigned_at: z.ZodPipe<z.ZodUnion<readonly [z.ZodString, z.ZodDate]>, z.ZodTransform<Date, string | Date>>;
57
57
  assignment_state: z.ZodEnum<{
58
- scheduled: "scheduled";
59
58
  applied: "applied";
59
+ scheduled: "scheduled";
60
60
  }>;
61
61
  }, z.core.$strict>;
62
62
  declare const EntitlementRowSchema: z.ZodObject<{
63
63
  feature_key: z.ZodString;
64
64
  feature_type: z.ZodEnum<{
65
- string: "string";
66
65
  boolean: "boolean";
67
66
  enum: "enum";
68
67
  integer: "integer";
68
+ string: "string";
69
69
  }>;
70
70
  feature_value: z.ZodJSONSchema;
71
71
  catalog_revision_id: z.ZodString;
@@ -101,8 +101,8 @@ declare const QuotaStateRowSchema: z.ZodObject<{
101
101
  remaining: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
102
102
  overage: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
103
103
  enforcement: z.ZodEnum<{
104
- block: "block";
105
104
  allow: "allow";
105
+ block: "block";
106
106
  }>;
107
107
  window_start: z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodString, z.ZodDate]>, z.ZodTransform<Date, string | Date>>, z.ZodTransform<string, Date>>;
108
108
  window_end: z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodString, z.ZodDate]>, z.ZodTransform<Date, string | Date>>, z.ZodTransform<string, Date>>;
@@ -114,8 +114,8 @@ declare const QuotaEventRowSchema: z.ZodObject<{
114
114
  operation_key: z.ZodString;
115
115
  measure_key: z.ZodString;
116
116
  event_type: z.ZodEnum<{
117
- threshold: "threshold";
118
117
  blocked: "blocked";
118
+ threshold: "threshold";
119
119
  }>;
120
120
  threshold_percent: z.ZodNullable<z.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AAE,+BAA+B,CAAC,CAAC;IAC1E,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport {\n optionalRecordRow,\n postgresUuid,\n requireRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\nimport { StoreError } from \"../../../errors.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\nconst timestamp = z.union([z.string().min(1), z.date()] as const).transform((value, context) => {\n const parsed = value instanceof Date ? value : new Date(value);\n if (Number.isNaN(parsed.getTime())) {\n context.addIssue({ code: \"custom\", message: \"expected a valid timestamp\" });\n return z.NEVER;\n }\n return parsed;\n});\nconst safeInteger = z\n .union([z.number().int(), z.string().regex(/^\\d+$/)] as const)\n .transform(Number)\n .refine(Number.isSafeInteger, \"expected a safe integer\");\nconst entitlementValue = z.object({ value: z.json() }).strict();\nconst admissionOperation = z\n .object({ max_in_flight: z.number().int().positive().nullable() })\n .strict();\n\nconst UserPlanRowSchema = z\n .object({\n user_id: postgresUuid,\n plan_assigned_at: timestamp,\n plan_assignment_ends_at: timestamp.nullable(),\n assignment_source_type: z.enum([\"manual\", \"subscription\", \"migration\", \"system\"]),\n assignment_source_id: postgresUuid.nullable(),\n catalog_revision_pinned: z.boolean(),\n plan_id: postgresUuid,\n plan_key: z.string().min(1),\n plan_label: z.string().min(1),\n rate_card: z.string().min(1).nullable(),\n allowed_operations: z.array(z.string().min(1)),\n credit_allowance_amount: decimal.nullable(),\n credit_allowance_priority: z.number().int().nonnegative().nullable(),\n credit_allowance_reset_unit: z\n .enum([\"second\", \"minute\", \"hour\", \"day\", \"week\", \"month\", \"year\"])\n .nullable(),\n credit_allowance_reset_count: z.number().int().positive().nullable(),\n credit_allowance_reset_anchor: z.enum([\"calendar\", \"plan_assignment\", \"rolling\"]).nullable(),\n credit_allowance_reset_timezone: z.string().min(1).nullable(),\n entitlements: z.record(z.string().min(1), entitlementValue),\n credit_policy_type: z.enum([\"prepaid\", \"credit_line\"]).nullable(),\n credit_limit: decimal.nullable(),\n admission_max_in_flight: z.number().int().positive().nullable(),\n operation_admission: z.record(z.string().min(1), admissionOperation),\n catalog_revision_no: safeInteger,\n })\n .strict()\n .superRefine((row, context) => {\n const allowance = [\n row.credit_allowance_amount,\n row.credit_allowance_priority,\n row.credit_allowance_reset_unit,\n row.credit_allowance_reset_count,\n row.credit_allowance_reset_anchor,\n row.credit_allowance_reset_timezone,\n ];\n const populated = allowance.filter((value) => value !== null).length;\n if (populated !== 0 && populated !== allowance.length) {\n context.addIssue({\n code: \"custom\",\n message: \"allowance policy fields must be all set or all null\",\n });\n }\n if (\n (row.credit_policy_type === null && row.credit_limit !== null) ||\n (row.credit_policy_type === \"prepaid\" && row.credit_limit !== null) ||\n (row.credit_policy_type === \"credit_line\" && row.credit_limit === null)\n ) {\n context.addIssue({ code: \"custom\", message: \"credit policy fields are inconsistent\" });\n }\n });\n\nconst SetUserPlanRowSchema = z\n .object({\n user_id: postgresUuid,\n plan_id: postgresUuid,\n plan_key: z.string().min(1),\n plan_assigned_at: timestamp,\n assignment_state: z.enum([\"applied\", \"scheduled\"]),\n })\n .strict();\n\nconst EntitlementRowSchema = z\n .object({\n feature_key: z.string().min(1),\n feature_type: z.enum([\"boolean\", \"integer\", \"string\", \"enum\"]),\n feature_value: z.json(),\n catalog_revision_id: postgresUuid,\n plan_key: z.string().min(1).nullable(),\n value_source: z.enum([\"default\", \"plan\"]),\n })\n .strict();\n\nconst AllowanceRowSchema = z\n .object({\n plan_id: postgresUuid,\n allowance_remaining: decimal,\n period_start: timestamp.transform((value) => value.toISOString()),\n period_end: timestamp.transform((value) => value.toISOString()),\n })\n .strict();\n\nconst UnsetPlanRowSchema = z\n .object({\n user_id: postgresUuid,\n })\n .strict();\n\nconst PlanMigrationStartRowSchema = postgresUuid;\nconst PlanMigrationBatchRowSchema = z\n .object({\n migrated: z.number().int().nonnegative(),\n done: z.boolean(),\n next_cursor: postgresUuid.nullable(),\n })\n .strict();\nconst QuotaStateRowSchema = z\n .object({\n user_id: postgresUuid,\n quota_key: z.string().min(1),\n operation_key: z.string().min(1),\n measure_key: z.string().min(1),\n quota_limit: decimal,\n consumed: decimal,\n reserved: decimal,\n remaining: decimal,\n overage: decimal,\n enforcement: z.enum([\"block\", \"allow\"]),\n window_start: timestamp.transform((value) => value.toISOString()),\n window_end: timestamp.transform((value) => value.toISOString()),\n emit_at_percent: z.array(z.number().finite().min(0).max(100)),\n })\n .strict();\nconst QuotaEventRowSchema = z\n .object({\n event_id: postgresUuid,\n quota_key: z.string().min(1),\n operation_key: z.string().min(1),\n measure_key: z.string().min(1),\n event_type: z.enum([\"threshold\", \"blocked\"]),\n threshold_percent: z.number().finite().min(0).max(100).nullable(),\n idempotency_key: z.string().min(1),\n usage_charge_id: postgresUuid.nullable(),\n created_at: timestamp.transform((value) => value.toISOString()),\n })\n .strict();\n\nexport type UnsetPlanRow = z.infer<typeof UnsetPlanRowSchema>;\nexport type UserPlanRow = z.infer<typeof UserPlanRowSchema>;\nexport type SetUserPlanRow = z.infer<typeof SetUserPlanRowSchema>;\nexport type EntitlementRow = z.infer<typeof EntitlementRowSchema>;\nexport type AllowanceRow = z.infer<typeof AllowanceRowSchema>;\nexport type PlanMigrationStartRow = z.infer<typeof PlanMigrationStartRowSchema>;\nexport type PlanMigrationBatchRow = z.infer<typeof PlanMigrationBatchRowSchema>;\nexport type QuotaStateRow = z.infer<typeof QuotaStateRowSchema>;\nexport type QuotaEventRow = z.infer<typeof QuotaEventRowSchema>;\n\n/** Repository for plan management operations. */\nexport class PlanRepository {\n constructor(private callproc: CallProc) {}\n\n /** Fetch a user's current plan. Returns null if user has no plan. */\n async getUserPlan(userId: string): Promise<UserPlanRow | null> {\n const rows = await this.callproc(\"get_subject_plan\", [userId]);\n const row = optionalRecordRow(rows, \"PlanRepository.getUserPlan\");\n return row === null ? null : safeParse(UserPlanRowSchema, row, \"PlanRepository.getUserPlan\");\n }\n\n async getEntitlement(userId: string, feature: string): Promise<EntitlementRow | null> {\n const rows = await this.callproc(\"get_subject_entitlements\", [userId]);\n const entitlements = (rows ?? []).map((row) =>\n safeParse(EntitlementRowSchema, row, \"PlanRepository.getEntitlement\"),\n );\n return entitlements.find((candidate) => candidate.feature_key === feature) ?? null;\n }\n\n /** Assign a plan to a user. */\n async setUserPlan(\n userId: string,\n planKey: string,\n planAssignedAt: string | null,\n ): Promise<SetUserPlanRow> {\n return safeParse(\n SetUserPlanRowSchema,\n requireRow(\n await this.callproc(\"set_subject_plan\", [userId, planKey, planAssignedAt]),\n \"PlanRepository.setUserPlan\",\n ),\n \"PlanRepository.setUserPlan\",\n );\n }\n\n /** Remove a user's plan assignment. */\n async unsetUserPlan(userId: string): Promise<UnsetPlanRow> {\n const rows = await this.callproc(\"unassign_plan\", [userId, \"sdk_unassignment\"]);\n if (\n !safeParse(\n z.boolean(),\n requireRow(rows, \"PlanRepository.unsetUserPlan\"),\n \"PlanRepository.unsetUserPlan\",\n )\n ) {\n throw new StoreError(\"PlanRepository.unsetUserPlan: unassign_plan returned false\");\n }\n return safeParse(UnsetPlanRowSchema, { user_id: userId }, \"PlanRepository.unsetUserPlan\");\n }\n\n /** Pin or unpin the user's current assignment to its catalog revision. */\n async setPlanRevisionPin(userId: string, pinned: boolean): Promise<boolean> {\n const rows = await this.callproc(\"set_plan_revision_pin\", [userId, pinned]);\n return safeParse(\n z.boolean(),\n requireRow(rows, \"PlanRepository.setPlanRevisionPin\"),\n \"PlanRepository.setPlanRevisionPin\",\n );\n }\n\n /** Apply one bounded batch of renewal-effective plan changes. */\n async applyDuePlanChanges(limit: number): Promise<number> {\n const rows = await this.callproc(\"apply_due_plan_assignment_changes\", [limit]);\n return safeParse(\n z.number().int().nonnegative(),\n requireRow(rows, \"PlanRepository.applyDuePlanChanges\"),\n \"PlanRepository.applyDuePlanChanges\",\n );\n }\n\n /** Check a user's remaining free allowance. */\n async startPlanMigration(\n fromPlanId: string | null,\n toPlanId: string,\n ): Promise<PlanMigrationStartRow> {\n const rows = await this.callproc(\"start_plan_migration\", [fromPlanId, toPlanId]);\n return safeParse(\n PlanMigrationStartRowSchema,\n requireRow(rows, \"PlanRepository.startPlanMigration\"),\n \"PlanRepository.startPlanMigration\",\n );\n }\n\n async migratePlanBatch(migrationId: string, batchSize?: number): Promise<PlanMigrationBatchRow> {\n const rows = await this.callproc(\"migrate_plan_batch\", [migrationId, batchSize ?? 100]);\n return safeParse(\n PlanMigrationBatchRowSchema,\n requireRow(rows, \"PlanRepository.migratePlanBatch\"),\n \"PlanRepository.migratePlanBatch\",\n );\n }\n\n async getQuotaState(userId: string, quotaKey?: string | null): Promise<QuotaStateRow[]> {\n const rows = await this.callproc(\"get_subject_quota_state\", [userId, quotaKey ?? null]);\n return (rows ?? []).map((row) =>\n safeParse(QuotaStateRowSchema, row, \"PlanRepository.getQuotaState\"),\n );\n }\n\n async listQuotaEvents(\n userId: string,\n after: string | null,\n limit: number,\n idempotencyKey: string | null,\n afterId: string | null,\n ): Promise<QuotaEventRow[]> {\n const rows = await this.callproc(\"list_subject_quota_events\", [\n userId,\n after,\n limit,\n idempotencyKey,\n afterId,\n ]);\n return (rows ?? []).map((row) =>\n safeParse(QuotaEventRowSchema, row, \"PlanRepository.listQuotaEvents\"),\n );\n }\n\n async checkAllowance(userId: string): Promise<AllowanceRow | null> {\n const rows = await this.callproc(\"get_subject_allowance\", [userId]);\n const row = optionalRecordRow(rows, \"PlanRepository.checkAllowance\");\n return row === null\n ? null\n : safeParse(AllowanceRowSchema, row, \"PlanRepository.checkAllowance\");\n }\n}\n"]}
1
+ {"version":3,"file":"plan.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/plan.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,UAAU,EACV,SAAS,GACV,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAEhD,MAAM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AAC,QAAQ,CAAC,uBAAuB,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;QACpE,MAAM,GAAG,GAAG,iBAAiB,CAAC,IAAI,EAAE,+BAA+B,CAAC,CAAC;QACrE,OAAO,GAAG,KAAK,IAAI;YACjB,CAAC,CAAC,IAAI;YACN,CAAC,CAAC,SAAS,CAAC,kBAAkB,EAAE,GAAG,EAAE,+BAA+B,CAAC,CAAC;IAC1E,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport {\n optionalRecordRow,\n postgresUuid,\n requireRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\nimport { StoreError } from \"../../../errors.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\nconst timestamp = z.union([z.string().min(1), z.date()] as const).transform((value, context) => {\n const parsed = value instanceof Date ? value : new Date(value);\n if (Number.isNaN(parsed.getTime())) {\n context.addIssue({ code: \"custom\", message: \"expected a valid timestamp\" });\n return z.NEVER;\n }\n return parsed;\n});\nconst safeInteger = z\n .union([z.number().int(), z.string().regex(/^\\d+$/)] as const)\n .transform(Number)\n .refine(Number.isSafeInteger, \"expected a safe integer\");\nconst entitlementValue = z.object({ value: z.json() }).strict();\nconst admissionOperation = z\n .object({ max_in_flight: z.number().int().positive().nullable() })\n .strict();\n\nconst UserPlanRowSchema = z\n .object({\n user_id: postgresUuid,\n plan_assigned_at: timestamp,\n plan_assignment_ends_at: timestamp.nullable(),\n assignment_source_type: z.enum([\"manual\", \"subscription\", \"migration\", \"system\"]),\n assignment_source_id: postgresUuid.nullable(),\n catalog_revision_pinned: z.boolean(),\n plan_id: postgresUuid,\n plan_key: z.string().min(1),\n plan_label: z.string().min(1),\n rate_card: z.string().min(1).nullable(),\n allowed_operations: z.array(z.string().min(1)),\n credit_allowance_amount: decimal.nullable(),\n credit_allowance_priority: z.number().int().nonnegative().nullable(),\n credit_allowance_reset_unit: z\n .enum([\"second\", \"minute\", \"hour\", \"day\", \"week\", \"month\", \"year\"])\n .nullable(),\n credit_allowance_reset_count: z.number().int().positive().nullable(),\n credit_allowance_reset_anchor: z.enum([\"calendar\", \"plan_assignment\", \"rolling\"]).nullable(),\n credit_allowance_reset_timezone: z.string().min(1).nullable(),\n entitlements: z.record(z.string().min(1), entitlementValue),\n credit_policy_type: z.enum([\"prepaid\", \"credit_line\"]).nullable(),\n credit_limit: decimal.nullable(),\n admission_max_in_flight: z.number().int().positive().nullable(),\n operation_admission: z.record(z.string().min(1), admissionOperation),\n catalog_revision_no: safeInteger,\n })\n .strict()\n .superRefine((row, context) => {\n const allowance = [\n row.credit_allowance_amount,\n row.credit_allowance_priority,\n row.credit_allowance_reset_unit,\n row.credit_allowance_reset_count,\n row.credit_allowance_reset_anchor,\n row.credit_allowance_reset_timezone,\n ];\n const populated = allowance.filter((value) => value !== null).length;\n if (populated !== 0 && populated !== allowance.length) {\n context.addIssue({\n code: \"custom\",\n message: \"allowance policy fields must be all set or all null\",\n });\n }\n if (\n (row.credit_policy_type === null && row.credit_limit !== null) ||\n (row.credit_policy_type === \"prepaid\" && row.credit_limit !== null) ||\n (row.credit_policy_type === \"credit_line\" && row.credit_limit === null)\n ) {\n context.addIssue({ code: \"custom\", message: \"credit policy fields are inconsistent\" });\n }\n });\n\nconst SetUserPlanRowSchema = z\n .object({\n user_id: postgresUuid,\n plan_id: postgresUuid,\n plan_key: z.string().min(1),\n plan_assigned_at: timestamp,\n assignment_state: z.enum([\"applied\", \"scheduled\"]),\n })\n .strict();\n\nconst EntitlementRowSchema = z\n .object({\n feature_key: z.string().min(1),\n feature_type: z.enum([\"boolean\", \"integer\", \"string\", \"enum\"]),\n feature_value: z.json(),\n catalog_revision_id: postgresUuid,\n plan_key: z.string().min(1).nullable(),\n value_source: z.enum([\"default\", \"plan\"]),\n })\n .strict();\n\nconst AllowanceRowSchema = z\n .object({\n plan_id: postgresUuid,\n allowance_remaining: decimal,\n period_start: timestamp.transform((value) => value.toISOString()),\n period_end: timestamp.transform((value) => value.toISOString()),\n })\n .strict();\n\nconst UnsetPlanRowSchema = z\n .object({\n user_id: postgresUuid,\n })\n .strict();\n\nconst PlanMigrationStartRowSchema = postgresUuid;\nconst PlanMigrationBatchRowSchema = z\n .object({\n migrated: z.number().int().nonnegative(),\n done: z.boolean(),\n next_cursor: postgresUuid.nullable(),\n })\n .strict();\nconst QuotaStateRowSchema = z\n .object({\n user_id: postgresUuid,\n quota_key: z.string().min(1),\n operation_key: z.string().min(1),\n measure_key: z.string().min(1),\n quota_limit: decimal,\n consumed: decimal,\n reserved: decimal,\n remaining: decimal,\n overage: decimal,\n enforcement: z.enum([\"block\", \"allow\"]),\n window_start: timestamp.transform((value) => value.toISOString()),\n window_end: timestamp.transform((value) => value.toISOString()),\n emit_at_percent: z.array(z.number().finite().min(0).max(100)),\n })\n .strict();\nconst QuotaEventRowSchema = z\n .object({\n event_id: postgresUuid,\n quota_key: z.string().min(1),\n operation_key: z.string().min(1),\n measure_key: z.string().min(1),\n event_type: z.enum([\"threshold\", \"blocked\"]),\n threshold_percent: z.number().finite().min(0).max(100).nullable(),\n idempotency_key: z.string().min(1),\n usage_charge_id: postgresUuid.nullable(),\n created_at: timestamp.transform((value) => value.toISOString()),\n })\n .strict();\n\nexport type UnsetPlanRow = z.infer<typeof UnsetPlanRowSchema>;\nexport type UserPlanRow = z.infer<typeof UserPlanRowSchema>;\nexport type SetUserPlanRow = z.infer<typeof SetUserPlanRowSchema>;\nexport type EntitlementRow = z.infer<typeof EntitlementRowSchema>;\nexport type AllowanceRow = z.infer<typeof AllowanceRowSchema>;\nexport type PlanMigrationStartRow = z.infer<typeof PlanMigrationStartRowSchema>;\nexport type PlanMigrationBatchRow = z.infer<typeof PlanMigrationBatchRowSchema>;\nexport type QuotaStateRow = z.infer<typeof QuotaStateRowSchema>;\nexport type QuotaEventRow = z.infer<typeof QuotaEventRowSchema>;\n\n/** Repository for plan management operations. */\nexport class PlanRepository {\n constructor(private callproc: CallProc) {}\n\n /** Fetch a user's current plan. Returns null if user has no plan. */\n async getUserPlan(userId: string): Promise<UserPlanRow | null> {\n const rows = await this.callproc(\"get_subject_plan\", [userId]);\n const row = optionalRecordRow(rows, \"PlanRepository.getUserPlan\");\n return row === null ? null : safeParse(UserPlanRowSchema, row, \"PlanRepository.getUserPlan\");\n }\n\n async getEntitlement(userId: string, feature: string): Promise<EntitlementRow | null> {\n const rows = await this.callproc(\"get_subject_entitlements\", [userId]);\n const entitlements = (rows ?? []).map((row) =>\n safeParse(EntitlementRowSchema, row, \"PlanRepository.getEntitlement\"),\n );\n return entitlements.find((candidate) => candidate.feature_key === feature) ?? null;\n }\n\n /** Assign a plan to a user. */\n async setUserPlan(\n userId: string,\n planKey: string,\n planAssignedAt: string | null,\n ): Promise<SetUserPlanRow> {\n return safeParse(\n SetUserPlanRowSchema,\n requireRow(\n await this.callproc(\"set_subject_plan\", [userId, planKey, planAssignedAt]),\n \"PlanRepository.setUserPlan\",\n ),\n \"PlanRepository.setUserPlan\",\n );\n }\n\n /** Remove a user's plan assignment. */\n async unsetUserPlan(userId: string): Promise<UnsetPlanRow> {\n const rows = await this.callproc(\"unassign_plan\", [userId, \"sdk_unassignment\"]);\n if (\n !safeParse(\n z.boolean(),\n requireRow(rows, \"PlanRepository.unsetUserPlan\"),\n \"PlanRepository.unsetUserPlan\",\n )\n ) {\n throw new StoreError(\"PlanRepository.unsetUserPlan: unassign_plan returned false\");\n }\n return safeParse(UnsetPlanRowSchema, { user_id: userId }, \"PlanRepository.unsetUserPlan\");\n }\n\n /** Pin or unpin the user's current assignment to its catalog revision. */\n async setPlanRevisionPin(userId: string, pinned: boolean): Promise<boolean> {\n const rows = await this.callproc(\"set_plan_revision_pin\", [userId, pinned]);\n return safeParse(\n z.boolean(),\n requireRow(rows, \"PlanRepository.setPlanRevisionPin\"),\n \"PlanRepository.setPlanRevisionPin\",\n );\n }\n\n /** Apply one bounded batch of renewal-effective plan changes. */\n async applyDuePlanChanges(limit: number): Promise<number> {\n const rows = await this.callproc(\"apply_due_plan_assignment_changes\", [limit]);\n return safeParse(\n z.number().int().nonnegative(),\n requireRow(rows, \"PlanRepository.applyDuePlanChanges\"),\n \"PlanRepository.applyDuePlanChanges\",\n );\n }\n\n /** Check a user's remaining free allowance. */\n async startPlanMigration(\n fromPlanId: string | null,\n toPlanId: string,\n ): Promise<PlanMigrationStartRow> {\n const rows = await this.callproc(\"start_plan_migration\", [fromPlanId, toPlanId]);\n return safeParse(\n PlanMigrationStartRowSchema,\n requireRow(rows, \"PlanRepository.startPlanMigration\"),\n \"PlanRepository.startPlanMigration\",\n );\n }\n\n async migratePlanBatch(migrationId: string, batchSize?: number): Promise<PlanMigrationBatchRow> {\n const rows = await this.callproc(\"migrate_plan_batch\", [migrationId, batchSize ?? 100]);\n return safeParse(\n PlanMigrationBatchRowSchema,\n requireRow(rows, \"PlanRepository.migratePlanBatch\"),\n \"PlanRepository.migratePlanBatch\",\n );\n }\n\n async getQuotaState(userId: string, quotaKey?: string | null): Promise<QuotaStateRow[]> {\n const rows = await this.callproc(\"get_subject_quota_state\", [userId, quotaKey ?? null]);\n return (rows ?? []).map((row) =>\n safeParse(QuotaStateRowSchema, row, \"PlanRepository.getQuotaState\"),\n );\n }\n\n async listQuotaEvents(\n userId: string,\n after: string | null,\n limit: number,\n idempotencyKey: string | null,\n afterId: string | null,\n ): Promise<QuotaEventRow[]> {\n const rows = await this.callproc(\"list_subject_quota_events\", [\n userId,\n after,\n limit,\n idempotencyKey,\n afterId,\n ]);\n return (rows ?? []).map((row) =>\n safeParse(QuotaEventRowSchema, row, \"PlanRepository.listQuotaEvents\"),\n );\n }\n\n async checkAllowance(userId: string): Promise<AllowanceRow | null> {\n const rows = await this.callproc(\"get_subject_allowance\", [userId]);\n const row = optionalRecordRow(rows, \"PlanRepository.checkAllowance\");\n return row === null\n ? null\n : safeParse(AllowanceRowSchema, row, \"PlanRepository.checkAllowance\");\n }\n}\n"]}
@@ -18,17 +18,17 @@ declare const AddTeamMemberRowSchema: z.ZodObject<{
18
18
  team_id: z.ZodString;
19
19
  user_id: z.ZodString;
20
20
  role: z.ZodEnum<{
21
- owner: "owner";
22
21
  admin: "admin";
23
22
  member: "member";
23
+ owner: "owner";
24
24
  }>;
25
25
  }, z.core.$strict>;
26
26
  declare const TeamMemberRowSchema: z.ZodObject<{
27
27
  user_id: z.ZodString;
28
28
  role: z.ZodEnum<{
29
- owner: "owner";
30
29
  admin: "admin";
31
30
  member: "member";
31
+ owner: "owner";
32
32
  }>;
33
33
  spend_cap: z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
34
34
  total_spent: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
@@ -1 +1 @@
1
- {"version":3,"file":"team.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/team.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;AAiBlE,QAAA,MAAM,mBAAmB;;;;;;;kBA8BrB,CAAC;AAEL,QAAA,MAAM,oBAAoB;;;;;kBAOf,CAAC;AAEZ,QAAA,MAAM,sBAAsB;;;;;;;;kBAMjB,CAAC;AAEZ,QAAA,MAAM,mBAAmB;;;;;;;;;kBAOd,CAAC;AAcZ,QAAA,MAAM,sBAAsB;;;;;;;;kBAwBxB,CAAC;AAEL,MAAM,MAAM,aAAa,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAChE,MAAM,MAAM,cAAc,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,oBAAoB,CAAC,CAAC;AAClE,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,sBAAsB,CAAC,CAAC;AACtE,MAAM,MAAM,aAAa,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAChE,MAAM,MAAM,gBAAgB,GAAG,C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,MAAM;YACrD,kBAAkB,EAAE,GAAG,CAAC,aAAa;YACrC,QAAQ,EAAE,GAAG,CAAC,QAAQ;YACtB,KAAK,EAAE,GAAG,CAAC,UAAU;SACtB,EACD,2BAA2B,CAC5B,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport { Decimal } from \"decimal.js\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport {\n optionalRecordRow,\n postgresUuid,\n requireRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\nimport { StoreError } from \"../../../errors.js\";\nimport { quantizeMoney } from \"../../../expr.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\nconst safeInteger = z\n .union([z.number().int(), z.string().regex(/^\\d+$/)] as const)\n .transform(Number)\n .refine(Number.isSafeInteger, \"expected a safe integer\");\nconst teamRole = z.enum([\"owner\", \"admin\", \"member\"]);\n\nconst CreateTeamRowSchema = z\n .object({\n team_id: postgresUuid.nullable(),\n name: z.string().min(1).nullable(),\n team_subject_id: postgresUuid.nullable(),\n account_id: postgresUuid.nullable(),\n idempotent: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n const identifiers = [row.team_id, row.name, row.team_subject_id, row.account_id];\n if (row.error_code === null && identifiers.some((value) => value === null)) {\n context.addIssue({\n code: \"custom\",\n message: \"successful team creation requires identity fields\",\n });\n }\n if (row.error_code !== null && identifiers.some((value) => value !== null)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed team creation cannot expose identity fields\",\n });\n }\n if (row.error_code !== null && row.idempotent) {\n context.addIssue({\n code: \"custom\",\n message: \"failed team creation cannot be idempotent\",\n });\n }\n });\n\nconst TeamBalanceRowSchema = z\n .object({\n team_id: postgresUuid,\n name: z.string().min(1),\n balance: decimal,\n member_count: safeInteger,\n })\n .strict();\n\nconst AddTeamMemberRowSchema = z\n .object({\n team_id: postgresUuid,\n user_id: postgresUuid,\n role: teamRole,\n })\n .strict();\n\nconst TeamMemberRowSchema = z\n .object({\n user_id: postgresUuid,\n role: teamRole,\n spend_cap: decimal.nullable(),\n total_spent: decimal,\n })\n .strict();\n\nconst TeamDeductionRpcRowSchema = z\n .object({\n entry_id: postgresUuid.nullable(),\n team_id: postgresUuid,\n subject_id: postgresUuid,\n amount: decimal,\n balance_after: decimal.nullable(),\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict();\n\nconst TeamDeductionRowSchema = z\n .object({\n entry_id: postgresUuid.nullable(),\n team_id: postgresUuid,\n user_id: postgresUuid,\n amount: decimal,\n team_balance_after: decimal.nullable(),\n error: z.string().min(1).nullable(),\n replayed: z.boolean(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error === null && (row.entry_id == null || row.team_balance_after === null)) {\n context.addIssue({\n code: \"custom\",\n message: \"successful team deductions require entry and balance fields\",\n });\n }\n if (row.error !== null && (row.entry_id !== null || row.replayed)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed team deductions cannot be replayed or committed\",\n });\n }\n });\n\nexport type CreateTeamRow = z.infer<typeof CreateTeamRowSchema>;\nexport type TeamBalanceRow = z.infer<typeof TeamBalanceRowSchema>;\nexport type AddTeamMemberRow = z.infer<typeof AddTeamMemberRowSchema>;\nexport type TeamMemberRow = z.infer<typeof TeamMemberRowSchema>;\nexport type TeamDeductionRow = z.infer<typeof TeamDeductionRowSchema>;\n\n/** Repository for team credit operations.\n *\n * All methods call Postgres RPCs via the callproc function.\n * Returns None when the RPC returns no rows.\n * Returns typed models for successful results.\n */\nexport class TeamRepository {\n constructor(private callproc: CallProc) {}\n\n /** Create a new team with an initial balance. */\n async createTeam(\n ownerSubjectId: string,\n name: string,\n idempotencyKey: string,\n initialBalance: string,\n ): Promise<CreateTeamRow> {\n const rows = await this.callproc(\"create_team\", [\n ownerSubjectId,\n name,\n idempotencyKey,\n initialBalance,\n ]);\n return safeParse(\n CreateTeamRowSchema,\n requireRow(rows, \"TeamRepository.createTeam\"),\n \"TeamRepository.createTeam\",\n );\n }\n\n /** Fetch a team's balance and member count. Returns null if the team does not exist. */\n async getTeamBalance(teamId: string): Promise<TeamBalanceRow | null> {\n const rows = await this.callproc(\"get_team_balance\", [teamId]);\n const row = optionalRecordRow(rows, \"TeamRepository.getTeamBalance\");\n return row === null\n ? null\n : safeParse(TeamBalanceRowSchema, row, \"TeamRepository.getTeamBalance\");\n }\n\n /** Add a member to a team with an optional spend cap. */\n async addTeamMember(\n teamId: string,\n userId: string,\n role: string,\n spendCap: string | null,\n ): Promise<AddTeamMemberRow> {\n const rows = await this.callproc(\"set_team_member\", [teamId, userId, role, spendCap]);\n const added = safeParse(\n z.boolean(),\n requireRow(rows, \"TeamRepository.addTeamMember\"),\n \"TeamRepository.addTeamMember\",\n );\n if (!added) {\n throw new StoreError(\"TeamRepository.addTeamMember: set_team_member returned false\");\n }\n return safeParse(\n AddTeamMemberRowSchema,\n { team_id: teamId, user_id: userId, role },\n \"TeamRepository.addTeamMember\",\n );\n }\n\n /** List all members of a team with their spend caps and totals. */\n async getTeamMembers(teamId: string): Promise<TeamMemberRow[]> {\n const rows = await this.callproc(\"list_team_members\", [teamId]);\n return (rows ?? []).map((r) =>\n safeParse(TeamMemberRowSchema, r, \"TeamRepository.getTeamMembers\"),\n );\n }\n\n /** Remove a team member, returning false when absent or the final owner. */\n async removeTeamMember(teamId: string, userId: string): Promise<boolean> {\n const rows = await this.callproc(\"remove_team_member\", [teamId, userId]);\n return safeParse(\n z.boolean(),\n requireRow(rows, \"TeamRepository.removeTeamMember\"),\n \"TeamRepository.removeTeamMember\",\n );\n }\n\n /** Deduct credits from a team's balance on behalf of a user. */\n async deductTeam(\n teamId: string,\n userId: string,\n amount: string,\n idempotencyKey: string,\n operation: string,\n metadata: string,\n ): Promise<TeamDeductionRow> {\n const rows = await this.callproc(\"deduct_team\", [\n teamId,\n userId,\n amount,\n idempotencyKey,\n operation,\n metadata,\n ]);\n const row = safeParse(\n TeamDeductionRpcRowSchema,\n requireRow(rows, \"TeamRepository.deductTeam\"),\n \"TeamRepository.deductTeam\",\n );\n if (\n row.error_code === null &&\n !new Decimal(row.amount).equals(quantizeMoney(new Decimal(amount)))\n ) {\n throw new StoreError(\"TeamRepository.deductTeam: committed amount differs from the request\", {\n indeterminate: true,\n });\n }\n return safeParse(\n TeamDeductionRowSchema,\n {\n entry_id: row.entry_id,\n team_id: row.team_id,\n user_id: row.subject_id,\n amount: row.error_code === null ? row.amount : amount,\n team_balance_after: row.balance_after,\n replayed: row.replayed,\n error: row.error_code,\n },\n \"TeamRepository.deductTeam\",\n );\n }\n}\n"]}
1
+ {"version":3,"file":"team.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/team.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAErC,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,UAAU,EACV,SAAS,GACV,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAEjD,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,CAAU,CAAC,CAAC;AAC3E,MAAM,WAAW,GAAG,CAAC;KAClB,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAU,CAAC;KAC7D,SAAS,CAAC,MAAM,CAAC;KACjB,MAAM,CAAC,MAAM,CAAC,aAAa,EAAE,yBAAyB,CAAC,CAAC;AAC3D,MAAM,QAAQ,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,OAAO,EA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C,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM;YACrD,kBAAkB,EAAE,GAAG,CAAC,aAAa;YACrC,QAAQ,EAAE,GAAG,CAAC,QAAQ;YACtB,KAAK,EAAE,GAAG,CAAC,UAAU;SACtB,EACD,2BAA2B,CAC5B,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport { Decimal } from \"decimal.js\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport {\n optionalRecordRow,\n postgresUuid,\n requireRow,\n safeParse,\n} from \"../../../shared/postgres-validation.js\";\nimport { StoreError } from \"../../../errors.js\";\nimport { quantizeMoney } from \"../../../expr.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\nconst safeInteger = z\n .union([z.number().int(), z.string().regex(/^\\d+$/)] as const)\n .transform(Number)\n .refine(Number.isSafeInteger, \"expected a safe integer\");\nconst teamRole = z.enum([\"owner\", \"admin\", \"member\"]);\n\nconst CreateTeamRowSchema = z\n .object({\n team_id: postgresUuid.nullable(),\n name: z.string().min(1).nullable(),\n team_subject_id: postgresUuid.nullable(),\n account_id: postgresUuid.nullable(),\n idempotent: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict()\n .superRefine((row, context) => {\n const identifiers = [row.team_id, row.name, row.team_subject_id, row.account_id];\n if (row.error_code === null && identifiers.some((value) => value === null)) {\n context.addIssue({\n code: \"custom\",\n message: \"successful team creation requires identity fields\",\n });\n }\n if (row.error_code !== null && identifiers.some((value) => value !== null)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed team creation cannot expose identity fields\",\n });\n }\n if (row.error_code !== null && row.idempotent) {\n context.addIssue({\n code: \"custom\",\n message: \"failed team creation cannot be idempotent\",\n });\n }\n });\n\nconst TeamBalanceRowSchema = z\n .object({\n team_id: postgresUuid,\n name: z.string().min(1),\n balance: decimal,\n member_count: safeInteger,\n })\n .strict();\n\nconst AddTeamMemberRowSchema = z\n .object({\n team_id: postgresUuid,\n user_id: postgresUuid,\n role: teamRole,\n })\n .strict();\n\nconst TeamMemberRowSchema = z\n .object({\n user_id: postgresUuid,\n role: teamRole,\n spend_cap: decimal.nullable(),\n total_spent: decimal,\n })\n .strict();\n\nconst TeamDeductionRpcRowSchema = z\n .object({\n entry_id: postgresUuid.nullable(),\n team_id: postgresUuid,\n subject_id: postgresUuid,\n amount: decimal,\n balance_after: decimal.nullable(),\n replayed: z.boolean(),\n error_code: z.string().min(1).nullable(),\n })\n .strict();\n\nconst TeamDeductionRowSchema = z\n .object({\n entry_id: postgresUuid.nullable(),\n team_id: postgresUuid,\n user_id: postgresUuid,\n amount: decimal,\n team_balance_after: decimal.nullable(),\n error: z.string().min(1).nullable(),\n replayed: z.boolean(),\n })\n .strict()\n .superRefine((row, context) => {\n if (row.error === null && (row.entry_id == null || row.team_balance_after === null)) {\n context.addIssue({\n code: \"custom\",\n message: \"successful team deductions require entry and balance fields\",\n });\n }\n if (row.error !== null && (row.entry_id !== null || row.replayed)) {\n context.addIssue({\n code: \"custom\",\n message: \"failed team deductions cannot be replayed or committed\",\n });\n }\n });\n\nexport type CreateTeamRow = z.infer<typeof CreateTeamRowSchema>;\nexport type TeamBalanceRow = z.infer<typeof TeamBalanceRowSchema>;\nexport type AddTeamMemberRow = z.infer<typeof AddTeamMemberRowSchema>;\nexport type TeamMemberRow = z.infer<typeof TeamMemberRowSchema>;\nexport type TeamDeductionRow = z.infer<typeof TeamDeductionRowSchema>;\n\n/** Repository for team credit operations.\n *\n * All methods call Postgres RPCs via the callproc function.\n * Returns None when the RPC returns no rows.\n * Returns typed models for successful results.\n */\nexport class TeamRepository {\n constructor(private callproc: CallProc) {}\n\n /** Create a new team with an initial balance. */\n async createTeam(\n ownerSubjectId: string,\n name: string,\n idempotencyKey: string,\n initialBalance: string,\n ): Promise<CreateTeamRow> {\n const rows = await this.callproc(\"create_team\", [\n ownerSubjectId,\n name,\n idempotencyKey,\n initialBalance,\n ]);\n return safeParse(\n CreateTeamRowSchema,\n requireRow(rows, \"TeamRepository.createTeam\"),\n \"TeamRepository.createTeam\",\n );\n }\n\n /** Fetch a team's balance and member count. Returns null if the team does not exist. */\n async getTeamBalance(teamId: string): Promise<TeamBalanceRow | null> {\n const rows = await this.callproc(\"get_team_balance\", [teamId]);\n const row = optionalRecordRow(rows, \"TeamRepository.getTeamBalance\");\n return row === null\n ? null\n : safeParse(TeamBalanceRowSchema, row, \"TeamRepository.getTeamBalance\");\n }\n\n /** Add a member to a team with an optional spend cap. */\n async addTeamMember(\n teamId: string,\n userId: string,\n role: string,\n spendCap: string | null,\n ): Promise<AddTeamMemberRow> {\n const rows = await this.callproc(\"set_team_member\", [teamId, userId, role, spendCap]);\n const added = safeParse(\n z.boolean(),\n requireRow(rows, \"TeamRepository.addTeamMember\"),\n \"TeamRepository.addTeamMember\",\n );\n if (!added) {\n throw new StoreError(\"TeamRepository.addTeamMember: set_team_member returned false\");\n }\n return safeParse(\n AddTeamMemberRowSchema,\n { team_id: teamId, user_id: userId, role },\n \"TeamRepository.addTeamMember\",\n );\n }\n\n /** List all members of a team with their spend caps and totals. */\n async getTeamMembers(teamId: string): Promise<TeamMemberRow[]> {\n const rows = await this.callproc(\"list_team_members\", [teamId]);\n return (rows ?? []).map((r) =>\n safeParse(TeamMemberRowSchema, r, \"TeamRepository.getTeamMembers\"),\n );\n }\n\n /** Remove a team member, returning false when absent or the final owner. */\n async removeTeamMember(teamId: string, userId: string): Promise<boolean> {\n const rows = await this.callproc(\"remove_team_member\", [teamId, userId]);\n return safeParse(\n z.boolean(),\n requireRow(rows, \"TeamRepository.removeTeamMember\"),\n \"TeamRepository.removeTeamMember\",\n );\n }\n\n /** Deduct credits from a team's balance on behalf of a user. */\n async deductTeam(\n teamId: string,\n userId: string,\n amount: string,\n idempotencyKey: string,\n operation: string,\n metadata: string,\n ): Promise<TeamDeductionRow> {\n const rows = await this.callproc(\"deduct_team\", [\n teamId,\n userId,\n amount,\n idempotencyKey,\n operation,\n metadata,\n ]);\n const row = safeParse(\n TeamDeductionRpcRowSchema,\n requireRow(rows, \"TeamRepository.deductTeam\"),\n \"TeamRepository.deductTeam\",\n );\n if (\n row.error_code === null &&\n !new Decimal(row.amount).equals(quantizeMoney(new Decimal(amount)))\n ) {\n throw new StoreError(\"TeamRepository.deductTeam: committed amount differs from the request\", {\n indeterminate: true,\n });\n }\n return safeParse(\n TeamDeductionRowSchema,\n {\n entry_id: row.entry_id,\n team_id: row.team_id,\n user_id: row.subject_id,\n amount: row.error_code === null ? row.amount : amount,\n team_balance_after: row.balance_after,\n replayed: row.replayed,\n error: row.error_code,\n },\n \"TeamRepository.deductTeam\",\n );\n }\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  import { Decimal } from "decimal.js";
2
2
  import { type BursarConfigData, type CatalogRollout } from "../../config.js";
3
3
  import { type PostgresConnectionOptions, type PostgresPool, type PostgresPoolConstructor } from "../../shared/postgres-client.js";
4
+ import type { JsonObject } from "../../shared/json.js";
4
5
  import type { AddCreditsResult, AddTeamMemberResult, AggregateStats, AllowanceResult, AvailableResult, BalanceResult, CheckFeatureResult, CreateTeamResult, DailySpendRow, DeductionResult, DeductWithAllowanceOptions, ExecuteGrantProgramRequest, GrantProgramAwardResult, GetUserPlanResult, LeaseResult, LeasePricingContext, ListLedgerEntriesOptions, ListUsageChargesOptions, ListQuotaEventsOptions, ListUsageEntriesOptions, PlanMigrationBatchResult, PlanMigrationStartResult, QuotaEvent, QuotaState, LedgerPage, UsageChargePage, UsageRecordResult, CatalogRevisionSummary, CatalogRevision, RefundResult, RevokeCreditsResult, ReleaseResult, SetUserPlanResult, SpendByModelRow, SpendByUserRow, SweepResult, TeamBalanceResult, TeamDeductionResult, TeamMember, TeamRole, BucketBalancesResult, TopUserRow, UnsetUserPlanResult, LedgerEntry } from "../types/index.js";
5
6
  import type { AddCreditsOptions, DeductTeamOptions, RefundCreditsOptions } from "../service-types.js";
6
7
  import { CreditStore } from "../store.js";
@@ -57,8 +58,8 @@ export declare class PostgresStore extends CreditStore {
57
58
  getAvailable(userId: string): Promise<AvailableResult>;
58
59
  getActiveCatalog(): Promise<CatalogRevision | null>;
59
60
  private loadActiveCatalog;
60
- publishAndActivateCatalog(config: BursarConfigData, label?: string | null, rollout?: CatalogRollout | null): Promise<string>;
61
- publishCatalogDraft(config: BursarConfigData, label?: string | null): Promise<string>;
61
+ publishAndActivateCatalog(config: BursarConfigData | JsonObject, label?: string | null, rollout?: CatalogRollout | null): Promise<string>;
62
+ publishCatalogDraft(config: BursarConfigData | JsonObject, label?: string | null): Promise<string>;
62
63
  getCatalogHistory(): Promise<CatalogRevisionSummary[]>;
63
64
  getCatalogRevision(version: number): Promise<CatalogRevision | null>;
64
65
  activateCatalogRevision(version: number, rollout?: CatalogRollout | null): Promise<string>;
@@ -1 +1 @@
1
- {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../../src/credits/postgres/store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAErC,OAAO,EAML,KAAK,gBAAgB,EACrB,KAAK,cAAc,EACpB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAEL,KAAK,yBAAyB,EAC9B,KAAK,YAAY,EACjB,KAAK,uBAAuB,EAC7B,MAAM,iCAAiC,CAAC;AACzC,OAAO,KAAK,EACV,gBAAgB,EAChB,mBAAmB,EACnB,cAAc,EACd,eAAe,EACf,eAAe,EACf,aAAa,EACb,kBAAkB,EAClB,gBAAgB,EAChB,aAAa,EACb,eAAe,EACf,0BAA0B,EAC1B,0BAA0B,EAC1B,uBAAuB,EACvB,iBAAiB,EACjB,WAAW,EACX,mBAAmB,EACnB,wBAAwB,EACxB,uBAAuB,EACvB,sBAAsB,EACtB,uBAAuB,EACvB,wBAAwB,EACxB,wBAAwB,EACxB,UAAU,EACV,UAAU,EACV,UAAU,EACV,eAAe,EACf,iBAAiB,EACjB,sBAAsB,EACtB,eAAe,EACf,YAAY,EACZ,mBAAmB,EACnB,aAAa,EACb,i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AAO,CAAC,OAAO,CAAC;IAIlE,UAAU,CACd,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,OAAO,EACf,OAAO,EAAE,iBAAiB,GACzB,OAAO,CAAC,mBAAmB,CAAC;IAsCzB,mBAAmB,CAAC,MAAM,UAAQ,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,KAAK,SAAM,GAAG,OAAO,CAAC,WAAW,CAAC;IAYvF,iBAAiB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,CAAC;IAYhE,mBAAmB,CACvB,OAAO,EAAE,0BAA0B,GAClC,OAAO,CAAC,uBAAuB,EAAE,CAAC;CAiCtC"}
1
+ {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../../src/credits/postgres/store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAIrC,OAAO,EAML,KAAK,gBAAgB,EACrB,KAAK,cAAc,EACpB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAEL,KAAK,yBAAyB,EAC9B,KAAK,YAAY,EACjB,KAAK,uBAAuB,EAC7B,MAAM,iCAAiC,CAAC;AACzC,OAAO,KAAK,EAAE,UAAU,EAAiC,MAAM,sBAAsB,CAAC;AACtF,OAAO,KAAK,EACV,gBAAgB,EAChB,mBAAmB,EACnB,cAAc,EACd,eAAe,EACf,eAAe,EACf,aAAa,EACb,kBAAkB,EAElB,gBAAgB,EAChB,aAAa,EACb,eAAe,EACf,0BAA0B,EAC1B,0BAA0B,EAC1B,uBAAuB,EACvB,iBAAiB,EACjB,WAAW,EACX,mBAAmB,EACnB,wBAAwB,EACxB,uBAAuB,EACvB,sBAAsB,EACtB,uBAAuB,EACvB,wBAAwB,EACxB,wBAAwB,EACxB,UAAU,EACV,UAAU,EACV,UAAU,EACV,eAAe,EACf,iBAAiB,EACjB,sBAAsB,EACtB,eAAe,EACf,YAAY,EACZ,mBAAmB,EACnB,aAAa,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,CACjB,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,IAAI,GAAE,QAAmB,EACzB,QAAQ,CAAC,EAAE,OAAO,GAAG,IAAI,GACxB,OAAO,CAAC,mBAAmB,CAAC,CAY9B;IAEK,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,EAAE,CAAC,CAQ1D;IAEK,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAEvE;IAEK,UAAU,CACd,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,OAAO,EACf,OAAO,EAAE,iBAAiB,GACzB,OAAO,CAAC,mBAAmB,CAAC,CAiC9B;IAEK,mBAAmB,CAAC,MAAM,UAAQ,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,KAAK,SAAM,GAAG,OAAO,CAAC,WAAW,CAAC,CAU5F;IAEK,iBAAiB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAUrE;IAEK,mBAAmB,CACvB,OAAO,EAAE,0BAA0B,GAClC,OAAO,CAAC,uBAAuB,EAAE,CAAC,CAgCpC;CACF"}
@@ -1,4 +1,5 @@
1
1
  import { Decimal } from "decimal.js";
2
+ import { z } from "zod";
2
3
  import { StoreClosedError, StoreError } from "../../errors.js";
3
4
  import { canonicalBursarConfigDict, canonicalCatalogRolloutDict, loadCatalogRollout, loadConfigFromDict, validateCatalogRollout, } from "../../config.js";
4
5
  import { PostgresClient, } from "../../shared/postgres-client.js";
@@ -17,10 +18,11 @@ const DEFAULT_LEASE_TTL_SECONDS = 600;
17
18
  const DEFAULT_PAGE_SIZE = 50;
18
19
  const MAX_PAGE_SIZE = 200;
19
20
  function requireText(value, context) {
20
- if (typeof value !== "string" || value.length === 0) {
21
+ const parsed = z.string().min(1).safeParse(value);
22
+ if (!parsed.success) {
21
23
  throw new StoreError(`${context} returned a missing or invalid identifier`);
22
24
  }
23
- return value;
25
+ return parsed.data;
24
26
  }
25
27
  export class PostgresStore extends CreditStore {
26
28
  providerEnvironment;
@@ -83,10 +85,10 @@ export class PostgresStore extends CreditStore {
83
85
  }
84
86
  constructor(options) {
85
87
  super();
86
- if (typeof options !== "object" || options === null) {
88
+ if (!z.object({}).safeParse(options).success) {
87
89
  throw new TypeError("PostgresStore options are required");
88
90
  }
89
- if (typeof options.postgres !== "string" && options.poolConstructor !== undefined) {
91
+ if (options.poolConstructor !== undefined && !z.string().safeParse(options.postgres).success) {
90
92
  throw new TypeError("poolConstructor cannot be used with an existing PostgreSQL pool");
91
93
  }
92
94
  this.providerEnvironment = options.providerEnvironment;
@@ -129,10 +131,14 @@ export class PostgresStore extends CreditStore {
129
131
  const rows = await this.query(`SELECT * FROM bursar.${name}(${placeholders})`, params);
130
132
  if (PostgresStore.SCALAR_RPC_NAMES.has(name) && rows.length === 1) {
131
133
  const row = rows[0];
134
+ if (row === undefined)
135
+ return rows;
132
136
  const keys = Object.keys(row);
133
137
  const key = keys[0];
134
138
  if (keys.length === 1 && key !== undefined) {
135
- return [row[key]];
139
+ const value = row[key];
140
+ if (value !== undefined)
141
+ return [value];
136
142
  }
137
143
  }
138
144
  return rows;
@@ -171,7 +177,8 @@ export class PostgresStore extends CreditStore {
171
177
  async deductWithAllowance(userId, amount, options) {
172
178
  const idempotencyKey = requireStableKey(options?.idempotencyKey);
173
179
  const operation = options?.operation ??
174
- (typeof options?.metadata?.operation === "string" ? options.metadata.operation : "usage");
180
+ z.string().min(1).safeParse(options?.metadata?.operation).data ??
181
+ "usage";
175
182
  const model = options?.model ?? null;
176
183
  const region = options?.region ?? null;
177
184
  const metadata = options?.metadata ?? {};
@@ -707,7 +714,9 @@ export class PostgresStore extends CreditStore {
707
714
  const cursor = options?.cursor ?? null;
708
715
  const entryTypes = usageOnly
709
716
  ? ["usage"]
710
- : (options?.entryTypes ?? null);
717
+ : options && "entryTypes" in options
718
+ ? (options.entryTypes ?? null)
719
+ : null;
711
720
  const rows = await this.analyticsRepo.listLedgerEntries(userId, entryTypes, options?.fromDate?.toISOString() ?? null, options?.toDate?.toISOString() ?? null, limit + 1, cursor?.createdAt ?? null, cursor?.entryId ?? null, usageOnly);
712
721
  const hasMore = rows.length > limit;
713
722
  const items = rows.slice(0, limit).map(mapLedgerEntry);
@@ -785,9 +794,7 @@ export class PostgresStore extends CreditStore {
785
794
  const meta = { ...(options?.metadata ?? {}) };
786
795
  const effectiveIdempotencyKey = requireStableKey(options?.idempotencyKey);
787
796
  meta.idempotency_key = effectiveIdempotencyKey;
788
- const operation = typeof meta.operation === "string" && meta.operation.length > 0
789
- ? meta.operation
790
- : "team_usage";
797
+ const operation = z.string().min(1).safeParse(meta.operation).data ?? "team_usage";
791
798
  const row = await this.teamRepo.deductTeam(teamId, userId, decParam(amount), effectiveIdempotencyKey, operation, JSON.stringify(meta));
792
799
  if (row.error !== null) {
793
800
  return {