@burdenoff/be-sdk 2026.1110.2 → 2026.1110.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 (497) hide show
  1. package/configs/eslint/index.js +1 -1
  2. package/configs/tsconfig/tsconfig.json +1 -1
  3. package/dist/EventQueueFactory-9NGZV9jl.js +1457 -0
  4. package/dist/EventQueueFactory-9NGZV9jl.js.map +1 -0
  5. package/dist/RedisStreamsConnection-CY8WySJy.js +283 -0
  6. package/dist/RedisStreamsConnection-CY8WySJy.js.map +1 -0
  7. package/dist/activity/index.d.ts +165 -0
  8. package/dist/activity/index.js +389 -0
  9. package/dist/activity/index.js.map +1 -0
  10. package/dist/ai-credits/index.d.ts +2 -3
  11. package/dist/ai-credits/index.js +3 -4
  12. package/dist/ai-credits/index.js.map +1 -1
  13. package/dist/ai-credits-xxfwGpHS.js +546 -0
  14. package/dist/ai-credits-xxfwGpHS.js.map +1 -0
  15. package/dist/{assistant-session-CJZhF4D6.d.ts → assistant-session-DA5ZKJOr.d.ts} +4 -5
  16. package/dist/auth/index.d.ts +2 -77
  17. package/dist/auth/index.js +3 -7
  18. package/dist/auth/index.js.map +1 -1
  19. package/dist/auth-C5ctwSLp.js +228 -0
  20. package/dist/auth-C5ctwSLp.js.map +1 -0
  21. package/dist/bootstrap/index.d.ts +74 -0
  22. package/dist/bootstrap/index.js +282 -0
  23. package/dist/bootstrap/index.js.map +1 -0
  24. package/dist/cache/index.d.ts +2 -3
  25. package/dist/cache/index.js +3 -7
  26. package/dist/cache/index.js.map +1 -1
  27. package/dist/cache-CU0uLwcS.js +1837 -0
  28. package/dist/cache-CU0uLwcS.js.map +1 -0
  29. package/dist/captcha/index.d.ts +2 -1
  30. package/dist/captcha/index.js +3 -3
  31. package/dist/captcha/index.js.map +1 -1
  32. package/dist/captcha-BT7yh1YS.js +77 -0
  33. package/dist/captcha-BT7yh1YS.js.map +1 -0
  34. package/dist/client/internal-client.d.ts +4 -7
  35. package/dist/client/internal-client.js +172 -4
  36. package/dist/client/internal-client.js.map +1 -1
  37. package/dist/client-BgAEvDC2.d.ts +86 -0
  38. package/dist/client-sAJTrb4i.js +565 -0
  39. package/dist/client-sAJTrb4i.js.map +1 -0
  40. package/dist/collector-endpoint-iyQYeI50.js +50 -0
  41. package/dist/collector-endpoint-iyQYeI50.js.map +1 -0
  42. package/dist/context/index.d.ts +35 -0
  43. package/dist/context/index.js +283 -0
  44. package/dist/context/index.js.map +1 -0
  45. package/dist/crypto/index.d.ts +2 -1
  46. package/dist/crypto/index.js +3 -3
  47. package/dist/crypto/index.js.map +1 -1
  48. package/dist/crypto-DO9fM0FO.js +145 -0
  49. package/dist/crypto-DO9fM0FO.js.map +1 -0
  50. package/dist/database/index.d.ts +104 -108
  51. package/dist/database/index.js +468 -6
  52. package/dist/database/index.js.map +1 -1
  53. package/dist/dataloader/index.d.ts +2 -1
  54. package/dist/dataloader/index.js +3 -3
  55. package/dist/dataloader/index.js.map +1 -1
  56. package/dist/dataloader-DwpT3YoS.js +294 -0
  57. package/dist/dataloader-DwpT3YoS.js.map +1 -0
  58. package/dist/deployed-environment-p_Tdl3sT.js +38 -0
  59. package/dist/deployed-environment-p_Tdl3sT.js.map +1 -0
  60. package/dist/dist-BGKdXVy3.js +1718 -0
  61. package/dist/dist-BGKdXVy3.js.map +1 -0
  62. package/dist/env-DdaoGjIt.js +74 -0
  63. package/dist/env-DdaoGjIt.js.map +1 -0
  64. package/dist/event-queue/index.d.ts +2 -7
  65. package/dist/event-queue/index.js +7 -9
  66. package/dist/event-queue/index.js.map +1 -1
  67. package/dist/event-queue-Cw-YJPY_.js +1384 -0
  68. package/dist/event-queue-Cw-YJPY_.js.map +1 -0
  69. package/dist/{explicit-activity-scope-CCoxVwAr.d.ts → explicit-activity-scope-D8VeGGpt.d.ts} +1 -2
  70. package/dist/explicit-activity-scope-DikJ7NAE.js +57 -0
  71. package/dist/explicit-activity-scope-DikJ7NAE.js.map +1 -0
  72. package/dist/export/index.d.ts +2 -2
  73. package/dist/export/index.js +3 -14
  74. package/dist/export/index.js.map +1 -1
  75. package/dist/export-DJXE3Osa.js +642 -0
  76. package/dist/export-DJXE3Osa.js.map +1 -0
  77. package/dist/feature-flags/index.d.ts +2 -10
  78. package/dist/feature-flags/index.js +3 -6
  79. package/dist/feature-flags/index.js.map +1 -1
  80. package/dist/feature-flags-CP1KRgwD.js +422 -0
  81. package/dist/feature-flags-CP1KRgwD.js.map +1 -0
  82. package/dist/files/index.d.ts +2 -3
  83. package/dist/files/index.js +3 -4
  84. package/dist/files/index.js.map +1 -1
  85. package/dist/files-h5U-D2AF.js +830 -0
  86. package/dist/files-h5U-D2AF.js.map +1 -0
  87. package/dist/gateway/index.d.ts +4 -6
  88. package/dist/gateway/index.js +7 -13
  89. package/dist/gateway/index.js.map +1 -1
  90. package/dist/gateway/security/index.d.ts +2 -2
  91. package/dist/gateway/security/index.js +3 -5
  92. package/dist/gateway/security/index.js.map +1 -1
  93. package/dist/gateway-ByVo-n37.js +50 -0
  94. package/dist/gateway-ByVo-n37.js.map +1 -0
  95. package/dist/graph/index.d.ts +3 -10
  96. package/dist/graph/index.js +4 -13
  97. package/dist/graph/index.js.map +1 -1
  98. package/dist/graph-CR7u4lpl.js +2152 -0
  99. package/dist/graph-CR7u4lpl.js.map +1 -0
  100. package/dist/graph-emitter-CdOXP7Tn.js +621 -0
  101. package/dist/graph-emitter-CdOXP7Tn.js.map +1 -0
  102. package/dist/graphql/index.d.ts +3 -2
  103. package/dist/graphql/index.js +4 -6
  104. package/dist/graphql/index.js.map +1 -1
  105. package/dist/graphql/services/index.d.ts +2 -24
  106. package/dist/graphql/services/index.js +3 -4
  107. package/dist/graphql/services/index.js.map +1 -1
  108. package/dist/graphql-CUDyhibV.d.ts +21 -0
  109. package/dist/graphql-DHAHHcww.js +161 -0
  110. package/dist/graphql-DHAHHcww.js.map +1 -0
  111. package/dist/i18n/index.d.ts +3 -3
  112. package/dist/i18n/index.js +3 -4
  113. package/dist/i18n/index.js.map +1 -1
  114. package/dist/i18n-BBMYFd0P.js +860 -0
  115. package/dist/i18n-BBMYFd0P.js.map +1 -0
  116. package/dist/import-optional-peer-B82VYxeX.js +18 -0
  117. package/dist/import-optional-peer-B82VYxeX.js.map +1 -0
  118. package/dist/index-3KOZ1zN9.d.ts +233 -0
  119. package/dist/index-ADmsX0BI.d.ts +646 -0
  120. package/dist/index-B2LCaK0R.d.ts +500 -0
  121. package/dist/index-BBqooJ52.d.ts +45 -0
  122. package/dist/index-BGzMYJsm.d.ts +209 -0
  123. package/dist/index-BMIMnp6T.d.ts +8 -0
  124. package/dist/index-BVOL7458.d.ts +10 -0
  125. package/dist/index-BcqQs-Uq.d.ts +69 -0
  126. package/dist/index-BeVtqGO-.d.ts +208 -0
  127. package/dist/index-BiTzGUZP.d.ts +114 -0
  128. package/dist/index-C0qLquY0.d.ts +150 -0
  129. package/dist/index-C5uEKchX.d.ts +60 -0
  130. package/dist/index-CDOqxSIi.d.ts +37 -0
  131. package/dist/index-CG6wj66Y.d.ts +148 -0
  132. package/dist/index-CHwMhK6v.d.ts +63 -0
  133. package/dist/index-CIgoeobA.d.ts +145 -0
  134. package/dist/index-CPQDMSFS.d.ts +103 -0
  135. package/dist/index-CSRcgkVi.d.ts +23 -0
  136. package/dist/index-CTTwo9av.d.ts +102 -0
  137. package/dist/index-CVCyKzhB.d.ts +207 -0
  138. package/dist/index-C_GXXF32.d.ts +704 -0
  139. package/dist/index-CaM9JUcc.d.ts +144 -0
  140. package/dist/index-CliOgq6L.d.ts +203 -0
  141. package/dist/index-Cot73bdh.d.ts +63 -0
  142. package/dist/index-DGgh9DWn.d.ts +59 -0
  143. package/dist/index-DY3dNhMN.d.ts +420 -0
  144. package/dist/index-DqbGqfAy.d.ts +127 -0
  145. package/dist/index-Dt1HJPTX.d.ts +12 -0
  146. package/dist/index-DtI6aBtB.d.ts +22 -0
  147. package/dist/index-FKohsiex.d.ts +38 -0
  148. package/dist/index-FRRaa6h2.d.ts +999 -0
  149. package/dist/index-FbXPfen7.d.ts +132 -0
  150. package/dist/index-MArCb8Aq.d.ts +306 -0
  151. package/dist/index-U_tu3zUl.d.ts +303 -0
  152. package/dist/index-YOShAwkq.d.ts +45 -0
  153. package/dist/index-cmR9k9ga.d.ts +26 -0
  154. package/dist/index-yBSjMY32.d.ts +24 -0
  155. package/dist/index-zd_NPGJo.d.ts +206 -0
  156. package/dist/index.d.ts +106 -609
  157. package/dist/index.js +769 -2590
  158. package/dist/index.js.map +1 -1
  159. package/dist/init/index.d.ts +2 -2
  160. package/dist/init/index.js +3 -16
  161. package/dist/init/index.js.map +1 -1
  162. package/dist/init-CQPFmOOe.js +325 -0
  163. package/dist/init-CQPFmOOe.js.map +1 -0
  164. package/dist/instrumentation/index.d.ts +3 -4
  165. package/dist/instrumentation/index.js +5 -5
  166. package/dist/instrumentation/index.js.map +1 -1
  167. package/dist/instrumentation-xkkmDgJ0.js +1678 -0
  168. package/dist/instrumentation-xkkmDgJ0.js.map +1 -0
  169. package/dist/lake/index.d.ts +50 -54
  170. package/dist/lake/index.js +169 -193
  171. package/dist/lake/index.js.map +1 -1
  172. package/dist/layer/index.d.ts +3 -2
  173. package/dist/layer/index.js +4 -5
  174. package/dist/layer/index.js.map +1 -1
  175. package/dist/layer-BZBZZWeV.d.ts +69 -0
  176. package/dist/layer-Bcix-WCl.js +105 -0
  177. package/dist/layer-Bcix-WCl.js.map +1 -0
  178. package/dist/layer-CEKy6cm8.js +252 -0
  179. package/dist/layer-CEKy6cm8.js.map +1 -0
  180. package/dist/lifecycle/index.d.ts +2 -1
  181. package/dist/lifecycle/index.js +3 -4
  182. package/dist/lifecycle/index.js.map +1 -1
  183. package/dist/lifecycle-DeoLSX0U.js +76 -0
  184. package/dist/lifecycle-DeoLSX0U.js.map +1 -0
  185. package/dist/logger/index.d.ts +2 -3
  186. package/dist/logger/index.js +3 -3
  187. package/dist/logger/index.js.map +1 -1
  188. package/dist/logger-B6rCpb7D.js +290 -0
  189. package/dist/logger-B6rCpb7D.js.map +1 -0
  190. package/dist/metrics/index.d.ts +13 -14
  191. package/dist/metrics/index.js +3 -4
  192. package/dist/metrics/index.js.map +1 -1
  193. package/dist/metrics-BrLwNUrb.js +52 -0
  194. package/dist/metrics-BrLwNUrb.js.map +1 -0
  195. package/dist/metrics-collector-C2eShrlW.js +922 -0
  196. package/dist/metrics-collector-C2eShrlW.js.map +1 -0
  197. package/dist/middleware/index.d.ts +3 -3
  198. package/dist/middleware/index.js +3 -4
  199. package/dist/middleware/index.js.map +1 -1
  200. package/dist/middleware-CUxJVUpD.js +1243 -0
  201. package/dist/middleware-CUxJVUpD.js.map +1 -0
  202. package/dist/middleware-Cq0zFMGp.js +253 -0
  203. package/dist/middleware-Cq0zFMGp.js.map +1 -0
  204. package/dist/notifications/index.d.ts +2 -5
  205. package/dist/notifications/index.js +3 -6
  206. package/dist/notifications/index.js.map +1 -1
  207. package/dist/notifications-DY_i37WN.js +869 -0
  208. package/dist/notifications-DY_i37WN.js.map +1 -0
  209. package/dist/observability/index.d.ts +2 -3
  210. package/dist/observability/index.js +3 -4
  211. package/dist/observability/index.js.map +1 -1
  212. package/dist/observability-DBDXipTU.js +272 -0
  213. package/dist/observability-DBDXipTU.js.map +1 -0
  214. package/dist/payments/index.d.ts +144 -0
  215. package/dist/payments/index.js +404 -0
  216. package/dist/payments/index.js.map +1 -0
  217. package/dist/platform/index.d.ts +2 -1
  218. package/dist/platform/index.js +3 -5
  219. package/dist/platform/index.js.map +1 -1
  220. package/dist/platform-DZwczW7v.js +1510 -0
  221. package/dist/platform-DZwczW7v.js.map +1 -0
  222. package/dist/prisma/generator/index.d.ts +1 -1
  223. package/dist/prisma/generator/index.js +97 -84
  224. package/dist/prisma/generator/index.js.map +1 -1
  225. package/dist/prisma/index.d.ts +4 -7
  226. package/dist/prisma/index.js +5 -12
  227. package/dist/prisma/index.js.map +1 -1
  228. package/dist/prisma-BzOOdt79.js +863 -0
  229. package/dist/prisma-BzOOdt79.js.map +1 -0
  230. package/dist/prisma-extension-Cfl09swM.d.ts +172 -0
  231. package/dist/product-alias/index.d.ts +2 -1
  232. package/dist/product-alias/index.js +3 -3
  233. package/dist/product-alias/index.js.map +1 -1
  234. package/dist/product-alias-BPqtskMq.js +273 -0
  235. package/dist/product-alias-BPqtskMq.js.map +1 -0
  236. package/dist/rate-limit-CBrK_U5H.js +142 -0
  237. package/dist/rate-limit-CBrK_U5H.js.map +1 -0
  238. package/dist/rbac/index.d.ts +2 -122
  239. package/dist/rbac/index.js +3 -6
  240. package/dist/rbac/index.js.map +1 -1
  241. package/dist/rbac-Dvz0YzEt.js +1486 -0
  242. package/dist/rbac-Dvz0YzEt.js.map +1 -0
  243. package/dist/resource-caps/index.d.ts +66 -72
  244. package/dist/resource-caps/index.js +430 -5
  245. package/dist/resource-caps/index.js.map +1 -1
  246. package/dist/rolldown-runtime-ad2WFvuA.js +17 -0
  247. package/dist/sdk-Dju9o-sq.js +124 -0
  248. package/dist/sdk-Dju9o-sq.js.map +1 -0
  249. package/dist/search/index.d.ts +112 -0
  250. package/dist/search/index.js +266 -0
  251. package/dist/search/index.js.map +1 -0
  252. package/dist/security/index.d.ts +2 -0
  253. package/dist/security/index.js +4 -0
  254. package/dist/security/index.js.map +1 -0
  255. package/dist/security/rate-limit/index.d.ts +2 -0
  256. package/dist/security/rate-limit/index.js +4 -0
  257. package/dist/security/rate-limit/index.js.map +1 -0
  258. package/dist/security-DIG-95Ic.js +1647 -0
  259. package/dist/security-DIG-95Ic.js.map +1 -0
  260. package/dist/server/index.d.ts +7 -164
  261. package/dist/server/index.js +2001 -1507
  262. package/dist/server/index.js.map +1 -1
  263. package/dist/service-jwt-Bu-WNA_-.js +80 -0
  264. package/dist/service-jwt-Bu-WNA_-.js.map +1 -0
  265. package/dist/services-BWzfz7vG.js +102 -0
  266. package/dist/services-BWzfz7vG.js.map +1 -0
  267. package/dist/sharding/index.d.ts +41 -44
  268. package/dist/sharding/index.js +156 -137
  269. package/dist/sharding/index.js.map +1 -1
  270. package/dist/sharing/index.d.ts +2 -1
  271. package/dist/sharing/index.js +3 -4
  272. package/dist/sharing/index.js.map +1 -1
  273. package/dist/sharing-CflDsSJ-.js +911 -0
  274. package/dist/sharing-CflDsSJ-.js.map +1 -0
  275. package/dist/stub-BUnfMiAS.js +577 -0
  276. package/dist/stub-BUnfMiAS.js.map +1 -0
  277. package/dist/tags/index.d.ts +2 -3
  278. package/dist/tags/index.js +3 -4
  279. package/dist/tags/index.js.map +1 -1
  280. package/dist/tags-CbijgoqR.js +868 -0
  281. package/dist/{chunk-PBZFAAOM.js.map → tags-CbijgoqR.js.map} +1 -1
  282. package/dist/telemetry/index.d.ts +64 -76
  283. package/dist/telemetry/index.js +369 -201
  284. package/dist/telemetry/index.js.map +1 -1
  285. package/dist/temporal/index.d.ts +2 -148
  286. package/dist/temporal/index.js +3 -5
  287. package/dist/temporal/index.js.map +1 -1
  288. package/dist/temporal-B534uYK8.js +706 -0
  289. package/dist/temporal-B534uYK8.js.map +1 -0
  290. package/dist/tracker/index.d.ts +5 -11
  291. package/dist/tracker/index.js +7 -20
  292. package/dist/tracker/index.js.map +1 -1
  293. package/dist/tracker-PQztSlhJ.js +458 -0
  294. package/dist/tracker-PQztSlhJ.js.map +1 -0
  295. package/dist/translation/index.d.ts +120 -0
  296. package/dist/translation/index.js +573 -0
  297. package/dist/translation/index.js.map +1 -0
  298. package/dist/types/index.d.ts +3 -0
  299. package/dist/types/index.js +90 -0
  300. package/dist/types/index.js.map +1 -0
  301. package/dist/types-BYMYND1L.js +44 -0
  302. package/dist/types-BYMYND1L.js.map +1 -0
  303. package/dist/types-C6EKaS3V.d.ts +106 -0
  304. package/dist/types-CWybW61E.d.ts +323 -0
  305. package/dist/types-C_yfu3XK.d.ts +34 -0
  306. package/dist/types-DgaQqvxo.d.ts +70 -0
  307. package/dist/usage/index.d.ts +2 -213
  308. package/dist/usage/index.js +3 -15
  309. package/dist/usage/index.js.map +1 -1
  310. package/dist/usage-BRqVP3CJ.js +682 -0
  311. package/dist/usage-BRqVP3CJ.js.map +1 -0
  312. package/dist/utils/index.d.ts +2 -1
  313. package/dist/utils/index.js +3 -3
  314. package/dist/utils/index.js.map +1 -1
  315. package/dist/utils-DL85Tnbn.js +500 -0
  316. package/dist/utils-DL85Tnbn.js.map +1 -0
  317. package/dist/validation/index.d.ts +2 -2
  318. package/dist/validation/index.js +3 -3
  319. package/dist/validation/index.js.map +1 -1
  320. package/dist/validation-CPUITdMk.js +762 -0
  321. package/dist/validation-CPUITdMk.js.map +1 -0
  322. package/dist/workspace-extension-COrC0dYi.js +979 -0
  323. package/dist/workspace-extension-COrC0dYi.js.map +1 -0
  324. package/dist/{workspace-extension-BGwTOV_r.d.ts → workspace-extension-DTFTdGVF.d.ts} +43 -45
  325. package/package.json +7 -10
  326. package/dist/EventQueueFactory-GXC3A7DH.js +0 -8
  327. package/dist/EventQueueFactory-GXC3A7DH.js.map +0 -1
  328. package/dist/chunk-4XIBXZ6J.js +0 -276
  329. package/dist/chunk-4XIBXZ6J.js.map +0 -1
  330. package/dist/chunk-554Z4C2K.js +0 -1006
  331. package/dist/chunk-554Z4C2K.js.map +0 -1
  332. package/dist/chunk-5CAFHK2Z.js +0 -107
  333. package/dist/chunk-5CAFHK2Z.js.map +0 -1
  334. package/dist/chunk-63ZXJ42X.js +0 -451
  335. package/dist/chunk-63ZXJ42X.js.map +0 -1
  336. package/dist/chunk-6XEXJATV.js +0 -304
  337. package/dist/chunk-6XEXJATV.js.map +0 -1
  338. package/dist/chunk-726AR6Q7.js +0 -1532
  339. package/dist/chunk-726AR6Q7.js.map +0 -1
  340. package/dist/chunk-A5F6Z5UE.js +0 -21
  341. package/dist/chunk-A5F6Z5UE.js.map +0 -1
  342. package/dist/chunk-A6DE32ZS.js +0 -1507
  343. package/dist/chunk-A6DE32ZS.js.map +0 -1
  344. package/dist/chunk-AXJDGQPE.js +0 -690
  345. package/dist/chunk-AXJDGQPE.js.map +0 -1
  346. package/dist/chunk-BJQOGOVW.js +0 -602
  347. package/dist/chunk-BJQOGOVW.js.map +0 -1
  348. package/dist/chunk-CFXWH2IS.js +0 -52
  349. package/dist/chunk-CFXWH2IS.js.map +0 -1
  350. package/dist/chunk-DRWH5XCJ.js +0 -876
  351. package/dist/chunk-DRWH5XCJ.js.map +0 -1
  352. package/dist/chunk-E4QNLVY4.js +0 -909
  353. package/dist/chunk-E4QNLVY4.js.map +0 -1
  354. package/dist/chunk-EBDHIL7V.js +0 -774
  355. package/dist/chunk-EBDHIL7V.js.map +0 -1
  356. package/dist/chunk-ELU7VL3E.js +0 -245
  357. package/dist/chunk-ELU7VL3E.js.map +0 -1
  358. package/dist/chunk-FZRODKIN.js +0 -31
  359. package/dist/chunk-FZRODKIN.js.map +0 -1
  360. package/dist/chunk-GCIB76AJ.js +0 -882
  361. package/dist/chunk-GCIB76AJ.js.map +0 -1
  362. package/dist/chunk-HC6MPUIH.js +0 -1571
  363. package/dist/chunk-HC6MPUIH.js.map +0 -1
  364. package/dist/chunk-HNMHPSAM.js +0 -272
  365. package/dist/chunk-HNMHPSAM.js.map +0 -1
  366. package/dist/chunk-HTLEGD3Q.js +0 -1480
  367. package/dist/chunk-HTLEGD3Q.js.map +0 -1
  368. package/dist/chunk-I3KOWRT3.js +0 -89
  369. package/dist/chunk-I3KOWRT3.js.map +0 -1
  370. package/dist/chunk-ID3WR4JS.js +0 -509
  371. package/dist/chunk-ID3WR4JS.js.map +0 -1
  372. package/dist/chunk-JS52ZHTK.js +0 -1346
  373. package/dist/chunk-JS52ZHTK.js.map +0 -1
  374. package/dist/chunk-JVMAQOA3.js +0 -521
  375. package/dist/chunk-JVMAQOA3.js.map +0 -1
  376. package/dist/chunk-KH4TRQCO.js +0 -1063
  377. package/dist/chunk-KH4TRQCO.js.map +0 -1
  378. package/dist/chunk-KJOSPVB2.js +0 -57
  379. package/dist/chunk-KJOSPVB2.js.map +0 -1
  380. package/dist/chunk-KO2ZXZ7W.js +0 -61
  381. package/dist/chunk-KO2ZXZ7W.js.map +0 -1
  382. package/dist/chunk-KS2HQCJR.js +0 -56
  383. package/dist/chunk-KS2HQCJR.js.map +0 -1
  384. package/dist/chunk-LA5KPWZ2.js +0 -413
  385. package/dist/chunk-LA5KPWZ2.js.map +0 -1
  386. package/dist/chunk-MESLAC5W.js +0 -574
  387. package/dist/chunk-MESLAC5W.js.map +0 -1
  388. package/dist/chunk-MWPYA2HD.js +0 -94
  389. package/dist/chunk-MWPYA2HD.js.map +0 -1
  390. package/dist/chunk-NUB5GQTU.js +0 -270
  391. package/dist/chunk-NUB5GQTU.js.map +0 -1
  392. package/dist/chunk-OBBCR6WY.js +0 -277
  393. package/dist/chunk-OBBCR6WY.js.map +0 -1
  394. package/dist/chunk-OQDSAOG3.js +0 -1908
  395. package/dist/chunk-OQDSAOG3.js.map +0 -1
  396. package/dist/chunk-OXNCBE7P.js +0 -971
  397. package/dist/chunk-OXNCBE7P.js.map +0 -1
  398. package/dist/chunk-PBZFAAOM.js +0 -941
  399. package/dist/chunk-PN6GIF3R.js +0 -1185
  400. package/dist/chunk-PN6GIF3R.js.map +0 -1
  401. package/dist/chunk-PYD44IHJ.js +0 -728
  402. package/dist/chunk-PYD44IHJ.js.map +0 -1
  403. package/dist/chunk-QVPIACWD.js +0 -679
  404. package/dist/chunk-QVPIACWD.js.map +0 -1
  405. package/dist/chunk-QWNNFE4P.js +0 -41
  406. package/dist/chunk-QWNNFE4P.js.map +0 -1
  407. package/dist/chunk-RU266375.js +0 -327
  408. package/dist/chunk-RU266375.js.map +0 -1
  409. package/dist/chunk-RYTSVGGA.js +0 -1624
  410. package/dist/chunk-RYTSVGGA.js.map +0 -1
  411. package/dist/chunk-RZOFS2BQ.js +0 -225
  412. package/dist/chunk-RZOFS2BQ.js.map +0 -1
  413. package/dist/chunk-SBS4S2PJ.js +0 -100
  414. package/dist/chunk-SBS4S2PJ.js.map +0 -1
  415. package/dist/chunk-SPRG6G6G.js +0 -530
  416. package/dist/chunk-SPRG6G6G.js.map +0 -1
  417. package/dist/chunk-STWFX5E2.js +0 -233
  418. package/dist/chunk-STWFX5E2.js.map +0 -1
  419. package/dist/chunk-UNASM5VJ.js +0 -419
  420. package/dist/chunk-UNASM5VJ.js.map +0 -1
  421. package/dist/chunk-VAT66FJA.js +0 -245
  422. package/dist/chunk-VAT66FJA.js.map +0 -1
  423. package/dist/chunk-VFCMR5GX.js +0 -49
  424. package/dist/chunk-VFCMR5GX.js.map +0 -1
  425. package/dist/chunk-VGAHZKNJ.js +0 -66
  426. package/dist/chunk-VGAHZKNJ.js.map +0 -1
  427. package/dist/chunk-VTJTAAXC.js +0 -627
  428. package/dist/chunk-VTJTAAXC.js.map +0 -1
  429. package/dist/chunk-VXVLKRU6.js +0 -758
  430. package/dist/chunk-VXVLKRU6.js.map +0 -1
  431. package/dist/chunk-WWUU5ETI.js +0 -163
  432. package/dist/chunk-WWUU5ETI.js.map +0 -1
  433. package/dist/chunk-XE4OXN2W.js +0 -10
  434. package/dist/chunk-XE4OXN2W.js.map +0 -1
  435. package/dist/chunk-XOJORS75.js +0 -1853
  436. package/dist/chunk-XOJORS75.js.map +0 -1
  437. package/dist/chunk-YMZEUTD2.js +0 -110
  438. package/dist/chunk-YMZEUTD2.js.map +0 -1
  439. package/dist/chunk-Z77BTSOK.js +0 -617
  440. package/dist/chunk-Z77BTSOK.js.map +0 -1
  441. package/dist/chunk-ZZK3WEDI.js +0 -181
  442. package/dist/chunk-ZZK3WEDI.js.map +0 -1
  443. package/dist/client-CCXpAZ2r.d.ts +0 -89
  444. package/dist/client-DSI_760t.d.ts +0 -36
  445. package/dist/client-JU6T3UPB.js +0 -11
  446. package/dist/client-JU6T3UPB.js.map +0 -1
  447. package/dist/dist-2X4Q7PJA.js +0 -1491
  448. package/dist/dist-2X4Q7PJA.js.map +0 -1
  449. package/dist/env-4UWSUS64.js +0 -4
  450. package/dist/env-4UWSUS64.js.map +0 -1
  451. package/dist/graph-emitter-r5TylDBm.d.ts +0 -47
  452. package/dist/graphql-CMHMQjvd.d.ts +0 -23
  453. package/dist/i18n-Qm2AkPC-.d.ts +0 -33
  454. package/dist/index--yvpa6ay.d.ts +0 -83
  455. package/dist/index-4gKQKZ2B.d.ts +0 -71
  456. package/dist/index-5x0XMKXN.d.ts +0 -149
  457. package/dist/index-B70b5mYS.d.ts +0 -33
  458. package/dist/index-B8KrxO4j.d.ts +0 -755
  459. package/dist/index-BOuDKnqD.d.ts +0 -201
  460. package/dist/index-BTMt4OjA.d.ts +0 -201
  461. package/dist/index-BejbszA7.d.ts +0 -39
  462. package/dist/index-BkeOYZye.d.ts +0 -198
  463. package/dist/index-BuAj5nXg.d.ts +0 -83
  464. package/dist/index-BvkVcW8I.d.ts +0 -349
  465. package/dist/index-CWmH_-RZ.d.ts +0 -247
  466. package/dist/index-CbgWNcus.d.ts +0 -258
  467. package/dist/index-CmfPeQza.d.ts +0 -166
  468. package/dist/index-CmpG-zak.d.ts +0 -607
  469. package/dist/index-CoMKgL-p.d.ts +0 -12
  470. package/dist/index-D8HGwglK.d.ts +0 -541
  471. package/dist/index-DCaVm66D.d.ts +0 -1101
  472. package/dist/index-DE2w7E0d.d.ts +0 -83
  473. package/dist/index-DSOpj8DI.d.ts +0 -17
  474. package/dist/index-DW9q22GH.d.ts +0 -75
  475. package/dist/index-DnjJ9CwI.d.ts +0 -347
  476. package/dist/index-DwMJZ8PP.d.ts +0 -317
  477. package/dist/index-PaojfSdd.d.ts +0 -71
  478. package/dist/index-aHtYvc3i.d.ts +0 -284
  479. package/dist/index-e_18DzAg.d.ts +0 -18
  480. package/dist/index-ffmipXSA.d.ts +0 -55
  481. package/dist/index-joONjwLt.d.ts +0 -33
  482. package/dist/index-kssw5ziY.d.ts +0 -250
  483. package/dist/index-lFffh5-G.d.ts +0 -125
  484. package/dist/index-pxYge_6k.d.ts +0 -79
  485. package/dist/layer-Cv9vSwBx.d.ts +0 -70
  486. package/dist/pino-logger-H4HPW5P6.js +0 -5
  487. package/dist/pino-logger-H4HPW5P6.js.map +0 -1
  488. package/dist/prisma-extension-gYhYriA0.d.ts +0 -174
  489. package/dist/sdk-L75WWUP3.js +0 -156
  490. package/dist/sdk-L75WWUP3.js.map +0 -1
  491. package/dist/shutdown-registry-CW9LryO8.d.ts +0 -10
  492. package/dist/types-Bo2wkjSP.d.ts +0 -35
  493. package/dist/types-DVpvrAhd.d.ts +0 -71
  494. package/dist/types-DgJ4lDYA.d.ts +0 -108
  495. package/dist/types-USOv09qy.d.ts +0 -327
  496. package/dist/workspace-guard-NXVYYBVJ.js +0 -5
  497. package/dist/workspace-guard-NXVYYBVJ.js.map +0 -1
