@zonastery/bursar 1.0.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (366) hide show
  1. package/README.md +86 -3
  2. package/dist/billing/auto-recharge-port.d.ts +3 -3
  3. package/dist/billing/auto-recharge-port.d.ts.map +1 -1
  4. package/dist/billing/auto-recharge-port.js.map +1 -1
  5. package/dist/billing/auto-recharge-service.d.ts +5 -4
  6. package/dist/billing/auto-recharge-service.d.ts.map +1 -1
  7. package/dist/billing/auto-recharge-service.js +64 -34
  8. package/dist/billing/auto-recharge-service.js.map +1 -1
  9. package/dist/billing/billing-service.d.ts +5 -5
  10. package/dist/billing/billing-service.d.ts.map +1 -1
  11. package/dist/billing/billing-service.js +2 -2
  12. package/dist/billing/billing-service.js.map +1 -1
  13. package/dist/billing/billing-store.d.ts +8 -7
  14. package/dist/billing/billing-store.d.ts.map +1 -1
  15. package/dist/billing/billing-store.js.map +1 -1
  16. package/dist/billing/contracts.d.ts +31 -31
  17. package/dist/billing/contracts.d.ts.map +1 -1
  18. package/dist/billing/contracts.js.map +1 -1
  19. package/dist/billing/event-handlers.d.ts.map +1 -1
  20. package/dist/billing/event-handlers.js +31 -9
  21. package/dist/billing/event-handlers.js.map +1 -1
  22. package/dist/billing/event-processor.d.ts.map +1 -1
  23. package/dist/billing/event-processor.js +2 -1
  24. package/dist/billing/event-processor.js.map +1 -1
  25. package/dist/billing/financial-event-handlers.d.ts.map +1 -1
  26. package/dist/billing/financial-event-handlers.js +69 -72
  27. package/dist/billing/financial-event-handlers.js.map +1 -1
  28. package/dist/billing/index.d.ts +1 -1
  29. package/dist/billing/index.d.ts.map +1 -1
  30. package/dist/billing/index.js.map +1 -1
  31. package/dist/billing/management.d.ts +5 -5
  32. package/dist/billing/management.d.ts.map +1 -1
  33. package/dist/billing/management.js +2 -2
  34. package/dist/billing/management.js.map +1 -1
  35. package/dist/billing/postgres/repositories/auto-recharge.d.ts +3 -3
  36. package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -1
  37. package/dist/billing/postgres/repositories/auto-recharge.js +202 -59
  38. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
  39. package/dist/billing/postgres/repositories/customer.d.ts.map +1 -1
  40. package/dist/billing/postgres/repositories/customer.js +19 -11
  41. package/dist/billing/postgres/repositories/customer.js.map +1 -1
  42. package/dist/billing/postgres/repositories/dispute.d.ts.map +1 -1
  43. package/dist/billing/postgres/repositories/dispute.js +3 -1
  44. package/dist/billing/postgres/repositories/dispute.js.map +1 -1
  45. package/dist/billing/postgres/repositories/event.d.ts +12 -5
  46. package/dist/billing/postgres/repositories/event.d.ts.map +1 -1
  47. package/dist/billing/postgres/repositories/event.js +18 -15
  48. package/dist/billing/postgres/repositories/event.js.map +1 -1
  49. package/dist/billing/postgres/repositories/invoice.d.ts +3 -3
  50. package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -1
  51. package/dist/billing/postgres/repositories/invoice.js +53 -11
  52. package/dist/billing/postgres/repositories/invoice.js.map +1 -1
  53. package/dist/billing/postgres/repositories/offer.d.ts +20 -17
  54. package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
  55. package/dist/billing/postgres/repositories/offer.js +123 -57
  56. package/dist/billing/postgres/repositories/offer.js.map +1 -1
  57. package/dist/billing/postgres/repositories/payment.d.ts +23 -20
  58. package/dist/billing/postgres/repositories/payment.d.ts.map +1 -1
  59. package/dist/billing/postgres/repositories/payment.js +43 -37
  60. package/dist/billing/postgres/repositories/payment.js.map +1 -1
  61. package/dist/billing/postgres/repositories/preferences.d.ts +3 -9
  62. package/dist/billing/postgres/repositories/preferences.d.ts.map +1 -1
  63. package/dist/billing/postgres/repositories/preferences.js +45 -7
  64. package/dist/billing/postgres/repositories/preferences.js.map +1 -1
  65. package/dist/billing/postgres/repositories/refund.d.ts +1 -1
  66. package/dist/billing/postgres/repositories/refund.d.ts.map +1 -1
  67. package/dist/billing/postgres/repositories/refund.js +13 -9
  68. package/dist/billing/postgres/repositories/refund.js.map +1 -1
  69. package/dist/billing/postgres/repositories/subscription-change.d.ts +15 -0
  70. package/dist/billing/postgres/repositories/subscription-change.d.ts.map +1 -0
  71. package/dist/billing/postgres/repositories/subscription-change.js +234 -0
  72. package/dist/billing/postgres/repositories/subscription-change.js.map +1 -0
  73. package/dist/billing/postgres/repositories/subscription.d.ts +38 -17
  74. package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -1
  75. package/dist/billing/postgres/repositories/subscription.js +199 -91
  76. package/dist/billing/postgres/repositories/subscription.js.map +1 -1
  77. package/dist/billing/postgres/repositories/topup.d.ts +13 -15
  78. package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
  79. package/dist/billing/postgres/repositories/topup.js +65 -34
  80. package/dist/billing/postgres/repositories/topup.js.map +1 -1
  81. package/dist/billing/postgres/store.d.ts +18 -11
  82. package/dist/billing/postgres/store.d.ts.map +1 -1
  83. package/dist/billing/postgres/store.js +260 -238
  84. package/dist/billing/postgres/store.js.map +1 -1
  85. package/dist/billing/service-types.d.ts +6 -5
  86. package/dist/billing/service-types.d.ts.map +1 -1
  87. package/dist/billing/service-types.js.map +1 -1
  88. package/dist/billing/types/auto-recharge.d.ts +6 -4
  89. package/dist/billing/types/auto-recharge.d.ts.map +1 -1
  90. package/dist/billing/types/auto-recharge.js.map +1 -1
  91. package/dist/billing/types/catalog.d.ts +18 -35
  92. package/dist/billing/types/catalog.d.ts.map +1 -1
  93. package/dist/billing/types/catalog.js.map +1 -1
  94. package/dist/billing/types/common.d.ts +0 -1
  95. package/dist/billing/types/common.d.ts.map +1 -1
  96. package/dist/billing/types/common.js.map +1 -1
  97. package/dist/billing/types/documents.d.ts +38 -12
  98. package/dist/billing/types/documents.d.ts.map +1 -1
  99. package/dist/billing/types/documents.js.map +1 -1
  100. package/dist/billing/types/events.d.ts +2 -0
  101. package/dist/billing/types/events.d.ts.map +1 -1
  102. package/dist/billing/types/events.js +238 -0
  103. package/dist/billing/types/events.js.map +1 -1
  104. package/dist/billing/types/subscriptions.d.ts +8 -8
  105. package/dist/billing/types/subscriptions.d.ts.map +1 -1
  106. package/dist/billing/types/subscriptions.js.map +1 -1
  107. package/dist/bursar.d.ts +27 -9
  108. package/dist/bursar.d.ts.map +1 -1
  109. package/dist/bursar.js +48 -20
  110. package/dist/bursar.js.map +1 -1
  111. package/dist/catalog.d.ts +1 -1
  112. package/dist/catalog.d.ts.map +1 -1
  113. package/dist/catalog.js +1 -1
  114. package/dist/catalog.js.map +1 -1
  115. package/dist/commerce/errors.d.ts +1 -10
  116. package/dist/commerce/errors.d.ts.map +1 -1
  117. package/dist/commerce/errors.js +1 -16
  118. package/dist/commerce/errors.js.map +1 -1
  119. package/dist/commerce/index.d.ts +1 -0
  120. package/dist/commerce/index.d.ts.map +1 -1
  121. package/dist/commerce/index.js.map +1 -1
  122. package/dist/commerce/provider-registry.d.ts.map +1 -1
  123. package/dist/commerce/provider-registry.js +27 -2
  124. package/dist/commerce/provider-registry.js.map +1 -1
  125. package/dist/commerce/service.d.ts +15 -7
  126. package/dist/commerce/service.d.ts.map +1 -1
  127. package/dist/commerce/service.js +85 -67
  128. package/dist/commerce/service.js.map +1 -1
  129. package/dist/commerce/types.d.ts +27 -15
  130. package/dist/commerce/types.d.ts.map +1 -1
  131. package/dist/commerce/types.js.map +1 -1
  132. package/dist/config/parse-plans.d.ts.map +1 -1
  133. package/dist/config/parse-plans.js +16 -15
  134. package/dist/config/parse-plans.js.map +1 -1
  135. package/dist/config/parse-pricing.d.ts.map +1 -1
  136. package/dist/config/parse-pricing.js +16 -5
  137. package/dist/config/parse-pricing.js.map +1 -1
  138. package/dist/config/types.d.ts +2 -2
  139. package/dist/config/types.d.ts.map +1 -1
  140. package/dist/config/types.js.map +1 -1
  141. package/dist/credits/{pricing-runtime.d.ts → catalog-runtime.d.ts} +8 -8
  142. package/dist/credits/catalog-runtime.d.ts.map +1 -0
  143. package/dist/credits/{pricing-runtime.js → catalog-runtime.js} +58 -38
  144. package/dist/credits/catalog-runtime.js.map +1 -0
  145. package/dist/credits/events.d.ts +4 -4
  146. package/dist/credits/events.d.ts.map +1 -1
  147. package/dist/credits/events.js +1 -1
  148. package/dist/credits/events.js.map +1 -1
  149. package/dist/credits/lease-workflow.d.ts +14 -14
  150. package/dist/credits/lease-workflow.d.ts.map +1 -1
  151. package/dist/credits/lease-workflow.js +18 -17
  152. package/dist/credits/lease-workflow.js.map +1 -1
  153. package/dist/credits/low-balance-monitor.d.ts +2 -2
  154. package/dist/credits/low-balance-monitor.d.ts.map +1 -1
  155. package/dist/credits/low-balance-monitor.js.map +1 -1
  156. package/dist/credits/postgres/repositories/analytics.d.ts +34 -34
  157. package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -1
  158. package/dist/credits/postgres/repositories/analytics.js +52 -52
  159. package/dist/credits/postgres/repositories/analytics.js.map +1 -1
  160. package/dist/credits/postgres/repositories/balance.d.ts +28 -30
  161. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
  162. package/dist/credits/postgres/repositories/balance.js +100 -59
  163. package/dist/credits/postgres/repositories/balance.js.map +1 -1
  164. package/dist/credits/postgres/repositories/bucket.d.ts +14 -8
  165. package/dist/credits/postgres/repositories/bucket.d.ts.map +1 -1
  166. package/dist/credits/postgres/repositories/bucket.js +22 -21
  167. package/dist/credits/postgres/repositories/bucket.js.map +1 -1
  168. package/dist/credits/postgres/repositories/catalog.d.ts +31 -0
  169. package/dist/credits/postgres/repositories/catalog.d.ts.map +1 -0
  170. package/dist/credits/postgres/repositories/catalog.js +90 -0
  171. package/dist/credits/postgres/repositories/catalog.js.map +1 -0
  172. package/dist/credits/postgres/repositories/deduction.d.ts +28 -26
  173. package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -1
  174. package/dist/credits/postgres/repositories/deduction.js +153 -68
  175. package/dist/credits/postgres/repositories/deduction.js.map +1 -1
  176. package/dist/credits/postgres/repositories/lease.d.ts +21 -18
  177. package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
  178. package/dist/credits/postgres/repositories/lease.js +157 -65
  179. package/dist/credits/postgres/repositories/lease.js.map +1 -1
  180. package/dist/credits/postgres/repositories/plan.d.ts +90 -43
  181. package/dist/credits/postgres/repositories/plan.d.ts.map +1 -1
  182. package/dist/credits/postgres/repositories/plan.js +126 -108
  183. package/dist/credits/postgres/repositories/plan.js.map +1 -1
  184. package/dist/credits/postgres/repositories/team.d.ts +36 -27
  185. package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
  186. package/dist/credits/postgres/repositories/team.js +96 -52
  187. package/dist/credits/postgres/repositories/team.js.map +1 -1
  188. package/dist/credits/postgres/store.d.ts +23 -18
  189. package/dist/credits/postgres/store.d.ts.map +1 -1
  190. package/dist/credits/postgres/store.js +282 -265
  191. package/dist/credits/postgres/store.js.map +1 -1
  192. package/dist/credits/postgres/value-mappers.d.ts +7 -9
  193. package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
  194. package/dist/credits/postgres/value-mappers.js +36 -61
  195. package/dist/credits/postgres/value-mappers.js.map +1 -1
  196. package/dist/credits/queries.d.ts +5 -5
  197. package/dist/credits/queries.d.ts.map +1 -1
  198. package/dist/credits/queries.js +4 -4
  199. package/dist/credits/queries.js.map +1 -1
  200. package/dist/credits/service-types.d.ts +42 -7
  201. package/dist/credits/service-types.d.ts.map +1 -1
  202. package/dist/credits/service-types.js.map +1 -1
  203. package/dist/credits/service.d.ts +42 -62
  204. package/dist/credits/service.d.ts.map +1 -1
  205. package/dist/credits/service.js +140 -121
  206. package/dist/credits/service.js.map +1 -1
  207. package/dist/credits/store.d.ts +20 -22
  208. package/dist/credits/store.d.ts.map +1 -1
  209. package/dist/credits/store.js +5 -5
  210. package/dist/credits/store.js.map +1 -1
  211. package/dist/credits/types/account.d.ts +49 -11
  212. package/dist/credits/types/account.d.ts.map +1 -1
  213. package/dist/credits/types/account.js.map +1 -1
  214. package/dist/credits/types/admission.d.ts +17 -6
  215. package/dist/credits/types/admission.d.ts.map +1 -1
  216. package/dist/credits/types/admission.js.map +1 -1
  217. package/dist/credits/types/analytics.d.ts +2 -2
  218. package/dist/credits/types/analytics.d.ts.map +1 -1
  219. package/dist/credits/types/analytics.js.map +1 -1
  220. package/dist/credits/types/catalog.d.ts +20 -15
  221. package/dist/credits/types/catalog.d.ts.map +1 -1
  222. package/dist/credits/types/catalog.js.map +1 -1
  223. package/dist/credits/types/grants.d.ts +22 -8
  224. package/dist/credits/types/grants.d.ts.map +1 -1
  225. package/dist/credits/types/grants.js.map +1 -1
  226. package/dist/credits/types/ledger.d.ts +12 -3
  227. package/dist/credits/types/ledger.d.ts.map +1 -1
  228. package/dist/credits/types/ledger.js.map +1 -1
  229. package/dist/credits/types/teams.d.ts +18 -6
  230. package/dist/credits/types/teams.d.ts.map +1 -1
  231. package/dist/credits/types/teams.js.map +1 -1
  232. package/dist/engine.d.ts.map +1 -1
  233. package/dist/engine.js +24 -10
  234. package/dist/engine.js.map +1 -1
  235. package/dist/errors.d.ts +52 -4
  236. package/dist/errors.d.ts.map +1 -1
  237. package/dist/errors.js +76 -4
  238. package/dist/errors.js.map +1 -1
  239. package/dist/expr/ast.d.ts.map +1 -1
  240. package/dist/expr/ast.js.map +1 -1
  241. package/dist/expr/evaluator.d.ts.map +1 -1
  242. package/dist/expr/evaluator.js +29 -17
  243. package/dist/expr/evaluator.js.map +1 -1
  244. package/dist/expr/parser.d.ts.map +1 -1
  245. package/dist/expr/parser.js +11 -4
  246. package/dist/expr/parser.js.map +1 -1
  247. package/dist/expr/tokenizer.d.ts.map +1 -1
  248. package/dist/expr/tokenizer.js +17 -13
  249. package/dist/expr/tokenizer.js.map +1 -1
  250. package/dist/expr.d.ts +2 -2
  251. package/dist/expr.d.ts.map +1 -1
  252. package/dist/expr.js +5 -7
  253. package/dist/expr.js.map +1 -1
  254. package/dist/generated/pricing-config.schema.json +5 -12
  255. package/dist/generated/pricing-config.types.d.ts +3 -3
  256. package/dist/generated/pricing-config.types.d.ts.map +1 -1
  257. package/dist/generated/pricing-config.types.js.map +1 -1
  258. package/dist/index.d.ts +6 -4
  259. package/dist/index.d.ts.map +1 -1
  260. package/dist/index.js +1 -1
  261. package/dist/index.js.map +1 -1
  262. package/dist/integrations/better-auth.d.ts +23 -0
  263. package/dist/integrations/better-auth.d.ts.map +1 -0
  264. package/dist/integrations/better-auth.js +54 -0
  265. package/dist/integrations/better-auth.js.map +1 -0
  266. package/dist/{load-pricing-file.d.ts → load-config-file.d.ts} +4 -4
  267. package/dist/load-config-file.d.ts.map +1 -0
  268. package/dist/{load-pricing-file.js → load-config-file.js} +15 -10
  269. package/dist/load-config-file.js.map +1 -0
  270. package/dist/node.d.ts +3 -3
  271. package/dist/node.d.ts.map +1 -1
  272. package/dist/node.js +2 -2
  273. package/dist/node.js.map +1 -1
  274. package/dist/providers/_shared.d.ts +5 -0
  275. package/dist/providers/_shared.d.ts.map +1 -1
  276. package/dist/providers/_shared.js +36 -0
  277. package/dist/providers/_shared.js.map +1 -1
  278. package/dist/providers/dodo/better-auth.d.ts +29 -0
  279. package/dist/providers/dodo/better-auth.d.ts.map +1 -0
  280. package/dist/providers/dodo/better-auth.js +23 -0
  281. package/dist/providers/dodo/better-auth.js.map +1 -0
  282. package/dist/providers/dodo/client-contract.d.ts +32 -70
  283. package/dist/providers/dodo/client-contract.d.ts.map +1 -1
  284. package/dist/providers/dodo/client-contract.js.map +1 -1
  285. package/dist/providers/dodo/event-mapper.d.ts +3 -1
  286. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  287. package/dist/providers/dodo/event-mapper.js +219 -148
  288. package/dist/providers/dodo/event-mapper.js.map +1 -1
  289. package/dist/providers/dodo/index.d.ts +5 -2
  290. package/dist/providers/dodo/index.d.ts.map +1 -1
  291. package/dist/providers/dodo/index.js +2 -1
  292. package/dist/providers/dodo/index.js.map +1 -1
  293. package/dist/providers/dodo/nextjs.d.ts +16 -0
  294. package/dist/providers/dodo/nextjs.d.ts.map +1 -0
  295. package/dist/providers/dodo/nextjs.js +16 -0
  296. package/dist/providers/dodo/nextjs.js.map +1 -0
  297. package/dist/providers/dodo/provider.d.ts +30 -11
  298. package/dist/providers/dodo/provider.d.ts.map +1 -1
  299. package/dist/providers/dodo/provider.js +192 -122
  300. package/dist/providers/dodo/provider.js.map +1 -1
  301. package/dist/providers/dodo/react-native.d.ts +56 -0
  302. package/dist/providers/dodo/react-native.d.ts.map +1 -0
  303. package/dist/providers/dodo/react-native.js +57 -0
  304. package/dist/providers/dodo/react-native.js.map +1 -0
  305. package/dist/providers/dodo/webhook-bridge.d.ts +17 -0
  306. package/dist/providers/dodo/webhook-bridge.d.ts.map +1 -0
  307. package/dist/providers/dodo/webhook-bridge.js +21 -0
  308. package/dist/providers/dodo/webhook-bridge.js.map +1 -0
  309. package/dist/providers/index.d.ts +1 -1
  310. package/dist/providers/index.d.ts.map +1 -1
  311. package/dist/providers/index.js.map +1 -1
  312. package/dist/providers/mock/index.d.ts +1 -0
  313. package/dist/providers/mock/index.d.ts.map +1 -1
  314. package/dist/providers/mock/index.js.map +1 -1
  315. package/dist/providers/mock/provider.d.ts +8 -8
  316. package/dist/providers/mock/provider.d.ts.map +1 -1
  317. package/dist/providers/mock/provider.js +26 -19
  318. package/dist/providers/mock/provider.js.map +1 -1
  319. package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
  320. package/dist/providers/stripe/event-mapper.js +214 -173
  321. package/dist/providers/stripe/event-mapper.js.map +1 -1
  322. package/dist/providers/stripe/index.d.ts +1 -0
  323. package/dist/providers/stripe/index.d.ts.map +1 -1
  324. package/dist/providers/stripe/index.js.map +1 -1
  325. package/dist/providers/stripe/provider.d.ts +13 -11
  326. package/dist/providers/stripe/provider.d.ts.map +1 -1
  327. package/dist/providers/stripe/provider.js +287 -107
  328. package/dist/providers/stripe/provider.js.map +1 -1
  329. package/dist/providers/types.d.ts +1 -2
  330. package/dist/providers/types.d.ts.map +1 -1
  331. package/dist/providers/types.js.map +1 -1
  332. package/dist/shared/postgres-client.d.ts +5 -0
  333. package/dist/shared/postgres-client.d.ts.map +1 -1
  334. package/dist/shared/postgres-client.js +23 -7
  335. package/dist/shared/postgres-client.js.map +1 -1
  336. package/dist/shared/postgres-validation.d.ts +15 -3
  337. package/dist/shared/postgres-validation.d.ts.map +1 -1
  338. package/dist/shared/postgres-validation.js +58 -14
  339. package/dist/shared/postgres-validation.js.map +1 -1
  340. package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
  341. package/dist/storage/adapters/clickhouse.js +2 -5
  342. package/dist/storage/adapters/clickhouse.js.map +1 -1
  343. package/dist/storage/adapters/s3.d.ts +0 -6
  344. package/dist/storage/adapters/s3.d.ts.map +1 -1
  345. package/dist/storage/adapters/s3.js +0 -2
  346. package/dist/storage/adapters/s3.js.map +1 -1
  347. package/dist/storage/ports.d.ts +0 -1
  348. package/dist/storage/ports.d.ts.map +1 -1
  349. package/dist/storage/ports.js.map +1 -1
  350. package/dist/storage/postgres-repository.d.ts +1 -1
  351. package/dist/storage/postgres-repository.d.ts.map +1 -1
  352. package/dist/storage/postgres-repository.js +2 -2
  353. package/dist/storage/postgres-repository.js.map +1 -1
  354. package/dist/storage/runtime.d.ts +24 -6
  355. package/dist/storage/runtime.d.ts.map +1 -1
  356. package/dist/storage/runtime.js +87 -30
  357. package/dist/storage/runtime.js.map +1 -1
  358. package/package.json +56 -7
  359. package/dist/credits/postgres/repositories/pricing.d.ts +0 -28
  360. package/dist/credits/postgres/repositories/pricing.d.ts.map +0 -1
  361. package/dist/credits/postgres/repositories/pricing.js +0 -76
  362. package/dist/credits/postgres/repositories/pricing.js.map +0 -1
  363. package/dist/credits/pricing-runtime.d.ts.map +0 -1
  364. package/dist/credits/pricing-runtime.js.map +0 -1
  365. package/dist/load-pricing-file.d.ts.map +0 -1
  366. package/dist/load-pricing-file.js.map +0 -1
