@zonastery/bursar 0.0.2 → 1.0.1

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 (505) hide show
  1. package/README.md +118 -333
  2. package/dist/billing/auto-recharge-port.d.ts +27 -0
  3. package/dist/billing/auto-recharge-port.d.ts.map +1 -0
  4. package/dist/billing/auto-recharge-port.js +2 -0
  5. package/dist/billing/auto-recharge-port.js.map +1 -0
  6. package/dist/billing/auto-recharge-service.d.ts +43 -0
  7. package/dist/billing/auto-recharge-service.d.ts.map +1 -0
  8. package/dist/billing/auto-recharge-service.js +218 -0
  9. package/dist/billing/auto-recharge-service.js.map +1 -0
  10. package/dist/billing/billing-service.d.ts +71 -0
  11. package/dist/billing/billing-service.d.ts.map +1 -0
  12. package/dist/billing/billing-service.js +172 -0
  13. package/dist/billing/billing-service.js.map +1 -0
  14. package/dist/billing/billing-store.d.ts +45 -13
  15. package/dist/billing/billing-store.d.ts.map +1 -1
  16. package/dist/billing/billing-store.js.map +1 -1
  17. package/dist/billing/contracts.d.ts +149 -0
  18. package/dist/billing/contracts.d.ts.map +1 -0
  19. package/dist/billing/contracts.js +2 -0
  20. package/dist/billing/contracts.js.map +1 -0
  21. package/dist/billing/event-handlers.d.ts +57 -0
  22. package/dist/billing/event-handlers.d.ts.map +1 -0
  23. package/dist/billing/event-handlers.js +684 -0
  24. package/dist/billing/event-handlers.js.map +1 -0
  25. package/dist/billing/event-processor.d.ts +20 -0
  26. package/dist/billing/event-processor.d.ts.map +1 -0
  27. package/dist/billing/event-processor.js +131 -0
  28. package/dist/billing/event-processor.js.map +1 -0
  29. package/dist/billing/financial-event-handlers.d.ts +26 -0
  30. package/dist/billing/financial-event-handlers.d.ts.map +1 -0
  31. package/dist/billing/financial-event-handlers.js +241 -0
  32. package/dist/billing/financial-event-handlers.js.map +1 -0
  33. package/dist/billing/index.d.ts +9 -5
  34. package/dist/billing/index.d.ts.map +1 -1
  35. package/dist/billing/index.js +4 -4
  36. package/dist/billing/index.js.map +1 -1
  37. package/dist/billing/management.d.ts +59 -0
  38. package/dist/billing/management.d.ts.map +1 -0
  39. package/dist/billing/management.js +113 -0
  40. package/dist/billing/management.js.map +1 -0
  41. package/dist/billing/policy-window.d.ts +24 -0
  42. package/dist/billing/policy-window.d.ts.map +1 -0
  43. package/dist/billing/policy-window.js +88 -0
  44. package/dist/billing/policy-window.js.map +1 -0
  45. package/dist/billing/postgres/repositories/auto-recharge.d.ts +32 -0
  46. package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -0
  47. package/dist/billing/postgres/repositories/auto-recharge.js +180 -0
  48. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -0
  49. package/dist/billing/postgres/repositories/customer.d.ts +12 -0
  50. package/dist/billing/postgres/repositories/customer.d.ts.map +1 -0
  51. package/dist/billing/postgres/repositories/customer.js +33 -0
  52. package/dist/billing/postgres/repositories/customer.js.map +1 -0
  53. package/dist/billing/postgres/repositories/dispute.d.ts +7 -0
  54. package/dist/billing/postgres/repositories/dispute.d.ts.map +1 -0
  55. package/dist/billing/postgres/repositories/dispute.js +18 -0
  56. package/dist/billing/postgres/repositories/dispute.js.map +1 -0
  57. package/dist/billing/postgres/repositories/event.d.ts +21 -0
  58. package/dist/billing/postgres/repositories/event.d.ts.map +1 -0
  59. package/dist/billing/postgres/repositories/event.js +45 -0
  60. package/dist/billing/postgres/repositories/event.js.map +1 -0
  61. package/dist/billing/postgres/repositories/invoice.d.ts +9 -0
  62. package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -0
  63. package/dist/billing/postgres/repositories/invoice.js +36 -0
  64. package/dist/billing/postgres/repositories/invoice.js.map +1 -0
  65. package/dist/billing/postgres/repositories/offer.d.ts +26 -0
  66. package/dist/billing/postgres/repositories/offer.d.ts.map +1 -0
  67. package/dist/billing/postgres/repositories/offer.js +73 -0
  68. package/dist/billing/postgres/repositories/offer.js.map +1 -0
  69. package/dist/billing/postgres/repositories/payment.d.ts +32 -0
  70. package/dist/billing/postgres/repositories/payment.d.ts.map +1 -0
  71. package/dist/billing/postgres/repositories/payment.js +78 -0
  72. package/dist/billing/postgres/repositories/payment.js.map +1 -0
  73. package/dist/billing/postgres/repositories/preferences.d.ts +15 -0
  74. package/dist/billing/postgres/repositories/preferences.d.ts.map +1 -0
  75. package/dist/billing/postgres/repositories/preferences.js +23 -0
  76. package/dist/billing/postgres/repositories/preferences.js.map +1 -0
  77. package/dist/billing/postgres/repositories/refund.d.ts +7 -0
  78. package/dist/billing/postgres/repositories/refund.d.ts.map +1 -0
  79. package/dist/billing/postgres/repositories/refund.js +32 -0
  80. package/dist/billing/postgres/repositories/refund.js.map +1 -0
  81. package/dist/billing/postgres/repositories/subscription.d.ts +46 -0
  82. package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -0
  83. package/dist/billing/postgres/repositories/subscription.js +187 -0
  84. package/dist/billing/postgres/repositories/subscription.js.map +1 -0
  85. package/dist/billing/postgres/repositories/topup.d.ts +27 -0
  86. package/dist/billing/postgres/repositories/topup.d.ts.map +1 -0
  87. package/dist/billing/postgres/repositories/topup.js +51 -0
  88. package/dist/billing/postgres/repositories/topup.js.map +1 -0
  89. package/dist/billing/postgres/store.d.ts +89 -0
  90. package/dist/billing/postgres/store.d.ts.map +1 -0
  91. package/dist/billing/postgres/store.js +542 -0
  92. package/dist/billing/postgres/store.js.map +1 -0
  93. package/dist/billing/service-types.d.ts +37 -0
  94. package/dist/billing/service-types.d.ts.map +1 -0
  95. package/dist/billing/service-types.js +2 -0
  96. package/dist/billing/service-types.js.map +1 -0
  97. package/dist/billing/types/auto-recharge.d.ts +56 -0
  98. package/dist/billing/types/auto-recharge.d.ts.map +1 -0
  99. package/dist/billing/types/auto-recharge.js +2 -0
  100. package/dist/billing/types/auto-recharge.js.map +1 -0
  101. package/dist/billing/types/catalog.d.ts +47 -0
  102. package/dist/billing/types/catalog.d.ts.map +1 -0
  103. package/dist/billing/types/catalog.js +2 -0
  104. package/dist/billing/types/catalog.js.map +1 -0
  105. package/dist/billing/types/common.d.ts +16 -0
  106. package/dist/billing/types/common.d.ts.map +1 -0
  107. package/dist/billing/types/common.js +2 -0
  108. package/dist/billing/types/common.js.map +1 -0
  109. package/dist/billing/types/documents.d.ts +39 -0
  110. package/dist/billing/types/documents.d.ts.map +1 -0
  111. package/dist/billing/types/documents.js +2 -0
  112. package/dist/billing/types/documents.js.map +1 -0
  113. package/dist/billing/types/events.d.ts +75 -0
  114. package/dist/billing/types/events.d.ts.map +1 -0
  115. package/dist/billing/types/events.js +38 -0
  116. package/dist/billing/types/events.js.map +1 -0
  117. package/dist/billing/types/index.d.ts +8 -0
  118. package/dist/billing/types/index.d.ts.map +1 -0
  119. package/dist/billing/types/index.js +8 -0
  120. package/dist/billing/types/index.js.map +1 -0
  121. package/dist/billing/types/preferences.d.ts +13 -0
  122. package/dist/billing/types/preferences.d.ts.map +1 -0
  123. package/dist/billing/types/preferences.js +2 -0
  124. package/dist/billing/types/preferences.js.map +1 -0
  125. package/dist/billing/types/subscriptions.d.ts +97 -0
  126. package/dist/billing/types/subscriptions.d.ts.map +1 -0
  127. package/dist/billing/types/subscriptions.js +12 -0
  128. package/dist/billing/types/subscriptions.js.map +1 -0
  129. package/dist/breakdown.d.ts +3 -1
  130. package/dist/breakdown.d.ts.map +1 -1
  131. package/dist/breakdown.js +4 -1
  132. package/dist/breakdown.js.map +1 -1
  133. package/dist/browser.d.ts +8 -0
  134. package/dist/browser.d.ts.map +1 -0
  135. package/dist/browser.js +7 -0
  136. package/dist/browser.js.map +1 -0
  137. package/dist/bursar.d.ts +84 -0
  138. package/dist/bursar.d.ts.map +1 -0
  139. package/dist/bursar.js +137 -0
  140. package/dist/bursar.js.map +1 -0
  141. package/dist/catalog.d.ts +62 -0
  142. package/dist/catalog.d.ts.map +1 -0
  143. package/dist/catalog.js +96 -0
  144. package/dist/catalog.js.map +1 -0
  145. package/dist/commerce/errors.d.ts +68 -0
  146. package/dist/commerce/errors.d.ts.map +1 -0
  147. package/dist/commerce/errors.js +105 -0
  148. package/dist/commerce/errors.js.map +1 -0
  149. package/dist/commerce/index.d.ts +6 -0
  150. package/dist/commerce/index.d.ts.map +1 -0
  151. package/dist/commerce/index.js +6 -0
  152. package/dist/commerce/index.js.map +1 -0
  153. package/dist/commerce/plan-change.d.ts +10 -0
  154. package/dist/commerce/plan-change.d.ts.map +1 -0
  155. package/dist/commerce/plan-change.js +42 -0
  156. package/dist/commerce/plan-change.js.map +1 -0
  157. package/dist/commerce/provider-registry.d.ts +18 -0
  158. package/dist/commerce/provider-registry.d.ts.map +1 -0
  159. package/dist/commerce/provider-registry.js +70 -0
  160. package/dist/commerce/provider-registry.js.map +1 -0
  161. package/dist/commerce/service.d.ts +73 -0
  162. package/dist/commerce/service.d.ts.map +1 -0
  163. package/dist/commerce/service.js +1016 -0
  164. package/dist/commerce/service.js.map +1 -0
  165. package/dist/commerce/types.d.ts +225 -0
  166. package/dist/commerce/types.d.ts.map +1 -0
  167. package/dist/commerce/types.js.map +1 -0
  168. package/dist/config/parse-access.d.ts +6 -0
  169. package/dist/config/parse-access.d.ts.map +1 -0
  170. package/dist/config/parse-access.js +72 -0
  171. package/dist/config/parse-access.js.map +1 -0
  172. package/dist/config/parse-commerce.d.ts +3 -0
  173. package/dist/config/parse-commerce.d.ts.map +1 -0
  174. package/dist/config/parse-commerce.js +236 -0
  175. package/dist/config/parse-commerce.js.map +1 -0
  176. package/dist/config/parse-credits.d.ts +3 -0
  177. package/dist/config/parse-credits.d.ts.map +1 -0
  178. package/dist/config/parse-credits.js +99 -0
  179. package/dist/config/parse-credits.js.map +1 -0
  180. package/dist/config/parse-plans.d.ts +5 -0
  181. package/dist/config/parse-plans.d.ts.map +1 -0
  182. package/dist/config/parse-plans.js +142 -0
  183. package/dist/config/parse-plans.js.map +1 -0
  184. package/dist/config/parse-pricing.d.ts +4 -0
  185. package/dist/config/parse-pricing.d.ts.map +1 -0
  186. package/dist/config/parse-pricing.js +252 -0
  187. package/dist/config/parse-pricing.js.map +1 -0
  188. package/dist/config/parse-utils.d.ts +18 -0
  189. package/dist/config/parse-utils.d.ts.map +1 -0
  190. package/dist/config/parse-utils.js +118 -0
  191. package/dist/config/parse-utils.js.map +1 -0
  192. package/dist/config/types.d.ts +340 -0
  193. package/dist/config/types.d.ts.map +1 -0
  194. package/dist/config/types.js +2 -0
  195. package/dist/config/types.js.map +1 -0
  196. package/dist/config.d.ts +12 -23
  197. package/dist/config.d.ts.map +1 -1
  198. package/dist/config.js +141 -377
  199. package/dist/config.js.map +1 -1
  200. package/dist/{stores → credits}/events.d.ts +6 -6
  201. package/dist/credits/events.d.ts.map +1 -0
  202. package/dist/{stores → credits}/events.js +5 -5
  203. package/dist/credits/events.js.map +1 -0
  204. package/dist/credits/lease-workflow.d.ts +90 -0
  205. package/dist/credits/lease-workflow.d.ts.map +1 -0
  206. package/dist/credits/lease-workflow.js +378 -0
  207. package/dist/credits/lease-workflow.js.map +1 -0
  208. package/dist/credits/low-balance-monitor.d.ts +26 -0
  209. package/dist/credits/low-balance-monitor.d.ts.map +1 -0
  210. package/dist/credits/low-balance-monitor.js +110 -0
  211. package/dist/credits/low-balance-monitor.js.map +1 -0
  212. package/dist/credits/postgres/repositories/analytics.d.ts +81 -0
  213. package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -0
  214. package/dist/credits/postgres/repositories/analytics.js +153 -0
  215. package/dist/credits/postgres/repositories/analytics.js.map +1 -0
  216. package/dist/credits/postgres/repositories/balance.d.ts +66 -0
  217. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -0
  218. package/dist/credits/postgres/repositories/balance.js +139 -0
  219. package/dist/credits/postgres/repositories/balance.js.map +1 -0
  220. package/dist/credits/postgres/repositories/bucket.d.ts +25 -0
  221. package/dist/credits/postgres/repositories/bucket.d.ts.map +1 -0
  222. package/dist/credits/postgres/repositories/bucket.js +52 -0
  223. package/dist/credits/postgres/repositories/bucket.js.map +1 -0
  224. package/dist/credits/postgres/repositories/deduction.d.ts +64 -0
  225. package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -0
  226. package/dist/credits/postgres/repositories/deduction.js +154 -0
  227. package/dist/credits/postgres/repositories/deduction.js.map +1 -0
  228. package/dist/credits/postgres/repositories/lease.d.ts +69 -0
  229. package/dist/credits/postgres/repositories/lease.d.ts.map +1 -0
  230. package/dist/credits/postgres/repositories/lease.js +148 -0
  231. package/dist/credits/postgres/repositories/lease.js.map +1 -0
  232. package/dist/credits/postgres/repositories/plan.d.ts +110 -0
  233. package/dist/credits/postgres/repositories/plan.d.ts.map +1 -0
  234. package/dist/credits/postgres/repositories/plan.js +194 -0
  235. package/dist/credits/postgres/repositories/plan.js.map +1 -0
  236. package/dist/credits/postgres/repositories/pricing.d.ts +28 -0
  237. package/dist/credits/postgres/repositories/pricing.d.ts.map +1 -0
  238. package/dist/credits/postgres/repositories/pricing.js +76 -0
  239. package/dist/credits/postgres/repositories/pricing.js.map +1 -0
  240. package/dist/credits/postgres/repositories/team.d.ts +63 -0
  241. package/dist/credits/postgres/repositories/team.d.ts.map +1 -0
  242. package/dist/credits/postgres/repositories/team.js +120 -0
  243. package/dist/credits/postgres/repositories/team.js.map +1 -0
  244. package/dist/credits/postgres/store.d.ts +89 -0
  245. package/dist/credits/postgres/store.d.ts.map +1 -0
  246. package/dist/credits/postgres/store.js +838 -0
  247. package/dist/credits/postgres/store.js.map +1 -0
  248. package/dist/credits/postgres/value-mappers.d.ts +17 -0
  249. package/dist/credits/postgres/value-mappers.d.ts.map +1 -0
  250. package/dist/credits/postgres/value-mappers.js +102 -0
  251. package/dist/credits/postgres/value-mappers.js.map +1 -0
  252. package/dist/credits/pricing-runtime.d.ts +35 -0
  253. package/dist/credits/pricing-runtime.d.ts.map +1 -0
  254. package/dist/credits/pricing-runtime.js +141 -0
  255. package/dist/credits/pricing-runtime.js.map +1 -0
  256. package/dist/credits/queries.d.ts +33 -0
  257. package/dist/credits/queries.d.ts.map +1 -0
  258. package/dist/credits/queries.js +71 -0
  259. package/dist/credits/queries.js.map +1 -0
  260. package/dist/credits/service-errors.d.ts +4 -0
  261. package/dist/credits/service-errors.d.ts.map +1 -0
  262. package/dist/credits/service-errors.js +57 -0
  263. package/dist/credits/service-errors.js.map +1 -0
  264. package/dist/credits/service-types.d.ts +122 -0
  265. package/dist/credits/service-types.d.ts.map +1 -0
  266. package/dist/credits/service-types.js +2 -0
  267. package/dist/credits/service-types.js.map +1 -0
  268. package/dist/credits/service.d.ts +220 -0
  269. package/dist/credits/service.d.ts.map +1 -0
  270. package/dist/credits/service.js +640 -0
  271. package/dist/credits/service.js.map +1 -0
  272. package/dist/credits/store.d.ts +172 -0
  273. package/dist/credits/store.d.ts.map +1 -0
  274. package/dist/{stores/credit-store.js → credits/store.js} +27 -43
  275. package/dist/credits/store.js.map +1 -0
  276. package/dist/credits/types/account.d.ts +82 -0
  277. package/dist/credits/types/account.d.ts.map +1 -0
  278. package/dist/credits/types/account.js +2 -0
  279. package/dist/credits/types/account.js.map +1 -0
  280. package/dist/credits/types/admission.d.ts +39 -0
  281. package/dist/credits/types/admission.d.ts.map +1 -0
  282. package/dist/credits/types/admission.js +2 -0
  283. package/dist/credits/types/admission.js.map +1 -0
  284. package/dist/credits/types/analytics.d.ts +52 -0
  285. package/dist/credits/types/analytics.d.ts.map +1 -0
  286. package/dist/credits/types/analytics.js +2 -0
  287. package/dist/credits/types/analytics.js.map +1 -0
  288. package/dist/credits/types/catalog.d.ts +71 -0
  289. package/dist/credits/types/catalog.d.ts.map +1 -0
  290. package/dist/credits/types/catalog.js +2 -0
  291. package/dist/credits/types/catalog.js.map +1 -0
  292. package/dist/credits/types/grants.d.ts +24 -0
  293. package/dist/credits/types/grants.d.ts.map +1 -0
  294. package/dist/credits/types/grants.js +2 -0
  295. package/dist/credits/types/grants.js.map +1 -0
  296. package/dist/credits/types/index.d.ts +9 -0
  297. package/dist/credits/types/index.d.ts.map +1 -0
  298. package/dist/credits/types/index.js +2 -0
  299. package/dist/credits/types/index.js.map +1 -0
  300. package/dist/credits/types/ledger.d.ts +87 -0
  301. package/dist/credits/types/ledger.d.ts.map +1 -0
  302. package/dist/credits/types/ledger.js +2 -0
  303. package/dist/credits/types/ledger.js.map +1 -0
  304. package/dist/credits/types/quotas.d.ts +40 -0
  305. package/dist/credits/types/quotas.d.ts.map +1 -0
  306. package/dist/credits/types/quotas.js +2 -0
  307. package/dist/credits/types/quotas.js.map +1 -0
  308. package/dist/credits/types/teams.d.ts +44 -0
  309. package/dist/credits/types/teams.d.ts.map +1 -0
  310. package/dist/credits/types/teams.js +2 -0
  311. package/dist/credits/types/teams.js.map +1 -0
  312. package/dist/engine.d.ts +18 -39
  313. package/dist/engine.d.ts.map +1 -1
  314. package/dist/engine.js +169 -145
  315. package/dist/engine.js.map +1 -1
  316. package/dist/errors.d.ts +133 -25
  317. package/dist/errors.d.ts.map +1 -1
  318. package/dist/errors.js +173 -24
  319. package/dist/errors.js.map +1 -1
  320. package/dist/expr/ast.d.ts +46 -0
  321. package/dist/expr/ast.d.ts.map +1 -0
  322. package/dist/expr/ast.js +18 -0
  323. package/dist/expr/ast.js.map +1 -0
  324. package/dist/expr/evaluator.d.ts +4 -0
  325. package/dist/expr/evaluator.d.ts.map +1 -0
  326. package/dist/expr/evaluator.js +144 -0
  327. package/dist/expr/evaluator.js.map +1 -0
  328. package/dist/expr/language.d.ts +5 -0
  329. package/dist/expr/language.d.ts.map +1 -0
  330. package/dist/expr/language.js +73 -0
  331. package/dist/expr/language.js.map +1 -0
  332. package/dist/expr/parser.d.ts +24 -0
  333. package/dist/expr/parser.d.ts.map +1 -0
  334. package/dist/expr/parser.js +175 -0
  335. package/dist/expr/parser.js.map +1 -0
  336. package/dist/expr/tokenizer.d.ts +7 -0
  337. package/dist/expr/tokenizer.d.ts.map +1 -0
  338. package/dist/expr/tokenizer.js +85 -0
  339. package/dist/expr/tokenizer.js.map +1 -0
  340. package/dist/expr.d.ts +7 -58
  341. package/dist/expr.d.ts.map +1 -1
  342. package/dist/expr.js +41 -640
  343. package/dist/expr.js.map +1 -1
  344. package/dist/generated/pricing-config.schema.json +2792 -0
  345. package/dist/generated/pricing-config.types.d.ts +685 -0
  346. package/dist/generated/pricing-config.types.d.ts.map +1 -0
  347. package/dist/generated/pricing-config.types.js +8 -0
  348. package/dist/generated/pricing-config.types.js.map +1 -0
  349. package/dist/index.d.ts +23 -17
  350. package/dist/index.d.ts.map +1 -1
  351. package/dist/index.js +12 -10
  352. package/dist/index.js.map +1 -1
  353. package/dist/load-pricing-file.d.ts.map +1 -1
  354. package/dist/load-pricing-file.js +8 -4
  355. package/dist/load-pricing-file.js.map +1 -1
  356. package/dist/metrics.d.ts +6 -16
  357. package/dist/metrics.d.ts.map +1 -1
  358. package/dist/metrics.js.map +1 -1
  359. package/dist/node.d.ts +9 -2
  360. package/dist/node.d.ts.map +1 -1
  361. package/dist/node.js +6 -2
  362. package/dist/node.js.map +1 -1
  363. package/dist/providers/_shared.d.ts +9 -0
  364. package/dist/providers/_shared.d.ts.map +1 -0
  365. package/dist/providers/_shared.js +52 -0
  366. package/dist/providers/_shared.js.map +1 -0
  367. package/dist/providers/dodo/client-contract.d.ts +106 -0
  368. package/dist/providers/dodo/client-contract.d.ts.map +1 -0
  369. package/dist/providers/dodo/client-contract.js +2 -0
  370. package/dist/providers/dodo/client-contract.js.map +1 -0
  371. package/dist/providers/dodo/event-mapper.d.ts +5 -3
  372. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  373. package/dist/providers/dodo/event-mapper.js +213 -38
  374. package/dist/providers/dodo/event-mapper.js.map +1 -1
  375. package/dist/providers/dodo/index.d.ts +1 -0
  376. package/dist/providers/dodo/index.d.ts.map +1 -1
  377. package/dist/providers/dodo/index.js.map +1 -1
  378. package/dist/providers/dodo/provider.d.ts +24 -14
  379. package/dist/providers/dodo/provider.d.ts.map +1 -1
  380. package/dist/providers/dodo/provider.js +249 -31
  381. package/dist/providers/dodo/provider.js.map +1 -1
  382. package/dist/providers/index.d.ts +3 -1
  383. package/dist/providers/index.d.ts.map +1 -1
  384. package/dist/providers/index.js +1 -0
  385. package/dist/providers/index.js.map +1 -1
  386. package/dist/providers/mock/index.js.map +1 -1
  387. package/dist/providers/mock/provider.d.ts +14 -10
  388. package/dist/providers/mock/provider.d.ts.map +1 -1
  389. package/dist/providers/mock/provider.js +78 -10
  390. package/dist/providers/mock/provider.js.map +1 -1
  391. package/dist/providers/stripe/event-mapper.d.ts +3 -3
  392. package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
  393. package/dist/providers/stripe/event-mapper.js +139 -30
  394. package/dist/providers/stripe/event-mapper.js.map +1 -1
  395. package/dist/providers/stripe/index.js.map +1 -1
  396. package/dist/providers/stripe/provider.d.ts +21 -12
  397. package/dist/providers/stripe/provider.d.ts.map +1 -1
  398. package/dist/providers/stripe/provider.js +175 -17
  399. package/dist/providers/stripe/provider.js.map +1 -1
  400. package/dist/providers/types.d.ts +128 -32
  401. package/dist/providers/types.d.ts.map +1 -1
  402. package/dist/providers/types.js +17 -1
  403. package/dist/providers/types.js.map +1 -1
  404. package/dist/retry.d.ts +35 -0
  405. package/dist/retry.d.ts.map +1 -0
  406. package/dist/retry.js +70 -0
  407. package/dist/retry.js.map +1 -0
  408. package/dist/shared/diagnostics.d.ts +7 -0
  409. package/dist/shared/diagnostics.d.ts.map +1 -0
  410. package/dist/shared/diagnostics.js +18 -0
  411. package/dist/shared/diagnostics.js.map +1 -0
  412. package/dist/shared/logger.d.ts +10 -0
  413. package/dist/shared/logger.d.ts.map +1 -0
  414. package/dist/shared/logger.js +15 -0
  415. package/dist/shared/logger.js.map +1 -0
  416. package/dist/shared/postgres-client.d.ts +84 -0
  417. package/dist/shared/postgres-client.d.ts.map +1 -0
  418. package/dist/shared/postgres-client.js +337 -0
  419. package/dist/shared/postgres-client.js.map +1 -0
  420. package/dist/shared/postgres-errors.d.ts +11 -0
  421. package/dist/shared/postgres-errors.d.ts.map +1 -0
  422. package/dist/shared/postgres-errors.js +105 -0
  423. package/dist/shared/postgres-errors.js.map +1 -0
  424. package/dist/shared/postgres-types.d.ts +7 -0
  425. package/dist/shared/postgres-types.d.ts.map +1 -0
  426. package/dist/shared/postgres-types.js +2 -0
  427. package/dist/shared/postgres-types.js.map +1 -0
  428. package/dist/shared/postgres-validation.d.ts +8 -0
  429. package/dist/shared/postgres-validation.d.ts.map +1 -0
  430. package/dist/shared/postgres-validation.js +40 -0
  431. package/dist/shared/postgres-validation.js.map +1 -0
  432. package/dist/storage/adapters/clickhouse.d.ts +61 -0
  433. package/dist/storage/adapters/clickhouse.d.ts.map +1 -0
  434. package/dist/storage/adapters/clickhouse.js +347 -0
  435. package/dist/storage/adapters/clickhouse.js.map +1 -0
  436. package/dist/storage/adapters/s3.d.ts +35 -0
  437. package/dist/storage/adapters/s3.d.ts.map +1 -0
  438. package/dist/storage/adapters/s3.js +100 -0
  439. package/dist/storage/adapters/s3.js.map +1 -0
  440. package/dist/storage/outbox-worker.d.ts +41 -0
  441. package/dist/storage/outbox-worker.d.ts.map +1 -0
  442. package/dist/storage/outbox-worker.js +146 -0
  443. package/dist/storage/outbox-worker.js.map +1 -0
  444. package/dist/storage/ports.d.ts +78 -0
  445. package/dist/storage/ports.d.ts.map +1 -0
  446. package/dist/storage/ports.js +2 -0
  447. package/dist/storage/ports.js.map +1 -0
  448. package/dist/storage/postgres-repository.d.ts +14 -0
  449. package/dist/storage/postgres-repository.d.ts.map +1 -0
  450. package/dist/storage/postgres-repository.js +140 -0
  451. package/dist/storage/postgres-repository.js.map +1 -0
  452. package/dist/storage/runtime.d.ts +77 -0
  453. package/dist/storage/runtime.d.ts.map +1 -0
  454. package/dist/storage/runtime.js +369 -0
  455. package/dist/storage/runtime.js.map +1 -0
  456. package/package.json +43 -21
  457. package/dist/allowance.d.ts +0 -48
  458. package/dist/allowance.d.ts.map +0 -1
  459. package/dist/allowance.js +0 -140
  460. package/dist/allowance.js.map +0 -1
  461. package/dist/billing/billing-manager.d.ts +0 -66
  462. package/dist/billing/billing-manager.d.ts.map +0 -1
  463. package/dist/billing/billing-manager.js +0 -560
  464. package/dist/billing/billing-manager.js.map +0 -1
  465. package/dist/billing/billing-types.d.ts +0 -203
  466. package/dist/billing/billing-types.d.ts.map +0 -1
  467. package/dist/billing/billing-types.js +0 -6
  468. package/dist/billing/billing-types.js.map +0 -1
  469. package/dist/billing/memory-billing-store.d.ts +0 -37
  470. package/dist/billing/memory-billing-store.d.ts.map +0 -1
  471. package/dist/billing/memory-billing-store.js +0 -197
  472. package/dist/billing/memory-billing-store.js.map +0 -1
  473. package/dist/billing/postgres-billing-store.d.ts +0 -35
  474. package/dist/billing/postgres-billing-store.d.ts.map +0 -1
  475. package/dist/billing/postgres-billing-store.js +0 -274
  476. package/dist/billing/postgres-billing-store.js.map +0 -1
  477. package/dist/billing/supabase-billing-store.d.ts +0 -29
  478. package/dist/billing/supabase-billing-store.d.ts.map +0 -1
  479. package/dist/billing/supabase-billing-store.js +0 -250
  480. package/dist/billing/supabase-billing-store.js.map +0 -1
  481. package/dist/manager.d.ts +0 -444
  482. package/dist/manager.d.ts.map +0 -1
  483. package/dist/manager.js +0 -1153
  484. package/dist/manager.js.map +0 -1
  485. package/dist/stores/credit-store.d.ts +0 -198
  486. package/dist/stores/credit-store.d.ts.map +0 -1
  487. package/dist/stores/credit-store.js.map +0 -1
  488. package/dist/stores/events.d.ts.map +0 -1
  489. package/dist/stores/events.js.map +0 -1
  490. package/dist/stores/memory-store.d.ts +0 -187
  491. package/dist/stores/memory-store.d.ts.map +0 -1
  492. package/dist/stores/memory-store.js +0 -1890
  493. package/dist/stores/memory-store.js.map +0 -1
  494. package/dist/stores/postgres-store.d.ts +0 -100
  495. package/dist/stores/postgres-store.d.ts.map +0 -1
  496. package/dist/stores/postgres-store.js +0 -891
  497. package/dist/stores/postgres-store.js.map +0 -1
  498. package/dist/stores/supabase-store.d.ts +0 -87
  499. package/dist/stores/supabase-store.d.ts.map +0 -1
  500. package/dist/stores/supabase-store.js +0 -948
  501. package/dist/stores/supabase-store.js.map +0 -1
  502. package/dist/types.d.ts +0 -463
  503. package/dist/types.d.ts.map +0 -1
  504. package/dist/types.js.map +0 -1
  505. /package/dist/{types.js → commerce/types.js} +0 -0
