@zonastery/bursar 2.0.2 → 2.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (395) hide show
  1. package/README.md +1 -0
  2. package/dist/billing/auto-recharge-port.d.ts +3 -2
  3. package/dist/billing/auto-recharge-port.d.ts.map +1 -1
  4. package/dist/billing/auto-recharge-port.js.map +1 -1
  5. package/dist/billing/auto-recharge-service.d.ts +1 -1
  6. package/dist/billing/auto-recharge-service.d.ts.map +1 -1
  7. package/dist/billing/auto-recharge-service.js +5 -4
  8. package/dist/billing/auto-recharge-service.js.map +1 -1
  9. package/dist/billing/billing-service.d.ts +3 -2
  10. package/dist/billing/billing-service.d.ts.map +1 -1
  11. package/dist/billing/billing-service.js +2 -10
  12. package/dist/billing/billing-service.js.map +1 -1
  13. package/dist/billing/billing-store.d.ts +7 -7
  14. package/dist/billing/billing-store.d.ts.map +1 -1
  15. package/dist/billing/billing-store.js.map +1 -1
  16. package/dist/billing/contracts.d.ts +10 -8
  17. package/dist/billing/contracts.d.ts.map +1 -1
  18. package/dist/billing/contracts.js.map +1 -1
  19. package/dist/billing/event-handlers.d.ts +5 -9
  20. package/dist/billing/event-handlers.d.ts.map +1 -1
  21. package/dist/billing/event-handlers.js +191 -285
  22. package/dist/billing/event-handlers.js.map +1 -1
  23. package/dist/billing/event-processor.d.ts +1 -1
  24. package/dist/billing/event-processor.d.ts.map +1 -1
  25. package/dist/billing/event-processor.js +42 -21
  26. package/dist/billing/event-processor.js.map +1 -1
  27. package/dist/billing/financial-event-handlers.d.ts +3 -9
  28. package/dist/billing/financial-event-handlers.d.ts.map +1 -1
  29. package/dist/billing/financial-event-handlers.js +10 -12
  30. package/dist/billing/financial-event-handlers.js.map +1 -1
  31. package/dist/billing/index.d.ts +1 -1
  32. package/dist/billing/index.d.ts.map +1 -1
  33. package/dist/billing/index.js.map +1 -1
  34. package/dist/billing/management.d.ts +3 -2
  35. package/dist/billing/management.d.ts.map +1 -1
  36. package/dist/billing/management.js.map +1 -1
  37. package/dist/billing/postgres/repositories/auto-recharge.d.ts +2 -1
  38. package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -1
  39. package/dist/billing/postgres/repositories/auto-recharge.js +59 -41
  40. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
  41. package/dist/billing/postgres/repositories/dispute.d.ts +2 -1
  42. package/dist/billing/postgres/repositories/dispute.d.ts.map +1 -1
  43. package/dist/billing/postgres/repositories/dispute.js.map +1 -1
  44. package/dist/billing/postgres/repositories/event.d.ts.map +1 -1
  45. package/dist/billing/postgres/repositories/event.js +33 -1
  46. package/dist/billing/postgres/repositories/event.js.map +1 -1
  47. package/dist/billing/postgres/repositories/invoice.d.ts +2 -1
  48. package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -1
  49. package/dist/billing/postgres/repositories/invoice.js +8 -12
  50. package/dist/billing/postgres/repositories/invoice.js.map +1 -1
  51. package/dist/billing/postgres/repositories/offer.d.ts +1 -1
  52. package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
  53. package/dist/billing/postgres/repositories/offer.js +6 -1
  54. package/dist/billing/postgres/repositories/offer.js.map +1 -1
  55. package/dist/billing/postgres/repositories/payment.d.ts +1 -1
  56. package/dist/billing/postgres/repositories/payment.d.ts.map +1 -1
  57. package/dist/billing/postgres/repositories/payment.js +1 -1
  58. package/dist/billing/postgres/repositories/payment.js.map +1 -1
  59. package/dist/billing/postgres/repositories/subscription-change.d.ts.map +1 -1
  60. package/dist/billing/postgres/repositories/subscription-change.js +1 -9
  61. package/dist/billing/postgres/repositories/subscription-change.js.map +1 -1
  62. package/dist/billing/postgres/repositories/subscription.d.ts +6 -6
  63. package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -1
  64. package/dist/billing/postgres/repositories/subscription.js +29 -30
  65. package/dist/billing/postgres/repositories/subscription.js.map +1 -1
  66. package/dist/billing/postgres/repositories/topup.d.ts +1 -1
  67. package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
  68. package/dist/billing/postgres/repositories/topup.js +1 -1
  69. package/dist/billing/postgres/repositories/topup.js.map +1 -1
  70. package/dist/billing/postgres/store.d.ts +7 -6
  71. package/dist/billing/postgres/store.d.ts.map +1 -1
  72. package/dist/billing/postgres/store.js +31 -19
  73. package/dist/billing/postgres/store.js.map +1 -1
  74. package/dist/billing/types/auto-recharge.d.ts +3 -2
  75. package/dist/billing/types/auto-recharge.d.ts.map +1 -1
  76. package/dist/billing/types/auto-recharge.js.map +1 -1
  77. package/dist/billing/types/catalog.d.ts +1 -1
  78. package/dist/billing/types/catalog.d.ts.map +1 -1
  79. package/dist/billing/types/catalog.js.map +1 -1
  80. package/dist/billing/types/documents.d.ts +3 -2
  81. package/dist/billing/types/documents.d.ts.map +1 -1
  82. package/dist/billing/types/documents.js.map +1 -1
  83. package/dist/billing/types/events.d.ts +11 -2
  84. package/dist/billing/types/events.d.ts.map +1 -1
  85. package/dist/billing/types/events.js +73 -39
  86. package/dist/billing/types/events.js.map +1 -1
  87. package/dist/billing/types/subscriptions.d.ts +4 -1
  88. package/dist/billing/types/subscriptions.d.ts.map +1 -1
  89. package/dist/billing/types/subscriptions.js.map +1 -1
  90. package/dist/breakdown.d.ts +4 -3
  91. package/dist/breakdown.d.ts.map +1 -1
  92. package/dist/breakdown.js +1 -1
  93. package/dist/breakdown.js.map +1 -1
  94. package/dist/bursar.d.ts.map +1 -1
  95. package/dist/bursar.js +4 -3
  96. package/dist/bursar.js.map +1 -1
  97. package/dist/catalog.d.ts.map +1 -1
  98. package/dist/catalog.js +45 -42
  99. package/dist/catalog.js.map +1 -1
  100. package/dist/commerce/provider-registry.d.ts.map +1 -1
  101. package/dist/commerce/provider-registry.js +11 -6
  102. package/dist/commerce/provider-registry.js.map +1 -1
  103. package/dist/commerce/service.d.ts.map +1 -1
  104. package/dist/commerce/service.js +70 -68
  105. package/dist/commerce/service.js.map +1 -1
  106. package/dist/commerce/types.d.ts +1 -1
  107. package/dist/commerce/types.d.ts.map +1 -1
  108. package/dist/commerce/types.js.map +1 -1
  109. package/dist/config/parse-access.d.ts +5 -2
  110. package/dist/config/parse-access.d.ts.map +1 -1
  111. package/dist/config/parse-access.js +60 -41
  112. package/dist/config/parse-access.js.map +1 -1
  113. package/dist/config/parse-commerce.d.ts +2 -1
  114. package/dist/config/parse-commerce.d.ts.map +1 -1
  115. package/dist/config/parse-commerce.js +49 -29
  116. package/dist/config/parse-commerce.js.map +1 -1
  117. package/dist/config/parse-credits.d.ts +2 -1
  118. package/dist/config/parse-credits.d.ts.map +1 -1
  119. package/dist/config/parse-credits.js +39 -23
  120. package/dist/config/parse-credits.js.map +1 -1
  121. package/dist/config/parse-plans.d.ts +7 -2
  122. package/dist/config/parse-plans.d.ts.map +1 -1
  123. package/dist/config/parse-plans.js +49 -22
  124. package/dist/config/parse-plans.js.map +1 -1
  125. package/dist/config/parse-pricing.d.ts +2 -1
  126. package/dist/config/parse-pricing.d.ts.map +1 -1
  127. package/dist/config/parse-pricing.js +41 -31
  128. package/dist/config/parse-pricing.js.map +1 -1
  129. package/dist/config/parse-utils.d.ts +16 -12
  130. package/dist/config/parse-utils.d.ts.map +1 -1
  131. package/dist/config/parse-utils.js +91 -28
  132. package/dist/config/parse-utils.js.map +1 -1
  133. package/dist/config/types.d.ts +1 -1
  134. package/dist/config/types.d.ts.map +1 -1
  135. package/dist/config/types.js.map +1 -1
  136. package/dist/config.d.ts +6 -5
  137. package/dist/config.d.ts.map +1 -1
  138. package/dist/config.js +66 -36
  139. package/dist/config.js.map +1 -1
  140. package/dist/credits/amount.d.ts +2 -2
  141. package/dist/credits/amount.d.ts.map +1 -1
  142. package/dist/credits/amount.js +6 -5
  143. package/dist/credits/amount.js.map +1 -1
  144. package/dist/credits/catalog-runtime.d.ts +1 -1
  145. package/dist/credits/catalog-runtime.d.ts.map +1 -1
  146. package/dist/credits/catalog-runtime.js +3 -4
  147. package/dist/credits/catalog-runtime.js.map +1 -1
  148. package/dist/credits/events.d.ts +12 -1
  149. package/dist/credits/events.d.ts.map +1 -1
  150. package/dist/credits/events.js +35 -21
  151. package/dist/credits/events.js.map +1 -1
  152. package/dist/credits/lease-workflow.d.ts +3 -2
  153. package/dist/credits/lease-workflow.d.ts.map +1 -1
  154. package/dist/credits/lease-workflow.js +4 -3
  155. package/dist/credits/lease-workflow.js.map +1 -1
  156. package/dist/credits/low-balance-monitor.d.ts +3 -2
  157. package/dist/credits/low-balance-monitor.d.ts.map +1 -1
  158. package/dist/credits/low-balance-monitor.js +1 -1
  159. package/dist/credits/low-balance-monitor.js.map +1 -1
  160. package/dist/credits/postgres/repositories/analytics.d.ts +2 -2
  161. package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -1
  162. package/dist/credits/postgres/repositories/analytics.js +14 -6
  163. package/dist/credits/postgres/repositories/analytics.js.map +1 -1
  164. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
  165. package/dist/credits/postgres/repositories/balance.js +7 -7
  166. package/dist/credits/postgres/repositories/balance.js.map +1 -1
  167. package/dist/credits/postgres/repositories/bucket.js +1 -1
  168. package/dist/credits/postgres/repositories/bucket.js.map +1 -1
  169. package/dist/credits/postgres/repositories/catalog.d.ts +4 -3
  170. package/dist/credits/postgres/repositories/catalog.d.ts.map +1 -1
  171. package/dist/credits/postgres/repositories/catalog.js +4 -3
  172. package/dist/credits/postgres/repositories/catalog.js.map +1 -1
  173. package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -1
  174. package/dist/credits/postgres/repositories/deduction.js +2 -2
  175. package/dist/credits/postgres/repositories/deduction.js.map +1 -1
  176. package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
  177. package/dist/credits/postgres/repositories/lease.js +4 -2
  178. package/dist/credits/postgres/repositories/lease.js.map +1 -1
  179. package/dist/credits/postgres/repositories/plan.d.ts +1 -1
  180. package/dist/credits/postgres/repositories/team.d.ts +2 -1
  181. package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
  182. package/dist/credits/postgres/repositories/team.js +19 -5
  183. package/dist/credits/postgres/repositories/team.js.map +1 -1
  184. package/dist/credits/postgres/store.d.ts +6 -5
  185. package/dist/credits/postgres/store.d.ts.map +1 -1
  186. package/dist/credits/postgres/store.js +23 -13
  187. package/dist/credits/postgres/store.js.map +1 -1
  188. package/dist/credits/postgres/value-mappers.d.ts +5 -4
  189. package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
  190. package/dist/credits/postgres/value-mappers.js +11 -12
  191. package/dist/credits/postgres/value-mappers.js.map +1 -1
  192. package/dist/credits/service-errors.d.ts +1 -1
  193. package/dist/credits/service-errors.d.ts.map +1 -1
  194. package/dist/credits/service-errors.js +1 -1
  195. package/dist/credits/service-errors.js.map +1 -1
  196. package/dist/credits/service-types.d.ts +4 -1
  197. package/dist/credits/service-types.d.ts.map +1 -1
  198. package/dist/credits/service-types.js.map +1 -1
  199. package/dist/credits/service.d.ts +5 -0
  200. package/dist/credits/service.d.ts.map +1 -1
  201. package/dist/credits/service.js +30 -10
  202. package/dist/credits/service.js.map +1 -1
  203. package/dist/credits/store.d.ts +15 -5
  204. package/dist/credits/store.d.ts.map +1 -1
  205. package/dist/credits/store.js +1 -1
  206. package/dist/credits/store.js.map +1 -1
  207. package/dist/credits/types/account.d.ts +5 -4
  208. package/dist/credits/types/account.d.ts.map +1 -1
  209. package/dist/credits/types/account.js.map +1 -1
  210. package/dist/credits/types/catalog.d.ts +2 -1
  211. package/dist/credits/types/catalog.d.ts.map +1 -1
  212. package/dist/credits/types/catalog.js.map +1 -1
  213. package/dist/credits/types/grants.d.ts.map +1 -1
  214. package/dist/credits/types/grants.js.map +1 -1
  215. package/dist/credits/types/ledger.d.ts +3 -2
  216. package/dist/credits/types/ledger.d.ts.map +1 -1
  217. package/dist/credits/types/ledger.js.map +1 -1
  218. package/dist/credits/types/teams.d.ts +1 -0
  219. package/dist/credits/types/teams.d.ts.map +1 -1
  220. package/dist/credits/types/teams.js.map +1 -1
  221. package/dist/engine.d.ts +2 -2
  222. package/dist/engine.d.ts.map +1 -1
  223. package/dist/engine.js +40 -11
  224. package/dist/engine.js.map +1 -1
  225. package/dist/errors.d.ts +10 -3
  226. package/dist/errors.d.ts.map +1 -1
  227. package/dist/errors.js +50 -9
  228. package/dist/errors.js.map +1 -1
  229. package/dist/expr/ast.d.ts.map +1 -1
  230. package/dist/expr/ast.js.map +1 -1
  231. package/dist/expr/evaluator.d.ts +1 -1
  232. package/dist/expr/evaluator.d.ts.map +1 -1
  233. package/dist/expr/evaluator.js +1 -1
  234. package/dist/expr/evaluator.js.map +1 -1
  235. package/dist/expr/parser.d.ts.map +1 -1
  236. package/dist/expr/parser.js.map +1 -1
  237. package/dist/expr/tokenizer.d.ts.map +1 -1
  238. package/dist/expr/tokenizer.js +34 -12
  239. package/dist/expr/tokenizer.js.map +1 -1
  240. package/dist/expr.d.ts +1 -1
  241. package/dist/expr.d.ts.map +1 -1
  242. package/dist/expr.js +13 -7
  243. package/dist/expr.js.map +1 -1
  244. package/dist/generated/pricing-config.types.d.ts.map +1 -1
  245. package/dist/generated/pricing-config.types.js.map +1 -1
  246. package/dist/index.d.ts +3 -1
  247. package/dist/index.d.ts.map +1 -1
  248. package/dist/index.js +1 -0
  249. package/dist/index.js.map +1 -1
  250. package/dist/integrations/better-auth.d.ts +4 -1
  251. package/dist/integrations/better-auth.d.ts.map +1 -1
  252. package/dist/integrations/better-auth.js +7 -4
  253. package/dist/integrations/better-auth.js.map +1 -1
  254. package/dist/load-config-file.d.ts +2 -1
  255. package/dist/load-config-file.d.ts.map +1 -1
  256. package/dist/load-config-file.js +19 -13
  257. package/dist/load-config-file.js.map +1 -1
  258. package/dist/metrics.d.ts +3 -2
  259. package/dist/metrics.d.ts.map +1 -1
  260. package/dist/metrics.js.map +1 -1
  261. package/dist/node.d.ts +6 -3
  262. package/dist/node.d.ts.map +1 -1
  263. package/dist/node.js +1 -0
  264. package/dist/node.js.map +1 -1
  265. package/dist/providers/_shared.d.ts +11 -8
  266. package/dist/providers/_shared.d.ts.map +1 -1
  267. package/dist/providers/_shared.js +26 -17
  268. package/dist/providers/_shared.js.map +1 -1
  269. package/dist/providers/dodo/better-auth-core.d.ts +32 -0
  270. package/dist/providers/dodo/better-auth-core.d.ts.map +1 -0
  271. package/dist/providers/dodo/better-auth-core.js +14 -0
  272. package/dist/providers/dodo/better-auth-core.js.map +1 -0
  273. package/dist/providers/dodo/better-auth.d.ts +5 -7
  274. package/dist/providers/dodo/better-auth.d.ts.map +1 -1
  275. package/dist/providers/dodo/better-auth.js +16 -13
  276. package/dist/providers/dodo/better-auth.js.map +1 -1
  277. package/dist/providers/dodo/client-contract.d.ts +16 -22
  278. package/dist/providers/dodo/client-contract.d.ts.map +1 -1
  279. package/dist/providers/dodo/client-contract.js.map +1 -1
  280. package/dist/providers/dodo/event-mapper.d.ts +7 -4
  281. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  282. package/dist/providers/dodo/event-mapper.js +130 -106
  283. package/dist/providers/dodo/event-mapper.js.map +1 -1
  284. package/dist/providers/dodo/nextjs-core.d.ts +22 -0
  285. package/dist/providers/dodo/nextjs-core.d.ts.map +1 -0
  286. package/dist/providers/dodo/nextjs-core.js +14 -0
  287. package/dist/providers/dodo/nextjs-core.js.map +1 -0
  288. package/dist/providers/dodo/nextjs.d.ts +5 -7
  289. package/dist/providers/dodo/nextjs.d.ts.map +1 -1
  290. package/dist/providers/dodo/nextjs.js +11 -10
  291. package/dist/providers/dodo/nextjs.js.map +1 -1
  292. package/dist/providers/dodo/provider.d.ts +3 -3
  293. package/dist/providers/dodo/provider.d.ts.map +1 -1
  294. package/dist/providers/dodo/provider.js +76 -58
  295. package/dist/providers/dodo/provider.js.map +1 -1
  296. package/dist/providers/dodo/react-native-core.d.ts +56 -0
  297. package/dist/providers/dodo/react-native-core.d.ts.map +1 -0
  298. package/dist/providers/dodo/react-native-core.js +56 -0
  299. package/dist/providers/dodo/react-native-core.js.map +1 -0
  300. package/dist/providers/dodo/react-native.d.ts +6 -50
  301. package/dist/providers/dodo/react-native.d.ts.map +1 -1
  302. package/dist/providers/dodo/react-native.js +5 -49
  303. package/dist/providers/dodo/react-native.js.map +1 -1
  304. package/dist/providers/dodo/webhook-bridge.d.ts +4 -2
  305. package/dist/providers/dodo/webhook-bridge.d.ts.map +1 -1
  306. package/dist/providers/dodo/webhook-bridge.js.map +1 -1
  307. package/dist/providers/environment.d.ts +1 -1
  308. package/dist/providers/environment.d.ts.map +1 -1
  309. package/dist/providers/environment.js +4 -2
  310. package/dist/providers/environment.js.map +1 -1
  311. package/dist/providers/mock/provider.d.ts.map +1 -1
  312. package/dist/providers/mock/provider.js +5 -10
  313. package/dist/providers/mock/provider.js.map +1 -1
  314. package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
  315. package/dist/providers/stripe/event-mapper.js +104 -12
  316. package/dist/providers/stripe/event-mapper.js.map +1 -1
  317. package/dist/providers/stripe/provider.d.ts.map +1 -1
  318. package/dist/providers/stripe/provider.js +100 -60
  319. package/dist/providers/stripe/provider.js.map +1 -1
  320. package/dist/providers/types.d.ts +0 -1
  321. package/dist/providers/types.d.ts.map +1 -1
  322. package/dist/providers/types.js.map +1 -1
  323. package/dist/retry.d.ts.map +1 -1
  324. package/dist/retry.js +16 -9
  325. package/dist/retry.js.map +1 -1
  326. package/dist/shared/diagnostics.d.ts +10 -2
  327. package/dist/shared/diagnostics.d.ts.map +1 -1
  328. package/dist/shared/diagnostics.js +65 -6
  329. package/dist/shared/diagnostics.js.map +1 -1
  330. package/dist/shared/idempotency.d.ts +4 -3
  331. package/dist/shared/idempotency.d.ts.map +1 -1
  332. package/dist/shared/idempotency.js +21 -10
  333. package/dist/shared/idempotency.js.map +1 -1
  334. package/dist/shared/json.d.ts +28 -0
  335. package/dist/shared/json.d.ts.map +1 -0
  336. package/dist/shared/json.js +41 -0
  337. package/dist/shared/json.js.map +1 -0
  338. package/dist/shared/logger.d.ts +10 -4
  339. package/dist/shared/logger.d.ts.map +1 -1
  340. package/dist/shared/logger.js.map +1 -1
  341. package/dist/shared/postgres-client.d.ts +10 -5
  342. package/dist/shared/postgres-client.d.ts.map +1 -1
  343. package/dist/shared/postgres-client.js +80 -45
  344. package/dist/shared/postgres-client.js.map +1 -1
  345. package/dist/shared/postgres-errors.d.ts +1 -1
  346. package/dist/shared/postgres-errors.d.ts.map +1 -1
  347. package/dist/shared/postgres-errors.js +32 -31
  348. package/dist/shared/postgres-errors.js.map +1 -1
  349. package/dist/shared/postgres-types.d.ts +3 -2
  350. package/dist/shared/postgres-types.d.ts.map +1 -1
  351. package/dist/shared/postgres-types.js.map +1 -1
  352. package/dist/shared/postgres-validation.d.ts +7 -6
  353. package/dist/shared/postgres-validation.d.ts.map +1 -1
  354. package/dist/shared/postgres-validation.js +17 -10
  355. package/dist/shared/postgres-validation.js.map +1 -1
  356. package/dist/storage/adapters/clickhouse.d.ts +20 -6
  357. package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
  358. package/dist/storage/adapters/clickhouse.js +150 -42
  359. package/dist/storage/adapters/clickhouse.js.map +1 -1
  360. package/dist/storage/adapters/s3.d.ts +67 -6
  361. package/dist/storage/adapters/s3.d.ts.map +1 -1
  362. package/dist/storage/adapters/s3.js +79 -26
  363. package/dist/storage/adapters/s3.js.map +1 -1
  364. package/dist/storage/diagnostics.d.ts +105 -0
  365. package/dist/storage/diagnostics.d.ts.map +1 -0
  366. package/dist/storage/diagnostics.js +228 -0
  367. package/dist/storage/diagnostics.js.map +1 -0
  368. package/dist/storage/maintenance.d.ts +88 -0
  369. package/dist/storage/maintenance.d.ts.map +1 -0
  370. package/dist/storage/maintenance.js +272 -0
  371. package/dist/storage/maintenance.js.map +1 -0
  372. package/dist/storage/outbox-worker.d.ts +21 -1
  373. package/dist/storage/outbox-worker.d.ts.map +1 -1
  374. package/dist/storage/outbox-worker.js +157 -28
  375. package/dist/storage/outbox-worker.js.map +1 -1
  376. package/dist/storage/ports.d.ts +52 -7
  377. package/dist/storage/ports.d.ts.map +1 -1
  378. package/dist/storage/ports.js.map +1 -1
  379. package/dist/storage/postgres-repository.d.ts +9 -2
  380. package/dist/storage/postgres-repository.d.ts.map +1 -1
  381. package/dist/storage/postgres-repository.js +97 -11
  382. package/dist/storage/postgres-repository.js.map +1 -1
  383. package/dist/storage/runtime.d.ts +20 -3
  384. package/dist/storage/runtime.d.ts.map +1 -1
  385. package/dist/storage/runtime.js +326 -156
  386. package/dist/storage/runtime.js.map +1 -1
  387. package/dist/telemetry/index.d.ts +41 -0
  388. package/dist/telemetry/index.d.ts.map +1 -0
  389. package/dist/telemetry/index.js +118 -0
  390. package/dist/telemetry/index.js.map +1 -0
  391. package/dist/telemetry/opentelemetry.d.ts +25 -0
  392. package/dist/telemetry/opentelemetry.d.ts.map +1 -0
  393. package/dist/telemetry/opentelemetry.js +74 -0
  394. package/dist/telemetry/opentelemetry.js.map +1 -0
  395. package/package.json +24 -14
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../src/storage/runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACtC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EACL,WAAW,EACX,WAAW,IAAI,iBAAiB,EAChC,sBAAsB,EACtB,qBAAqB,EACrB,gBAAgB,GACjB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AAEpE,OAAO,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAI7D,OAAO,EACL,4BAA4B,GAE7B,MAAM,6BAA6B,CAAC;AAErC,OAAO,EACL,iBAAiB,EACjB,cAAc,EACd,kBAAkB,GAGnB,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EAAE,oBAAoB,EAAoC,MAAM,0BAA0B,CAAC;AAClG,OAAO,EAAE,gBAAgB,EAAgC,MAAM,kBAAkB,CAAC;AA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,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,IAAI;QACvE,QAAQ,EAAE,OAAO,CAAC,QAAQ;QAC1B,SAAS,EAAG,OAAO,CAAC,UAA4B,IAAI,IAAI;QACxD,aAAa,EAAG,OAAO,CAAC,cAAgC,IAAI,IAAI;QAChE,UAAU,EAAG,OAAO,CAAC,WAA6B,IAAI,IAAI;KAC3D,CAAC;AACJ,CAAC;AAED,SAAS,gBAAgB,CAAC,KAAc;IACtC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC;AACvD,CAAC;AAED,SAAS,gBAAgB,CAAC,KAAc;IACtC,OAAO,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,IAAI,OAAO,KAAK,KAAK,QAAQ,CAAC;AAC5E,CAAC;AAED,SAAS,YAAY,CAAC,KAAc;IAClC,OAAO,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC","sourcesContent":["import { Bursar } from \"../bursar.js\";\nimport { z } from \"zod\";\nimport {\n ConfigError,\n ImportError as BursarImportError,\n isRetryableBursarError,\n CatalogNotLoadedError,\n StoreClosedError,\n} from \"../errors.js\";\nimport { retryBursarOperation } from \"../retry.js\";\nimport { PostgresBillingStore } from \"../billing/postgres/store.js\";\nimport type { BillingServiceOptions } from \"../billing/billing-service.js\";\nimport { PostgresStore } from \"../credits/postgres/store.js\";\nimport type { CreditsServiceOptions } from \"../credits/service.js\";\nimport type { CreditEventEmitter } from \"../credits/events.js\";\nimport type { CommerceOptions } from \"../commerce/types.js\";\nimport {\n normalizeProviderEnvironment,\n type ProviderEnvironment,\n} from \"../providers/environment.js\";\nimport type { UsageAnalyticsStore, UsageChargeStore } from \"../credits/types/index.js\";\nimport {\n normalizeTenantId,\n PostgresClient,\n postgresPoolConfig,\n type PostgresConnectionOptions,\n type PostgresPool,\n} from \"../shared/postgres-client.js\";\nimport type { QueryFn } from \"../shared/postgres-types.js\";\nimport { ClickHouseUsageStore, type ClickHouseUsageStoreOptions } from \"./adapters/clickhouse.js\";\nimport { S3BillingArchive, type S3BillingArchiveOptions } from \"./adapters/s3.js\";\nimport { OutboxWorker, type OutboxRunResult, type OutboxWorkerOptions } from \"./outbox-worker.js\";\nimport type {\n BillingEventPayloadExport,\n BillingPayloadArchive,\n OutboxHandler,\n UsageChargeExport,\n UsageEventSink,\n} from \"./ports.js\";\nimport { PostgresStorageRepository } from \"./postgres-repository.js\";\n\n/** Facade configuration accepted by the composed Node.js runtime. */\nexport interface BursarRuntimeBursarOptions {\n creditsOptions?: Omit<CreditsServiceOptions, \"analytics\" | \"usageStore\">;\n billingOptions?: Omit<BillingServiceOptions, \"provisioning\">;\n commerceOptions?: Omit<CommerceOptions, \"tenantId\" | \"providerEnvironment\">;\n emitter?: CreditEventEmitter;\n}\n\nexport interface BursarRuntimeOptions {\n postgres: string | PostgresPool;\n /** Explicit financial namespace shared by persistence and provider factories. */\n providerEnvironment: ProviderEnvironment;\n /** Applied to SDK-owned pools and per-transaction statement deadlines. */\n postgresOptions?: Omit<PostgresConnectionOptions, \"providerEnvironment\">;\n tenantId: string;\n /**\n * Optional provisioned tenant slug. When supplied, startup verifies that it\n * resolves to `tenantId` before any worker or catalog lifecycle begins.\n */\n tenantSlug?: string;\n s3?: BillingPayloadArchive | S3BillingArchiveOptions;\n clickhouse?: (UsageEventSink & UsageAnalyticsStore) | ClickHouseUsageStoreOptions;\n /**\n * Background delivery configuration. Set false only when another process\n * consumes Bursar's outbox.\n */\n outbox?: OutboxWorkerOptions | false;\n bursar?: BursarRuntimeBursarOptions;\n}\n\nexport interface BursarRuntimeStartOptions {\n /** Load the active catalog before starting background workers. */\n loadCatalog?: boolean;\n /** Total catalog-load attempts, including the first. Defaults to 1. */\n maxAttempts?: number;\n /** Initial retry delay. Each retry doubles up to 5 seconds. */\n retryDelayMs?: number;\n shouldRetry?: (error: unknown) => boolean;\n /** Maximum elapsed catalog-load retry budget. Defaults to 30 seconds. */\n maxElapsedMs?: number;\n /** Abort startup retries and pending backoff. */\n signal?: AbortSignal;\n}\n\nconst runtimeStartOptionsSchema = z\n .object({\n loadCatalog: z.boolean().default(true),\n maxAttempts: z.number().finite().int().min(1).max(Number.MAX_SAFE_INTEGER).default(1),\n retryDelayMs: z.number().finite().min(0).max(5_000).default(250),\n shouldRetry: z\n .custom<(error: unknown) => boolean>(\n (value) => typeof value === \"function\",\n \"shouldRetry must be a function\",\n )\n .optional(),\n maxElapsedMs: z.number().finite().min(0).max(2_147_483_647).optional(),\n signal: z\n .custom<AbortSignal>(\n (value) =>\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { throwIfAborted?: unknown }).throwIfAborted === \"function\",\n \"signal must be an AbortSignal\",\n )\n .optional(),\n })\n .strict();\n\nexport interface BursarRuntimeHealth {\n ready: boolean;\n started: boolean;\n closed: boolean;\n catalogLoaded: boolean;\n}\n\n/**\n * Node composition root for Bursar's stores and optional data infrastructure.\n *\n * Without S3 or ClickHouse it constructs the same PostgreSQL-only Bursar and\n * no outbox polling loop. All components share one PostgreSQL pool.\n */\nexport class BursarRuntime {\n readonly bursar: Bursar;\n readonly creditStore: PostgresStore;\n readonly billingStore: PostgresBillingStore;\n readonly worker: OutboxWorker | null;\n readonly clickhouse: (UsageEventSink & UsageAnalyticsStore) | null;\n readonly s3: BillingPayloadArchive | null;\n\n private readonly pool: PostgresPool;\n private readonly ownsPool: boolean;\n private readonly postgres: PostgresClient;\n private readonly query: QueryFn;\n private readonly tenantId: string;\n private readonly tenantSlug: string | null;\n readonly providerEnvironment: ProviderEnvironment;\n private startPromise: Promise<void> | null = null;\n private closePromise: Promise<void> | null = null;\n private started = false;\n private closed = false;\n\n /** Construct a runtime while keeping pool ownership inside the SDK. */\n static async create(options: BursarRuntimeOptions): Promise<BursarRuntime> {\n if (typeof options.postgres !== \"string\") {\n return new BursarRuntime(options.postgres, false, options);\n }\n if (!options.postgres.trim()) {\n throw new TypeError(\"postgres connection string must not be empty\");\n }\n let pg: typeof import(\"pg\");\n try {\n pg = await import(\"pg\");\n } catch (cause) {\n throw new BursarImportError(\"pg is required for the Bursar runtime: npm install pg\", {\n cause,\n });\n }\n const pool = new pg.Pool(\n postgresPoolConfig(options.postgres, options.postgresOptions),\n ) as PostgresPool;\n try {\n return new BursarRuntime(pool, true, options);\n } catch (error) {\n try {\n await pool.end();\n } catch {\n // Preserve the composition error; no runtime exists to report cleanup.\n }\n throw error;\n }\n }\n\n private constructor(\n pool: PostgresPool,\n ownsPool: boolean,\n options: Omit<BursarRuntimeOptions, \"postgres\">,\n ) {\n this.pool = pool;\n this.ownsPool = ownsPool;\n this.tenantId = normalizeTenantId(options.tenantId);\n this.providerEnvironment = normalizeProviderEnvironment(options.providerEnvironment);\n this.tenantSlug =\n options.tenantSlug === undefined ? null : normalizeTenantSlug(options.tenantSlug);\n for (const optionName of [\"bursar\", \"s3\", \"clickhouse\"] as const) {\n if (options[optionName] === null) {\n throw new TypeError(`${optionName} must not be null`);\n }\n }\n const bursarOptions = options.bursar ?? {};\n if (bursarOptions.creditsOptions === null) {\n throw new TypeError(\"bursar.creditsOptions must not be null\");\n }\n if (\n bursarOptions.creditsOptions &&\n (\"analytics\" in bursarOptions.creditsOptions || \"usageStore\" in bursarOptions.creditsOptions)\n ) {\n throw new TypeError(\"BursarRuntime owns creditsOptions.analytics and usageStore\");\n }\n if (bursarOptions.commerceOptions === null) {\n throw new TypeError(\"bursar.commerceOptions must not be null\");\n }\n if (\n bursarOptions.commerceOptions &&\n (\"tenantId\" in bursarOptions.commerceOptions ||\n \"providerEnvironment\" in bursarOptions.commerceOptions)\n ) {\n throw new TypeError(\"BursarRuntime owns commerceOptions.tenantId and providerEnvironment\");\n }\n if (\n options.clickhouse &&\n !(\"writeUsage\" in options.clickhouse) &&\n normalizeTenantId(options.clickhouse.tenantId) !== this.tenantId\n ) {\n throw new TypeError(\"ClickHouse tenantId must match runtime tenantId\");\n }\n this.clickhouse = options.clickhouse\n ? \"writeUsage\" in options.clickhouse\n ? options.clickhouse\n : new ClickHouseUsageStore({ ...options.clickhouse, tenantId: this.tenantId })\n : null;\n this.s3 = options.s3\n ? \"archive\" in options.s3\n ? options.s3\n : new S3BillingArchive(options.s3)\n : null;\n\n this.creditStore = new PostgresStore({\n postgres: pool,\n tenantId: this.tenantId,\n ...(options.postgresOptions ?? {}),\n providerEnvironment: this.providerEnvironment,\n usageBackend: this.clickhouse ? \"clickhouse\" : \"postgres\",\n });\n this.billingStore = new PostgresBillingStore({\n postgres: pool,\n tenantId: this.tenantId,\n ...(options.postgresOptions ?? {}),\n providerEnvironment: this.providerEnvironment,\n billingPayloadBackend: this.s3 ? \"s3\" : \"postgres\",\n });\n const commerceOptions = bursarOptions.commerceOptions\n ? {\n ...bursarOptions.commerceOptions,\n tenantId: this.tenantId,\n providerEnvironment: this.providerEnvironment,\n }\n : undefined;\n this.bursar = new Bursar({\n ...bursarOptions,\n commerceOptions,\n creditStore: this.creditStore,\n billingStore: this.billingStore,\n creditsOptions: {\n ...(bursarOptions.creditsOptions ?? {}),\n analytics: this.clickhouse ?? undefined,\n usageStore:\n this.clickhouse && \"listUsageCharges\" in this.clickhouse\n ? (this.clickhouse as UsageChargeStore)\n : undefined,\n },\n });\n\n this.postgres = new PostgresClient(pool, {\n ...(options.postgresOptions ?? {}),\n tenantId: this.tenantId,\n providerEnvironment: this.providerEnvironment,\n accessRole: \"bursar_operator\",\n usageBackend: this.clickhouse ? \"clickhouse\" : \"postgres\",\n billingPayloadBackend: this.s3 ? \"s3\" : \"postgres\",\n });\n this.query = this.postgres.query;\n const repository = new PostgresStorageRepository(this.query, this.tenantId);\n const handlers = this.createHandlers(repository);\n this.worker =\n handlers.length > 0 && options.outbox !== false\n ? new OutboxWorker(repository, handlers, options.outbox)\n : null;\n }\n\n start(options: BursarRuntimeStartOptions = {}): Promise<void> {\n if (this.closed) {\n return Promise.reject(new StoreClosedError(\"BursarRuntime has been closed\"));\n }\n if (this.started) return Promise.resolve();\n if (!this.startPromise) {\n this.startPromise = this.startRuntime(options).catch((error: unknown) => {\n this.startPromise = null;\n throw error;\n });\n }\n return this.startPromise;\n }\n\n private async startRuntime(options: BursarRuntimeStartOptions): Promise<void> {\n const startOptions = runtimeStartOptionsSchema.parse(options);\n if (this.tenantSlug) await this.verifyTenantIdentity();\n if (startOptions.loadCatalog) {\n const shouldRetry =\n startOptions.shouldRetry ??\n ((error: unknown) =>\n error instanceof CatalogNotLoadedError || isRetryableBursarError(error));\n await retryBursarOperation(() => this.bursar.loadCatalog(), {\n maxAttempts: startOptions.maxAttempts,\n baseDelayMs: startOptions.retryDelayMs,\n maxDelayMs: 5_000,\n maxElapsedMs: startOptions.maxElapsedMs,\n signal: startOptions.signal,\n shouldRetry,\n });\n }\n await this.clickhouse?.initialize?.();\n await this.worker?.start();\n this.started = true;\n }\n\n health(): BursarRuntimeHealth {\n const catalogLoaded = this.bursar.catalog.isLoaded;\n return {\n ready: this.started && !this.closed && catalogLoaded,\n started: this.started,\n closed: this.closed,\n catalogLoaded,\n };\n }\n\n async flush(): Promise<OutboxRunResult> {\n if (this.closed) throw new StoreClosedError(\"BursarRuntime has been closed\");\n return this.worker?.runOnce() ?? { claimed: 0, delivered: 0, failed: 0 };\n }\n\n close(): Promise<void> {\n if (this.closePromise) return this.closePromise;\n this.closed = true;\n this.closePromise = this.closeRuntime();\n return this.closePromise;\n }\n\n private async closeRuntime(): Promise<void> {\n const failures: unknown[] = [];\n const pendingStart = this.startPromise;\n if (pendingStart && !this.started) {\n try {\n await pendingStart;\n } catch {\n // Startup callers receive their own failure; shutdown must still clean up.\n }\n }\n\n try {\n await this.worker?.stop();\n } catch (error) {\n failures.push(error);\n }\n\n const resources = await Promise.allSettled([\n Promise.resolve().then(() => this.s3?.close?.()),\n Promise.resolve().then(() => this.creditStore.close()),\n Promise.resolve().then(() => this.billingStore.close()),\n Promise.resolve().then(() => this.postgres.close()),\n ]);\n for (const result of resources) {\n if (result.status === \"rejected\") failures.push(result.reason);\n }\n\n if (this.ownsPool) {\n try {\n await this.pool.end();\n } catch (error) {\n failures.push(error);\n }\n }\n\n if (failures.length === 1) throw failures[0];\n if (failures.length > 1) {\n throw new AggregateError(failures, \"BursarRuntime failed to close all resources\");\n }\n }\n\n private createHandlers(repository: PostgresStorageRepository): OutboxHandler[] {\n const handlers: OutboxHandler[] = [];\n if (this.clickhouse) {\n handlers.push({\n topics: [\"usage.charge_recorded\"],\n handle: async (outboxEvent) => {\n if (outboxEvent.payloadVersion !== 1) {\n throw new Error(\n `Unsupported usage outbox payload version ${outboxEvent.payloadVersion}`,\n );\n }\n let usage = usageExportFromOutbox(outboxEvent.payload);\n usage ??= await repository.getUsageCharge(outboxEvent.aggregateId);\n if (!usage) {\n throw new Error(`Usage charge ${outboxEvent.aggregateId} is unavailable for export`);\n }\n if (usage.tenantId !== outboxEvent.tenantId) {\n throw new Error(\"Usage export tenant does not match its outbox event\");\n }\n if (usage.chargeId !== outboxEvent.aggregateId) {\n throw new Error(\"Usage export charge does not match its outbox event\");\n }\n await this.clickhouse?.writeUsage(usage, outboxEvent.eventId);\n },\n });\n }\n if (this.s3) {\n handlers.push({\n topics: [\"billing.webhook_received\", \"billing.webhook_completed\"],\n handle: async (outboxEvent) => {\n if (outboxEvent.payloadVersion !== 1) {\n throw new Error(\n `Unsupported billing outbox payload version ${outboxEvent.payloadVersion}`,\n );\n }\n const stored = await repository.getBillingEventPayload(outboxEvent.aggregateId);\n if (stored?.objectKey) return;\n const event =\n outboxEvent.topic === \"billing.webhook_received\"\n ? billingExportFromOutbox(outboxEvent.payload)\n : stored;\n if (!event) {\n throw new Error(`Billing event ${outboxEvent.aggregateId} is unavailable for archive`);\n }\n if (event.tenantId !== outboxEvent.tenantId) {\n throw new Error(\"Billing export tenant does not match its outbox event\");\n }\n if (event.eventId !== outboxEvent.aggregateId) {\n throw new Error(\"Billing export event does not match its outbox event\");\n }\n const archived = await this.s3?.archive(event);\n if (!archived) throw new Error(\"S3 archive is not configured\");\n const recorded = await repository.archiveBillingEventPayload(\n event.eventId,\n archived.key,\n archived.versionId,\n );\n if (!recorded) {\n throw new Error(`Could not record archive pointer for billing event ${event.eventId}`);\n }\n },\n });\n }\n return handlers;\n }\n\n private async verifyTenantIdentity(): Promise<void> {\n if (!this.tenantSlug) return;\n const rows = await this.query(\n \"SELECT bursar.resolve_active_tenant_for_trigger($1)::text AS tenant_id\",\n [this.tenantSlug],\n );\n const resolved = rows[0];\n const tenantId =\n resolved && typeof resolved === \"object\" && \"tenant_id\" in resolved\n ? (resolved as { tenant_id?: unknown }).tenant_id\n : undefined;\n if (tenantId !== this.tenantId) {\n throw new ConfigError(\n `Bursar tenant slug '${this.tenantSlug}' resolves to a different tenant ID`,\n );\n }\n }\n}\n\nexport async function createBursarRuntime(options: BursarRuntimeOptions): Promise<BursarRuntime> {\n return BursarRuntime.create(options);\n}\n\nfunction normalizeTenantSlug(value: string): string {\n if (typeof value !== \"string\") throw new TypeError(\"tenantSlug must be a string\");\n const normalized = value.trim().toLowerCase();\n if (\n normalized.length < 1 ||\n normalized.length > 100 ||\n !/^[a-z0-9]+(?:[a-z0-9-]*[a-z0-9])?$/.test(normalized)\n ) {\n throw new TypeError(\"tenantSlug must be a valid Bursar tenant slug\");\n }\n return normalized;\n}\n\nfunction usageExportFromOutbox(payload: Record<string, unknown>): UsageChargeExport | null {\n const requiredStrings = [\n \"tenant_id\",\n \"charge_id\",\n \"account_id\",\n \"subject_id\",\n \"operation\",\n \"requested\",\n \"charged\",\n \"allowance_requested\",\n \"allowance_covered\",\n \"idempotency_key\",\n \"request_digest\",\n \"event_at\",\n \"created_at\",\n ] as const;\n if (requiredStrings.some((key) => !isNonEmptyString(payload[key]))) return null;\n if (\n !isJsonObject(payload.measures) ||\n !isJsonObject(payload.dimensions) ||\n !isJsonObject(payload.metadata) ||\n !isJsonObject(payload.pricing_snapshot)\n ) {\n return null;\n }\n const optionalStrings = [\n \"feature\",\n \"model\",\n \"region\",\n \"catalog_revision_id\",\n \"plan_id\",\n \"rate_card_key\",\n \"ledger_entry_id\",\n \"correction_of_charge_id\",\n ] as const;\n if (optionalStrings.some((key) => !isOptionalString(payload[key]))) return null;\n if (\n payload.billing_disposition !== undefined &&\n payload.billing_disposition !== \"billable\" &&\n payload.billing_disposition !== \"record_only\"\n ) {\n return null;\n }\n return {\n tenantId: payload.tenant_id as string,\n chargeId: payload.charge_id as string,\n accountId: payload.account_id as string,\n subjectId: payload.subject_id as string,\n operation: payload.operation as string,\n feature: (payload.feature as string | null) ?? null,\n model: (payload.model as string | null) ?? null,\n region: (payload.region as string | null) ?? null,\n measures: payload.measures,\n dimensions: payload.dimensions,\n metadata: payload.metadata,\n requested: payload.requested as string,\n charged: payload.charged as string,\n allowanceRequested: payload.allowance_requested as string,\n allowanceCovered: payload.allowance_covered as string,\n billingDisposition: payload.billing_disposition === \"record_only\" ? \"record_only\" : \"billable\",\n catalogRevisionId: (payload.catalog_revision_id as string | null) ?? null,\n planId: (payload.plan_id as string | null) ?? null,\n rateCardKey: (payload.rate_card_key as string | null) ?? null,\n pricingSnapshot: payload.pricing_snapshot,\n ledgerEntryId: (payload.ledger_entry_id as string | null) ?? null,\n correctionOfChargeId: (payload.correction_of_charge_id as string | null) ?? null,\n idempotencyKey: payload.idempotency_key as string,\n requestDigest: payload.request_digest as string,\n eventAt: payload.event_at as string,\n createdAt: payload.created_at as string,\n };\n}\n\nfunction billingExportFromOutbox(\n payload: Record<string, unknown>,\n): BillingEventPayloadExport | null {\n const requiredStrings = [\n \"tenant_id\",\n \"event_id\",\n \"provider\",\n \"provider_environment\",\n \"provider_event_id\",\n \"event_type\",\n \"status\",\n \"received_at\",\n ] as const;\n if (requiredStrings.some((key) => !isNonEmptyString(payload[key]))) return null;\n if (!isJsonObject(payload.envelope)) return null;\n if (!isOptionalString(payload.completed_at)) return null;\n return {\n tenantId: payload.tenant_id as string,\n eventId: payload.event_id as string,\n provider: payload.provider as string,\n providerEnvironment: payload.provider_environment as string,\n providerEventId: payload.provider_event_id as string,\n eventType: payload.event_type as string,\n status: payload.status as string,\n receivedAt: payload.received_at as string,\n completedAt: payload.completed_at ? String(payload.completed_at) : null,\n envelope: payload.envelope,\n objectKey: (payload.object_key as string | null) ?? null,\n objectVersion: (payload.object_version as string | null) ?? null,\n archivedAt: (payload.archived_at as string | null) ?? null,\n };\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0;\n}\n\nfunction isOptionalString(value: unknown): value is string | null | undefined {\n return value === null || value === undefined || typeof value === \"string\";\n}\n\nfunction isJsonObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n"]}
1
+ {"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../src/storage/runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACtC,OAAO,EACL,WAAW,EACX,WAAW,IAAI,iBAAiB,EAChC,sBAAsB,EACtB,qBAAqB,EACrB,gBAAgB,GACjB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AAEpE,OAAO,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAI7D,OAAO,EACL,4BAA4B,GAE7B,MAAM,6BAA6B,CAAC;AAErC,OAAO,EACL,iBAAiB,EACjB,cAAc,EACd,kBAAkB,GAGnB,MAAM,8BAA8B,CAAC;AAGtC,OAAO,EAAE,oBAAoB,EAAoC,MAAM,0BAA0B,CAAC;AAClG,OAAO,EAAE,gBAAgB,EAAgC,MAAM,kBAAkB,CAAC;AAClF,OAAO,EACL,yBAAyB,GAK1B,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,iBAAiB,EAAE,yB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,EAAE,KAAK,CAAC,UAAU;KAC5B,CAAC;AACJ,CAAC;AAED,SAAS,uBAAuB,CAAC,OAAmB;IAClD,MAAM,MAAM,GAAG,0BAA0B,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;IAC7D,IAAI,CAAC,MAAM,CAAC,OAAO;QAAE,OAAO,IAAI,CAAC;IACjC,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC;IAC1B,OAAO;QACL,QAAQ,EAAE,KAAK,CAAC,SAAS;QACzB,OAAO,EAAE,KAAK,CAAC,QAAQ;QACvB,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,mBAAmB,EAAE,KAAK,CAAC,oBAAoB;QAC/C,eAAe,EAAE,KAAK,CAAC,iBAAiB;QACxC,SAAS,EAAE,KAAK,CAAC,UAAU;QAC3B,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,UAAU,EAAE,KAAK,CAAC,WAAW;QAC7B,WAAW,EAAE,KAAK,CAAC,YAAY,IAAI,IAAI;QACvC,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,SAAS,EAAE,KAAK,CAAC,UAAU,IAAI,IAAI;QACnC,aAAa,EAAE,KAAK,CAAC,cAAc,IAAI,IAAI;QAC3C,UAAU,EAAE,KAAK,CAAC,WAAW,IAAI,IAAI;KACtC,CAAC;AACJ,CAAC","sourcesContent":["import { z } from \"zod\";\n\nimport { Bursar } from \"../bursar.js\";\nimport {\n ConfigError,\n ImportError as BursarImportError,\n isRetryableBursarError,\n CatalogNotLoadedError,\n StoreClosedError,\n} from \"../errors.js\";\nimport { retryBursarOperation } from \"../retry.js\";\nimport { PostgresBillingStore } from \"../billing/postgres/store.js\";\nimport type { BillingServiceOptions } from \"../billing/billing-service.js\";\nimport { PostgresStore } from \"../credits/postgres/store.js\";\nimport type { CreditsServiceOptions } from \"../credits/service.js\";\nimport type { CreditEventEmitter } from \"../credits/events.js\";\nimport type { CommerceOptions } from \"../commerce/types.js\";\nimport {\n normalizeProviderEnvironment,\n type ProviderEnvironment,\n} from \"../providers/environment.js\";\nimport type { UsageAnalyticsStore, UsageChargeStore } from \"../credits/types/index.js\";\nimport {\n normalizeTenantId,\n PostgresClient,\n postgresPoolConfig,\n type PostgresConnectionOptions,\n type PostgresPool,\n} from \"../shared/postgres-client.js\";\nimport type { QueryFn } from \"../shared/postgres-types.js\";\nimport type { JsonObject } from \"../shared/json.js\";\nimport { ClickHouseUsageStore, type ClickHouseUsageStoreOptions } from \"./adapters/clickhouse.js\";\nimport { S3BillingArchive, type S3BillingArchiveOptions } from \"./adapters/s3.js\";\nimport {\n RuntimeDiagnosticsTracker,\n type BursarRuntimeDiagnostics,\n type BursarRuntimeState,\n type CheckDependenciesOptions,\n type OutboxStatusSnapshot,\n} from \"./diagnostics.js\";\nimport { BursarMaintenance, BursarOperatorMaintenance } from \"./maintenance.js\";\nimport { OutboxWorker, type OutboxRunResult, type OutboxWorkerOptions } from \"./outbox-worker.js\";\nimport type {\n BillingEventPayloadExport,\n BillingPayloadArchive,\n OutboxHandler,\n OutboxRecoveryStore,\n UsageChargeExport,\n UsageEventSink,\n} from \"./ports.js\";\nimport { PostgresStorageRepository } from \"./postgres-repository.js\";\n\n/** Facade configuration accepted by the composed Node.js runtime. */\nexport interface BursarRuntimeBursarOptions {\n creditsOptions?: Omit<CreditsServiceOptions, \"analytics\" | \"usageStore\">;\n billingOptions?: Omit<BillingServiceOptions, \"provisioning\">;\n commerceOptions?: Omit<CommerceOptions, \"tenantId\" | \"providerEnvironment\">;\n emitter?: CreditEventEmitter;\n}\n\nexport interface BursarRuntimeOptions {\n /** Tenant-scoped caller with SET-only membership in bursar_client. */\n postgres: string | PostgresPool;\n /** Cross-tenant caller with SET-only membership in bursar_operator. */\n operatorPostgres: string | PostgresPool;\n /** Explicit financial namespace shared by persistence and provider factories. */\n providerEnvironment: ProviderEnvironment;\n /** Applied to SDK-owned pools and per-transaction statement deadlines. */\n postgresOptions?: Omit<PostgresConnectionOptions, \"providerEnvironment\">;\n tenantId: string;\n /**\n * Optional provisioned tenant slug. When supplied, startup verifies that it\n * resolves to `tenantId` before any worker or catalog lifecycle begins.\n */\n tenantSlug?: string;\n s3?: BillingPayloadArchive | S3BillingArchiveOptions;\n clickhouse?: (UsageEventSink & UsageAnalyticsStore) | ClickHouseUsageStoreOptions;\n /**\n * Background delivery configuration. Set false only when another process\n * consumes Bursar's outbox.\n */\n outbox?: OutboxWorkerOptions | false;\n bursar?: BursarRuntimeBursarOptions;\n}\n\nexport interface BursarRuntimeStartOptions {\n /** Load the active catalog before starting background workers. */\n loadCatalog?: boolean;\n /** Total catalog-load attempts, including the first. Defaults to 1. */\n maxAttempts?: number;\n /** Initial retry delay. Each retry doubles up to 5 seconds. */\n retryDelayMs?: number;\n shouldRetry?: (cause: unknown) => boolean;\n /** Maximum elapsed catalog-load retry budget. Defaults to 30 seconds. */\n maxElapsedMs?: number;\n /** Abort startup retries and pending backoff. */\n signal?: AbortSignal;\n}\n\nconst abortSignalSchema = z.custom<AbortSignal>(\n (value) =>\n z\n .object({\n aborted: z.boolean(),\n addEventListener: z.function(),\n removeEventListener: z.function(),\n throwIfAborted: z.function(),\n })\n .safeParse(value).success,\n \"signal must be an AbortSignal\",\n);\n\nconst shouldRetrySchema = z.custom<(cause: unknown) => boolean>(\n (value) => z.function().safeParse(value).success,\n \"shouldRetry must be a function\",\n);\n\nconst runtimeStartOptionsSchema = z\n .object({\n loadCatalog: z.boolean().default(true),\n maxAttempts: z.number().finite().int().min(1).max(Number.MAX_SAFE_INTEGER).default(1),\n retryDelayMs: z.number().finite().min(0).max(5_000).default(250),\n shouldRetry: shouldRetrySchema.optional(),\n maxElapsedMs: z.number().finite().min(0).max(2_147_483_647).optional(),\n signal: abortSignalSchema.optional(),\n })\n .strict();\n\nexport interface BursarRuntimeHealth {\n ready: boolean;\n financialReady: boolean;\n projectionReady: boolean;\n degraded: boolean;\n started: boolean;\n closed: boolean;\n catalogLoaded: boolean;\n}\n\ninterface PendingUsageWrite {\n event: UsageChargeExport;\n outboxEventId: string;\n resolve: () => void;\n reject: (error: Error) => void;\n}\n\n/** Coalesce concurrently dispatched usage events into one optional sink write. */\nclass UsageWriteBatcher {\n private pending: PendingUsageWrite[] = [];\n private scheduled = false;\n\n constructor(private readonly sink: UsageEventSink) {}\n\n write(event: UsageChargeExport, outboxEventId: string): Promise<void> {\n if (!this.sink.writeUsageBatch) return this.sink.writeUsage(event, outboxEventId);\n return new Promise<void>((resolve, reject) => {\n this.pending.push({ event, outboxEventId, resolve, reject });\n if (this.scheduled) return;\n this.scheduled = true;\n queueMicrotask(() => {\n void this.flush();\n });\n });\n }\n\n private async flush(): Promise<void> {\n const pending = this.pending.splice(0);\n this.scheduled = false;\n try {\n await this.sink.writeUsageBatch!(\n pending.map(({ event, outboxEventId }) => [event, outboxEventId] as const),\n );\n for (const write of pending) write.resolve();\n } catch (error) {\n const failure =\n error instanceof Error ? error : new Error(\"Usage batch write failed\", { cause: error });\n for (const write of pending) write.reject(failure);\n }\n }\n}\n\n/**\n * Node composition root for Bursar's stores and optional data infrastructure.\n *\n * Without S3 or ClickHouse it constructs the same PostgreSQL-only Bursar and\n * no outbox polling loop. Tenant and operator work always use distinct pools.\n */\nexport class BursarRuntime {\n readonly bursar: Bursar;\n readonly creditStore: PostgresStore;\n readonly billingStore: PostgresBillingStore;\n readonly maintenance: BursarMaintenance;\n readonly operatorMaintenance: BursarOperatorMaintenance;\n readonly worker: OutboxWorker | null;\n readonly outboxRecovery: OutboxRecoveryStore;\n readonly clickhouse: (UsageEventSink & UsageAnalyticsStore) | null;\n readonly s3: BillingPayloadArchive | null;\n\n private readonly pool: PostgresPool;\n private readonly operatorPool: PostgresPool;\n private readonly ownsPool: boolean;\n private readonly ownsOperatorPool: boolean;\n private readonly postgres: PostgresClient;\n private readonly query: QueryFn;\n private readonly tenantId: string;\n private readonly tenantSlug: string | null;\n private readonly diagnosticsTracker: RuntimeDiagnosticsTracker;\n private readonly usageBatcher: UsageWriteBatcher | null;\n readonly providerEnvironment: ProviderEnvironment;\n private startPromise: Promise<void> | null = null;\n private closePromise: Promise<void> | null = null;\n private started = false;\n private closed = false;\n\n /** Construct a runtime while keeping pool ownership inside the SDK. */\n static async create(options: BursarRuntimeOptions): Promise<BursarRuntime> {\n if (options.operatorPostgres === undefined || options.operatorPostgres === null) {\n throw new TypeError(\"operatorPostgres is required\");\n }\n const postgresConnection = connectionStringValue(options.postgres);\n const operatorPostgresConnection = connectionStringValue(options.operatorPostgres);\n const ownsPool = postgresConnection !== null;\n const ownsOperatorPool = operatorPostgresConnection !== null;\n if (postgresConnection !== null && !postgresConnection.trim()) {\n throw new TypeError(\"postgres connection string must not be empty\");\n }\n if (operatorPostgresConnection !== null && !operatorPostgresConnection.trim()) {\n throw new TypeError(\"operatorPostgres connection string must not be empty\");\n }\n if (options.postgres === options.operatorPostgres) {\n throw new TypeError(\"postgres and operatorPostgres must use distinct connections\");\n }\n\n let pg: typeof import(\"pg\") | undefined;\n if (ownsPool || ownsOperatorPool) {\n try {\n pg = await import(\"pg\");\n } catch (cause) {\n throw new BursarImportError(\"pg is required for the Bursar runtime: npm install pg\", {\n cause,\n });\n }\n }\n let pool: PostgresPool | undefined;\n let operatorPool: PostgresPool | undefined;\n try {\n if ((ownsPool || ownsOperatorPool) && pg === undefined) {\n throw new BursarImportError(\"pg is required for the Bursar runtime: npm install pg\");\n }\n pool = ownsPool\n ? createOwnedPool(\n pg,\n postgresConnection ?? requiredConnectionString(options.postgres),\n options.postgresOptions,\n )\n : providedPool(options.postgres);\n operatorPool = ownsOperatorPool\n ? createOwnedPool(\n pg,\n operatorPostgresConnection ?? requiredConnectionString(options.operatorPostgres),\n options.postgresOptions,\n )\n : providedPool(options.operatorPostgres);\n return new BursarRuntime(pool, ownsPool, operatorPool, ownsOperatorPool, options);\n } catch (error) {\n await Promise.allSettled([\n ...(ownsPool && pool ? [pool.end()] : []),\n ...(ownsOperatorPool && operatorPool ? [operatorPool.end()] : []),\n ]);\n throw error;\n }\n }\n\n private constructor(\n pool: PostgresPool,\n ownsPool: boolean,\n operatorPool: PostgresPool,\n ownsOperatorPool: boolean,\n options: BursarRuntimeOptions,\n ) {\n this.pool = pool;\n this.operatorPool = operatorPool;\n this.ownsPool = ownsPool;\n this.ownsOperatorPool = ownsOperatorPool;\n this.tenantId = normalizeTenantId(options.tenantId);\n this.providerEnvironment = normalizeProviderEnvironment(options.providerEnvironment);\n this.tenantSlug =\n options.tenantSlug === undefined ? null : normalizeTenantSlug(options.tenantSlug);\n for (const optionName of [\"bursar\", \"s3\", \"clickhouse\"] as const) {\n if (options[optionName] === null) {\n throw new TypeError(`${optionName} must not be null`);\n }\n }\n const bursarOptions = options.bursar ?? {};\n if (bursarOptions.creditsOptions === null) {\n throw new TypeError(\"bursar.creditsOptions must not be null\");\n }\n if (\n bursarOptions.creditsOptions &&\n (\"analytics\" in bursarOptions.creditsOptions || \"usageStore\" in bursarOptions.creditsOptions)\n ) {\n throw new TypeError(\"BursarRuntime owns creditsOptions.analytics and usageStore\");\n }\n if (bursarOptions.commerceOptions === null) {\n throw new TypeError(\"bursar.commerceOptions must not be null\");\n }\n if (\n bursarOptions.commerceOptions &&\n (\"tenantId\" in bursarOptions.commerceOptions ||\n \"providerEnvironment\" in bursarOptions.commerceOptions)\n ) {\n throw new TypeError(\"BursarRuntime owns commerceOptions.tenantId and providerEnvironment\");\n }\n if (\n options.clickhouse &&\n !(\"writeUsage\" in options.clickhouse) &&\n normalizeTenantId(options.clickhouse.tenantId) !== this.tenantId\n ) {\n throw new TypeError(\"ClickHouse tenantId must match runtime tenantId\");\n }\n this.clickhouse = options.clickhouse\n ? \"writeUsage\" in options.clickhouse\n ? options.clickhouse\n : new ClickHouseUsageStore({ ...options.clickhouse, tenantId: this.tenantId })\n : null;\n this.usageBatcher = this.clickhouse ? new UsageWriteBatcher(this.clickhouse) : null;\n this.s3 = options.s3\n ? \"archive\" in options.s3\n ? options.s3\n : new S3BillingArchive(options.s3)\n : null;\n\n this.creditStore = new PostgresStore({\n postgres: pool,\n tenantId: this.tenantId,\n ...(options.postgresOptions ?? {}),\n providerEnvironment: this.providerEnvironment,\n usageBackend: this.clickhouse ? \"clickhouse\" : \"postgres\",\n });\n this.billingStore = new PostgresBillingStore({\n postgres: pool,\n tenantId: this.tenantId,\n ...(options.postgresOptions ?? {}),\n providerEnvironment: this.providerEnvironment,\n billingPayloadBackend: this.s3 ? \"s3\" : \"postgres\",\n });\n const commerceOptions = bursarOptions.commerceOptions\n ? {\n ...bursarOptions.commerceOptions,\n tenantId: this.tenantId,\n providerEnvironment: this.providerEnvironment,\n }\n : undefined;\n this.bursar = new Bursar({\n ...bursarOptions,\n commerceOptions,\n creditStore: this.creditStore,\n billingStore: this.billingStore,\n creditsOptions: {\n ...(bursarOptions.creditsOptions ?? {}),\n analytics: this.clickhouse ?? undefined,\n usageStore:\n this.clickhouse && supportsUsageHistory(this.clickhouse) ? this.clickhouse : undefined,\n },\n });\n\n this.postgres = new PostgresClient(operatorPool, {\n ...(options.postgresOptions ?? {}),\n tenantId: this.tenantId,\n providerEnvironment: this.providerEnvironment,\n accessRole: \"bursar_operator\",\n usageBackend: this.clickhouse ? \"clickhouse\" : \"postgres\",\n billingPayloadBackend: this.s3 ? \"s3\" : \"postgres\",\n });\n this.query = this.postgres.query;\n this.maintenance = new BursarMaintenance({\n expireLeases: (limit) => this.creditStore.expireLeases(limit),\n expireCredits: async (limit) =>\n (await this.creditStore.sweepExpiredCredits(false, undefined, limit)).expiredCount,\n applyDuePlanChanges: (limit) => this.creditStore.applyDuePlanChanges(limit),\n expirePastDueGracePeriods: this.bursar.billing\n ? (now) => this.bursar.billing!.expirePastDueGracePeriods(now)\n : undefined,\n pastDueGracePeriodLimit: 100,\n pastDueGracePeriodsUnavailableReason: this.bursar.billing\n ? undefined\n : \"billing is not configured\",\n });\n this.operatorMaintenance = new BursarOperatorMaintenance(this.query);\n const repository = new PostgresStorageRepository(this.query, this.tenantId);\n this.outboxRecovery = repository;\n const handlers = this.createHandlers(repository);\n const configuredOutboxOptions =\n options.outbox === false || options.outbox === undefined ? {} : options.outbox;\n const originalOnError = configuredOutboxOptions.onError;\n let diagnosticsTracker: RuntimeDiagnosticsTracker | null = null;\n const workerOptions: OutboxWorkerOptions = {\n ...configuredOutboxOptions,\n onError: async (error) => {\n diagnosticsTracker?.recordWorkerError(error);\n await originalOnError?.(error);\n },\n };\n this.worker =\n handlers.length > 0 && options.outbox !== false\n ? new OutboxWorker(repository, handlers, workerOptions)\n : null;\n this.diagnosticsTracker = new RuntimeDiagnosticsTracker(\n {\n checkPostgres: async () => {\n const rows = await this.query(\"SELECT 1 AS bursar_reachable\");\n const row = rows[0];\n if (\n !row ||\n !z.number().int().safeParse(row.bursar_reachable).success ||\n row.bursar_reachable !== 1\n ) {\n throw new Error(\"PostgreSQL reachability check returned an invalid result\");\n }\n },\n getCatalogRevision: async () => {\n const revision = await this.bursar.catalog.getActive();\n return revision ? { id: revision.id, version: revision.version } : null;\n },\n getOutboxStatus: outboxStatusProvider(repository),\n },\n this.worker !== null,\n );\n diagnosticsTracker = this.diagnosticsTracker;\n }\n\n start(options: BursarRuntimeStartOptions = {}): Promise<void> {\n if (this.closed) {\n return Promise.reject(new StoreClosedError(\"BursarRuntime has been closed\"));\n }\n if (this.started) return Promise.resolve();\n if (!this.startPromise) {\n this.startPromise = this.startRuntime(options).catch((error) => {\n this.startPromise = null;\n throw error;\n });\n }\n return this.startPromise;\n }\n\n private async startRuntime(options: BursarRuntimeStartOptions): Promise<void> {\n const startOptions = runtimeStartOptionsSchema.parse(options);\n if (this.tenantSlug) await this.verifyTenantIdentity();\n if (startOptions.loadCatalog) {\n const shouldRetry =\n startOptions.shouldRetry ??\n ((cause: unknown) =>\n cause instanceof CatalogNotLoadedError || isRetryableBursarError(cause));\n await retryBursarOperation(() => this.bursar.loadCatalog(), {\n maxAttempts: startOptions.maxAttempts,\n baseDelayMs: startOptions.retryDelayMs,\n maxDelayMs: 5_000,\n maxElapsedMs: startOptions.maxElapsedMs,\n signal: startOptions.signal,\n shouldRetry,\n });\n }\n await this.clickhouse?.initialize?.();\n await this.clickhouse?.checkSchemaCompatibility?.();\n await this.worker?.start();\n if (this.worker) this.diagnosticsTracker.markWorkerStarted();\n this.started = true;\n }\n\n state(): BursarRuntimeState {\n return this.diagnosticsTracker.state({\n started: this.started,\n closed: this.closed,\n catalogLoaded: this.bursar.catalog.isLoaded,\n });\n }\n\n checkDependencies(options: CheckDependenciesOptions = {}): Promise<BursarRuntimeDiagnostics> {\n return this.diagnosticsTracker.checkDependencies(\n {\n started: this.started,\n closed: this.closed,\n catalogLoaded: this.bursar.catalog.isLoaded,\n },\n options,\n );\n }\n\n health(): BursarRuntimeHealth {\n const state = this.state();\n return {\n ready: state.ready,\n financialReady: state.financialReady,\n projectionReady: state.projectionReady,\n degraded: state.degraded,\n started: state.started,\n closed: state.closed,\n catalogLoaded: state.catalogLoaded,\n };\n }\n\n async flush(): Promise<OutboxRunResult> {\n if (this.closed) throw new StoreClosedError(\"BursarRuntime has been closed\");\n if (!this.worker) return { claimed: 0, delivered: 0, failed: 0, claimLost: 0 };\n return this.diagnosticsTracker.observeManualRun(() => this.worker!.runOnce());\n }\n\n close(): Promise<void> {\n if (this.closePromise) return this.closePromise;\n this.closed = true;\n this.closePromise = this.closeRuntime();\n return this.closePromise;\n }\n\n private async closeRuntime(): Promise<void> {\n const failures: unknown[] = [];\n const pendingStart = this.startPromise;\n if (pendingStart && !this.started) {\n try {\n await pendingStart;\n } catch {\n // Startup callers receive their own failure; shutdown must still clean up.\n }\n }\n\n try {\n await this.worker?.stop();\n } catch (error) {\n failures.push(error);\n } finally {\n if (this.worker) this.diagnosticsTracker.markWorkerStopped();\n }\n\n const resources = await Promise.allSettled([\n Promise.resolve().then(() => this.s3?.close?.()),\n Promise.resolve().then(() => this.creditStore.close()),\n Promise.resolve().then(() => this.billingStore.close()),\n Promise.resolve().then(() => this.postgres.close()),\n ]);\n for (const result of resources) {\n if (result.status === \"rejected\") failures.push(result.reason);\n }\n\n if (this.ownsPool) {\n try {\n await this.pool.end();\n } catch (error) {\n failures.push(error);\n }\n }\n if (this.ownsOperatorPool) {\n try {\n await this.operatorPool.end();\n } catch (error) {\n failures.push(error);\n }\n }\n\n if (failures.length === 1) throw failures[0];\n if (failures.length > 1) {\n throw new AggregateError(failures, \"BursarRuntime failed to close all resources\");\n }\n }\n\n private createHandlers(repository: PostgresStorageRepository): OutboxHandler[] {\n const handlers: OutboxHandler[] = [];\n if (this.clickhouse) {\n handlers.push({\n topics: [\"usage.charge_recorded\"],\n handle: async (outboxEvent) => {\n if (outboxEvent.payloadVersion !== 1) {\n throw new Error(\n `Unsupported usage outbox payload version ${outboxEvent.payloadVersion}`,\n );\n }\n let usage = usageExportFromOutbox(outboxEvent.payload);\n usage ??= await repository.getUsageCharge(outboxEvent.aggregateId);\n if (!usage) {\n throw new Error(`Usage charge ${outboxEvent.aggregateId} is unavailable for export`);\n }\n if (usage.tenantId !== outboxEvent.tenantId) {\n throw new Error(\"Usage export tenant does not match its outbox event\");\n }\n if (usage.chargeId !== outboxEvent.aggregateId) {\n throw new Error(\"Usage export charge does not match its outbox event\");\n }\n if (!this.usageBatcher) throw new Error(\"ClickHouse usage sink is not configured\");\n await this.usageBatcher.write(usage, outboxEvent.eventId);\n },\n });\n }\n if (this.s3) {\n handlers.push({\n topics: [\"billing.webhook_received\", \"billing.webhook_completed\"],\n handle: async (outboxEvent) => {\n if (outboxEvent.payloadVersion !== 1) {\n throw new Error(\n `Unsupported billing outbox payload version ${outboxEvent.payloadVersion}`,\n );\n }\n const stored = await repository.getBillingEventPayload(outboxEvent.aggregateId);\n if (stored?.objectKey) return;\n const event =\n outboxEvent.topic === \"billing.webhook_received\"\n ? billingExportFromOutbox(outboxEvent.payload)\n : stored;\n if (!event) {\n throw new Error(`Billing event ${outboxEvent.aggregateId} is unavailable for archive`);\n }\n if (event.tenantId !== outboxEvent.tenantId) {\n throw new Error(\"Billing export tenant does not match its outbox event\");\n }\n if (event.eventId !== outboxEvent.aggregateId) {\n throw new Error(\"Billing export event does not match its outbox event\");\n }\n const archived = await this.s3?.archive(event);\n if (!archived) throw new Error(\"S3 archive is not configured\");\n const recorded = await repository.archiveBillingEventPayload(\n event.eventId,\n archived.key,\n archived.versionId,\n );\n if (!recorded) {\n throw new Error(`Could not record archive pointer for billing event ${event.eventId}`);\n }\n },\n });\n }\n return handlers;\n }\n\n private async verifyTenantIdentity(): Promise<void> {\n if (!this.tenantSlug) return;\n const rows = await this.query(\n \"SELECT bursar.resolve_active_tenant_for_trigger($1)::text AS tenant_id\",\n [this.tenantSlug],\n );\n const resolved = rows[0];\n const tenantId = z.string().safeParse(resolved?.tenant_id);\n if (!tenantId.success || tenantId.data !== this.tenantId) {\n throw new ConfigError(\n `Bursar tenant slug '${this.tenantSlug}' resolves to a different tenant ID`,\n );\n }\n }\n}\n\nexport async function createBursarRuntime(options: BursarRuntimeOptions): Promise<BursarRuntime> {\n return BursarRuntime.create(options);\n}\n\nfunction outboxStatusProvider(\n repository: PostgresStorageRepository,\n): (limit: number) => Promise<OutboxStatusSnapshot> {\n return async (limit) => repository.stats({ limit });\n}\n\ntype PostgresConnectionInput = string | PostgresPool;\n\nfunction isPostgresConnectionString(value: PostgresConnectionInput): value is string {\n return z.string().safeParse(value).success;\n}\n\nfunction connectionStringValue(value: PostgresConnectionInput): string | null {\n const parsed = z.string().safeParse(value);\n return parsed.success ? parsed.data : null;\n}\n\nfunction requiredConnectionString(value: PostgresConnectionInput): string {\n const parsed = z.string().min(1).safeParse(value);\n if (!parsed.success) {\n throw new TypeError(\"an owned PostgreSQL pool requires a connection string\");\n }\n return parsed.data;\n}\n\nfunction createOwnedPool(\n pg: typeof import(\"pg\") | undefined,\n connectionString: string,\n options: Omit<PostgresConnectionOptions, \"providerEnvironment\"> | undefined,\n): PostgresPool {\n if (pg === undefined) {\n throw new BursarImportError(\"pg is required for the Bursar runtime: npm install pg\");\n }\n // SAFETY: the runtime's PostgresPool contract is the subset used by Bursar,\n // and the node-postgres Pool is created from the validated connection options above.\n return new pg.Pool(postgresPoolConfig(connectionString, options)) as PostgresPool;\n}\n\nfunction providedPool(value: PostgresConnectionInput): PostgresPool {\n if (isPostgresConnectionString(value)) {\n throw new TypeError(\"a connection string cannot be used as an external PostgreSQL pool\");\n }\n return value;\n}\n\ntype RuntimeClickhouseStore = UsageEventSink & UsageAnalyticsStore;\ntype RuntimeClickhouseHistoryStore = RuntimeClickhouseStore & UsageChargeStore;\n\nfunction supportsUsageHistory(\n value: RuntimeClickhouseStore,\n): value is RuntimeClickhouseHistoryStore {\n return z.object({ listUsageCharges: z.function() }).safeParse(value).success;\n}\n\nfunction normalizeTenantSlug(value: string): string {\n const trimmed = z.string().trim().min(1).max(100).safeParse(value);\n if (!trimmed.success) throw new TypeError(\"tenantSlug must be a valid Bursar tenant slug\");\n const normalized = z\n .string()\n .regex(/^[a-z0-9]+(?:[a-z0-9-]*[a-z0-9])?$/u)\n .safeParse(trimmed.data.toLowerCase());\n if (!normalized.success) throw new TypeError(\"tenantSlug must be a valid Bursar tenant slug\");\n return normalized.data;\n}\n\nconst outboxJsonObjectSchema = z.record(z.string(), z.json());\n\nconst usageOutboxPayloadSchema = z\n .object({\n tenant_id: z.string().min(1),\n charge_id: z.string().min(1),\n account_id: z.string().min(1),\n subject_id: z.string().min(1),\n operation: z.string().min(1),\n feature: z.string().nullable().optional(),\n model: z.string().nullable().optional(),\n region: z.string().nullable().optional(),\n measures: outboxJsonObjectSchema,\n dimensions: outboxJsonObjectSchema,\n metadata: outboxJsonObjectSchema,\n requested: z.string().min(1),\n charged: z.string().min(1),\n allowance_requested: z.string().min(1),\n allowance_covered: z.string().min(1),\n billing_disposition: z.enum([\"billable\", \"record_only\"]).optional(),\n catalog_revision_id: z.string().nullable().optional(),\n plan_id: z.string().nullable().optional(),\n rate_card_key: z.string().nullable().optional(),\n pricing_snapshot: outboxJsonObjectSchema,\n ledger_entry_id: z.string().nullable().optional(),\n correction_of_charge_id: z.string().nullable().optional(),\n idempotency_key: z.string().min(1),\n request_digest: z.string().min(1),\n event_at: z.string().min(1),\n created_at: z.string().min(1),\n })\n .passthrough();\n\nconst billingOutboxPayloadSchema = z\n .object({\n tenant_id: z.string().min(1),\n event_id: z.string().min(1),\n provider: z.string().min(1),\n provider_environment: z.string().min(1),\n provider_event_id: z.string().min(1),\n event_type: z.string().min(1),\n status: z.string().min(1),\n received_at: z.string().min(1),\n completed_at: z.string().nullable().optional(),\n envelope: outboxJsonObjectSchema,\n object_key: z.string().nullable().optional(),\n object_version: z.string().nullable().optional(),\n archived_at: z.string().nullable().optional(),\n })\n .passthrough();\n\nfunction usageExportFromOutbox(payload: JsonObject): UsageChargeExport | null {\n const parsed = usageOutboxPayloadSchema.safeParse(payload);\n if (!parsed.success) return null;\n const value = parsed.data;\n return {\n tenantId: value.tenant_id,\n chargeId: value.charge_id,\n accountId: value.account_id,\n subjectId: value.subject_id,\n operation: value.operation,\n feature: value.feature ?? null,\n model: value.model ?? null,\n region: value.region ?? null,\n measures: value.measures,\n dimensions: value.dimensions,\n metadata: value.metadata,\n requested: value.requested,\n charged: value.charged,\n allowanceRequested: value.allowance_requested,\n allowanceCovered: value.allowance_covered,\n billingDisposition: value.billing_disposition ?? \"billable\",\n catalogRevisionId: value.catalog_revision_id ?? null,\n planId: value.plan_id ?? null,\n rateCardKey: value.rate_card_key ?? null,\n pricingSnapshot: value.pricing_snapshot,\n ledgerEntryId: value.ledger_entry_id ?? null,\n correctionOfChargeId: value.correction_of_charge_id ?? null,\n idempotencyKey: value.idempotency_key,\n requestDigest: value.request_digest,\n eventAt: value.event_at,\n createdAt: value.created_at,\n };\n}\n\nfunction billingExportFromOutbox(payload: JsonObject): BillingEventPayloadExport | null {\n const parsed = billingOutboxPayloadSchema.safeParse(payload);\n if (!parsed.success) return null;\n const value = parsed.data;\n return {\n tenantId: value.tenant_id,\n eventId: value.event_id,\n provider: value.provider,\n providerEnvironment: value.provider_environment,\n providerEventId: value.provider_event_id,\n eventType: value.event_type,\n status: value.status,\n receivedAt: value.received_at,\n completedAt: value.completed_at ?? null,\n envelope: value.envelope,\n objectKey: value.object_key ?? null,\n objectVersion: value.object_version ?? null,\n archivedAt: value.archived_at ?? null,\n };\n}\n"]}
@@ -0,0 +1,41 @@
1
+ export declare const BURSAR_INSTRUMENTATION_SCOPE = "@zonastery/bursar";
2
+ export declare const BURSAR_INSTRUMENTATION_VERSION = "2.0.4";
3
+ export type TelemetryAttributeValue = string | number | boolean;
4
+ export interface TelemetryAttributes {
5
+ readonly [key: string]: TelemetryAttributeValue;
6
+ }
7
+ export interface SanitizedTelemetryAttributes {
8
+ [key: string]: TelemetryAttributeValue;
9
+ }
10
+ /**
11
+ * Keep telemetry attributes bounded and low-cardinality.
12
+ *
13
+ * Unknown keys and non-scalar values are discarded. String values are
14
+ * normalized to stable tokens so identifiers, metadata, and raw payloads
15
+ * cannot accidentally pass through this boundary.
16
+ */
17
+ export declare function sanitizeTelemetryAttributes<T extends object>(attributes?: T): SanitizedTelemetryAttributes;
18
+ /** Build the safe base attributes for one Bursar operation. */
19
+ export declare function telemetryOperationAttributes<T extends object>(operation: string, attributes?: T): SanitizedTelemetryAttributes;
20
+ /** Normalize an error without reading or recording its message or details. */
21
+ export declare function telemetryErrorAttributes(cause: unknown): SanitizedTelemetryAttributes;
22
+ /** Vendor-neutral contract used by Bursar's core runtime. */
23
+ export interface Instrumentation {
24
+ run<T>(operation: string, attributes: TelemetryAttributes | undefined, callback: () => Promise<T>): Promise<T>;
25
+ }
26
+ /** Default implementation: execute normally and emit nothing. */
27
+ export declare class NoopInstrumentation implements Instrumentation {
28
+ run<T>(_operation: string, _attributes: TelemetryAttributes | undefined, callback: () => Promise<T>): Promise<T>;
29
+ }
30
+ export declare const NOOP_INSTRUMENTATION: Instrumentation;
31
+ /** Return the instrumentation selected by the embedding application. */
32
+ export declare function getDefaultInstrumentation(): Instrumentation;
33
+ /**
34
+ * Select a process-wide Bursar instrumentation implementation.
35
+ *
36
+ * This does not configure an OpenTelemetry provider or exporter. Call the
37
+ * returned function to restore the previous implementation. A stale restore
38
+ * cannot overwrite a newer registration.
39
+ */
40
+ export declare function setDefaultInstrumentation(instrumentation: Instrumentation | null): () => void;
41
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/telemetry/index.ts"],"names":[],"mappings":"AAKA,eAAO,MAAM,4BAA4B,sBAAsB,CAAC;AAChE,eAAO,MAAM,8BAA8B,UAAU,CAAC;AAEtD,MAAM,MAAM,uBAAuB,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC;AAChE,MAAM,WAAW,mBAAmB;IAClC,QAAQ,EAAE,GAAG,EAAE,MAAM,GAAG,uBAAuB,CAAC;CACjD;AAED,MAAM,WAAW,4BAA4B;IAC3C,CAAC,GAAG,EAAE,MAAM,GAAG,uBAAuB,CAAC;CACxC;AAyBD;;;;;;GAMG;AACH,wBAAgB,2BAA2B,CAAC,CAAC,SAAS,MAAM,EAC1D,UAAU,CAAC,EAAE,CAAC,GACb,4BAA4B,CAkB9B;AAED,+DAA+D;AAC/D,wBAAgB,4BAA4B,CAAC,CAAC,SAAS,MAAM,EAC3D,SAAS,EAAE,MAAM,EACjB,UAAU,CAAC,EAAE,CAAC,GACb,4BAA4B,CAI9B;AAED,8EAA8E;AAC9E,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,OAAO,GAAG,4BAA4B,CAMrF;AAED,6DAA6D;AAC7D,MAAM,WAAW,eAAe;IAC9B,GAAG,CAAC,CAAC,EACH,SAAS,EAAE,MAAM,EACjB,UAAU,EAAE,mBAAmB,GAAG,SAAS,EAC3C,QAAQ,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GACzB,OAAO,CAAC,CAAC,CAAC,CAAC;CACf;AAED,iEAAiE;AACjE,qBAAa,mBAAoB,YAAW,eAAe;IACnD,GAAG,CAAC,CAAC,EACT,UAAU,EAAE,MAAM,EAClB,WAAW,EAAE,mBAAmB,GAAG,SAAS,EAC5C,QAAQ,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GACzB,OAAO,CAAC,CAAC,CAAC;CAGd;AAED,eAAO,MAAM,oBAAoB,EAAE,eAA0D,CAAC;AAc9F,wEAAwE;AACxE,wBAAgB,yBAAyB,IAAI,eAAe,CAE3D;AAED;;;;;;GAMG;AACH,wBAAgB,yBAAyB,CAAC,eAAe,EAAE,eAAe,GAAG,IAAI,GAAG,MAAM,IAAI,CAa7F"}
@@ -0,0 +1,118 @@
1
+ /** Package-scoped telemetry constants shared by every instrumentation adapter. */
2
+ import { z } from "zod";
3
+ import { diagnosticErrorCode, diagnosticErrorType } from "../shared/diagnostics.js";
4
+ export const BURSAR_INSTRUMENTATION_SCOPE = "@zonastery/bursar";
5
+ export const BURSAR_INSTRUMENTATION_VERSION = "2.0.4";
6
+ const ALLOWED_ATTRIBUTE_KEYS = new Set([
7
+ "bursar.operation",
8
+ "bursar.outcome",
9
+ "bursar.backend",
10
+ "bursar.provider",
11
+ "error.type",
12
+ "error.code",
13
+ ]);
14
+ const MAX_ATTRIBUTE_LENGTH = 64;
15
+ function normalizeToken(value, fallback) {
16
+ const parsed = z.string().safeParse(value);
17
+ if (!parsed.success)
18
+ return fallback;
19
+ const normalized = parsed.data
20
+ .trim()
21
+ .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
22
+ .replace(/[^a-zA-Z0-9._-]+/g, "_")
23
+ .replace(/^[_\-.]+|[_\-.]+$/g, "")
24
+ .toLowerCase()
25
+ .slice(0, MAX_ATTRIBUTE_LENGTH);
26
+ return normalized || fallback;
27
+ }
28
+ /**
29
+ * Keep telemetry attributes bounded and low-cardinality.
30
+ *
31
+ * Unknown keys and non-scalar values are discarded. String values are
32
+ * normalized to stable tokens so identifiers, metadata, and raw payloads
33
+ * cannot accidentally pass through this boundary.
34
+ */
35
+ export function sanitizeTelemetryAttributes(attributes) {
36
+ const sanitized = {};
37
+ for (const [key, value] of Object.entries(attributes ?? {})) {
38
+ if (!ALLOWED_ATTRIBUTE_KEYS.has(key))
39
+ continue;
40
+ const booleanValue = z.boolean().safeParse(value);
41
+ if (booleanValue.success) {
42
+ sanitized[key] = booleanValue.data;
43
+ continue;
44
+ }
45
+ const numberValue = z.number().finite().safeParse(value);
46
+ if (numberValue.success) {
47
+ sanitized[key] = numberValue.data;
48
+ continue;
49
+ }
50
+ const normalized = normalizeToken(value);
51
+ if (normalized !== undefined)
52
+ sanitized[key] = normalized;
53
+ }
54
+ return sanitized;
55
+ }
56
+ /** Build the safe base attributes for one Bursar operation. */
57
+ export function telemetryOperationAttributes(operation, attributes) {
58
+ const result = sanitizeTelemetryAttributes(attributes);
59
+ result["bursar.operation"] = normalizeToken(operation, "unknown") ?? "unknown";
60
+ return result;
61
+ }
62
+ /** Normalize an error without reading or recording its message or details. */
63
+ export function telemetryErrorAttributes(cause) {
64
+ const type = normalizeToken(diagnosticErrorType(cause), "unknown_error") ?? "unknown_error";
65
+ const code = normalizeToken(diagnosticErrorCode(cause));
66
+ const result = { "error.type": type };
67
+ if (code !== undefined)
68
+ result["error.code"] = code;
69
+ return result;
70
+ }
71
+ /** Default implementation: execute normally and emit nothing. */
72
+ export class NoopInstrumentation {
73
+ async run(_operation, _attributes, callback) {
74
+ return callback();
75
+ }
76
+ }
77
+ export const NOOP_INSTRUMENTATION = Object.freeze(new NoopInstrumentation());
78
+ let defaultInstrumentation = NOOP_INSTRUMENTATION;
79
+ const instrumentationRegistrations = [];
80
+ function assertInstrumentation(value) {
81
+ if (!z.object({ run: z.function() }).safeParse(value).success) {
82
+ throw new TypeError("instrumentation must provide run()");
83
+ }
84
+ }
85
+ /** Return the instrumentation selected by the embedding application. */
86
+ export function getDefaultInstrumentation() {
87
+ return defaultInstrumentation;
88
+ }
89
+ /**
90
+ * Select a process-wide Bursar instrumentation implementation.
91
+ *
92
+ * This does not configure an OpenTelemetry provider or exporter. Call the
93
+ * returned function to restore the previous implementation. A stale restore
94
+ * cannot overwrite a newer registration.
95
+ */
96
+ export function setDefaultInstrumentation(instrumentation) {
97
+ const selected = instrumentation ?? NOOP_INSTRUMENTATION;
98
+ assertInstrumentation(selected);
99
+ const registration = { instrumentation: selected, active: true };
100
+ instrumentationRegistrations.push(registration);
101
+ refreshDefaultInstrumentation();
102
+ let restored = false;
103
+ return () => {
104
+ if (restored)
105
+ return;
106
+ restored = true;
107
+ registration.active = false;
108
+ refreshDefaultInstrumentation();
109
+ };
110
+ }
111
+ function refreshDefaultInstrumentation() {
112
+ while (instrumentationRegistrations.at(-1)?.active === false) {
113
+ instrumentationRegistrations.pop();
114
+ }
115
+ defaultInstrumentation =
116
+ instrumentationRegistrations.at(-1)?.instrumentation ?? NOOP_INSTRUMENTATION;
117
+ }
118
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/telemetry/index.ts"],"names":[],"mappings":"AAAA,kFAAkF;AAClF,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAEpF,MAAM,CAAC,MAAM,4BAA4B,GAAG,mBAAmB,CAAC;AAChE,MAAM,CAAC,MAAM,8BAA8B,GAAG,OAAO,CAAC;AAWtD,MAAM,sBAAsB,GAAG,IAAI,GAAG,CAAC;IACrC,kBAAkB;IAClB,gBAAgB;IAChB,gBAAgB;IAChB,iBAAiB;IACjB,YAAY;IACZ,YAAY;CACb,CAAC,CAAC;AACH,MAAM,oBAAoB,GAAG,EAAE,CAAC;AAEhC,SAAS,cAAc,CAAI,KAAQ,EAAE,QAAiB;IACpD,MAAM,MAAM,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;IAC3C,IAAI,CAAC,MAAM,CAAC,OAAO;QAAE,OAAO,QAAQ,CAAC;IACrC,MAAM,UAAU,GAAG,MAAM,CAAC,IAAI;SAC3B,IAAI,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AAChC,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,yBAAyB,CAAC,eAAuC;IAC/E,MAAM,QAAQ,GAAG,eAAe,IAAI,oBAAoB,CAAC;IACzD,qBAAqB,CAAC,QAAQ,CAAC,CAAC;IAChC,MAAM,YAAY,GAAG,EAAE,eAAe,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;IACjE,4BAA4B,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;IAChD,6BAA6B,EAAE,CAAC;IAChC,IAAI,QAAQ,GAAG,KAAK,CAAC;IACrB,OAAO,GAAG,EAAE;QACV,IAAI,QAAQ;YAAE,OAAO;QACrB,QAAQ,GAAG,IAAI,CAAC;QAChB,YAAY,CAAC,MAAM,GAAG,KAAK,CAAC;QAC5B,6BAA6B,EAAE,CAAC;IAClC,CAAC,CAAC;AACJ,CAAC;AAED,SAAS,6BAA6B;IACpC,OAAO,4BAA4B,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,MAAM,KAAK,KAAK,EAAE,CAAC;QAC7D,4BAA4B,CAAC,GAAG,EAAE,CAAC;IACrC,CAAC;IACD,sBAAsB;QACpB,4BAA4B,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,eAAe,IAAI,oBAAoB,CAAC;AACjF,CAAC","sourcesContent":["/** Package-scoped telemetry constants shared by every instrumentation adapter. */\nimport { z } from \"zod\";\n\nimport { diagnosticErrorCode, diagnosticErrorType } from \"../shared/diagnostics.js\";\n\nexport const BURSAR_INSTRUMENTATION_SCOPE = \"@zonastery/bursar\";\nexport const BURSAR_INSTRUMENTATION_VERSION = \"2.0.4\";\n\nexport type TelemetryAttributeValue = string | number | boolean;\nexport interface TelemetryAttributes {\n readonly [key: string]: TelemetryAttributeValue;\n}\n\nexport interface SanitizedTelemetryAttributes {\n [key: string]: TelemetryAttributeValue;\n}\n\nconst ALLOWED_ATTRIBUTE_KEYS = new Set([\n \"bursar.operation\",\n \"bursar.outcome\",\n \"bursar.backend\",\n \"bursar.provider\",\n \"error.type\",\n \"error.code\",\n]);\nconst MAX_ATTRIBUTE_LENGTH = 64;\n\nfunction normalizeToken<T>(value: T, fallback?: string): string | undefined {\n const parsed = z.string().safeParse(value);\n if (!parsed.success) return fallback;\n const normalized = parsed.data\n .trim()\n .replace(/([a-z0-9])([A-Z])/g, \"$1_$2\")\n .replace(/[^a-zA-Z0-9._-]+/g, \"_\")\n .replace(/^[_\\-.]+|[_\\-.]+$/g, \"\")\n .toLowerCase()\n .slice(0, MAX_ATTRIBUTE_LENGTH);\n return normalized || fallback;\n}\n\n/**\n * Keep telemetry attributes bounded and low-cardinality.\n *\n * Unknown keys and non-scalar values are discarded. String values are\n * normalized to stable tokens so identifiers, metadata, and raw payloads\n * cannot accidentally pass through this boundary.\n */\nexport function sanitizeTelemetryAttributes<T extends object>(\n attributes?: T,\n): SanitizedTelemetryAttributes {\n const sanitized: SanitizedTelemetryAttributes = {};\n for (const [key, value] of Object.entries(attributes ?? {})) {\n if (!ALLOWED_ATTRIBUTE_KEYS.has(key)) continue;\n const booleanValue = z.boolean().safeParse(value);\n if (booleanValue.success) {\n sanitized[key] = booleanValue.data;\n continue;\n }\n const numberValue = z.number().finite().safeParse(value);\n if (numberValue.success) {\n sanitized[key] = numberValue.data;\n continue;\n }\n const normalized = normalizeToken(value);\n if (normalized !== undefined) sanitized[key] = normalized;\n }\n return sanitized;\n}\n\n/** Build the safe base attributes for one Bursar operation. */\nexport function telemetryOperationAttributes<T extends object>(\n operation: string,\n attributes?: T,\n): SanitizedTelemetryAttributes {\n const result: SanitizedTelemetryAttributes = sanitizeTelemetryAttributes(attributes);\n result[\"bursar.operation\"] = normalizeToken(operation, \"unknown\") ?? \"unknown\";\n return result;\n}\n\n/** Normalize an error without reading or recording its message or details. */\nexport function telemetryErrorAttributes(cause: unknown): SanitizedTelemetryAttributes {\n const type = normalizeToken(diagnosticErrorType(cause), \"unknown_error\") ?? \"unknown_error\";\n const code = normalizeToken(diagnosticErrorCode(cause));\n const result: SanitizedTelemetryAttributes = { \"error.type\": type };\n if (code !== undefined) result[\"error.code\"] = code;\n return result;\n}\n\n/** Vendor-neutral contract used by Bursar's core runtime. */\nexport interface Instrumentation {\n run<T>(\n operation: string,\n attributes: TelemetryAttributes | undefined,\n callback: () => Promise<T>,\n ): Promise<T>;\n}\n\n/** Default implementation: execute normally and emit nothing. */\nexport class NoopInstrumentation implements Instrumentation {\n async run<T>(\n _operation: string,\n _attributes: TelemetryAttributes | undefined,\n callback: () => Promise<T>,\n ): Promise<T> {\n return callback();\n }\n}\n\nexport const NOOP_INSTRUMENTATION: Instrumentation = Object.freeze(new NoopInstrumentation());\n\nlet defaultInstrumentation: Instrumentation = NOOP_INSTRUMENTATION;\nconst instrumentationRegistrations: Array<{\n instrumentation: Instrumentation;\n active: boolean;\n}> = [];\n\nfunction assertInstrumentation(value: Instrumentation): void {\n if (!z.object({ run: z.function() }).safeParse(value).success) {\n throw new TypeError(\"instrumentation must provide run()\");\n }\n}\n\n/** Return the instrumentation selected by the embedding application. */\nexport function getDefaultInstrumentation(): Instrumentation {\n return defaultInstrumentation;\n}\n\n/**\n * Select a process-wide Bursar instrumentation implementation.\n *\n * This does not configure an OpenTelemetry provider or exporter. Call the\n * returned function to restore the previous implementation. A stale restore\n * cannot overwrite a newer registration.\n */\nexport function setDefaultInstrumentation(instrumentation: Instrumentation | null): () => void {\n const selected = instrumentation ?? NOOP_INSTRUMENTATION;\n assertInstrumentation(selected);\n const registration = { instrumentation: selected, active: true };\n instrumentationRegistrations.push(registration);\n refreshDefaultInstrumentation();\n let restored = false;\n return () => {\n if (restored) return;\n restored = true;\n registration.active = false;\n refreshDefaultInstrumentation();\n };\n}\n\nfunction refreshDefaultInstrumentation(): void {\n while (instrumentationRegistrations.at(-1)?.active === false) {\n instrumentationRegistrations.pop();\n }\n defaultInstrumentation =\n instrumentationRegistrations.at(-1)?.instrumentation ?? NOOP_INSTRUMENTATION;\n}\n"]}
@@ -0,0 +1,25 @@
1
+ import { type Meter, type Tracer } from "@opentelemetry/api";
2
+ import { type Instrumentation, type TelemetryAttributes } from "./index.js";
3
+ export interface OpenTelemetryInstrumentationOptions {
4
+ /** Override the API tracer, primarily for host-level composition or tests. */
5
+ tracer?: Tracer;
6
+ /** Override the API meter, primarily for host-level composition or tests. */
7
+ meter?: Meter;
8
+ }
9
+ /** OpenTelemetry API-only adapter. It never creates an SDK or exporter. */
10
+ export declare class OpenTelemetryInstrumentation implements Instrumentation {
11
+ private readonly tracer;
12
+ private readonly operationCounter;
13
+ private readonly operationDuration;
14
+ constructor(options?: OpenTelemetryInstrumentationOptions);
15
+ run<T>(operation: string, attributes: TelemetryAttributes | undefined, callback: () => Promise<T>): Promise<T>;
16
+ private runInSpan;
17
+ private recordMetrics;
18
+ }
19
+ export declare function createOpenTelemetryInstrumentation(options?: OpenTelemetryInstrumentationOptions): Instrumentation;
20
+ /**
21
+ * Enable the API-only adapter for subsequently constructed Bursar services.
22
+ * The embedding application remains responsible for the OTel SDK and export.
23
+ */
24
+ export declare function enableOpenTelemetry(options?: OpenTelemetryInstrumentationOptions): () => void;
25
+ //# sourceMappingURL=opentelemetry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"opentelemetry.d.ts","sourceRoot":"","sources":["../../src/telemetry/opentelemetry.ts"],"names":[],"mappings":"AAAA,OAAO,EAOL,KAAK,KAAK,EAEV,KAAK,MAAM,EACZ,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAML,KAAK,eAAe,EACpB,KAAK,mBAAmB,EAEzB,MAAM,YAAY,CAAC;AAEpB,MAAM,WAAW,mCAAmC;IAClD,8EAA8E;IAC9E,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,6EAA6E;IAC7E,KAAK,CAAC,EAAE,KAAK,CAAC;CACf;AAMD,2EAA2E;AAC3E,qBAAa,4BAA6B,YAAW,eAAe;IAClE,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;IAChC,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAU;IAC3C,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAY;gBAElC,OAAO,GAAE,mCAAwC;IAiB7D,GAAG,CAAC,CAAC,EACH,SAAS,EAAE,MAAM,EACjB,UAAU,EAAE,mBAAmB,GAAG,SAAS,EAC3C,QAAQ,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GACzB,OAAO,CAAC,CAAC,CAAC;YAUC,SAAS;IA8BvB,OAAO,CAAC,aAAa;CAWtB;AAED,wBAAgB,kCAAkC,CAChD,OAAO,GAAE,mCAAwC,GAChD,eAAe,CAEjB;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,GAAE,mCAAwC,GAAG,MAAM,IAAI,CAEjG"}
@@ -0,0 +1,74 @@
1
+ import { metrics, SpanStatusCode, trace, } from "@opentelemetry/api";
2
+ import { BURSAR_INSTRUMENTATION_SCOPE, BURSAR_INSTRUMENTATION_VERSION, setDefaultInstrumentation, telemetryErrorAttributes, telemetryOperationAttributes, } from "./index.js";
3
+ function otelAttributes(attributes) {
4
+ return attributes;
5
+ }
6
+ /** OpenTelemetry API-only adapter. It never creates an SDK or exporter. */
7
+ export class OpenTelemetryInstrumentation {
8
+ tracer;
9
+ operationCounter;
10
+ operationDuration;
11
+ constructor(options = {}) {
12
+ this.tracer =
13
+ options.tracer ??
14
+ trace.getTracer(BURSAR_INSTRUMENTATION_SCOPE, BURSAR_INSTRUMENTATION_VERSION);
15
+ const meter = options.meter ??
16
+ metrics.getMeter(BURSAR_INSTRUMENTATION_SCOPE, BURSAR_INSTRUMENTATION_VERSION);
17
+ this.operationCounter = meter.createCounter("bursar.operation.count", {
18
+ description: "Completed Bursar operations",
19
+ unit: "{operation}",
20
+ });
21
+ this.operationDuration = meter.createHistogram("bursar.operation.duration", {
22
+ description: "Bursar operation duration",
23
+ unit: "s",
24
+ });
25
+ }
26
+ run(operation, attributes, callback) {
27
+ const baseAttributes = telemetryOperationAttributes(operation, attributes);
28
+ const spanName = `bursar.${baseAttributes["bursar.operation"]}`;
29
+ return this.tracer.startActiveSpan(spanName, { attributes: otelAttributes(baseAttributes) }, async (span) => this.runInSpan(span, baseAttributes, callback));
30
+ }
31
+ async runInSpan(span, baseAttributes, callback) {
32
+ const startedAt = performance.now();
33
+ try {
34
+ const result = await callback();
35
+ const completed = { ...baseAttributes, "bursar.outcome": "success" };
36
+ span.setAttributes(otelAttributes(completed));
37
+ span.setStatus({ code: SpanStatusCode.OK });
38
+ this.recordMetrics(startedAt, completed);
39
+ return result;
40
+ }
41
+ catch (cause) {
42
+ const completed = {
43
+ ...baseAttributes,
44
+ "bursar.outcome": "error",
45
+ ...telemetryErrorAttributes(cause),
46
+ };
47
+ span.setAttributes(otelAttributes(completed));
48
+ // Deliberately omit a description and exception event: both may include
49
+ // the raw error message, SQL text, identifiers, or provider payloads.
50
+ span.setStatus({ code: SpanStatusCode.ERROR });
51
+ this.recordMetrics(startedAt, completed);
52
+ throw cause;
53
+ }
54
+ finally {
55
+ span.end();
56
+ }
57
+ }
58
+ recordMetrics(startedAt, attributes) {
59
+ const safeAttributes = otelAttributes(attributes);
60
+ this.operationCounter.add(1, safeAttributes);
61
+ this.operationDuration.record(Math.max(0, performance.now() - startedAt) / 1_000, safeAttributes);
62
+ }
63
+ }
64
+ export function createOpenTelemetryInstrumentation(options = {}) {
65
+ return new OpenTelemetryInstrumentation(options);
66
+ }
67
+ /**
68
+ * Enable the API-only adapter for subsequently constructed Bursar services.
69
+ * The embedding application remains responsible for the OTel SDK and export.
70
+ */
71
+ export function enableOpenTelemetry(options = {}) {
72
+ return setDefaultInstrumentation(createOpenTelemetryInstrumentation(options));
73
+ }
74
+ //# sourceMappingURL=opentelemetry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"opentelemetry.js","sourceRoot":"","sources":["../../src/telemetry/opentelemetry.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,OAAO,EACP,cAAc,EACd,KAAK,GAON,MAAM,oBAAoB,CA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,CAC3B,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,WAAW,CAAC,GAAG,EAAE,GAAG,SAAS,CAAC,GAAG,KAAK,EAClD,cAAc,CACf,CAAC;IACJ,CAAC;CACF;AAED,MAAM,UAAU,kCAAkC,CAChD,UAA+C,EAAE;IAEjD,OAAO,IAAI,4BAA4B,CAAC,OAAO,CAAC,CAAC;AACnD,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,mBAAmB,CAAC,UAA+C,EAAE;IACnF,OAAO,yBAAyB,CAAC,kCAAkC,CAAC,OAAO,CAAC,CAAC,CAAC;AAChF,CAAC","sourcesContent":["import {\n metrics,\n SpanStatusCode,\n trace,\n type Attributes,\n type Counter,\n type Histogram,\n type Meter,\n type Span,\n type Tracer,\n} from \"@opentelemetry/api\";\n\nimport {\n BURSAR_INSTRUMENTATION_SCOPE,\n BURSAR_INSTRUMENTATION_VERSION,\n setDefaultInstrumentation,\n telemetryErrorAttributes,\n telemetryOperationAttributes,\n type Instrumentation,\n type TelemetryAttributes,\n type TelemetryAttributeValue,\n} from \"./index.js\";\n\nexport interface OpenTelemetryInstrumentationOptions {\n /** Override the API tracer, primarily for host-level composition or tests. */\n tracer?: Tracer;\n /** Override the API meter, primarily for host-level composition or tests. */\n meter?: Meter;\n}\n\nfunction otelAttributes(attributes: Readonly<Record<string, TelemetryAttributeValue>>): Attributes {\n return attributes;\n}\n\n/** OpenTelemetry API-only adapter. It never creates an SDK or exporter. */\nexport class OpenTelemetryInstrumentation implements Instrumentation {\n private readonly tracer: Tracer;\n private readonly operationCounter: Counter;\n private readonly operationDuration: Histogram;\n\n constructor(options: OpenTelemetryInstrumentationOptions = {}) {\n this.tracer =\n options.tracer ??\n trace.getTracer(BURSAR_INSTRUMENTATION_SCOPE, BURSAR_INSTRUMENTATION_VERSION);\n const meter =\n options.meter ??\n metrics.getMeter(BURSAR_INSTRUMENTATION_SCOPE, BURSAR_INSTRUMENTATION_VERSION);\n this.operationCounter = meter.createCounter(\"bursar.operation.count\", {\n description: \"Completed Bursar operations\",\n unit: \"{operation}\",\n });\n this.operationDuration = meter.createHistogram(\"bursar.operation.duration\", {\n description: \"Bursar operation duration\",\n unit: \"s\",\n });\n }\n\n run<T>(\n operation: string,\n attributes: TelemetryAttributes | undefined,\n callback: () => Promise<T>,\n ): Promise<T> {\n const baseAttributes = telemetryOperationAttributes(operation, attributes);\n const spanName = `bursar.${baseAttributes[\"bursar.operation\"]}`;\n return this.tracer.startActiveSpan(\n spanName,\n { attributes: otelAttributes(baseAttributes) },\n async (span) => this.runInSpan(span, baseAttributes, callback),\n );\n }\n\n private async runInSpan<T>(\n span: Span,\n baseAttributes: Record<string, TelemetryAttributeValue>,\n callback: () => Promise<T>,\n ): Promise<T> {\n const startedAt = performance.now();\n try {\n const result = await callback();\n const completed = { ...baseAttributes, \"bursar.outcome\": \"success\" };\n span.setAttributes(otelAttributes(completed));\n span.setStatus({ code: SpanStatusCode.OK });\n this.recordMetrics(startedAt, completed);\n return result;\n } catch (cause) {\n const completed = {\n ...baseAttributes,\n \"bursar.outcome\": \"error\",\n ...telemetryErrorAttributes(cause),\n };\n span.setAttributes(otelAttributes(completed));\n // Deliberately omit a description and exception event: both may include\n // the raw error message, SQL text, identifiers, or provider payloads.\n span.setStatus({ code: SpanStatusCode.ERROR });\n this.recordMetrics(startedAt, completed);\n throw cause;\n } finally {\n span.end();\n }\n }\n\n private recordMetrics(\n startedAt: number,\n attributes: Record<string, TelemetryAttributeValue>,\n ): void {\n const safeAttributes = otelAttributes(attributes);\n this.operationCounter.add(1, safeAttributes);\n this.operationDuration.record(\n Math.max(0, performance.now() - startedAt) / 1_000,\n safeAttributes,\n );\n }\n}\n\nexport function createOpenTelemetryInstrumentation(\n options: OpenTelemetryInstrumentationOptions = {},\n): Instrumentation {\n return new OpenTelemetryInstrumentation(options);\n}\n\n/**\n * Enable the API-only adapter for subsequently constructed Bursar services.\n * The embedding application remains responsible for the OTel SDK and export.\n */\nexport function enableOpenTelemetry(options: OpenTelemetryInstrumentationOptions = {}): () => void {\n return setDefaultInstrumentation(createOpenTelemetryInstrumentation(options));\n}\n"]}