@@ -1,111 +1,144 @@
1
1
  import { z } from "zod";
2
- import { safeParse } from "../../../shared/postgres-validation.js";
2
+ import { optionalRecordRow, postgresUuid, requireRow, safeParse, } from "../../../shared/postgres-validation.js";
3
+ import { StoreError } from "../../../errors.js";
4
+ const decimal = z.union([z.string().min(1), z.number().finite()]);
5
+ const timestamp = z.union([z.string().min(1), z.date()]).transform((value, context) => {
6
+ const parsed = value instanceof Date ? value : new Date(value);
7
+ if (Number.isNaN(parsed.getTime())) {
8
+ context.addIssue({ code: "custom", message: "expected a valid timestamp" });
9
+ return z.NEVER;
10
+ }
11
+ return parsed;
12
+ });
13
+ const safeInteger = z
14
+ .union([z.number().int(), z.string().regex(/^\d+$/)])
15
+ .transform(Number)
16
+ .refine(Number.isSafeInteger, "expected a safe integer");
17
+ const entitlementValue = z.object({ value: z.json() }).strict();
18
+ const admissionOperation = z
19
+ .object({ max_in_flight: z.number().int().positive().nullable() })
20
+ .strict();
3
21
  const UserPlanRowSchema = z
4
22
  .object({
5
- user_id: z.string().optional(),
6
- plan_id: z.string().nullable().optional(),
7
- plan_key: z.string().nullable().optional(),
8
- plan_label: z.string().nullable().optional(),
9
- rate_card: z.string().nullable().optional(),
10
- credit_allowance_amount: z
11
- .union([z.string(), z.number()])
12
- .nullable()
13
- .optional(),
14
- credit_allowance_priority: z.coerce.number().int().nonnegative().nullable().optional(),
15
- credit_allowance_reset_unit: z.string().nullable().optional(),
16
- credit_allowance_reset_count: z.coerce.number().nullable().optional(),
17
- credit_allowance_reset_anchor: z.string().nullable().optional(),
18
- credit_allowance_reset_timezone: z.string().nullable().optional(),
19
- entitlements: z.record(z.string(), z.unknown()).optional(),
20
- credit_policy_type: z.string().nullable().optional(),
21
- credit_limit: z
22
- .union([z.string(), z.number()])
23
- .nullable()
24
- .optional(),
25
- admission_max_in_flight: z.coerce.number().nullable().optional(),
26
- operation_admission: z.record(z.string(), z.unknown()).optional(),
27
- allowed_operations: z.array(z.string()).optional(),
28
- assignment_source_type: z.string().nullable().optional(),
29
- assignment_source_id: z.string().nullable().optional(),
30
- catalog_revision_pinned: z.boolean().optional(),
31
- plan_assigned_at: z
32
- .union([z.string(), z.date().transform((value) => value.toISOString())])
33
- .nullable()
34
- .optional(),
35
- catalog_revision_no: z.coerce.number().nullable().optional(),
23
+ user_id: postgresUuid,
24
+ plan_assigned_at: timestamp,
25
+ plan_assignment_ends_at: timestamp.nullable(),
26
+ assignment_source_type: z.enum(["manual", "subscription", "migration", "system"]),
27
+ assignment_source_id: postgresUuid.nullable(),
28
+ catalog_revision_pinned: z.boolean(),
29
+ plan_id: postgresUuid,
30
+ plan_key: z.string().min(1),
31
+ plan_label: z.string().min(1),
32
+ rate_card: z.string().min(1).nullable(),
33
+ allowed_operations: z.array(z.string().min(1)),
34
+ credit_allowance_amount: decimal.nullable(),
35
+ credit_allowance_priority: z.number().int().nonnegative().nullable(),
36
+ credit_allowance_reset_unit: z
37
+ .enum(["second", "minute", "hour", "day", "week", "month", "year"])
38
+ .nullable(),
39
+ credit_allowance_reset_count: z.number().int().positive().nullable(),
40
+ credit_allowance_reset_anchor: z.enum(["calendar", "plan_assignment", "rolling"]).nullable(),
41
+ credit_allowance_reset_timezone: z.string().min(1).nullable(),
42
+ entitlements: z.record(z.string().min(1), entitlementValue),
43
+ credit_policy_type: z.enum(["prepaid", "credit_line"]).nullable(),
44
+ credit_limit: decimal.nullable(),
45
+ admission_max_in_flight: z.number().int().positive().nullable(),
46
+ operation_admission: z.record(z.string().min(1), admissionOperation),
47
+ catalog_revision_no: safeInteger,
36
48
  })