@@ -0,0 +1,1016 @@
1
+ import { createHash } from "node:crypto";
2
+ import Decimal from "decimal.js";
3
+ import { loadConfigFromDict } from "../config.js";
4
+ import { ConfigError } from "../errors.js";
5
+ import { normalizeLogger } from "../shared/logger.js";
6
+ import { ActiveSubscriptionError, CheckoutCompletedError, CheckoutConflictError, CommerceResourceNotFoundError, CoreBillingDataUnavailableError, InvalidOfferQuantityError, MissingPaymentMethodError, ProviderCapabilityNotSupportedError, QuoteChangedError, UnknownOfferError, } from "./errors.js";
7
+ import { CommerceProviderRegistry } from "./provider-registry.js";
8
+ import { classifySubscriptionChange } from "./plan-change.js";
9
+ const DEFAULT_CHECKOUT_INTENT_TTL_MS = 24 * 60 * 60 * 1_000;
10
+ const DEFAULT_PREFERENCES = {
11
+ autoRecharge: false,
12
+ overageProtection: true,
13
+ emailNotifications: true,
14
+ usageAlerts: true,
15
+ invoiceReminders: false,
16
+ };
17
+ const TERMINAL_CHECKOUT_STATUSES = new Set(["failed", "cancelled", "requires_payment_method"]);
18
+ const CURRENT_SUBSCRIPTION_STATUSES = new Set(["active", "trialing", "past_due", "incomplete"]);
19
+ const BLOCKING_SUBSCRIPTION_STATUSES = new Set(["active", "trialing", "past_due", "incomplete"]);
20
+ const TERMINAL_SUBSCRIPTION_STATUSES = new Set([
21
+ "canceled",
22
+ "unpaid",
23
+ "paused",
24
+ "incomplete_expired",
25
+ "expired",
26
+ ]);
27
+ function externalId(reference) {
28
+ switch (reference.type) {
29
+ case "stripe_price":
30
+ return reference.priceId;
31
+ case "dodo_product":
32
+ return reference.productId;
33
+ case "custom_object":
34
+ return reference.externalId;
35
+ }
36
+ }
37
+ function checkoutRedirectUrl(template, intentId) {
38
+ return template.replaceAll("{intentId}", encodeURIComponent(intentId));
39
+ }
40
+ function quoteFingerprint(preview) {
41
+ const amount = (value) => {
42
+ const numeric = Number(value);
43
+ return Number.isFinite(numeric) ? numeric : null;
44
+ };
45
+ const financialFields = {
46
+ totalAmount: amount(preview.totalAmount),
47
+ settlementAmount: amount(preview.settlementAmount),
48
+ currency: preview.currency.toUpperCase(),
49
+ recurringAmount: amount(preview.recurringAmount),
50
+ recurringCurrency: preview.recurringCurrency?.toUpperCase() ?? null,
51
+ taxAmount: amount(preview.taxAmount),
52
+ customerCredits: amount(preview.customerCredits),
53
+ lineItems: preview.lineItems.map((item) => ({
54
+ productId: item.productId,
55
+ unitPrice: amount(item.unitPrice),
56
+ quantity: amount(item.quantity),
57
+ prorationFactor: amount(item.prorationFactor),
58
+ currency: item.currency.toUpperCase(),
59
+ tax: amount(item.tax),
60
+ subtotal: amount(item.subtotal),
61
+ })),
62
+ };
63
+ return createHash("sha256").update(JSON.stringify(financialFields)).digest("hex");
64
+ }
65
+ function providerPlanChangeParams(policy) {
66
+ return {
67
+ effectiveAt: policy.effective === "renewal" ? "next_billing_date" : "immediately",
68
+ prorationBillingMode: policy.proration === "none" ? "do_not_bill" : "prorated_immediately",
69
+ };
70
+ }
71
+ class CommerceAutoRechargeService {
72
+ commerce;
73
+ constructor(commerce) {
74
+ this.commerce = commerce;
75
+ }
76
+ async getStatus(input) {
77
+ const provider = await this.commerce.providerForAccount(input.accountId);
78
+ return this.commerce.billing.autoRecharge.getStatus({
79
+ userId: input.accountId,
80
+ provider,
81
+ });
82
+ }
83
+ async enable(input) {
84
+ const [provider, balance] = await Promise.all([
85
+ this.commerce.providerForAccount(input.accountId),
86
+ this.commerce.credits.getBalance(input.accountId),
87
+ ]);
88
+ try {
89
+ return await this.commerce.billing.autoRecharge.enable({
90
+ userId: input.accountId,
91
+ provider,
92
+ balance: Number(balance.balance),
93
+ returnUrl: input.returnUrl,
94
+ });
95
+ }
96
+ catch (error) {
97
+ if (error instanceof Error && error.message.includes("payment_method")) {
98
+ throw new MissingPaymentMethodError();
99
+ }
100
+ throw error;
101
+ }
102
+ }
103
+ async disable(input) {
104
+ await this.commerce.billing.autoRecharge.disable(input.accountId);
105
+ }
106
+ async retry(input) {
107
+ const [provider, balance] = await Promise.all([
108
+ this.commerce.providerForAccount(input.accountId),
109
+ this.commerce.credits.getBalance(input.accountId),
110
+ ]);
111
+ try {
112
+ await this.commerce.billing.autoRecharge.retry({
113
+ userId: input.accountId,
114
+ provider,
115
+ balance: Number(balance.balance),
116
+ returnUrl: input.returnUrl,
117
+ });
118
+ return this.commerce.billing.autoRecharge.getStatus({
119
+ userId: input.accountId,
120
+ provider,
121
+ });
122
+ }
123
+ catch (error) {
124
+ if (error instanceof Error && error.message.includes("payment_method")) {
125
+ throw new MissingPaymentMethodError();
126
+ }
127
+ throw error;
128
+ }
129
+ }
130
+ async processIfNeeded(input) {
131
+ const profile = await this.commerce.billing.getAutoRechargeProfile(input.accountId);
132
+ if (!profile?.enabled || profile.state !== "active") {
133
+ return { outcome: "disabled" };
134
+ }
135
+ const [provider, balance] = await Promise.all([
136
+ profile.provider
137
+ ? this.commerce.providers.get(profile.provider)
138
+ : this.commerce.providerForAccount(input.accountId),
139
+ this.commerce.credits.getBalance(input.accountId),
140
+ ]);
141
+ return this.commerce.billing.autoRecharge.processIfNeeded({
142
+ userId: input.accountId,
143
+ provider,
144
+ balance: Number(balance.balance),
145
+ returnUrl: input.returnUrl,
146
+ });
147
+ }
148
+ }
149
+ /** Framework-independent catalog, billing-state, and provider coordinator. */
150
+ export class CommerceService {
151
+ billing;
152
+ credits;
153
+ options;
154
+ autoRecharge;
155
+ providers;
156
+ logger;
157
+ constructor(billing, credits, eventSink, options) {
158
+ this.billing = billing;
159
+ this.credits = credits;
160
+ this.options = options;
161
+ this.logger = normalizeLogger(options.logger);
162
+ const identityResolver = options.identityResolver
163
+ ? async (input) => {
164
+ const accountId = await options.identityResolver(input);
165
+ if (accountId && input.customerId) {
166
+ await this.billing.upsertCustomer(input.provider, input.customerId, accountId, input.email);
167
+ }
168
+ return accountId;
169
+ }
170
+ : undefined;
171
+ this.providers = new CommerceProviderRegistry(options, {
172
+ tenantId: options.tenantId,
173
+ eventSink,
174
+ identityResolver,
175
+ });
176
+ this.autoRecharge = new CommerceAutoRechargeService(this);
177
+ }
178
+ /** Exposed for application composition and compatibility, not provider selection policy. */
179
+ getProvider(providerName) {
180
+ return this.providers.get(providerName);
181
+ }
182
+ clearProviderCache() {
183
+ this.providers.clear();
184
+ }
185
+ async activeConfig() {
186
+ const raw = await this.billing.getActiveBursarConfig();
187
+ if (!raw) {
188
+ throw new CoreBillingDataUnavailableError("The active commerce catalog is unavailable");
189
+ }
190
+ try {
191
+ return loadConfigFromDict(raw);
192
+ }
193
+ catch (error) {
194
+ throw new CoreBillingDataUnavailableError("The active commerce catalog is invalid", error);
195
+ }
196
+ }
197
+ async resolveOffer(input) {
198
+ const config = await this.activeConfig();
199
+ const offer = config.commerce.offers[input.offerKey];
200
+ if (!offer)
201
+ throw new UnknownOfferError(`Unknown offer '${input.offerKey}'`);
202
+ this.assertOfferType(offer, input.type);
203
+ return { config, offerKey: input.offerKey, offer };
204
+ }
205
+ assertOfferType(offer, type) {
206
+ if (!type)
207
+ return;
208
+ const expected = type === "credit_pack" ? "topup" : "subscription";
209
+ if (offer.type !== expected) {
210
+ throw new UnknownOfferError(`Offer is not a ${type} offer`);
211
+ }
212
+ }
213
+ quantity(offer, requested) {
214
+ if (offer.type === "subscription") {
215
+ if (requested != null && requested !== 1) {
216
+ throw new InvalidOfferQuantityError("Subscription quantity must be 1", 1, 1);
217
+ }
218
+ return 1;
219
+ }
220
+ const quantity = requested ?? offer.quantity.default;
221
+ if (!Number.isInteger(quantity) || quantity < offer.quantity.minimum) {
222
+ throw new InvalidOfferQuantityError(`Minimum quantity is ${offer.quantity.minimum}`, offer.quantity.minimum, offer.quantity.maximum);
223
+ }
224
+ if (quantity > offer.quantity.maximum) {
225
+ throw new InvalidOfferQuantityError(`Maximum quantity is ${offer.quantity.maximum}`, offer.quantity.minimum, offer.quantity.maximum);
226
+ }
227
+ return quantity;
228
+ }
229
+ async providerForAccount(accountId, offer) {
230
+ const subscription = await this.billing.getUserSubscription(accountId);
231
+ const customer = await this.billing.getCustomerByUserId(accountId, subscription?.provider);
232
+ return this.providers.select({
233
+ current: subscription?.provider ?? customer?.provider,
234
+ offer,
235
+ });
236
+ }
237
+ async createCheckout(input) {
238
+ const resolved = await this.resolveOffer(input);
239
+ const quantity = this.quantity(resolved.offer, input.quantity);
240
+ const accountState = input.accountId
241
+ ? await Promise.all([
242
+ this.billing.getBlockingSubscription(input.accountId),
243
+ this.billing.getCustomerByUserId(input.accountId),
244
+ ])
245
+ : [null, null];
246
+ if (resolved.offer.type === "subscription" && accountState[0]) {
247
+ throw new ActiveSubscriptionError();
248
+ }
249
+ const provider = await this.providers.select({
250
+ requested: input.provider,
251
+ current: accountState[1]?.provider,
252
+ offer: resolved.offer,
253
+ });
254
+ const reference = resolved.offer.providers[provider.provider];
255
+ if (!reference)
256
+ throw new UnknownOfferError("Offer has no reference for the selected provider");
257
+ const productId = externalId(reference);
258
+ const customer = input.accountId
259
+ ? await this.billing.getCustomerByUserId(input.accountId, provider.provider)
260
+ : null;
261
+ const metadata = {
262
+ ...(input.metadata ?? {}),
263
+ ...(input.accountId ? { userId: input.accountId } : {}),
264
+ };
265
+ if (resolved.offer.type === "subscription") {
266
+ metadata.plan_slug = resolved.offer.plan;
267
+ metadata.billing_interval = resolved.offer.billingInterval.unit;
268
+ }
269
+ else {
270
+ metadata.credits = resolved.offer.creditsPerUnit.mul(quantity).toString();
271
+ metadata.quantity = String(quantity);
272
+ }
273
+ const requestDigest = createHash("sha256")
274
+ .update(JSON.stringify({
275
+ checkoutKind: resolved.offer.type,
276
+ offerKey: resolved.offerKey,
277
+ provider: provider.provider,
278
+ quantity,
279
+ }))
280
+ .digest("hex");
281
+ const expiresAt = () => new Date(Date.now() + (this.options.checkoutIntentTtlMs ?? DEFAULT_CHECKOUT_INTENT_TTL_MS)).toISOString();
282
+ const createIntent = () => this.billing.createOrGetCheckoutIntent({
283
+ subjectId: input.subjectId,
284
+ provider: provider.provider,
285
+ checkoutKind: resolved.offer.type === "subscription" ? "subscription" : "credit_topup",
286
+ productKey: resolved.offerKey,
287
+ requestDigest,
288
+ expiresAt: expiresAt(),
289
+ });
290
+ let intent = await createIntent();
291
+ if (intent.requestDigest !== requestDigest) {
292
+ throw new CheckoutConflictError("A checkout is already in progress for a different offer");
293
+ }
294
+ if (intent.checkoutUrl) {
295
+ const locallyExpired = new Date(intent.expiresAt).getTime() <= Date.now();
296
+ if (!locallyExpired && (!intent.providerSessionId || !provider.getCheckoutSessionStatus)) {
297
+ throw new CheckoutConflictError("A checkout is already in progress; continue it in the existing checkout window");
298
+ }
299
+ const providerState = locallyExpired
300
+ ? null
301
+ : await provider.getCheckoutSessionStatus(intent.providerSessionId);
302
+ if (providerState?.paymentStatus === "succeeded") {
303
+ await this.billing.updateCheckoutIntent(intent.id, { status: "completed" });
304
+ throw new CheckoutCompletedError();
305
+ }
306
+ if (!locallyExpired &&
307
+ providerState !== null &&
308
+ !TERMINAL_CHECKOUT_STATUSES.has(providerState.paymentStatus ?? "")) {
309
+ throw new CheckoutConflictError("A checkout is already in progress; continue it in the existing checkout window");
310
+ }
311
+ await this.billing.updateCheckoutIntent(intent.id, {
312
+ status: providerState === null ? "expired" : "failed",
313
+ });
314
+ intent = await createIntent();
315
+ }
316
+ try {
317
+ const session = await provider.createCheckoutSession({
318
+ ...(input.accountId ? { userId: input.accountId } : {}),
319
+ ...(customer?.providerCustomerId ? { customerId: customer.providerCustomerId } : {}),
320
+ ...(input.email ? { email: input.email } : {}),
321
+ productId,
322
+ type: resolved.offer.type === "subscription" ? "subscription" : "credit_pack",
323
+ quantity,
324
+ returnUrl: checkoutRedirectUrl(input.returnUrl, intent.id),
325
+ cancelUrl: checkoutRedirectUrl(input.cancelUrl, intent.id),
326
+ metadata: { ...metadata, checkout_intent_id: intent.id },
327
+ idempotencyKey: input.operationKey,
328
+ });
329
+ await this.billing.updateCheckoutIntent(intent.id, {
330
+ providerSessionId: session.providerSessionId,
331
+ checkoutUrl: session.url,
332
+ });
333
+ if (input.accountId &&
334
+ session.customerId &&
335
+ session.customerId !== customer?.providerCustomerId) {
336
+ await this.billing.upsertCustomer(provider.provider, session.customerId, input.accountId, input.email ?? null);
337
+ }
338
+ return {
339
+ intentId: intent.id,
340
+ url: session.url,
341
+ provider: provider.provider,
342
+ offerKey: resolved.offerKey,
343
+ };
344
+ }
345
+ catch (error) {
346
+ await this.billing.updateCheckoutIntent(intent.id, { status: "failed" });
347
+ throw error;
348
+ }
349
+ }
350
+ async getCheckoutStatus(input) {
351
+ const intent = await this.billing.getCheckoutIntent(input.intentId, input.subjectId);
352
+ if (!intent)
353
+ throw new CommerceResourceNotFoundError("Checkout intent not found");
354
+ const expired = intent.status === "open" && new Date(intent.expiresAt).getTime() <= Date.now();
355
+ return {
356
+ intentId: intent.id,
357
+ status: expired
358
+ ? "expired"
359
+ : intent.status === "open"
360
+ ? "pending"
361
+ : intent.status === "completed"
362
+ ? "succeeded"
363
+ : intent.status,
364
+ };
365
+ }
366
+ async cancelSubscription(input) {
367
+ const subscription = await this.billing.getUserSubscription(input.accountId);
368
+ if (!subscription?.providerSubscriptionId) {
369
+ throw new CommerceResourceNotFoundError("No active subscription found");
370
+ }
371
+ if (!["active", "trialing", "past_due"].includes(subscription.status ?? "")) {
372
+ return { ok: true };
373
+ }
374
+ const provider = await this.providers.get(subscription.provider);
375
+ if (!provider.cancelSubscription) {
376
+ throw new ProviderCapabilityNotSupportedError(provider.provider, "cancelSubscription");
377
+ }
378
+ await provider.cancelSubscription(subscription.providerSubscriptionId, input.operationKey);
379
+ await this.billing.ingestBillingEvent({
380
+ provider: subscription.provider,
381
+ eventId: `cancel_${input.accountId}_${input.operationKey}`,
382
+ eventType: "subscription.cancellation_scheduled",
383
+ occurredAt: new Date().toISOString(),
384
+ userId: input.accountId,
385
+ customer: { providerCustomerId: subscription.providerCustomerId },
386
+ subscription: {
387
+ providerSubscriptionId: subscription.providerSubscriptionId,
388
+ cancelAtPeriodEnd: true,
389
+ },
390
+ });
391
+ return { ok: true, pending: true };
392
+ }
393
+ async reactivateSubscription(input) {
394
+ const subscription = await this.billing.getUserSubscription(input.accountId);
395
+ if (!subscription?.providerSubscriptionId) {
396
+ throw new CommerceResourceNotFoundError("No subscription found");
397
+ }
398
+ if ((subscription.status === "active" && !subscription.cancelAtPeriodEnd) ||
399
+ (!subscription.cancelAtPeriodEnd && subscription.status !== "canceled")) {
400
+ return { ok: true };
401
+ }
402
+ const provider = await this.providers.get(subscription.provider);
403
+ if (!provider.reactivateSubscription) {
404
+ throw new ProviderCapabilityNotSupportedError(provider.provider, "reactivateSubscription");
405
+ }
406
+ await provider.reactivateSubscription(subscription.providerSubscriptionId, input.operationKey);
407
+ await this.billing.ingestBillingEvent({
408
+ provider: subscription.provider,
409
+ eventId: `reactivate_${input.accountId}_${input.operationKey}`,
410
+ eventType: "subscription.cancellation_unscheduled",
411
+ occurredAt: new Date().toISOString(),
412
+ userId: input.accountId,
413
+ customer: { providerCustomerId: subscription.providerCustomerId },
414
+ subscription: {
415
+ providerSubscriptionId: subscription.providerSubscriptionId,
416
+ cancelAtPeriodEnd: false,
417
+ },
418
+ });
419
+ return { ok: true, pending: true };
420
+ }
421
+ async cancelAllSubscriptions(input) {
422
+ if (!input.operationKey.trim()) {
423
+ throw new ConfigError("operationKey must not be empty");
424
+ }
425
+ const subscriptions = await this.billing.listCancellableSubscriptions(input.accountId);
426
+ const results = await Promise.all(subscriptions.map(async (subscription) => {
427
+ try {
428
+ const provider = await this.providers.get(subscription.provider);
429
+ if (!provider.cancelSubscription) {
430
+ throw new ProviderCapabilityNotSupportedError(provider.provider, "cancelSubscription");
431
+ }
432
+ const operationKey = `${input.operationKey}:${subscription.provider}:${subscription.providerSubscriptionId}`;
433
+ await provider.cancelSubscription(subscription.providerSubscriptionId, operationKey);
434
+ await this.billing.ingestBillingEvent({
435
+ provider: subscription.provider,
436
+ eventId: `cancel_all_${input.accountId}_${operationKey}`,
437
+ eventType: "subscription.cancellation_scheduled",
438
+ occurredAt: new Date().toISOString(),
439
+ userId: input.accountId,
440
+ customer: { providerCustomerId: subscription.providerCustomerId },
441
+ subscription: {
442
+ providerSubscriptionId: subscription.providerSubscriptionId,
443
+ cancelAtPeriodEnd: true,
444
+ },
445
+ });
446
+ return {
447
+ provider: subscription.provider,
448
+ providerSubscriptionId: subscription.providerSubscriptionId,
449
+ canceled: true,
450
+ error: null,
451
+ };
452
+ }
453
+ catch (error) {
454
+ return {
455
+ provider: subscription.provider,
456
+ providerSubscriptionId: subscription.providerSubscriptionId,
457
+ canceled: false,
458
+ error: error instanceof Error ? error.message : String(error),
459
+ };
460
+ }
461
+ }));
462
+ const failures = results.filter((result) => !result.canceled);
463
+ if (failures.length) {
464
+ throw new AggregateError(failures.map((failure) => new Error(failure.error ?? "Subscription cancellation failed")), "One or more subscriptions could not be cancelled");
465
+ }
466
+ return {
467
+ accountId: input.accountId,
468
+ canceledCount: results.length,
469
+ subscriptions: results,
470
+ };
471
+ }
472
+ accountSubscriptionSummary(accountId, subscription, entitlement, config, pending) {
473
+ let pendingChange = null;
474
+ if (pending) {
475
+ const planKey = pending.toOffer.plan;
476
+ const interval = pending.toOffer.interval;
477
+ if (!planKey ||
478
+ !config.plans[planKey] ||
479
+ (interval !== "month" && interval !== "year") ||
480
+ !pending.effectiveAt) {
481
+ throw new CoreBillingDataUnavailableError("Pending subscription change has incomplete catalog context");
482
+ }
483
+ pendingChange = {
484
+ planKey,
485
+ interval,
486
+ effectiveAt: pending.effectiveAt,
487
+ scheduled: pending.effective === "renewal",
488
+ providerOperationId: pending.providerOperationId ?? null,
489
+ };
490
+ }
491
+ const status = subscription?.status ?? null;
492
+ const isCurrent = status != null && CURRENT_SUBSCRIPTION_STATUSES.has(status);
493
+ const isEntitled = entitlement.planKey != null;
494
+ const planKey = entitlement.planKey ?? (isCurrent ? (subscription?.plan ?? null) : null);
495
+ if (planKey && !config.plans[planKey]) {
496
+ throw new CoreBillingDataUnavailableError("The account plan is not present in the catalog");
497
+ }
498
+ const inGrace = status === "past_due" &&
499
+ subscription?.graceEndsAt != null &&
500
+ Date.parse(subscription.graceEndsAt) > Date.now();
501
+ return {
502
+ accountId,
503
+ planKey,
504
+ status,
505
+ lifecycleState: status ?? "none",
506
+ accessState: isEntitled ? (inGrace ? "grace" : "entitled") : status ? "blocked" : "none",
507
+ isCurrent,
508
+ isEntitled,
509
+ isBlockingCheckout: status != null && BLOCKING_SUBSCRIPTION_STATUSES.has(status),
510
+ isCancellable: status != null &&
511
+ ["active", "trialing", "past_due"].includes(status) &&
512
+ !subscription?.cancelAtPeriodEnd,
513
+ isTerminal: status != null && TERMINAL_SUBSCRIPTION_STATUSES.has(status),
514
+ subscription,
515
+ pendingChange,
516
+ };
517
+ }
518
+ async getAccountSubscriptionSummary(accountId) {
519
+ const [subscription, entitlement, config] = await Promise.all([
520
+ this.billing.getUserSubscription(accountId),
521
+ this.credits.getUserPlan(accountId),
522
+ this.activeConfig(),
523
+ ]);
524
+ const pending = subscription
525
+ ? await this.billing.getOpenBillingSubscriptionChange(subscription.provider, subscription.providerSubscriptionId)
526
+ : null;
527
+ return this.accountSubscriptionSummary(accountId, subscription, entitlement, config, pending);
528
+ }
529
+ async planChangeContext(input) {
530
+ const [subscription, entitlement, resolved] = await Promise.all([
531
+ this.billing.getActiveSubscription(input.accountId),
532
+ this.credits.getUserPlan(input.accountId),
533
+ this.resolveOffer({
534
+ offerKey: input.offerKey,
535
+ type: "subscription",
536
+ }),
537
+ ]);
538
+ if (!subscription?.providerSubscriptionId) {
539
+ throw new CommerceResourceNotFoundError("No active subscription found");
540
+ }
541
+ if (resolved.offer.type !== "subscription")
542
+ throw new UnknownOfferError();
543
+ const provider = await this.providers.select({
544
+ requested: subscription.provider,
545
+ current: subscription.provider,
546
+ offer: resolved.offer,
547
+ });
548
+ const reference = resolved.offer.providers[provider.provider];
549
+ if (!reference)
550
+ throw new UnknownOfferError("Target offer is unavailable from the provider");
551
+ const persistedOffer = reference.type === "stripe_price"
552
+ ? await this.billing.resolveOffer(provider.provider, null, reference.priceId)
553
+ : reference.type === "dodo_product"
554
+ ? await this.billing.resolveOffer(provider.provider, reference.productId, null)
555
+ : await this.billing.resolveOfferByLookup(provider.provider, reference.externalId);
556
+ if (!persistedOffer) {
557
+ throw new CommerceResourceNotFoundError("Target offer is not present in persisted billing state");
558
+ }
559
+ const currentPlan = entitlement.planKey ?? subscription.plan;
560
+ if (!currentPlan) {
561
+ throw new CommerceResourceNotFoundError("Current subscription plan is unknown");
562
+ }
563
+ const { classification, targetInterval, policy } = classifySubscriptionChange(resolved.config, currentPlan, subscription.interval, resolved.offer);
564
+ return {
565
+ subscription,
566
+ provider,
567
+ targetOfferId: persistedOffer.offerId,
568
+ targetOffer: resolved.offer,
569
+ targetProductId: externalId(reference),
570
+ targetInterval,
571
+ classification,
572
+ policy,
573
+ };
574
+ }
575
+ async refreshPlanPreview(context) {
576
+ if (!context.provider.previewChangePlan) {
577
+ throw new ProviderCapabilityNotSupportedError(context.provider.provider, "previewChangePlan");
578
+ }
579
+ return context.provider.previewChangePlan({
580
+ providerSubscriptionId: context.subscription.providerSubscriptionId,
581
+ productId: context.targetProductId,
582
+ ...providerPlanChangeParams(context.policy),
583
+ });
584
+ }
585
+ async previewPlanChange(input) {
586
+ const context = await this.planChangeContext(input);
587
+ if (context.classification === "unchanged") {
588
+ return {
589
+ unchanged: true,
590
+ classification: "unchanged",
591
+ scheduled: false,
592
+ planId: context.targetOffer.plan,
593
+ interval: context.targetInterval,
594
+ };
595
+ }
596
+ const preview = await this.refreshPlanPreview(context);
597
+ return {
598
+ unchanged: false,
599
+ classification: context.classification,
600
+ scheduled: context.policy.effective === "renewal",
601
+ planId: context.targetOffer.plan,
602
+ interval: context.targetInterval,
603
+ preview,
604
+ quoteFingerprint: quoteFingerprint(preview),
605
+ };
606
+ }
607
+ async confirmPlanChange(input) {
608
+ const context = await this.planChangeContext(input);
609
+ if (context.classification === "unchanged") {
610
+ return {
611
+ success: true,
612
+ unchanged: true,
613
+ planId: context.targetOffer.plan,
614
+ interval: context.targetInterval,
615
+ };
616
+ }
617
+ const preview = await this.refreshPlanPreview(context);
618
+ const fingerprint = quoteFingerprint(preview);
619
+ const refreshed = {
620
+ unchanged: false,
621
+ classification: context.classification,
622
+ scheduled: context.policy.effective === "renewal",
623
+ planId: context.targetOffer.plan,
624
+ interval: context.targetInterval,
625
+ preview,
626
+ quoteFingerprint: fingerprint,
627
+ };
628
+ if (!input.quoteFingerprint || input.quoteFingerprint !== fingerprint) {
629
+ throw new QuoteChangedError(refreshed);
630
+ }
631
+ if (!context.provider.changePlan) {
632
+ throw new ProviderCapabilityNotSupportedError(context.provider.provider, "changePlan");
633
+ }
634
+ const existing = await this.billing.getOpenBillingSubscriptionChange(context.subscription.provider, context.subscription.providerSubscriptionId);
635
+ if (existing?.state === "scheduled" && existing.effective === "renewal") {
636
+ throw new CheckoutConflictError("Cancel the existing plan change before choosing another plan");
637
+ }
638
+ else if (existing) {
639
+ throw new CheckoutConflictError("A plan change is already awaiting payment");
640
+ }
641
+ const scheduled = context.policy.effective === "renewal";
642
+ const effectiveAt = scheduled
643
+ ? preview.nextBillingDate
644
+ : Number.isFinite(Date.parse(preview.effectiveAt))
645
+ ? preview.effectiveAt
646
+ : new Date().toISOString();
647
+ if (!effectiveAt) {
648
+ throw new CoreBillingDataUnavailableError("The provider did not return the scheduled change date");
649
+ }
650
+ const change = await this.billing.createBillingSubscriptionChange({
651
+ provider: context.subscription.provider,
652
+ providerSubscriptionId: context.subscription.providerSubscriptionId,
653
+ toOfferId: context.targetOfferId,
654
+ effectiveAt,
655
+ effective: context.policy.effective,
656
+ idempotencyKey: input.operationKey,
657
+ prorationBehavior: context.policy.proration === "none" ? "none" : "invoice_immediately",
658
+ });
659
+ let cancellationWasReactivated = false;
660
+ try {
661
+ if (context.subscription.cancelAtPeriodEnd) {
662
+ if (!context.provider.reactivateSubscription) {
663
+ throw new ProviderCapabilityNotSupportedError(context.provider.provider, "reactivateSubscription");
664
+ }
665
+ if (!context.provider.cancelSubscription) {
666
+ throw new ProviderCapabilityNotSupportedError(context.provider.provider, "cancelSubscription");
667
+ }
668
+ await context.provider.reactivateSubscription(context.subscription.providerSubscriptionId, `${input.operationKey}:keep`);
669
+ cancellationWasReactivated = true;
670
+ }
671
+ const result = await context.provider.changePlan({
672
+ providerSubscriptionId: context.subscription.providerSubscriptionId,
673
+ productId: context.targetProductId,
674
+ ...providerPlanChangeParams(context.policy),
675
+ onPaymentFailure: context.policy.paymentFailure,
676
+ metadata: {
677
+ userId: input.accountId,
678
+ plan_slug: context.targetOffer.plan,
679
+ billing_interval: context.targetInterval,
680
+ },
681
+ idempotencyKey: input.operationKey,
682
+ });
683
+ await this.billing.updateBillingSubscriptionChange(change.id, {
684
+ providerOperationId: result && "providerOperationId" in result ? (result.providerOperationId ?? null) : null,
685
+ });
686
+ }
687
+ catch (error) {
688
+ let failure = error;
689
+ if (cancellationWasReactivated) {
690
+ try {
691
+ await context.provider.cancelSubscription(context.subscription.providerSubscriptionId, `${input.operationKey}:restore-cancellation`);
692
+ }
693
+ catch (compensationError) {
694
+ failure = new AggregateError([error, compensationError], "Plan change failed and the original subscription cancellation could not be restored");
695
+ }
696
+ }
697
+ await this.billing.updateBillingSubscriptionChange(change.id, {
698
+ state: "failed",
699
+ errorMessage: failure instanceof Error ? failure.message : String(failure),
700
+ });
701
+ throw failure;
702
+ }
703
+ return {
704
+ success: true,
705
+ pending: true,
706
+ scheduled,
707
+ effectiveAt,
708
+ planId: context.targetOffer.plan,
709
+ interval: context.targetInterval,
710
+ };
711
+ }
712
+ async cancelScheduledPlanChange(input) {
713
+ const subscription = await this.billing.getActiveSubscription(input.accountId);
714
+ if (!subscription)
715
+ throw new CommerceResourceNotFoundError("No active subscription found");
716
+ const change = await this.billing.getOpenBillingSubscriptionChange(subscription.provider, subscription.providerSubscriptionId);
717
+ if (!change || change.state !== "scheduled" || change.effective !== "renewal") {
718
+ throw new CommerceResourceNotFoundError("No scheduled plan change found");
719
+ }
720
+ const provider = await this.providers.get(subscription.provider);
721
+ if (!provider.cancelScheduledPlanChange) {
722
+ throw new ProviderCapabilityNotSupportedError(provider.provider, "cancelScheduledPlanChange");
723
+ }
724
+ await provider.cancelScheduledPlanChange(subscription.providerSubscriptionId, change.providerOperationId, input.operationKey);
725
+ await this.billing.updateBillingSubscriptionChange(change.id, { state: "canceled" });
726
+ return { success: true };
727
+ }
728
+ async createPortalSession(input) {
729
+ const subscription = await this.billing.getUserSubscription(input.accountId);
730
+ const customer = await this.billing.getCustomerByUserId(input.accountId, subscription?.provider);
731
+ if (!customer?.providerCustomerId) {
732
+ throw new CommerceResourceNotFoundError("No billing customer found");
733
+ }
734
+ const provider = await this.providers.get(customer.provider);
735
+ if (input.purpose === "payment-method") {
736
+ if (subscription?.providerSubscriptionId) {
737
+ if (!provider.createUpdatePaymentMethodSession) {
738
+ throw new ProviderCapabilityNotSupportedError(provider.provider, "createUpdatePaymentMethodSession");
739
+ }
740
+ return provider.createUpdatePaymentMethodSession({
741
+ customerId: customer.providerCustomerId,
742
+ subscriptionId: subscription.providerSubscriptionId,
743
+ returnUrl: input.returnUrl,
744
+ });
745
+ }
746
+ if (!provider.createPaymentMethodSetupSession) {
747
+ throw new ProviderCapabilityNotSupportedError(provider.provider, "createPaymentMethodSetupSession");
748
+ }
749
+ return provider.createPaymentMethodSetupSession({
750
+ customerId: customer.providerCustomerId,
751
+ returnUrl: input.returnUrl,
752
+ cancelUrl: input.cancelUrl,
753
+ });
754
+ }
755
+ if (!provider.createCustomerPortalSession) {
756
+ throw new ProviderCapabilityNotSupportedError(provider.provider, "createCustomerPortalSession");
757
+ }
758
+ return provider.createCustomerPortalSession({
759
+ customerId: customer.providerCustomerId,
760
+ returnUrl: input.returnUrl,
761
+ });
762
+ }
763
+ preferences(accountId, current) {
764
+ return {
765
+ userId: accountId,
766
+ ...DEFAULT_PREFERENCES,
767
+ ...(this.options.preferenceDefaults ?? {}),
768
+ ...(current ?? {}),
769
+ };
770
+ }
771
+ async updatePreferences(input) {
772
+ const current = await this.billing.getUserPreferences(input.accountId);
773
+ const next = { ...this.preferences(input.accountId, current), ...input.patch };
774
+ await this.billing.updateUserPreferences(next);
775
+ return next;
776
+ }
777
+ ledgerDocument(entry) {
778
+ const metadata = entry.metadata ?? {};
779
+ const normalizedProvider = typeof metadata.provider === "string" ? metadata.provider : undefined;
780
+ const normalizedDocumentId = typeof metadata.provider_document_id === "string"
781
+ ? metadata.provider_document_id
782
+ : typeof metadata.provider_invoice_id === "string"
783
+ ? metadata.provider_invoice_id
784
+ : typeof metadata.provider_payment_id === "string"
785
+ ? metadata.provider_payment_id
786
+ : undefined;
787
+ if (!normalizedDocumentId)
788
+ return null;
789
+ return {
790
+ kind: "ledger_entry",
791
+ ledgerEntryId: entry.entryId,
792
+ provider: normalizedProvider ?? null,
793
+ providerDocumentId: normalizedDocumentId,
794
+ createdAt: entry.createdAt,
795
+ entryType: entry.entryType,
796
+ amount: entry.amount,
797
+ };
798
+ }
799
+ async getAccountOverview(accountId) {
800
+ let core;
801
+ try {
802
+ const [balance, available, bucketBalances, entitlement, allowance, subscription, prefs, config,] = await Promise.all([
803
+ this.credits.getBalance(accountId),
804
+ this.credits.getAvailable(accountId),
805
+ this.credits.getBucketBalances(accountId),
806
+ this.credits.getUserPlan(accountId),
807
+ this.credits.checkAllowance(accountId),
808
+ this.billing.getUserSubscription(accountId),
809
+ this.billing.getUserPreferences(accountId),
810
+ this.activeConfig(),
811
+ ]);
812
+ core = {
813
+ balance,
814
+ available,
815
+ bucketBalances,
816
+ entitlement,
817
+ allowance,
818
+ subscription,
819
+ preferences: this.preferences(accountId, prefs),
820
+ config,
821
+ };
822
+ }
823
+ catch (error) {
824
+ throw new CoreBillingDataUnavailableError(undefined, error);
825
+ }
826
+ const pendingChange = core.subscription
827
+ ? await this.billing.getOpenBillingSubscriptionChange(core.subscription.provider, core.subscription.providerSubscriptionId)
828
+ : null;
829
+ const subscriptionSummary = this.accountSubscriptionSummary(accountId, core.subscription, core.entitlement, core.config, pendingChange);
830
+ const [transactionsResult, usageResult, invoicesResult] = await Promise.allSettled([
831
+ this.credits.listLedgerEntries(accountId, { limit: 50 }),
832
+ this.credits.listUsageCharges(accountId, { limit: 100, includeRecordOnly: false }),
833
+ this.billing.listBillingInvoices(accountId),
834
+ ]);
835
+ const transactions = transactionsResult.status === "fulfilled"
836
+ ? transactionsResult.value.items.filter((entry) => entry.entryType !== "usage")
837
+ : [];
838
+ const usage = usageResult.status === "fulfilled" ? usageResult.value.items : [];
839
+ const invoices = invoicesResult.status === "fulfilled" ? invoicesResult.value : [];
840
+ const documents = [
841
+ ...invoices.flatMap((invoice) => {
842
+ const provider = invoice.provider ?? core.subscription?.provider;
843
+ return provider
844
+ ? [
845
+ {
846
+ kind: "provider_invoice",
847
+ provider,
848
+ providerDocumentId: invoice.providerInvoiceId,
849
+ status: invoice.status,
850
+ amountPaidMinor: invoice.amountPaidMinor,
851
+ amountDueMinor: invoice.amountDueMinor,
852
+ currency: invoice.currency,
853
+ periodStart: invoice.periodStart,
854
+ periodEnd: invoice.periodEnd,
855
+ },
856
+ ]
857
+ : [];
858
+ }),
859
+ ...transactions.flatMap((entry) => {
860
+ const document = this.ledgerDocument(entry);
861
+ return document ? [document] : [];
862
+ }),
863
+ ];
864
+ let paymentMethods = [];
865
+ let paymentMethodsAvailable = true;
866
+ let autoRecharge = null;
867
+ let autoRechargeAvailable = true;
868
+ try {
869
+ const customer = await this.billing.getCustomerByUserId(accountId, core.subscription?.provider);
870
+ if (customer) {
871
+ const provider = await this.providers.get(customer.provider);
872
+ if (provider.listPaymentMethods) {
873
+ paymentMethods = await provider.listPaymentMethods(customer.providerCustomerId);
874
+ }
875
+ else {
876
+ paymentMethodsAvailable = false;
877
+ }
878
+ try {
879
+ autoRecharge = await this.billing.autoRecharge.getStatus({
880
+ userId: accountId,
881
+ provider,
882
+ });
883
+ }
884
+ catch (error) {
885
+ autoRechargeAvailable = false;
886
+ this.logger.warn("[CommerceService] auto-recharge overview unavailable", {
887
+ accountId,
888
+ error: error instanceof Error ? error.message : String(error),
889
+ });
890
+ }
891
+ }
892
+ }
893
+ catch (error) {
894
+ paymentMethodsAvailable = false;
895
+ autoRechargeAvailable = false;
896
+ this.logger.warn("[CommerceService] provider overview unavailable", {
897
+ accountId,
898
+ error: error instanceof Error ? error.message : String(error),
899
+ });
900
+ }
901
+ const floor = core.entitlement.creditPolicy?.type === "credit_line"
902
+ ? (core.entitlement.creditPolicy.creditLimit ?? new Decimal(0)).negated()
903
+ : new Decimal(0);
904
+ const spendOrder = [
905
+ ...(core.entitlement.allowance
906
+ ? [
907
+ {
908
+ type: "allowance",
909
+ key: "allowance",
910
+ label: "Plan allowance",
911
+ priority: core.entitlement.allowance.priority ?? null,
912
+ },
913
+ ]
914
+ : []),
915
+ ...core.bucketBalances.buckets.map((bucket) => ({
916
+ type: "bucket",
917
+ key: bucket.bucketKey,
918
+ label: bucket.label,
919
+ priority: bucket.priority,
920
+ })),
921
+ ].sort((left, right) => {
922
+ const priority = (left.priority ?? -1) - (right.priority ?? -1);
923
+ if (priority !== 0)
924
+ return priority;
925
+ if (left.type !== right.type)
926
+ return left.type === "allowance" ? -1 : 1;
927
+ return left.key.localeCompare(right.key);
928
+ });
929
+ return {
930
+ accountId,
931
+ credits: {
932
+ ledgerBalance: core.balance.balance,
933
+ effectiveSpendableBalance: core.available.available
934
+ .plus(core.allowance.allowanceRemaining)
935
+ .minus(floor),
936
+ lifetimePurchases: core.balance.lifetimePurchased,
937
+ allowance: {
938
+ remaining: core.allowance.allowanceRemaining,
939
+ limit: core.entitlement.allowance?.amount ?? null,
940
+ periodStart: core.allowance.periodStart ?? null,
941
+ periodEnd: core.allowance.periodEnd ?? null,
942
+ },
943
+ buckets: core.bucketBalances.buckets,
944
+ bucketsByKey: Object.fromEntries(core.bucketBalances.buckets.map((bucket) => [bucket.bucketKey, bucket.balance])),
945
+ spendOrder,
946
+ display: core.config.credits.display ?? null,
947
+ },
948
+ entitlement: core.entitlement,
949
+ subscriptionSummary,
950
+ subscription: core.subscription,
951
+ pendingChange,
952
+ preferences: core.preferences,
953
+ paymentMethods,
954
+ documents,
955
+ providerInvoices: invoices,
956
+ transactions,
957
+ usage,
958
+ autoRecharge,
959
+ availability: {
960
+ paymentMethods: paymentMethodsAvailable,
961
+ documents: invoicesResult.status === "fulfilled" && transactionsResult.status === "fulfilled",
962
+ providerInvoices: invoicesResult.status === "fulfilled",
963
+ transactions: transactionsResult.status === "fulfilled",
964
+ usage: usageResult.status === "fulfilled",
965
+ autoRecharge: autoRechargeAvailable,
966
+ },
967
+ };
968
+ }
969
+ async getInvoiceLink(input) {
970
+ let providerName;
971
+ let providerDocumentId;
972
+ if (input.document.kind === "provider_invoice") {
973
+ const document = input.document;
974
+ const owned = (await this.billing.listBillingInvoices(input.accountId)).find((invoice) => (invoice.provider ?? document.provider) === document.provider &&
975
+ invoice.providerInvoiceId === document.providerDocumentId);
976
+ if (!owned)
977
+ throw new CommerceResourceNotFoundError("Invoice not found");
978
+ providerName = document.provider;
979
+ providerDocumentId = owned.providerInvoiceId;
980
+ }
981
+ else {
982
+ const entry = await this.credits.getLedgerEntry(input.accountId, input.document.ledgerEntryId);
983
+ if (!entry)
984
+ throw new CommerceResourceNotFoundError("Ledger entry not found");
985
+ const owned = this.ledgerDocument(entry);
986
+ if (!owned?.provider || !owned.providerDocumentId) {
987
+ throw new CommerceResourceNotFoundError("No provider document is associated with the ledger entry");
988
+ }
989
+ providerName = owned.provider;
990
+ providerDocumentId = owned.providerDocumentId;
991
+ }
992
+ const provider = await this.providers.get(providerName);
993
+ if (!provider.getInvoiceUrl) {
994
+ throw new ProviderCapabilityNotSupportedError(provider.provider, "getInvoiceUrl");
995
+ }
996
+ const result = await provider.getInvoiceUrl(providerDocumentId);
997
+ if (!result)
998
+ throw new CommerceResourceNotFoundError("No invoice URL is available");
999
+ return result;
1000
+ }
1001
+ async handleWebhook(input) {
1002
+ const provider = await this.providers.select({ requested: input.provider });
1003
+ const result = await provider.handleWebhook({
1004
+ rawBody: input.rawBody,
1005
+ headers: input.headers,
1006
+ });
1007
+ return {
1008
+ received: result.received,
1009
+ retryable: result.retryable,
1010
+ provider: result.provider,
1011
+ eventId: result.eventId,
1012
+ eventType: result.eventType,
1013
+ };
1014
+ }
1015
+ }
1016
+ //# sourceMappingURL=service.js.map