@@ -0,0 +1,1510 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-ad2WFvuA.js";
2
+ import { a as logger } from "./logger-B6rCpb7D.js";
3
+ import { D as productSlugVariants, c as emitProductSlug } from "./product-alias-BPqtskMq.js";
4
+
5
+ // src/platform/httpClient.ts
6
+ /**
7
+ * httpClient — hardened wrapper around global `fetch` with:
8
+ * - per-request AbortSignal.timeout (default 5s)
9
+ * - retries (default 3) with exponential backoff + full jitter
10
+ * - per-host circuit breaker (opens at 5 consecutive 5xx, half-open after 30s)
11
+ * - structured logging via existing be-sdk logger
12
+ *
13
+ * No required upstream dependency — we use the runtime `fetch` so the same
14
+ * code path works on Bun and Node 20+. Consumers may pass an undici Agent
15
+ * via `init.dispatcher` if they need keep-alive pooling; we forward unknown
16
+ * init fields through.
17
+ */
18
+ const breakers = /* @__PURE__ */ new Map();
19
+ function hostOf(url) {
20
+ try {
21
+ return new URL(url).host;
22
+ } catch {
23
+ return url;
24
+ }
25
+ }
26
+ function getBreaker(host) {
27
+ let b = breakers.get(host);
28
+ if (!b) {
29
+ b = {
30
+ failures: 0,
31
+ openedAt: null,
32
+ state: "CLOSED"
33
+ };
34
+ breakers.set(host, b);
35
+ }
36
+ return b;
37
+ }
38
+ function defaultRetryOn(status) {
39
+ return status === 408 || status === 425 || status === 429 || status >= 500 && status <= 599;
40
+ }
41
+ function jitter$1(delay) {
42
+ return Math.floor(Math.random() * delay);
43
+ }
44
+ function sleep$1(ms) {
45
+ return new Promise((r) => setTimeout(r, ms));
46
+ }
47
+ var CircuitBreakerOpenError = class extends Error {
48
+ constructor(host) {
49
+ super(`circuit breaker OPEN for host=${host}`);
50
+ this.name = "CircuitBreakerOpenError";
51
+ }
52
+ };
53
+ /**
54
+ * Reset all breaker state (test helper).
55
+ */
56
+ function __resetHttpClientBreakers() {
57
+ breakers.clear();
58
+ }
59
+ async function executeOnce(url, init, timeoutMs) {
60
+ const signal = init.signal ?? AbortSignal.timeout(timeoutMs);
61
+ return fetch(url, {
62
+ ...init,
63
+ signal
64
+ });
65
+ }
66
+ async function httpClient(url, init = {}, config = {}) {
67
+ const fullUrl = config.baseUrl && !/^https?:\/\//i.test(url) ? `${config.baseUrl.replace(/\/$/, "")}/${url.replace(/^\//, "")}` : url;
68
+ const host = hostOf(fullUrl);
69
+ const breaker = getBreaker(host);
70
+ const breakerThreshold = config.breaker?.threshold ?? 5;
71
+ const cooldownMs = config.breaker?.cooldownMs ?? 3e4;
72
+ if (breaker.state === "OPEN") {
73
+ if (breaker.openedAt && Date.now() - breaker.openedAt >= cooldownMs) {
74
+ breaker.state = "HALF_OPEN";
75
+ logger.info("httpClient.breaker.halfOpen", { host });
76
+ } else throw new CircuitBreakerOpenError(host);
77
+ }
78
+ const attempts = init.retry?.attempts ?? config.retry?.attempts ?? 3;
79
+ const initialDelay = init.retry?.initialDelayMs ?? config.retry?.initialDelayMs ?? 100;
80
+ const maxDelay = init.retry?.maxDelayMs ?? config.retry?.maxDelayMs ?? 2e3;
81
+ const retryOn = init.retry?.retryOn ?? config.retry?.retryOn ?? defaultRetryOn;
82
+ const timeoutMs = init.timeoutMs ?? config.defaultTimeoutMs ?? 5e3;
83
+ const headers = {
84
+ ...config.defaultHeaders ?? {},
85
+ ...init.headers ?? {}
86
+ };
87
+ let lastErr;
88
+ for (let attempt = 1; attempt <= attempts; attempt++) try {
89
+ const response = await executeOnce(fullUrl, {
90
+ ...init,
91
+ headers
92
+ }, timeoutMs);
93
+ if (response.status >= 500) {
94
+ breaker.failures += 1;
95
+ if (breaker.failures >= breakerThreshold) {
96
+ breaker.state = "OPEN";
97
+ breaker.openedAt = Date.now();
98
+ logger.warn("httpClient.breaker.open", {
99
+ host,
100
+ failures: breaker.failures
101
+ });
102
+ }
103
+ if (attempt < attempts && retryOn(response.status)) {
104
+ await sleep$1(jitter$1(Math.min(initialDelay * 2 ** (attempt - 1), maxDelay)));
105
+ continue;
106
+ }
107
+ return response;
108
+ }
109
+ breaker.failures = 0;
110
+ if (breaker.state === "HALF_OPEN") {
111
+ breaker.state = "CLOSED";
112
+ breaker.openedAt = null;
113
+ logger.info("httpClient.breaker.closed", { host });
114
+ }
115
+ if (attempt < attempts && retryOn(response.status)) {
116
+ await sleep$1(jitter$1(Math.min(initialDelay * 2 ** (attempt - 1), maxDelay)));
117
+ continue;
118
+ }
119
+ return response;
120
+ } catch (err) {
121
+ lastErr = err;
122
+ breaker.failures += 1;
123
+ if (breaker.failures >= breakerThreshold) {
124
+ breaker.state = "OPEN";
125
+ breaker.openedAt = Date.now();
126
+ logger.warn("httpClient.breaker.open", {
127
+ host,
128
+ failures: breaker.failures
129
+ });
130
+ }
131
+ if (attempt >= attempts) break;
132
+ await sleep$1(jitter$1(Math.min(initialDelay * 2 ** (attempt - 1), maxDelay)));
133
+ }
134
+ logger.error("httpClient.exhausted", {
135
+ url: fullUrl,
136
+ attempts,
137
+ host
138
+ });
139
+ throw lastErr instanceof Error ? lastErr : /* @__PURE__ */ new Error(`httpClient failed: ${String(lastErr)}`);
140
+ }
141
+ function createHttpClient(config = {}) {
142
+ return (url, init = {}) => httpClient(url, init, config);
143
+ }
144
+
145
+ // src/platform/leaderLock.ts
146
+ /**
147
+ * Redis-based leader election primitives.
148
+ *
149
+ * Two public entry points share one core (`besdk:leader:{name}` key,
150
+ * `SET NX EX` acquire, Redis-side compare-and-renew / compare-and-delete
151
+ * LUA scripts, per-holder token):
152
+ *
153
+ * - {@link withLeaderLock} — run-once wrapper: acquire, run `fn()` while
154
+ * auto-renewing, release. Resolves `{ acquired: false }` (without running
155
+ * `fn`) when another holder owns the lease.
156
+ * - {@link createLeaderLease} — long-lived, self-renewing lease HANDLE for a
157
+ * continuously-running singleton worker: acquire, auto-renew every
158
+ * `ttlMs/3`, and re-acquire on failover, until `release()`.
159
+ *
160
+ * The Redis client is duck-typed (ioredis-compatible) so consumers can pass
161
+ * either ioredis or any client exposing the same `set`/`eval` shape.
162
+ */
163
+ const RELEASE_LUA = `
164
+ if redis.call("get", KEYS[1]) == ARGV[1] then
165
+ return redis.call("del", KEYS[1])
166
+ else
167
+ return 0
168
+ end
169
+ `;
170
+ const RENEW_LUA = `
171
+ if redis.call("get", KEYS[1]) == ARGV[1] then
172
+ return redis.call("pexpire", KEYS[1], ARGV[2])
173
+ else
174
+ return 0
175
+ end
176
+ `;
177
+ /** Standard Redis key for a named leader lease. */
178
+ function leaderKey(name) {
179
+ return `besdk:leader:${name}`;
180
+ }
181
+ function generateToken() {
182
+ return `${Date.now()}-${Math.random().toString(36).slice(2)}-${process.pid}`;
183
+ }
184
+ function defaultRenewMs(ttlMs) {
185
+ return Math.max(1e3, Math.floor(ttlMs / 3));
186
+ }
187
+ /** Attempt to acquire the lease with `SET key token EX ttl NX`. */
188
+ async function acquireLease(redis, key, token, ttlMs) {
189
+ const ttlSeconds = Math.max(1, Math.ceil(ttlMs / 1e3));
190
+ return await redis.set(key, token, "EX", ttlSeconds, "NX") === "OK";
191
+ }
192
+ /** Compare-and-renew: extend the lease only if we still own it (Redis-side). */
193
+ async function renewLease(redis, key, token, ttlMs) {
194
+ return await redis.eval(RENEW_LUA, 1, key, token, String(ttlMs)) === 1;
195
+ }
196
+ /** Compare-and-delete: release the lease only if we still own it (Redis-side). */
197
+ async function releaseLease(redis, key, token) {
198
+ await redis.eval(RELEASE_LUA, 1, key, token);
199
+ }
200
+ /**
201
+ * Normalise a Valkey/Redis URL to an ioredis-understood scheme:
202
+ * - `valkeys://…` → `rediss://…` (TLS)
203
+ * - `valkey://…` → `redis://…`
204
+ * Any other scheme (incl. `redis://` / `rediss://`) is returned unchanged.
205
+ *
206
+ * Consumers building the ioredis client they hand to {@link createLeaderLease}
207
+ * or {@link withLeaderLock} should run their `VALKEY_URL`/`REDIS_URL` through
208
+ * this so they can retire their own copy of the same normaliser.
209
+ */
210
+ function normalizeRedisUrl(url) {
211
+ if (url.startsWith("valkeys://")) return url.replace(/^valkeys:\/\//, "rediss://");
212
+ if (url.startsWith("valkey://")) return url.replace(/^valkey:\/\//, "redis://");
213
+ return url;
214
+ }
215
+ async function withLeaderLock(redis, name, fn, options) {
216
+ const key = leaderKey(name);
217
+ const token = generateToken();
218
+ const ttlMs = options.ttlMs;
219
+ const renewMs = options.renewMs ?? defaultRenewMs(ttlMs);
220
+ if (!await acquireLease(redis, key, token, ttlMs)) return { acquired: false };
221
+ logger.info("leaderLock.acquired", {
222
+ name,
223
+ token,
224
+ ttlMs
225
+ });
226
+ let stopped = false;
227
+ const renewTimer = setInterval(() => {
228
+ if (stopped) return;
229
+ renewLease(redis, key, token, ttlMs).catch((err) => {
230
+ logger.warn("leaderLock.renew.failed", {
231
+ name,
232
+ err: String(err)
233
+ });
234
+ });
235
+ }, renewMs);
236
+ if (typeof renewTimer.unref === "function") renewTimer.unref();
237
+ try {
238
+ return {
239
+ acquired: true,
240
+ result: await fn()
241
+ };
242
+ } finally {
243
+ stopped = true;
244
+ clearInterval(renewTimer);
245
+ try {
246
+ await releaseLease(redis, key, token);
247
+ logger.info("leaderLock.released", {
248
+ name,
249
+ token
250
+ });
251
+ } catch (err) {
252
+ logger.warn("leaderLock.release.failed", {
253
+ name,
254
+ err: String(err)
255
+ });
256
+ }
257
+ }
258
+ }
259
+ /**
260
+ * Create a self-renewing leader lease for a continuously-running singleton
261
+ * worker. On creation an auto-renew timer starts (`renewMs`, default `ttlMs/3`,
262
+ * unref'd) that acquires-if-free / renews-if-held — so a replica that starts as
263
+ * a follower automatically takes over when the current holder dies and its
264
+ * lease expires. Call `renew()` once up front to acquire deterministically:
265
+ *
266
+ * ```ts
267
+ * const lease = createLeaderLease({ name: 'notification-sweep', ttlMs: 90_000, redis });
268
+ * if (await lease.renew()) startWorker(); // became leader
269
+ * // ...auto-renews in the background...
270
+ * await lease.release(); // on graceful shutdown
271
+ * ```
272
+ */
273
+ function createLeaderLease(options) {
274
+ const { name, ttlMs, redis } = options;
275
+ const key = leaderKey(name);
276
+ const token = generateToken();
277
+ const renewMs = options.renewMs ?? defaultRenewMs(ttlMs);
278
+ let held = false;
279
+ let released = false;
280
+ let inFlight = null;
281
+ const acquireOrRenew = async () => {
282
+ if (released) return false;
283
+ try {
284
+ if (held) {
285
+ if (await renewLease(redis, key, token, ttlMs)) return true;
286
+ held = false;
287
+ }
288
+ const acquired = await acquireLease(redis, key, token, ttlMs);
289
+ if (acquired && !held) logger.info("leaderLease.acquired", {
290
+ name,
291
+ token,
292
+ ttlMs
293
+ });
294
+ held = acquired;
295
+ return held;
296
+ } catch (err) {
297
+ logger.warn("leaderLease.renew.failed", {
298
+ name,
299
+ err: String(err)
300
+ });
301
+ return held;
302
+ }
303
+ };
304
+ const runAttempt = () => {
305
+ if (inFlight) return inFlight;
306
+ const attempt = acquireOrRenew().finally(() => {
307
+ if (inFlight === attempt) inFlight = null;
308
+ });
309
+ inFlight = attempt;
310
+ return attempt;
311
+ };
312
+ const timer = setInterval(() => {
313
+ if (released) return;
314
+ runAttempt();
315
+ }, renewMs);
316
+ if (typeof timer.unref === "function") timer.unref();
317
+ return {
318
+ renew() {
319
+ return runAttempt();
320
+ },
321
+ async release() {
322
+ if (released) return;
323
+ released = true;
324
+ clearInterval(timer);
325
+ if (inFlight) try {
326
+ await inFlight;
327
+ } catch {}
328
+ if (!held) return;
329
+ held = false;
330
+ try {
331
+ await releaseLease(redis, key, token);
332
+ logger.info("leaderLease.released", {
333
+ name,
334
+ token
335
+ });
336
+ } catch (err) {
337
+ logger.warn("leaderLease.release.failed", {
338
+ name,
339
+ err: String(err)
340
+ });
341
+ }
342
+ },
343
+ isHeld() {
344
+ return held && !released;
345
+ }
346
+ };
347
+ }
348
+
349
+ // src/platform/rateLimit.ts
350
+ async function rateLimitIncr(redis, input) {
351
+ const fullKey = `besdk:rl:${input.key}`;
352
+ const count = await redis.incr(fullKey);
353
+ if (count === 1) await redis.pexpire(fullKey, input.windowMs);
354
+ let ttl = -1;
355
+ try {
356
+ ttl = await redis.pttl(fullKey);
357
+ } catch {
358
+ ttl = input.windowMs;
359
+ }
360
+ const resetAt = Date.now() + (ttl > 0 ? ttl : input.windowMs);
361
+ const remaining = Math.max(0, input.limit - count);
362
+ return {
363
+ allowed: count <= input.limit,
364
+ count,
365
+ remaining,
366
+ resetAt
367
+ };
368
+ }
369
+
370
+ // src/platform/paginator.ts
371
+ const DEFAULT_GRAPHQL_PAGE_LIMIT = 50;
372
+ const MAX_GRAPHQL_PAGE_LIMIT = 100;
373
+ function clampLimit(input, opts = {}) {
374
+ const def = opts.defaultLimit ?? 50;
375
+ const max = opts.maxLimit ?? 200;
376
+ const min = opts.minLimit ?? 1;
377
+ if (input == null || Number.isNaN(input)) return def;
378
+ return Math.min(Math.max(Math.floor(input), min), max);
379
+ }
380
+ function clampOffset(input) {
381
+ if (input == null || Number.isNaN(input)) return 0;
382
+ return Math.max(0, Math.floor(input));
383
+ }
384
+ function clampGraphqlLimit(input, opts = {}) {
385
+ return clampLimit(input, {
386
+ defaultLimit: opts.defaultLimit ?? 50,
387
+ maxLimit: opts.maxLimit ?? 100,
388
+ minLimit: opts.minLimit ?? 1
389
+ });
390
+ }
391
+ function normalizeOffsetPagination(input, opts = {}) {
392
+ return {
393
+ limit: clampGraphqlLimit(input?.limit, opts),
394
+ offset: clampOffset(input?.offset)
395
+ };
396
+ }
397
+ function normalizeCursorPagination(input, opts = {}) {
398
+ const first = clampGraphqlLimit(input?.first, opts);
399
+ return {
400
+ first,
401
+ after: typeof input?.after === "string" && input.after.trim().length > 0 ? input.after : null,
402
+ take: first + 1
403
+ };
404
+ }
405
+ function encodeCursor(payload) {
406
+ return Buffer.from(JSON.stringify(payload), "utf8").toString("base64url");
407
+ }
408
+ function decodeCursor(cursor) {
409
+ if (typeof cursor !== "string" || cursor.trim().length === 0) return null;
410
+ try {
411
+ const decoded = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
412
+ if (decoded == null || typeof decoded !== "object" || Array.isArray(decoded)) return null;
413
+ const payload = {};
414
+ for (const [key, value] of Object.entries(decoded)) if (typeof value === "string" || typeof value === "number" || typeof value === "boolean" || value == null) payload[key] = value;
415
+ return Object.keys(payload).length > 0 ? payload : null;
416
+ } catch {
417
+ return null;
418
+ }
419
+ }
420
+ function buildConnection(items, opts) {
421
+ const nodes = items.length > opts.limit ? items.slice(0, opts.limit) : items;
422
+ const edges = nodes.map((node) => ({
423
+ node,
424
+ cursor: opts.cursorForNode(node)
425
+ }));
426
+ const firstEdge = edges[0];
427
+ const lastEdge = edges.at(-1);
428
+ return {
429
+ edges,
430
+ nodes,
431
+ pageInfo: {
432
+ hasNextPage: items.length > opts.limit,
433
+ hasPreviousPage: opts.hasPreviousPage ?? false,
434
+ startCursor: firstEdge?.cursor ?? null,
435
+ endCursor: lastEdge?.cursor ?? null
436
+ },
437
+ totalCount: opts.totalCount
438
+ };
439
+ }
440
+ function buildOffsetPage(items, total, pagination) {
441
+ const nextOffset = pagination.offset + items.length;
442
+ const hasMore = nextOffset < total;
443
+ return {
444
+ items,
445
+ total,
446
+ limit: pagination.limit,
447
+ offset: pagination.offset,
448
+ hasMore,
449
+ nextOffset: hasMore ? nextOffset : null
450
+ };
451
+ }
452
+ /**
453
+ * Convert a normalized offset pagination result to Prisma's `take`/`skip` args.
454
+ *
455
+ * ```ts
456
+ * const pg = normalizeOffsetPagination(args);
457
+ * const rows = await prisma.tag.findMany({ ...toPrismaPage(pg), where });
458
+ * ```
459
+ *
460
+ * `limit` is clamped to MAX_GRAPHQL_PAGE_LIMIT (100) by `normalizeOffsetPagination`.
461
+ * Always call normalizeOffsetPagination first — never pass a raw limit directly.
462
+ */
463
+ function toPrismaPage(pagination) {
464
+ return {
465
+ take: pagination.limit,
466
+ skip: pagination.offset
467
+ };
468
+ }
469
+ async function paginate(model, input, opts = {}) {
470
+ const take = clampGraphqlLimit(input.take ?? void 0, opts);
471
+ const items = await model.findMany({
472
+ take: take + 1,
473
+ skip: input.cursor ? 1 : 0,
474
+ cursor: input.cursor ? { id: input.cursor } : void 0,
475
+ where: input.where,
476
+ orderBy: input.orderBy
477
+ });
478
+ const hasMore = items.length > take;
479
+ const trimmed = hasMore ? items.slice(0, take) : items;
480
+ return {
481
+ items: trimmed,
482
+ hasMore,
483
+ nextCursor: hasMore && trimmed.length > 0 ? trimmed[trimmed.length - 1].id : null
484
+ };
485
+ }
486
+
487
+ // src/platform/dataLoaderFactory.ts
488
+ /**
489
+ * Build a fresh loader collection from a context.
490
+ *
491
+ * @example
492
+ * const loaders = buildLoaders(ctx, (c) => ({
493
+ * userById: createSimpleLoader(async ids => c.db.user.findMany({ where: { id: { in: [...ids] } } }), u => u.id),
494
+ * tagById: createSimpleLoader(...),
495
+ * }));
496
+ * await loaders.userById.load('user-123');
497
+ */
498
+ function buildLoaders(ctx, builder) {
499
+ return builder(ctx);
500
+ }
501
+ function resolveReferenceLoader(loaderName, keyField = "id") {
502
+ return async (reference, ctx) => {
503
+ const loader = ctx.loaders[loaderName];
504
+ if (!loader) throw new Error(`resolveReferenceLoader: loader "${loaderName}" not found on ctx.loaders`);
505
+ const key = reference[keyField];
506
+ if (typeof key !== "string") return null;
507
+ return loader.load(key);
508
+ };
509
+ }
510
+
511
+ // src/platform/cacheInvalidation.ts
512
+ const VERSION_PREFIX = "besdk:cv:";
513
+ async function getNamespaceVersion(redis, namespace) {
514
+ const v = await redis.get(`${VERSION_PREFIX}${namespace}`);
515
+ if (!v) return 1;
516
+ const n = Number.parseInt(v, 10);
517
+ return Number.isFinite(n) && n > 0 ? n : 1;
518
+ }
519
+ async function buildCacheKey(redis, namespace, ...parts) {
520
+ return `${namespace}:v${await getNamespaceVersion(redis, namespace)}:${parts.join(":")}`;
521
+ }
522
+ async function invalidateNamespace(redis, namespace) {
523
+ return redis.incr(`${VERSION_PREFIX}${namespace}`);
524
+ }
525
+
526
+ // src/platform/pgPartition.ts
527
+ function pad2(n) {
528
+ return n < 10 ? `0${n}` : `${n}`;
529
+ }
530
+ function monthlyPartitionName(table, year, month) {
531
+ return `${table}_y${year}m${pad2(month)}`;
532
+ }
533
+ async function ensureMonthlyPartitions(prisma, opts) {
534
+ const created = [];
535
+ const cur = new Date(Date.UTC(opts.from.getUTCFullYear(), opts.from.getUTCMonth(), 1));
536
+ const end = new Date(Date.UTC(opts.to.getUTCFullYear(), opts.to.getUTCMonth(), 1));
537
+ while (cur <= end) {
538
+ const y = cur.getUTCFullYear();
539
+ const m = cur.getUTCMonth() + 1;
540
+ const next = new Date(Date.UTC(y, m, 1));
541
+ const partition = monthlyPartitionName(opts.table, y, m);
542
+ const lower = `${y}-${pad2(m)}-01`;
543
+ const upper = `${next.getUTCFullYear()}-${pad2(next.getUTCMonth() + 1)}-01`;
544
+ await prisma.$executeRawUnsafe(`CREATE TABLE IF NOT EXISTS "${partition}" PARTITION OF "${opts.table}" FOR VALUES FROM ('${lower}') TO ('${upper}');`);
545
+ created.push(partition);
546
+ cur.setUTCMonth(cur.getUTCMonth() + 1);
547
+ }
548
+ return created;
549
+ }
550
+ async function dropOldPartitions(prisma, opts) {
551
+ const rows = await prisma.$queryRawUnsafe(`SELECT child.relname AS partition_name
552
+ FROM pg_inherits
553
+ JOIN pg_class parent ON pg_inherits.inhparent = parent.oid
554
+ JOIN pg_class child ON pg_inherits.inhrelid = child.oid
555
+ WHERE parent.relname = $1`, opts.table);
556
+ const dropped = [];
557
+ const cutoffYear = opts.beforeDate.getUTCFullYear();
558
+ const cutoffMonth = opts.beforeDate.getUTCMonth() + 1;
559
+ for (const row of rows) {
560
+ const m = /_y(\d{4})m(\d{2})$/.exec(row.partition_name);
561
+ if (!m) continue;
562
+ const y = Number(m[1]);
563
+ const mo = Number(m[2]);
564
+ if (y < cutoffYear || y === cutoffYear && mo < cutoffMonth) {
565
+ await prisma.$executeRawUnsafe(`DROP TABLE IF EXISTS "${row.partition_name}";`);
566
+ dropped.push(row.partition_name);
567
+ }
568
+ }
569
+ return dropped;
570
+ }
571
+
572
+ // src/platform/llmClient.ts
573
+ /**
574
+ * Multi-provider LLM wrapper with timeout, retries, jitter, provider
575
+ * fallback chain, token cap, and streaming passthrough.
576
+ *
577
+ * No hard dependency on a specific SDK — consumers register adapters.
578
+ * Provider chain order is controlled by env `LLM_PROVIDER_CHAIN`
579
+ * (comma-separated, e.g. `anthropic,openai,openrouter`).
580
+ *
581
+ * The wrapper is intentionally minimal — callers should construct it
582
+ * once at boot, register adapters, and inject the singleton.
583
+ */
584
+ const DEFAULTS = {
585
+ timeoutMs: 3e4,
586
+ maxAttempts: 3,
587
+ initialDelayMs: 500,
588
+ maxOutputTokensCap: 4096
589
+ };
590
+ function jitter(n) {
591
+ return Math.floor(Math.random() * n);
592
+ }
593
+ function sleep(ms) {
594
+ return new Promise((r) => setTimeout(r, ms));
595
+ }
596
+ var LLMRouter = class {
597
+ adapters = /* @__PURE__ */ new Map();
598
+ opts;
599
+ constructor(opts = {}) {
600
+ this.opts = {
601
+ ...DEFAULTS,
602
+ ...opts
603
+ };
604
+ }
605
+ register(adapter) {
606
+ this.adapters.set(adapter.name, adapter);
607
+ }
608
+ resolveChain() {
609
+ const envChain = process.env["LLM_PROVIDER_CHAIN"]?.trim();
610
+ if (envChain) return envChain.split(",").map((s) => s.trim()).filter(Boolean);
611
+ return Array.from(this.adapters.keys());
612
+ }
613
+ async complete(req) {
614
+ const cappedReq = {
615
+ ...req,
616
+ maxTokens: Math.min(req.maxTokens ?? this.opts.maxOutputTokensCap, this.opts.maxOutputTokensCap)
617
+ };
618
+ const chain = this.resolveChain();
619
+ if (chain.length === 0) throw new Error("LLMRouter: no providers registered");
620
+ let lastErr = null;
621
+ for (let attempt = 0; attempt < this.opts.maxAttempts; attempt++) {
622
+ const providerName = chain[attempt % chain.length];
623
+ const adapter = providerName ? this.adapters.get(providerName) : void 0;
624
+ if (!adapter) {
625
+ logger.warn("llmRouter.provider.notRegistered", { providerName });
626
+ continue;
627
+ }
628
+ const timeoutMs = req.timeoutMs ?? this.opts.timeoutMs;
629
+ const ctrl = new AbortController();
630
+ const t = setTimeout(() => ctrl.abort(), timeoutMs);
631
+ try {
632
+ return await adapter.complete(cappedReq, ctrl.signal);
633
+ } catch (err) {
634
+ lastErr = err;
635
+ logger.warn("llmRouter.attempt.failed", {
636
+ provider: adapter.name,
637
+ attempt,
638
+ err: String(err)
639
+ });
640
+ if (attempt < this.opts.maxAttempts - 1) await sleep(jitter(this.opts.initialDelayMs * 2 ** attempt));
641
+ } finally {
642
+ clearTimeout(t);
643
+ }
644
+ }
645
+ throw lastErr instanceof Error ? lastErr : /* @__PURE__ */ new Error(`LLMRouter exhausted ${this.opts.maxAttempts} attempts`);
646
+ }
647
+ };
648
+
649
+ // src/platform/invocation-accounting/documents.ts
650
+ /**
651
+ * Prompts V2 contract (eaae000, plus BOFF-9935 attribution fields, server
652
+ * pricing and the breakdown query). Source binding is not composed/runtime
653
+ * admission. The record document always asks prompts-svc to price on the
654
+ * server (`serverPricing: true` is added by the coordinator).
655
+ */
656
+ const PROMPTS_V2_DOCUMENTS = Object.freeze({
657
+ begin: "mutation SdkBeginInvocationAttemptV2($input:PromptBeginInvocationAttemptV2Input!){promptBeginInvocationAttemptV2(input:$input){id workspaceId attemptKey operationKey productKey providerKey modelKey startedAt trigger subjectType subjectId subjectPartId sequence createdBy origin fingerprint createdAt revisions{id attemptId revision predecessorId eventKey fingerprint outcome inputTokens outputTokens totalTokens cachedInputTokens costMicroUsd currency costKind pricingReference origin finishedAt createdAt} hasMoreRevisions}}",
658
+ record: "mutation SdkRecordInvocationUsageV2($input:PromptRecordInvocationUsageV2Input!){promptRecordInvocationUsageV2(input:$input){id attemptId revision predecessorId eventKey fingerprint outcome inputTokens outputTokens totalTokens cachedInputTokens costMicroUsd currency costKind pricingReference origin finishedAt createdAt}}",
659
+ read: "query SdkInvocationAttemptV2($key:String!,$offset:Int){promptInvocationAttemptV2(attemptKey:$key,revisionOffset:$offset){id workspaceId attemptKey operationKey productKey providerKey modelKey startedAt trigger subjectType subjectId subjectPartId sequence createdBy origin fingerprint createdAt revisions{id attemptId revision predecessorId eventKey fingerprint outcome inputTokens outputTokens totalTokens cachedInputTokens costMicroUsd currency costKind pricingReference origin finishedAt createdAt} hasMoreRevisions}}",
660
+ summary: "query SdkUsageSummaryV2($from:DateTime!,$to:DateTime!,$product:String,$operation:String){promptUsageSummaryV2(from:$from,to:$to,productKey:$product,operationKey:$operation){workspaceId from to scope productKey operationKey origin currency costKind operations attempts pendingAttempts knownAttempts partialAttempts unknownAttempts inputTokens{knownSubtotal knownAttempts missingAttempts} outputTokens{knownSubtotal knownAttempts missingAttempts} totalTokens{knownSubtotal knownAttempts missingAttempts} costMicroUsd{knownSubtotal knownAttempts missingAttempts}}}",
661
+ breakdown: "query SdkUsageBreakdownV2($from:DateTime!,$to:DateTime!,$groupBy:[PromptUsageDimensionV2!]!,$product:String,$operation:String,$subjectType:String,$subjectId:String,$trigger:String){promptUsageBreakdownV2(from:$from,to:$to,groupBy:$groupBy,productKey:$product,operationKey:$operation,subjectType:$subjectType,subjectId:$subjectId,trigger:$trigger){workspaceId from to scope groupBy productKey operationKey subjectType subjectId trigger origin currency costKind truncated rows{productKey providerKey modelKey operationKey trigger subjectType subjectId subjectPartId attempts pendingAttempts inputTokens{knownSubtotal knownAttempts missingAttempts} outputTokens{knownSubtotal knownAttempts missingAttempts} totalTokens{knownSubtotal knownAttempts missingAttempts} costMicroUsd{knownSubtotal knownAttempts missingAttempts}}}}"
662
+ });
663
+
664
+ // src/platform/invocation-accounting/contracts.ts
665
+ var InvocationAccountingValidationError = class extends Error {
666
+ constructor() {
667
+ super("Invalid invocation accounting contract");
668
+ this.name = "InvocationAccountingValidationError";
669
+ }
670
+ };
671
+ function requireContract(value) {
672
+ if (!value) throw new InvocationAccountingValidationError();
673
+ }
674
+ function isRecord(value) {
675
+ return value !== null && typeof value === "object" && !Array.isArray(value);
676
+ }
677
+ function fields(value, names) {
678
+ requireContract(isRecord(value));
679
+ requireContract(Object.keys(value).length === names.length && names.every((name) => Object.hasOwn(value, name)));
680
+ return value;
681
+ }
682
+ /** Every required field present; nothing outside required + optional. */
683
+ function fieldsAllowing(value, required, optional) {
684
+ requireContract(isRecord(value));
685
+ requireContract(required.every((name) => Object.hasOwn(value, name)));
686
+ requireContract(Object.keys(value).every((name) => required.includes(name) || optional.includes(name)));
687
+ return value;
688
+ }
689
+ function uuid(value) {
690
+ requireContract(typeof value === "string" && value === value.trim() && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value));
691
+ return value.toLowerCase();
692
+ }
693
+ function key(value, maximum = 128) {
694
+ requireContract(typeof value === "string" && value.length <= maximum && value === value.trim() && /^[a-zA-Z0-9][a-zA-Z0-9._:-]*$/.test(value));
695
+ return value;
696
+ }
697
+ function date(value) {
698
+ requireContract(typeof value === "string" && value.length === 24);
699
+ const parsed = new Date(value);
700
+ requireContract(Number.isFinite(parsed.getTime()) && parsed.getUTCFullYear() >= 1 && value === parsed.toISOString());
701
+ return value;
702
+ }
703
+ function fingerprint(value) {
704
+ requireContract(typeof value === "string" && value.length === 64 && /^[0-9a-f]+$/.test(value));
705
+ return value;
706
+ }
707
+ function decimal(value, maximumDigits = 19) {
708
+ requireContract(typeof value === "string" && value.length <= maximumDigits && value === value.trim() && /^(?:0|[1-9]\d*)$/.test(value));
709
+ return value;
710
+ }
711
+ function nullableCounter(value) {
712
+ if (value === null) return null;
713
+ const text = decimal(value);
714
+ requireContract(BigInt(text) <= 9223372036854775807n);
715
+ return text;
716
+ }
717
+ function validateInvocationIdentity(value) {
718
+ const row = fields(value, [
719
+ "workspaceId",
720
+ "actorId",
721
+ "actorType",
722
+ "onBehalfOf"
723
+ ]);
724
+ const actorType = row["actorType"];
725
+ requireContract(actorType === "user" || actorType === "app" || actorType === "service" || actorType === "super_admin");
726
+ return Object.freeze({
727
+ workspaceId: uuid(row["workspaceId"]),
728
+ actorId: uuid(row["actorId"]),
729
+ actorType,
730
+ onBehalfOf: row["onBehalfOf"] === null ? null : uuid(row["onBehalfOf"])
731
+ });
732
+ }
733
+ function sameIdentity(a, b) {
734
+ return a.workspaceId === b.workspaceId && a.actorId === b.actorId && a.actorType === b.actorType && a.onBehalfOf === b.onBehalfOf;
735
+ }
736
+ const ATTEMPT_FIELDS = [
737
+ "attemptKey",
738
+ "operationKey",
739
+ "productKey",
740
+ "providerKey",
741
+ "modelKey",
742
+ "startedAt"
743
+ ];
744
+ const DIMENSION_FIELDS = [
745
+ "trigger",
746
+ "subjectType",
747
+ "subjectId",
748
+ "subjectPartId",
749
+ "sequence"
750
+ ];
751
+ const TRIGGERS = [
752
+ "interactive",
753
+ "scheduled",
754
+ "event",
755
+ "api",
756
+ "webhook",
757
+ "test"
758
+ ];
759
+ function isTrigger(value) {
760
+ return typeof value === "string" && TRIGGERS.includes(value);
761
+ }
762
+ /**
763
+ * Reported dimensions only: null and absent both mean "not reported" and are
764
+ * omitted, so an attempt without dimensions keeps its original shape.
765
+ */
766
+ function attemptDimensions(row) {
767
+ const present = (name) => row[name] !== void 0 && row[name] !== null;
768
+ const trigger = row["trigger"];
769
+ const sequence = row["sequence"];
770
+ if (present("trigger")) requireContract(isTrigger(trigger));
771
+ if (present("sequence")) requireContract(typeof sequence === "number" && Number.isInteger(sequence) && sequence >= 0 && sequence <= 2147483647);
772
+ requireContract(!present("subjectId") || present("subjectType"));
773
+ requireContract(!present("subjectPartId") || present("subjectId"));
774
+ return {
775
+ ...isTrigger(trigger) ? { trigger } : {},
776
+ ...present("subjectType") ? { subjectType: key(row["subjectType"], 64) } : {},
777
+ ...present("subjectId") ? { subjectId: key(row["subjectId"]) } : {},
778
+ ...present("subjectPartId") ? { subjectPartId: key(row["subjectPartId"]) } : {},
779
+ ...typeof sequence === "number" ? { sequence } : {}
780
+ };
781
+ }
782
+ function validateInvocationAttemptInput(value) {
783
+ const row = fieldsAllowing(value, ATTEMPT_FIELDS, DIMENSION_FIELDS);
784
+ const modelKey = row["modelKey"];
785
+ requireContract(typeof modelKey === "string" && modelKey.length <= 128 && modelKey.split("/").every((segment) => {
786
+ key(segment);
787
+ return true;
788
+ }));
789
+ const product = key(row["productKey"], 64);
790
+ return Object.freeze({
791
+ attemptKey: key(row["attemptKey"]),
792
+ operationKey: key(row["operationKey"]),
793
+ productKey: productSlugVariants(product).length > 1 ? emitProductSlug(product) : product,
794
+ providerKey: key(row["providerKey"], 64),
795
+ modelKey,
796
+ startedAt: date(row["startedAt"]),
797
+ ...attemptDimensions(row)
798
+ });
799
+ }
800
+ function validateInvocationUsageInput(value) {
801
+ const row = fields(value, [
802
+ "attemptKey",
803
+ "eventKey",
804
+ "revision",
805
+ "predecessorId",
806
+ "outcome",
807
+ "inputTokens",
808
+ "outputTokens",
809
+ "cachedInputTokens",
810
+ "costMicroUsd",
811
+ "finishedAt"
812
+ ]);
813
+ const revision = row["revision"];
814
+ const outcome = row["outcome"];
815
+ requireContract(typeof revision === "number" && Number.isInteger(revision) && revision >= 1 && revision <= 2147483647);
816
+ requireContract(outcome === "succeeded" || outcome === "failed" || outcome === "blocked" || outcome === "timed_out");
817
+ const predecessorId = row["predecessorId"] === null ? null : uuid(row["predecessorId"]);
818
+ requireContract(revision === 1 === (predecessorId === null) && row["costMicroUsd"] === null);
819
+ const inputTokens = nullableCounter(row["inputTokens"]);
820
+ const outputTokens = nullableCounter(row["outputTokens"]);
821
+ const cachedInputTokens = nullableCounter(row["cachedInputTokens"]);
822
+ requireContract(cachedInputTokens === null || inputTokens !== null && BigInt(cachedInputTokens) <= BigInt(inputTokens));
823
+ return Object.freeze({
824
+ attemptKey: key(row["attemptKey"]),
825
+ eventKey: key(row["eventKey"]),
826
+ revision,
827
+ predecessorId,
828
+ outcome,
829
+ inputTokens,
830
+ outputTokens,
831
+ cachedInputTokens,
832
+ costMicroUsd: null,
833
+ finishedAt: date(row["finishedAt"])
834
+ });
835
+ }
836
+ const usageFields = [
837
+ "id",
838
+ "attemptId",
839
+ "revision",
840
+ "predecessorId",
841
+ "eventKey",
842
+ "fingerprint",
843
+ "outcome",
844
+ "inputTokens",
845
+ "outputTokens",
846
+ "totalTokens",
847
+ "cachedInputTokens",
848
+ "costMicroUsd",
849
+ "currency",
850
+ "costKind",
851
+ "pricingReference",
852
+ "origin",
853
+ "finishedAt",
854
+ "createdAt"
855
+ ];
856
+ function historyReceipt(value, attemptKey, attemptId) {
857
+ const row = fields(value, usageFields);
858
+ const input = validateInvocationUsageInput({
859
+ attemptKey,
860
+ eventKey: row["eventKey"],
861
+ revision: row["revision"],
862
+ predecessorId: row["predecessorId"],
863
+ outcome: row["outcome"],
864
+ inputTokens: row["inputTokens"],
865
+ outputTokens: row["outputTokens"],
866
+ cachedInputTokens: row["cachedInputTokens"],
867
+ costMicroUsd: null,
868
+ finishedAt: row["finishedAt"]
869
+ });
870
+ const costMicroUsd = nullableCounter(row["costMicroUsd"]);
871
+ const pricingReference = row["pricingReference"] === null ? null : key(row["pricingReference"], 255);
872
+ requireContract(costMicroUsd === null || pricingReference !== null);
873
+ const totalTokens = input.inputTokens === null || input.outputTokens === null ? null : (BigInt(input.inputTokens) + BigInt(input.outputTokens)).toString();
874
+ requireContract(row["totalTokens"] === totalTokens && row["attemptId"] === attemptId && row["origin"] === "CALLER_REPORTED" && row["currency"] === "USD" && row["costKind"] === "ESTIMATE");
875
+ return Object.freeze({
876
+ id: uuid(row["id"]),
877
+ attemptId,
878
+ revision: input.revision,
879
+ predecessorId: input.predecessorId,
880
+ eventKey: input.eventKey,
881
+ fingerprint: fingerprint(row["fingerprint"]),
882
+ outcome: input.outcome,
883
+ inputTokens: input.inputTokens,
884
+ outputTokens: input.outputTokens,
885
+ totalTokens,
886
+ cachedInputTokens: input.cachedInputTokens,
887
+ costMicroUsd,
888
+ currency: "USD",
889
+ costKind: "ESTIMATE",
890
+ pricingReference,
891
+ origin: "CALLER_REPORTED",
892
+ finishedAt: input.finishedAt,
893
+ createdAt: date(row["createdAt"])
894
+ });
895
+ }
896
+ function validateInvocationUsageReceipt(value, expected, attemptId) {
897
+ const input = validateInvocationUsageInput(expected);
898
+ const known = historyReceipt(value, input.attemptKey, uuid(attemptId));
899
+ requireContract(known.costMicroUsd === null === (known.pricingReference === null));
900
+ for (const [field, actual] of Object.entries(known)) {
901
+ if (field === "costMicroUsd") continue;
902
+ const entry = Object.entries(input).find(([name]) => name === field);
903
+ if (entry !== void 0) requireContract(entry[1] === actual);
904
+ }
905
+ return known;
906
+ }
907
+ /** Fixed validated structures only. Never a server-fingerprint recomputation. */
908
+ function sameValues(a, b) {
909
+ const left = Object.entries(a);
910
+ const right = Object.entries(b);
911
+ return left.length === right.length && left.every(([name, value]) => right.some(([other, item]) => other === name && item === value));
912
+ }
913
+ function envelope(value, field) {
914
+ requireContract(isRecord(value));
915
+ requireContract(value["errors"] === void 0 || Array.isArray(value["errors"]) && value["errors"].length === 0);
916
+ return fields(value["data"], [field])[field];
917
+ }
918
+ /** History may contain caller estimates or server prices; this SDK itself never sends a price or cost. */
919
+ function validateInvocationAttemptReceipt(value, expected, identity) {
920
+ const context = validateInvocationIdentity(identity);
921
+ const selected = validateInvocationAttemptInput(expected);
922
+ const row = fieldsAllowing(value, [
923
+ "id",
924
+ "workspaceId",
925
+ "attemptKey",
926
+ "operationKey",
927
+ "productKey",
928
+ "providerKey",
929
+ "modelKey",
930
+ "startedAt",
931
+ "createdBy",
932
+ "origin",
933
+ "fingerprint",
934
+ "createdAt",
935
+ "revisions",
936
+ "hasMoreRevisions"
937
+ ], DIMENSION_FIELDS);
938
+ const input = validateInvocationAttemptInput({
939
+ attemptKey: row["attemptKey"],
940
+ operationKey: row["operationKey"],
941
+ productKey: row["productKey"],
942
+ providerKey: row["providerKey"],
943
+ modelKey: row["modelKey"],
944
+ startedAt: row["startedAt"],
945
+ ...Object.fromEntries(DIMENSION_FIELDS.filter((name) => Object.hasOwn(row, name)).map((name) => [name, row[name]]))
946
+ });
947
+ requireContract(sameValues(input, selected) && row["workspaceId"] === context.workspaceId && row["createdBy"] === context.actorId && row["origin"] === "CALLER_REPORTED");
948
+ requireContract(Array.isArray(row["revisions"]) && row["revisions"].length <= 50 && typeof row["hasMoreRevisions"] === "boolean");
949
+ const entries = row["revisions"];
950
+ const id = uuid(row["id"]);
951
+ const revisions = entries.map((entry) => historyReceipt(entry, selected.attemptKey, id));
952
+ requireContract(new Set(revisions.map((revision) => revision.id)).size === revisions.length);
953
+ requireContract(new Set(revisions.map((revision) => revision.eventKey)).size === revisions.length);
954
+ requireContract(revisions.every((revision, index) => index === 0 || revision.revision < (revisions[index - 1]?.revision ?? 0)));
955
+ return Object.freeze({
956
+ ...input,
957
+ id,
958
+ workspaceId: context.workspaceId,
959
+ createdBy: context.actorId,
960
+ origin: "CALLER_REPORTED",
961
+ fingerprint: fingerprint(row["fingerprint"]),
962
+ createdAt: date(row["createdAt"]),
963
+ revisions: Object.freeze(revisions),
964
+ hasMoreRevisions: row["hasMoreRevisions"]
965
+ });
966
+ }
967
+
968
+ // src/platform/invocation-accounting/coordinator.ts
969
+ function parseIntent(value) {
970
+ requireContract(isRecord(value));
971
+ const kind = value["kind"];
972
+ const row = fields(value, kind === "begin" ? [
973
+ "kind",
974
+ "identity",
975
+ "key",
976
+ "input"
977
+ ] : [
978
+ "kind",
979
+ "identity",
980
+ "key",
981
+ "input",
982
+ "attempt",
983
+ "attemptId"
984
+ ]);
985
+ const identity = validateInvocationIdentity(row["identity"]);
986
+ const key = uuid(row["key"]);
987
+ if (kind === "begin") return Object.freeze({
988
+ kind,
989
+ identity,
990
+ key,
991
+ input: validateInvocationAttemptInput(row["input"])
992
+ });
993
+ requireContract(kind === "record");
994
+ const input = validateInvocationUsageInput(row["input"]);
995
+ const attempt = validateInvocationAttemptInput(row["attempt"]);
996
+ requireContract(input.attemptKey === attempt.attemptKey && input.finishedAt >= attempt.startedAt);
997
+ return Object.freeze({
998
+ kind,
999
+ identity,
1000
+ key,
1001
+ input,
1002
+ attempt,
1003
+ attemptId: uuid(row["attemptId"])
1004
+ });
1005
+ }
1006
+ function receipt(value, intent) {
1007
+ return intent.kind === "begin" ? validateInvocationAttemptReceipt(value, intent.input, intent.identity) : validateInvocationUsageReceipt(value, intent.input, intent.attemptId);
1008
+ }
1009
+ function validateInvocationDelivery(value) {
1010
+ const row = fields(value, [
1011
+ "intent",
1012
+ "version",
1013
+ "state",
1014
+ "receipt",
1015
+ "observedIds"
1016
+ ]);
1017
+ const intent = parseIntent(row["intent"]);
1018
+ const version = row["version"];
1019
+ const state = row["state"];
1020
+ requireContract(typeof version === "number" && Number.isSafeInteger(version) && version >= 0);
1021
+ requireContract(state === "UNSENT" || state === "DISPATCHED" || state === "UNKNOWN" || state === "ACKNOWLEDGED");
1022
+ requireContract(Array.isArray(row["observedIds"]) && row["observedIds"].length <= 3);
1023
+ const values = row["observedIds"];
1024
+ const observedIds = Object.freeze(values.map(uuid));
1025
+ requireContract(new Set(observedIds).size === observedIds.length);
1026
+ const known = row["receipt"] === null ? null : receipt(row["receipt"], intent);
1027
+ requireContract(state === "ACKNOWLEDGED" === (known !== null));
1028
+ requireContract(known === null || observedIds.every((id) => ids(known).includes(id)));
1029
+ return Object.freeze({
1030
+ intent,
1031
+ version,
1032
+ state,
1033
+ receipt: known,
1034
+ observedIds
1035
+ });
1036
+ }
1037
+ function sameIntent(a, b) {
1038
+ return a.kind === b.kind && a.key === b.key && sameIdentity(a.identity, b.identity) && sameValues(a.input, b.input) && (a.kind !== "record" || b.kind === "record" && a.attemptId === b.attemptId && sameValues(a.attempt, b.attempt));
1039
+ }
1040
+ function ids(value) {
1041
+ if (!isRecord(value)) return [];
1042
+ const found = [];
1043
+ for (const name of [
1044
+ "id",
1045
+ "attemptId",
1046
+ "predecessorId"
1047
+ ]) try {
1048
+ const id = uuid(value[name]);
1049
+ if (!found.includes(id)) found.push(id);
1050
+ } catch {}
1051
+ return Object.freeze(found);
1052
+ }
1053
+ const hold = (reason, observedIds = [], knownReceipt) => knownReceipt ? {
1054
+ status: "HOLD",
1055
+ reason,
1056
+ observedIds,
1057
+ knownReceipt
1058
+ } : {
1059
+ status: "HOLD",
1060
+ reason,
1061
+ observedIds
1062
+ };
1063
+ /** Opt-in delivery ONLY. No provider callback, auth helper, production store or autonomous worker. */
1064
+ var InvocationAccountingCoordinator = class {
1065
+ options;
1066
+ now;
1067
+ constructor(options) {
1068
+ this.options = options;
1069
+ this.now = options.now ?? Date.now;
1070
+ }
1071
+ async admitted(identity) {
1072
+ try {
1073
+ const admission = await this.options.admit();
1074
+ const now = this.now();
1075
+ return admission !== null && sameIdentity(validateInvocationIdentity(admission.identity), identity) && Number.isFinite(admission.expiresAt) && Number.isFinite(now) && now < admission.expiresAt;
1076
+ } catch {
1077
+ return false;
1078
+ }
1079
+ }
1080
+ async load(identity, key) {
1081
+ const row = await this.options.store.load(identity, key);
1082
+ if (row === null) return null;
1083
+ const parsed = validateInvocationDelivery(row);
1084
+ requireContract(parsed.intent.key === key && sameIdentity(parsed.intent.identity, identity));
1085
+ return parsed;
1086
+ }
1087
+ async unknown(previous, observedIds) {
1088
+ try {
1089
+ await this.options.store.compareAndSet(previous, Object.freeze({
1090
+ ...previous,
1091
+ version: previous.version + 1,
1092
+ state: "UNKNOWN",
1093
+ observedIds
1094
+ }));
1095
+ } catch {}
1096
+ }
1097
+ async acknowledge(previous, known, observedIds) {
1098
+ if (!previous.observedIds.every((id) => ids(known).includes(id))) return hold("RECEIPT", observedIds, known);
1099
+ try {
1100
+ if (!await this.options.store.compareAndSet(previous, Object.freeze({
1101
+ ...previous,
1102
+ version: previous.version + 1,
1103
+ state: "ACKNOWLEDGED",
1104
+ receipt: known,
1105
+ observedIds
1106
+ }))) return hold("STORE", observedIds, known);
1107
+ } catch {
1108
+ return hold("STORE", observedIds, known);
1109
+ }
1110
+ if (!await this.admitted(previous.intent.identity)) return hold("CONTEXT", observedIds, known);
1111
+ return {
1112
+ status: "ACKNOWLEDGED",
1113
+ receipt: known,
1114
+ observedIds
1115
+ };
1116
+ }
1117
+ async deliver(intent) {
1118
+ if (!await this.admitted(intent.identity)) return hold("CONTEXT");
1119
+ let previous;
1120
+ try {
1121
+ let existing = await this.load(intent.identity, intent.key);
1122
+ if (existing === null) {
1123
+ const initial = Object.freeze({
1124
+ intent,
1125
+ version: 0,
1126
+ state: "UNSENT",
1127
+ receipt: null,
1128
+ observedIds: Object.freeze([])
1129
+ });
1130
+ await this.options.store.create(initial);
1131
+ existing = await this.load(intent.identity, intent.key);
1132
+ }
1133
+ if (existing === null) return hold("STORE");
1134
+ if (!sameIntent(existing.intent, intent)) return hold("OCCUPIED", existing.observedIds);
1135
+ if (existing.state === "ACKNOWLEDGED" && existing.receipt !== null) return await this.admitted(intent.identity) ? {
1136
+ status: "ACKNOWLEDGED",
1137
+ receipt: existing.receipt,
1138
+ observedIds: existing.observedIds
1139
+ } : hold("CONTEXT", existing.observedIds);
1140
+ if (existing.state !== "UNSENT") return hold("UNKNOWN", existing.observedIds);
1141
+ previous = Object.freeze({
1142
+ ...existing,
1143
+ version: existing.version + 1,
1144
+ state: "DISPATCHED"
1145
+ });
1146
+ if (!await this.options.store.compareAndSet(existing, previous)) return hold("OCCUPIED", existing.observedIds);
1147
+ } catch {
1148
+ return hold("STORE");
1149
+ }
1150
+ if (!await this.admitted(intent.identity)) {
1151
+ await this.unknown(previous, []);
1152
+ return hold("CONTEXT");
1153
+ }
1154
+ let raw;
1155
+ try {
1156
+ const input = intent.kind === "record" ? Object.freeze({
1157
+ ...intent.input,
1158
+ serverPricing: true
1159
+ }) : intent.input;
1160
+ raw = await this.options.transport(PROMPTS_V2_DOCUMENTS[intent.kind], Object.freeze({ input }));
1161
+ } catch {
1162
+ await this.unknown(previous, []);
1163
+ return hold("UNKNOWN");
1164
+ }
1165
+ const field = intent.kind === "begin" ? "promptBeginInvocationAttemptV2" : "promptRecordInvocationUsageV2";
1166
+ const observedIds = ids(isRecord(raw) && isRecord(raw["data"]) ? raw["data"][field] : null);
1167
+ let known;
1168
+ try {
1169
+ known = receipt(envelope(raw, field), intent);
1170
+ } catch {
1171
+ await this.unknown(previous, observedIds);
1172
+ return hold("RECEIPT", observedIds);
1173
+ }
1174
+ return this.acknowledge(previous, known, observedIds);
1175
+ }
1176
+ async begin(identity, key, input) {
1177
+ return this.deliver(parseIntent({
1178
+ kind: "begin",
1179
+ identity,
1180
+ key,
1181
+ input
1182
+ }));
1183
+ }
1184
+ async record(identity, key, beginKey, input, predecessorKey = null) {
1185
+ const context = validateInvocationIdentity(identity);
1186
+ const observation = validateInvocationUsageInput(input);
1187
+ if (!await this.admitted(context)) return hold("CONTEXT");
1188
+ try {
1189
+ const begin = await this.load(context, uuid(beginKey));
1190
+ if (begin?.state !== "ACKNOWLEDGED" || begin.intent.kind !== "begin") return hold("UNKNOWN");
1191
+ const attempt = validateInvocationAttemptReceipt(begin.receipt, begin.intent.input, context);
1192
+ if (observation.revision > 1) {
1193
+ const previous = predecessorKey === null ? null : await this.load(context, uuid(predecessorKey));
1194
+ if (previous?.state !== "ACKNOWLEDGED" || previous.intent.kind !== "record" || previous.intent.attemptId !== attempt.id) return hold("UNKNOWN");
1195
+ const known = validateInvocationUsageReceipt(previous.receipt, previous.intent.input, attempt.id);
1196
+ if (observation.predecessorId !== known.id || observation.revision !== known.revision + 1 || observation.eventKey === known.eventKey) return hold("RECEIPT");
1197
+ } else if (predecessorKey !== null) return hold("RECEIPT");
1198
+ return await this.deliver(parseIntent({
1199
+ kind: "record",
1200
+ identity: context,
1201
+ key,
1202
+ input: observation,
1203
+ attempt: begin.intent.input,
1204
+ attemptId: attempt.id
1205
+ }));
1206
+ } catch {
1207
+ return hold("STORE");
1208
+ }
1209
+ }
1210
+ /** Explicit read-only reconciliation; no mutation retransmit, no absence proof. At most four pages. */
1211
+ async reconcile(identity, key) {
1212
+ const context = validateInvocationIdentity(identity);
1213
+ if (!await this.admitted(context)) return hold("CONTEXT");
1214
+ let previous;
1215
+ try {
1216
+ const existing = await this.load(context, uuid(key));
1217
+ if (existing === null) return hold("UNKNOWN");
1218
+ previous = existing;
1219
+ } catch {
1220
+ return hold("STORE");
1221
+ }
1222
+ if (!await this.admitted(context)) return hold("CONTEXT", previous.observedIds);
1223
+ if (previous.state === "ACKNOWLEDGED" && previous.receipt !== null) return {
1224
+ status: "ACKNOWLEDGED",
1225
+ receipt: previous.receipt,
1226
+ observedIds: previous.observedIds
1227
+ };
1228
+ if (previous.state === "UNSENT") return hold("UNKNOWN");
1229
+ const intent = previous.intent;
1230
+ if (intent.kind === "begin") return hold("HISTORY", previous.observedIds);
1231
+ const expected = intent.attempt;
1232
+ for (let page = 0; page < 4; page++) {
1233
+ if (!await this.admitted(context)) return hold("CONTEXT", previous.observedIds);
1234
+ try {
1235
+ const response = await this.options.transport(PROMPTS_V2_DOCUMENTS.read, {
1236
+ key: expected.attemptKey,
1237
+ offset: page * 50
1238
+ });
1239
+ const row = envelope(response, "promptInvocationAttemptV2");
1240
+ if (row === null) return hold("HISTORY", previous.observedIds);
1241
+ const attempt = validateInvocationAttemptReceipt(row, expected, context);
1242
+ const matches = attempt.revisions.filter((revision) => revision.eventKey === intent.input.eventKey);
1243
+ const match = matches[0];
1244
+ if (matches.length === 1 && match !== void 0) {
1245
+ const known = validateInvocationUsageReceipt(match, intent.input, intent.attemptId);
1246
+ return await this.acknowledge(previous, known, ids(known));
1247
+ }
1248
+ if (matches.length > 1 || !attempt.hasMoreRevisions) return hold("HISTORY", previous.observedIds);
1249
+ } catch {
1250
+ return hold("HISTORY", previous.observedIds);
1251
+ }
1252
+ }
1253
+ return hold("HISTORY", previous.observedIds);
1254
+ }
1255
+ };
1256
+
1257
+ // src/platform/invocation-accounting/normalizers.ts
1258
+ const MAX_COUNTER = 9223372036854775807n;
1259
+ function isObject(value) {
1260
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1261
+ }
1262
+ function object(value) {
1263
+ return isObject(value) ? value : {};
1264
+ }
1265
+ function counter(value, issue, issues) {
1266
+ if (value == null) return null;
1267
+ const text = typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? String(value) : value;
1268
+ if (typeof text !== "string" || text.length > 19 || !/^(?:0|[1-9]\d*)$/.test(text) || text !== text.trim() || BigInt(text) > MAX_COUNTER) {
1269
+ issues.push(issue);
1270
+ return null;
1271
+ }
1272
+ return text;
1273
+ }
1274
+ function model(value) {
1275
+ return typeof value === "string" && value.length > 0 && value.length <= 255 && value === value.trim() && !/[\u0000-\u001f\u007f]/.test(value) ? value : null;
1276
+ }
1277
+ /** OpenAI prompt_tokens already includes cached_tokens. Missing usage is never zero. */
1278
+ function normalizeOpenAIUsage(response) {
1279
+ const row = object(response);
1280
+ const usage = object(row["usage"]);
1281
+ const issues = [];
1282
+ const inputTokens = counter(usage["prompt_tokens"], "INPUT", issues);
1283
+ const outputTokens = counter(usage["completion_tokens"], "OUTPUT", issues);
1284
+ let cachedInputTokens = counter(object(usage["prompt_tokens_details"])["cached_tokens"], "CACHE_READ", issues);
1285
+ if (cachedInputTokens !== null && (inputTokens === null || BigInt(cachedInputTokens) > BigInt(inputTokens))) {
1286
+ issues.push("CACHE_SUBSET");
1287
+ cachedInputTokens = null;
1288
+ }
1289
+ return {
1290
+ inputTokens,
1291
+ outputTokens,
1292
+ cachedInputTokens,
1293
+ costMicroUsd: null,
1294
+ reportedModel: model(row["model"]),
1295
+ issues
1296
+ };
1297
+ }
1298
+ /** Claude's three input fields are disjoint. Missing cache components cannot be invented zero. */
1299
+ function normalizeClaudeUsage(response) {
1300
+ const row = object(response);
1301
+ const usage = object(row["usage"]);
1302
+ const issues = [];
1303
+ const uncachedInputTokens = counter(usage["input_tokens"], "INPUT", issues);
1304
+ const outputTokens = counter(usage["output_tokens"], "OUTPUT", issues);
1305
+ const cacheCreationInputTokens = counter(usage["cache_creation_input_tokens"], "CACHE_WRITE", issues);
1306
+ const cacheReadInputTokens = counter(usage["cache_read_input_tokens"], "CACHE_READ", issues);
1307
+ let inputTokens = null;
1308
+ if (uncachedInputTokens !== null && cacheCreationInputTokens !== null && cacheReadInputTokens !== null) {
1309
+ const total = BigInt(uncachedInputTokens) + BigInt(cacheCreationInputTokens) + BigInt(cacheReadInputTokens);
1310
+ if (total <= MAX_COUNTER) inputTokens = total.toString();
1311
+ else issues.push("INPUT_OVERFLOW");
1312
+ }
1313
+ return {
1314
+ inputTokens,
1315
+ outputTokens,
1316
+ cachedInputTokens: inputTokens === null ? null : cacheReadInputTokens,
1317
+ costMicroUsd: null,
1318
+ reportedModel: model(row["model"]),
1319
+ issues,
1320
+ uncachedInputTokens,
1321
+ cacheCreationInputTokens,
1322
+ cacheReadInputTokens
1323
+ };
1324
+ }
1325
+ /**
1326
+ * Merge cumulative Claude usage snapshots, NOT token deltas. A supplied invalid
1327
+ * field replaces that component with unknown; an absent field retains prior data.
1328
+ * One accumulator per provider message/attempt. No storage or stream transport.
1329
+ */
1330
+ function createClaudeUsageAccumulator() {
1331
+ let usage = {};
1332
+ let reportedModel;
1333
+ const highest = /* @__PURE__ */ new Map();
1334
+ const regressed = /* @__PURE__ */ new Set();
1335
+ return (snapshot) => {
1336
+ const row = object(snapshot);
1337
+ const incoming = object(row["usage"]);
1338
+ for (const key of [
1339
+ "input_tokens",
1340
+ "output_tokens",
1341
+ "cache_creation_input_tokens",
1342
+ "cache_read_input_tokens"
1343
+ ]) if (Object.hasOwn(incoming, key)) {
1344
+ const parsed = counter(incoming[key], "INPUT", []);
1345
+ const previous = highest.get(key);
1346
+ if (parsed !== null && previous !== void 0 && BigInt(parsed) < previous) {
1347
+ usage = {
1348
+ ...usage,
1349
+ [key]: null
1350
+ };
1351
+ regressed.add(key);
1352
+ } else {
1353
+ usage = {
1354
+ ...usage,
1355
+ [key]: incoming[key]
1356
+ };
1357
+ if (parsed !== null) {
1358
+ highest.set(key, BigInt(parsed));
1359
+ regressed.delete(key);
1360
+ }
1361
+ }
1362
+ }
1363
+ if (Object.hasOwn(row, "model")) reportedModel = row["model"];
1364
+ const result = normalizeClaudeUsage({
1365
+ model: reportedModel,
1366
+ usage
1367
+ });
1368
+ return regressed.size === 0 ? result : {
1369
+ ...result,
1370
+ issues: [...result.issues, "CUMULATIVE_REGRESSION"]
1371
+ };
1372
+ };
1373
+ }
1374
+
1375
+ // src/platform/invocation-accounting/summary.ts
1376
+ function canonicalProduct(value) {
1377
+ if (value === null) return null;
1378
+ const product = key(value, 64);
1379
+ return productSlugVariants(product).length > 1 ? emitProductSlug(product) : product;
1380
+ }
1381
+ /** Selected recorded attempts only. Does not upgrade caller reports or price estimates. */
1382
+ function validateInvocationUsageSummary(value, selection) {
1383
+ const row = fields(value, [
1384
+ "workspaceId",
1385
+ "from",
1386
+ "to",
1387
+ "productKey",
1388
+ "operationKey",
1389
+ "scope",
1390
+ "origin",
1391
+ "currency",
1392
+ "costKind",
1393
+ "attempts",
1394
+ "operations",
1395
+ "pendingAttempts",
1396
+ "knownAttempts",
1397
+ "partialAttempts",
1398
+ "unknownAttempts",
1399
+ "inputTokens",
1400
+ "outputTokens",
1401
+ "totalTokens",
1402
+ "costMicroUsd"
1403
+ ]);
1404
+ const workspaceId = uuid(selection.workspaceId);
1405
+ const from = date(selection.from), to = date(selection.to);
1406
+ requireContract(from < to && new Date(to).getTime() - new Date(from).getTime() <= 316224e5);
1407
+ const productKey = canonicalProduct(selection.productKey);
1408
+ requireContract(canonicalProduct(row["productKey"]) === productKey);
1409
+ const operationKey = selection.operationKey === null ? null : key(selection.operationKey);
1410
+ for (const [name, expected] of Object.entries({
1411
+ workspaceId,
1412
+ from,
1413
+ to,
1414
+ operationKey,
1415
+ scope: "RECORDED_V2_ATTEMPTS",
1416
+ origin: "CALLER_REPORTED",
1417
+ currency: "USD",
1418
+ costKind: "ESTIMATE"
1419
+ })) requireContract(row[name] === expected);
1420
+ const attempts = decimal(row["attempts"]), operations = decimal(row["operations"]);
1421
+ const pendingAttempts = decimal(row["pendingAttempts"]), knownAttempts = decimal(row["knownAttempts"]);
1422
+ const partialAttempts = decimal(row["partialAttempts"]), unknownAttempts = decimal(row["unknownAttempts"]);
1423
+ requireContract(BigInt(operations) <= BigInt(attempts) && BigInt(pendingAttempts) <= BigInt(unknownAttempts) && BigInt(knownAttempts) + BigInt(partialAttempts) + BigInt(unknownAttempts) === BigInt(attempts));
1424
+ const component = (value) => {
1425
+ const item = fields(value, [
1426
+ "knownSubtotal",
1427
+ "knownAttempts",
1428
+ "missingAttempts"
1429
+ ]);
1430
+ const known = decimal(item["knownAttempts"]), missing = decimal(item["missingAttempts"]);
1431
+ const subtotal = item["knownSubtotal"] === null ? null : decimal(item["knownSubtotal"], 255);
1432
+ requireContract(BigInt(known) + BigInt(missing) === BigInt(attempts) && known === "0" === (subtotal === null));
1433
+ return Object.freeze({
1434
+ knownSubtotal: subtotal,
1435
+ knownAttempts: known,
1436
+ missingAttempts: missing
1437
+ });
1438
+ };
1439
+ return Object.freeze({
1440
+ workspaceId,
1441
+ from,
1442
+ to,
1443
+ productKey,
1444
+ operationKey,
1445
+ scope: "RECORDED_V2_ATTEMPTS",
1446
+ origin: "CALLER_REPORTED",
1447
+ currency: "USD",
1448
+ costKind: "ESTIMATE",
1449
+ attempts,
1450
+ operations,
1451
+ pendingAttempts,
1452
+ knownAttempts,
1453
+ partialAttempts,
1454
+ unknownAttempts,
1455
+ inputTokens: component(row["inputTokens"]),
1456
+ outputTokens: component(row["outputTokens"]),
1457
+ totalTokens: component(row["totalTokens"]),
1458
+ costMicroUsd: component(row["costMicroUsd"])
1459
+ });
1460
+ }
1461
+
1462
+ // src/platform/index.ts
1463
+ var platform_exports = /* @__PURE__ */ __exportAll({
1464
+ CircuitBreakerOpenError: () => CircuitBreakerOpenError,
1465
+ DEFAULT_GRAPHQL_PAGE_LIMIT: () => 50,
1466
+ InvocationAccountingCoordinator: () => InvocationAccountingCoordinator,
1467
+ InvocationAccountingValidationError: () => InvocationAccountingValidationError,
1468
+ LLMRouter: () => LLMRouter,
1469
+ MAX_GRAPHQL_PAGE_LIMIT: () => 100,
1470
+ PROMPTS_V2_DOCUMENTS: () => PROMPTS_V2_DOCUMENTS,
1471
+ __resetHttpClientBreakers: () => __resetHttpClientBreakers,
1472
+ buildCacheKey: () => buildCacheKey,
1473
+ buildConnection: () => buildConnection,
1474
+ buildLoaders: () => buildLoaders,
1475
+ buildOffsetPage: () => buildOffsetPage,
1476
+ clampGraphqlLimit: () => clampGraphqlLimit,
1477
+ clampLimit: () => clampLimit,
1478
+ clampOffset: () => clampOffset,
1479
+ createClaudeUsageAccumulator: () => createClaudeUsageAccumulator,
1480
+ createHttpClient: () => createHttpClient,
1481
+ createLeaderLease: () => createLeaderLease,
1482
+ decodeCursor: () => decodeCursor,
1483
+ dropOldPartitions: () => dropOldPartitions,
1484
+ encodeCursor: () => encodeCursor,
1485
+ ensureMonthlyPartitions: () => ensureMonthlyPartitions,
1486
+ getNamespaceVersion: () => getNamespaceVersion,
1487
+ httpClient: () => httpClient,
1488
+ invalidateNamespace: () => invalidateNamespace,
1489
+ monthlyPartitionName: () => monthlyPartitionName,
1490
+ normalizeClaudeUsage: () => normalizeClaudeUsage,
1491
+ normalizeCursorPagination: () => normalizeCursorPagination,
1492
+ normalizeOffsetPagination: () => normalizeOffsetPagination,
1493
+ normalizeOpenAIUsage: () => normalizeOpenAIUsage,
1494
+ normalizeRedisUrl: () => normalizeRedisUrl,
1495
+ paginate: () => paginate,
1496
+ rateLimitIncr: () => rateLimitIncr,
1497
+ resolveReferenceLoader: () => resolveReferenceLoader,
1498
+ toPrismaPage: () => toPrismaPage,
1499
+ validateInvocationAttemptInput: () => validateInvocationAttemptInput,
1500
+ validateInvocationAttemptReceipt: () => validateInvocationAttemptReceipt,
1501
+ validateInvocationDelivery: () => validateInvocationDelivery,
1502
+ validateInvocationIdentity: () => validateInvocationIdentity,
1503
+ validateInvocationUsageInput: () => validateInvocationUsageInput,
1504
+ validateInvocationUsageReceipt: () => validateInvocationUsageReceipt,
1505
+ validateInvocationUsageSummary: () => validateInvocationUsageSummary,
1506
+ withLeaderLock: () => withLeaderLock
1507
+ });
1508
+
1509
+ export { clampOffset as A, withLeaderLock as B, resolveReferenceLoader as C, buildOffsetPage as D, buildConnection as E, paginate as F, __resetHttpClientBreakers as H, toPrismaPage as I, rateLimitIncr as L, encodeCursor as M, normalizeCursorPagination as N, clampGraphqlLimit as O, normalizeOffsetPagination as P, createLeaderLease as R, buildLoaders as S, MAX_GRAPHQL_PAGE_LIMIT as T, createHttpClient as U, CircuitBreakerOpenError as V, httpClient as W, ensureMonthlyPartitions as _, normalizeOpenAIUsage as a, getNamespaceVersion as b, InvocationAccountingValidationError as c, validateInvocationIdentity as d, validateInvocationUsageInput as f, dropOldPartitions as g, LLMRouter as h, normalizeClaudeUsage as i, decodeCursor as j, clampLimit as k, validateInvocationAttemptInput as l, PROMPTS_V2_DOCUMENTS as m, validateInvocationUsageSummary as n, InvocationAccountingCoordinator as o, validateInvocationUsageReceipt as p, createClaudeUsageAccumulator as r, validateInvocationDelivery as s, platform_exports as t, validateInvocationAttemptReceipt as u, monthlyPartitionName as v, DEFAULT_GRAPHQL_PAGE_LIMIT as w, invalidateNamespace as x, buildCacheKey as y, normalizeRedisUrl as z };
1510
+ //# sourceMappingURL=platform-DZwczW7v.js.map