37
- .passthrough();
49
+ .strict()
50
+ .superRefine((row, context) => {
51
+ const allowance = [
52
+ row.credit_allowance_amount,
53
+ row.credit_allowance_priority,
54
+ row.credit_allowance_reset_unit,
55
+ row.credit_allowance_reset_count,
56
+ row.credit_allowance_reset_anchor,
57
+ row.credit_allowance_reset_timezone,
58
+ ];
59
+ const populated = allowance.filter((value) => value !== null).length;
60
+ if (populated !== 0 && populated !== allowance.length) {
61
+ context.addIssue({
62
+ code: "custom",
63
+ message: "allowance policy fields must be all set or all null",
64
+ });
65
+ }
66
+ if ((row.credit_policy_type === null && row.credit_limit !== null) ||
67
+ (row.credit_policy_type === "prepaid" && row.credit_limit !== null) ||
68
+ (row.credit_policy_type === "credit_line" && row.credit_limit === null)) {
69
+ context.addIssue({ code: "custom", message: "credit policy fields are inconsistent" });
70
+ }
71
+ });
38
72
  const SetUserPlanRowSchema = z
39
73
  .object({
40
- user_id: z.string().optional(),
41
- plan_id: z.string().optional(),
42
- plan_assigned_at: z
43
- .union([z.string(), z.date().transform((value) => value.toISOString())])
44
- .nullable()
45
- .optional(),
74
+ user_id: postgresUuid,
75
+ plan_id: postgresUuid,
76
+ plan_key: z.string().min(1),
77
+ plan_assigned_at: timestamp,
78
+ assignment_state: z.enum(["applied", "scheduled"]),
46
79
  })
47
- .passthrough();
80
+ .strict();
81
+ const EntitlementRowSchema = z
82
+ .object({
83
+ feature_key: z.string().min(1),
84
+ feature_type: z.enum(["boolean", "integer", "string", "enum"]),
85
+ feature_value: z.json(),
86
+ catalog_revision_id: postgresUuid,
87
+ plan_key: z.string().min(1).nullable(),
88
+ value_source: z.enum(["default", "plan"]),
89
+ })
90
+ .strict();
48
91
  const AllowanceRowSchema = z
49
92
  .object({
50
- plan_id: z.string().nullable().optional(),
51
- allowance_remaining: z
52
- .union([z.string(), z.number()])
53
- .nullable()
54
- .optional(),
55
- period_start: z
56
- .union([z.string(), z.date().transform((value) => value.toISOString())])
57
- .nullable()
58
- .optional(),
59
- period_end: z
60
- .union([z.string(), z.date().transform((value) => value.toISOString())])
61
- .nullable()
62
- .optional(),
93
+ plan_id: postgresUuid,
94
+ allowance_remaining: decimal,
95
+ period_start: timestamp.transform((value) => value.toISOString()),
96
+ period_end: timestamp.transform((value) => value.toISOString()),
63
97
  })
64
- .passthrough();
98
+ .strict();
65
99
  const UnsetPlanRowSchema = z
66
100
  .object({
67
- user_id: z.string().optional(),
101
+ user_id: postgresUuid,
68
102
  })
69
- .passthrough();
70
- const PlanMigrationStartRowSchema = z.string().nullable();
103
+ .strict();
104
+ const PlanMigrationStartRowSchema = postgresUuid;
71
105
  const PlanMigrationBatchRowSchema = z
72
106
  .object({
73
- migrated: z.number(),
107
+ migrated: z.number().int().nonnegative(),
74
108
  done: z.boolean(),
75
- next_cursor: z.string().nullable(),
109
+ next_cursor: postgresUuid.nullable(),
76
110
  })
77
- .passthrough();
78
- const decimal = z.union([z.string(), z.number()]);
111
+ .strict();
79
112
  const QuotaStateRowSchema = z
80
113
  .object({
81
- user_id: z.string(),
82
- quota_key: z.string(),
83
- operation_key: z.string(),
84
- measure_key: z.string(),
114
+ user_id: postgresUuid,
115
+ quota_key: z.string().min(1),
116
+ operation_key: z.string().min(1),
117
+ measure_key: z.string().min(1),
85
118
  quota_limit: decimal,
86
119
  consumed: decimal,
87
120
  reserved: decimal,
88
121
  remaining: decimal,
89
122
  overage: decimal,
90
123
  enforcement: z.enum(["block", "allow"]),
91
- window_start: z.union([z.string(), z.date().transform((value) => value.toISOString())]),
92
- window_end: z.union([z.string(), z.date().transform((value) => value.toISOString())]),
93
- emit_at_percent: z.array(z.number()),
124
+ window_start: timestamp.transform((value) => value.toISOString()),
125
+ window_end: timestamp.transform((value) => value.toISOString()),
126
+ emit_at_percent: z.array(z.number().finite().min(0).max(100)),
94
127
  })
95
- .passthrough();
128
+ .strict();
96
129
  const QuotaEventRowSchema = z
97
130
  .object({
98
- event_id: z.string(),
99
- quota_key: z.string(),
100
- operation_key: z.string(),
101
- measure_key: z.string(),
131
+ event_id: postgresUuid,
132
+ quota_key: z.string().min(1),
133
+ operation_key: z.string().min(1),
134
+ measure_key: z.string().min(1),
102
135
  event_type: z.enum(["threshold", "blocked"]),
103
- threshold_percent: z.coerce.number().nullable(),
104
- idempotency_key: z.string(),
105
- usage_charge_id: z.string().nullable(),
106
- created_at: z.union([z.string(), z.date().transform((value) => value.toISOString())]),
136
+ threshold_percent: z.number().finite().min(0).max(100).nullable(),
137
+ idempotency_key: z.string().min(1),
138
+ usage_charge_id: postgresUuid.nullable(),
139
+ created_at: timestamp.transform((value) => value.toISOString()),
107
140
  })
108
- .passthrough();
141
+ .strict();
109
142
  /** Repository for plan management operations. */
110
143
  export class PlanRepository {
111
144
  callproc;
@@ -115,60 +148,44 @@ export class PlanRepository {
115
148
  /** Fetch a user's current plan. Returns null if user has no plan. */
116
149
  async getUserPlan(userId) {
117
150
  const rows = await this.callproc("get_subject_plan", [userId]);
118
- if (!rows || rows.length === 0)
119
- return null;
120
- return safeParse(UserPlanRowSchema, rows[0], "PlanRepository.getUserPlan");
151
+ const row = optionalRecordRow(rows, "PlanRepository.getUserPlan");
152
+ return row === null ? null : safeParse(UserPlanRowSchema, row, "PlanRepository.getUserPlan");
121
153
  }
122
154
  async getEntitlement(userId, feature) {
123
155
  const rows = await this.callproc("get_subject_entitlements", [userId]);
124
- const row = rows.find((candidate) => candidate.feature_key === feature);
125
- return row ?? null;
156
+ const entitlements = (rows ?? []).map((row) => safeParse(EntitlementRowSchema, row, "PlanRepository.getEntitlement"));
157
+ return entitlements.find((candidate) => candidate.feature_key === feature) ?? null;
126
158
  }
127
159
  /** Assign a plan to a user. */
128
160
  async setUserPlan(userId, planKey, planAssignedAt) {
129
- const planRows = await this.callproc("resolve_active_plan", [planKey]);
130
- const planRow = planRows[0];
131
- if (planRow?.id == null)
132
- throw new Error(`unknown active plan '${planKey}'`);
133
- const planId = String(planRow.id);
134
- const params = planAssignedAt ? [userId, planId, planAssignedAt] : [userId, planId];
135
- const rows = await this.callproc("assign_plan", params);
136
- if (rows?.[0] !== true) {
137
- throw new Error("PlanRepository.setUserPlan: assign_plan returned false");
138
- }
139
- const assigned = await this.getUserPlan(userId);
140
- return safeParse(SetUserPlanRowSchema, {
141
- user_id: userId,
142
- plan_id: assigned?.plan_id ?? planId,
143
- plan_assigned_at: assigned?.plan_assigned_at ?? planAssignedAt,
144
- }, "PlanRepository.setUserPlan");
161
+ return safeParse(SetUserPlanRowSchema, requireRow(await this.callproc("set_subject_plan", [userId, planKey, planAssignedAt]), "PlanRepository.setUserPlan"), "PlanRepository.setUserPlan");
145
162
  }
146
163
  /** Remove a user's plan assignment. */
147
164
  async unsetUserPlan(userId) {
148
165
  const rows = await this.callproc("unassign_plan", [userId, "sdk_unassignment"]);
149
- if (rows?.[0] !== true) {
150
- throw new Error("PlanRepository.unsetUserPlan: unassign_plan returned false");
166
+ if (!safeParse(z.boolean(), requireRow(rows, "PlanRepository.unsetUserPlan"), "PlanRepository.unsetUserPlan")) {
167
+ throw new StoreError("PlanRepository.unsetUserPlan: unassign_plan returned false");
151
168
  }
152
169
  return safeParse(UnsetPlanRowSchema, { user_id: userId }, "PlanRepository.unsetUserPlan");
153
170
  }
154
171
  /** Pin or unpin the user's current assignment to its catalog revision. */
155
172
  async setPlanRevisionPin(userId, pinned) {
156
173
  const rows = await this.callproc("set_plan_revision_pin", [userId, pinned]);
157
- return rows?.[0] === true;
174
+ return safeParse(z.boolean(), requireRow(rows, "PlanRepository.setPlanRevisionPin"), "PlanRepository.setPlanRevisionPin");
158
175
  }
159
176
  /** Apply one bounded batch of renewal-effective plan changes. */
160
177
  async applyDuePlanChanges(limit) {
161
178
  const rows = await this.callproc("apply_due_plan_assignment_changes", [limit]);
162
- return Number(rows?.[0] ?? 0);
179
+ return safeParse(z.number().int().nonnegative(), requireRow(rows, "PlanRepository.applyDuePlanChanges"), "PlanRepository.applyDuePlanChanges");
163
180
  }
164
181
  /** Check a user's remaining free allowance. */
165
182
  async startPlanMigration(fromPlanId, toPlanId) {
166
183
  const rows = await this.callproc("start_plan_migration", [fromPlanId, toPlanId]);
167
- return safeParse(PlanMigrationStartRowSchema, rows?.[0] ?? null, "PlanRepository.startPlanMigration");
184
+ return safeParse(PlanMigrationStartRowSchema, requireRow(rows, "PlanRepository.startPlanMigration"), "PlanRepository.startPlanMigration");
168
185
  }
169
186
  async migratePlanBatch(migrationId, batchSize) {
170
187
  const rows = await this.callproc("migrate_plan_batch", [migrationId, batchSize ?? 100]);
171
- return safeParse(PlanMigrationBatchRowSchema, rows?.[0] ?? {}, "PlanRepository.migratePlanBatch");
188
+ return safeParse(PlanMigrationBatchRowSchema, requireRow(rows, "PlanRepository.migratePlanBatch"), "PlanRepository.migratePlanBatch");
172
189
  }
173
190
  async getQuotaState(userId, quotaKey) {
174
191
  const rows = await this.callproc("get_subject_quota_state", [userId, quotaKey ?? null]);
@@ -186,9 +203,10 @@ export class PlanRepository {
186
203
  }
187
204
  async checkAllowance(userId) {
188
205
  const rows = await this.callproc("get_subject_allowance", [userId]);
189
- if (!rows || rows.length === 0)
190
- return null;
191
- return safeParse(AllowanceRowSchema, rows[0], "PlanRepository.checkAllowance");
206
+ const row = optionalRecordRow(rows, "PlanRepository.checkAllowance");
207
+ return row === null
208
+ ? null
209
+ : safeParse(AllowanceRowSchema, row, "PlanRepository.checkAllowance");
192
210
  }
193
211
  }
194
212
  //# sourceMappingURL=plan.js.map
@@ -1 +1 @@
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,EAAE,SAAS,EAAE,MAAM,wCAAwC,CAAC;AAEnE,MAAM,iBAAiB,GAAG,CAAC;KACxB,MAAM,CAAC;IACN,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAC9B,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,CAAC,QAAQ,EAAE;IACzC,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,CAAC,QAAQ,EAAE;IAC1C,UAAU,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,CAAC,QAAQ,EAAE;IAC5C,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,CAAC,QAAQ,EAAE;IAC3C,uBAAuB,EAAE,CAAC;SACvB,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAU,CAAC;SACxC,QAAQ,EAAE;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AI,IAAI,CAAC,CAAC,CAAC;QACxF,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAC9B,SAAS,CAAC,mBAAmB,EAAE,GAAG,EAAE,8BAA8B,CAAC,CACpE,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,eAAe,CACnB,MAAc,EACd,KAAoB,EACpB,KAAa,EACb,cAA6B,EAC7B,OAAsB;QAEtB,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,2BAA2B,EAAE;YAC5D,MAAM;YACN,KAAK;YACL,KAAK;YACL,cAAc;YACd,OAAO;SACR,CAAC,CAAC;QACH,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAC9B,SAAS,CAAC,mBAAmB,EAAE,GAAG,EAAE,gCAAgC,CAAC,CACtE,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,cAAc,CAAC,MAAc;QACjC,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,uBAAuB,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;QACpE,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,IAAI,CAAC;QAC5C,OAAO,SAAS,CAAC,kBAAkB,EAAE,IAAI,CAAC,CAAC,CAAC,EAAE,+BAA+B,CAAC,CAAC;IACjF,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport { safeParse } from \"../../../shared/postgres-validation.js\";\n\nconst UserPlanRowSchema = z\n .object({\n user_id: z.string().optional(),\n plan_id: z.string().nullable().optional(),\n plan_key: z.string().nullable().optional(),\n plan_label: z.string().nullable().optional(),\n rate_card: z.string().nullable().optional(),\n credit_allowance_amount: z\n .union([z.string(), z.number()] as const)\n .nullable()\n .optional(),\n credit_allowance_priority: z.coerce.number().int().nonnegative().nullable().optional(),\n credit_allowance_reset_unit: z.string().nullable().optional(),\n credit_allowance_reset_count: z.coerce.number().nullable().optional(),\n credit_allowance_reset_anchor: z.string().nullable().optional(),\n credit_allowance_reset_timezone: z.string().nullable().optional(),\n entitlements: z.record(z.string(), z.unknown()).optional(),\n credit_policy_type: z.string().nullable().optional(),\n credit_limit: z\n .union([z.string(), z.number()] as const)\n .nullable()\n .optional(),\n admission_max_in_flight: z.coerce.number().nullable().optional(),\n operation_admission: z.record(z.string(), z.unknown()).optional(),\n allowed_operations: z.array(z.string()).optional(),\n assignment_source_type: z.string().nullable().optional(),\n assignment_source_id: z.string().nullable().optional(),\n catalog_revision_pinned: z.boolean().optional(),\n plan_assigned_at: z\n .union([z.string(), z.date().transform((value) => value.toISOString())])\n .nullable()\n .optional(),\n catalog_revision_no: z.coerce.number().nullable().optional(),\n })\n .passthrough();\n\nconst SetUserPlanRowSchema = z\n .object({\n user_id: z.string().optional(),\n plan_id: z.string().optional(),\n plan_assigned_at: z\n .union([z.string(), z.date().transform((value) => value.toISOString())])\n .nullable()\n .optional(),\n })\n .passthrough();\n\nconst AllowanceRowSchema = z\n .object({\n plan_id: z.string().nullable().optional(),\n allowance_remaining: z\n .union([z.string(), z.number()] as const)\n .nullable()\n .optional(),\n period_start: z\n .union([z.string(), z.date().transform((value) => value.toISOString())])\n .nullable()\n .optional(),\n period_end: z\n .union([z.string(), z.date().transform((value) => value.toISOString())])\n .nullable()\n .optional(),\n })\n .passthrough();\n\nconst UnsetPlanRowSchema = z\n .object({\n user_id: z.string().optional(),\n })\n .passthrough();\n\nconst PlanMigrationStartRowSchema = z.string().nullable();\nconst PlanMigrationBatchRowSchema = z\n .object({\n migrated: z.number(),\n done: z.boolean(),\n next_cursor: z.string().nullable(),\n })\n .passthrough();\nconst decimal = z.union([z.string(), z.number()] as const);\nconst QuotaStateRowSchema = z\n .object({\n user_id: z.string(),\n quota_key: z.string(),\n operation_key: z.string(),\n measure_key: z.string(),\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: z.union([z.string(), z.date().transform((value) => value.toISOString())]),\n window_end: z.union([z.string(), z.date().transform((value) => value.toISOString())]),\n emit_at_percent: z.array(z.number()),\n })\n .passthrough();\nconst QuotaEventRowSchema = z\n .object({\n event_id: z.string(),\n quota_key: z.string(),\n operation_key: z.string(),\n measure_key: z.string(),\n event_type: z.enum([\"threshold\", \"blocked\"]),\n threshold_percent: z.coerce.number().nullable(),\n idempotency_key: z.string(),\n usage_charge_id: z.string().nullable(),\n created_at: z.union([z.string(), z.date().transform((value) => value.toISOString())]),\n })\n .passthrough();\n\nexport type UnsetPlanRow = z.infer<typeof UnsetPlanRowSchema>;\nexport type UserPlanRow = z.infer<typeof UserPlanRowSchema>;\nexport type SetUserPlanRow = z.infer<typeof SetUserPlanRowSchema>;\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 if (!rows || rows.length === 0) return null;\n return safeParse(UserPlanRowSchema, rows[0], \"PlanRepository.getUserPlan\");\n }\n\n async getEntitlement(userId: string, feature: string): Promise<Record<string, unknown> | null> {\n const rows = await this.callproc(\"get_subject_entitlements\", [userId]);\n const row = (rows as Array<Record<string, unknown>>).find(\n (candidate) => candidate.feature_key === feature,\n );\n return row ?? 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 const planRows = await this.callproc(\"resolve_active_plan\", [planKey]);\n const planRow = planRows[0] as Record<string, unknown> | undefined;\n if (planRow?.id == null) throw new Error(`unknown active plan '${planKey}'`);\n const planId = String(planRow.id);\n const params = planAssignedAt ? [userId, planId, planAssignedAt] : [userId, planId];\n const rows = await this.callproc(\"assign_plan\", params);\n if (rows?.[0] !== true) {\n throw new Error(\"PlanRepository.setUserPlan: assign_plan returned false\");\n }\n const assigned = await this.getUserPlan(userId);\n return safeParse(\n SetUserPlanRowSchema,\n {\n user_id: userId,\n plan_id: assigned?.plan_id ?? planId,\n plan_assigned_at: assigned?.plan_assigned_at ?? planAssignedAt,\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 (rows?.[0] !== true) {\n throw new Error(\"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 rows?.[0] === true;\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 Number(rows?.[0] ?? 0);\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 rows?.[0] ?? null,\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 rows?.[0] ?? {},\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 if (!rows || rows.length === 0) return null;\n return safeParse(AllowanceRowSchema, rows[0], \"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,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,KA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AAC,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"]}
@@ -1,37 +1,46 @@
1
1
  import { z } from "zod";
2
2
  import type { CallProc } from "../../../shared/postgres-types.js";
3
3
  declare const CreateTeamRowSchema: z.ZodObject<{
4
- team_id: z.ZodOptional<z.ZodString>;
5
- name: z.ZodOptional<z.ZodString>;
6
- }, z.core.$loose>;
4
+ team_id: z.ZodNullable<z.ZodString>;
5
+ name: z.ZodNullable<z.ZodString>;
6
+ team_subject_id: z.ZodNullable<z.ZodString>;
7
+ account_id: z.ZodNullable<z.ZodString>;
8
+ error_code: z.ZodNullable<z.ZodString>;
9
+ }, z.core.$strict>;
7
10
  declare const TeamBalanceRowSchema: z.ZodObject<{
8
- team_id: z.ZodOptional<z.ZodString>;
9
- name: z.ZodOptional<z.ZodString>;
10
- balance: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
11
- member_count: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
12
- error: z.ZodOptional<z.ZodNullable<z.ZodString>>;
13
- }, z.core.$loose>;
11
+ team_id: z.ZodString;
12
+ name: z.ZodString;
13
+ balance: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
14
+ member_count: z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>;
15
+ }, z.core.$strict>;
14
16
  declare const AddTeamMemberRowSchema: z.ZodObject<{
15
- team_id: z.ZodOptional<z.ZodString>;
16
- user_id: z.ZodOptional<z.ZodString>;
17
- role: z.ZodOptional<z.ZodString>;
18
- }, z.core.$loose>;
17
+ team_id: z.ZodString;
18
+ user_id: z.ZodString;
19
+ role: z.ZodEnum<{
20
+ owner: "owner";
21
+ admin: "admin";
22
+ member: "member";
23
+ }>;
24
+ }, z.core.$strict>;
19
25
  declare const TeamMemberRowSchema: z.ZodObject<{
20
- user_id: z.ZodOptional<z.ZodString>;
21
- role: z.ZodOptional<z.ZodString>;
22
- spend_cap: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
23
- total_spent: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
24
- }, z.core.$loose>;
26
+ user_id: z.ZodString;
27
+ role: z.ZodEnum<{
28
+ owner: "owner";
29
+ admin: "admin";
30
+ member: "member";
31
+ }>;
32
+ spend_cap: z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
33
+ total_spent: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
34
+ }, z.core.$strict>;
25
35
  declare const TeamDeductionRowSchema: z.ZodObject<{
26
- entry_id: z.ZodOptional<z.ZodNullable<z.ZodString>>;
27
- team_id: z.ZodOptional<z.ZodString>;
28
- user_id: z.ZodOptional<z.ZodString>;
29
- amount: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
30
- team_balance_after: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
31
- error: z.ZodOptional<z.ZodNullable<z.ZodString>>;
32
- error_code: z.ZodOptional<z.ZodNullable<z.ZodString>>;
33
- replayed: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodString, z.ZodNumber]>>;
34
- }, z.core.$loose>;
36
+ entry_id: z.ZodNullable<z.ZodString>;
37
+ team_id: z.ZodString;
38
+ user_id: z.ZodString;
39
+ amount: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
40
+ team_balance_after: z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
41
+ error: z.ZodNullable<z.ZodString>;
42
+ replayed: z.ZodBoolean;
43
+ }, z.core.$strict>;
35
44
  export type CreateTeamRow = z.infer<typeof CreateTeamRowSchema>;
36
45
  export type TeamBalanceRow = z.infer<typeof TeamBalanceRowSchema>;
37
46
  export type AddTeamMemberRow = z.infer<typeof AddTeamMemberRowSchema>;
@@ -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;AACxB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;AAGlE,QAAA,MAAM,mBAAmB;;;iBAKT,CAAC;AAEjB,QAAA,MAAM,oBAAoB;;;;;;iBA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