@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
package/dist/index.js CHANGED
@@ -1,2612 +1,791 @@
1
- export { NAME_MAX_LENGTH, NAME_MIN_LENGTH, RbacCoverageError, USERNAME_MAX_LENGTH, USERNAME_MIN_LENGTH, validation_exports as Validation, analyzeRbacCoverage, assertRbacCoverage, lengthInCodePoints, validateName, validateUserFields, validateUsername } from './chunk-PYD44IHJ.js';
2
- export { sharing_exports as Sharing } from './chunk-554Z4C2K.js';
3
- export { tags_exports as Tags } from './chunk-PBZFAAOM.js';
4
- export { TemporalClient, TemporalClientFactory, TemporalModule, TemporalWorker, TemporalWorkerFactory, TemporalWorkerManager } from './chunk-VXVLKRU6.js';
5
- import { ActivityModule, TrackerModule } from './chunk-DRWH5XCJ.js';
6
- export { ActivityModule, ActivityOperationUnsupportedError, TrackerModule } from './chunk-DRWH5XCJ.js';
7
- import './chunk-JVMAQOA3.js';
8
- import { UsageModule } from './chunk-QVPIACWD.js';
9
- export { BillingUsageClient, UsageModule } from './chunk-QVPIACWD.js';
10
- export { middleware_exports as Middleware } from './chunk-ELU7VL3E.js';
11
- import { TenantNotificationsModule, NotificationsModule } from './chunk-KH4TRQCO.js';
12
- export { tenant_notifications_exports as Notifications, NotificationsModule } from './chunk-KH4TRQCO.js';
13
- export { observability_exports as Observability } from './chunk-VAT66FJA.js';
14
- export { platform_exports as Platform } from './chunk-HC6MPUIH.js';
15
- export { prisma_exports as Prisma } from './chunk-AXJDGQPE.js';
16
- import './chunk-E4QNLVY4.js';
17
- export { PRODUCT_RENAMES, PRODUCT_RENAME_EMIT, PRODUCT_SLUG_ALIASES, product_alias_exports as ProductAlias, RENAME_CONCERNS, billingIdVariants, emitBillingId, emitName, emitProductSlug, emitQuotaKey, emitRbacResource, emitTemplateKey, isLegacyName, isSameBillingId, isSameGraphQLName, isSameName, isSameProductSlug, isSameQuotaKey, isSameRbacResource, isSameTemplateKey, nameVariants, normalizeBillingId, normalizeGraphQLName, normalizeProductSlug, normalizeQuotaKey, normalizeRbacResource, normalizeTemplateKey, productSlugVariants, quotaKeyVariants, rbacResourceVariants, readRenamedEnv, templateKeyVariants, toCurrentName, toLegacyName } from './chunk-OBBCR6WY.js';
18
- import { RBACModule } from './chunk-A6DE32ZS.js';
19
- export { RBACModule, createRBACDirective, createRBACDirectiveForLayer, createRBACDirectiveFromEnv } from './chunk-A6DE32ZS.js';
20
- export { i18n_exports as I18n, createTranslator, getLanguage, getLocale, hasI18n, t } from './chunk-EBDHIL7V.js';
21
- export { init_exports as Init } from './chunk-HNMHPSAM.js';
22
- export { RESOURCE_CAP_DEFAULTS, ResourceCapExceededError, ResourceCapsModule, configureResourceCaps, getResourceCaps } from './chunk-63ZXJ42X.js';
23
- export { instrumentation_exports as Instrumentation } from './chunk-RYTSVGGA.js';
24
- import './chunk-GCIB76AJ.js';
25
- export { dataloader_exports as DataLoader } from './chunk-NUB5GQTU.js';
26
- export { export_exports as Export } from './chunk-VTJTAAXC.js';
27
- export { feature_flags_exports as FeatureFlags } from './chunk-UNASM5VJ.js';
28
- export { files_exports as Files } from './chunk-OXNCBE7P.js';
29
- export { gateway_exports as Gateway } from './chunk-CFXWH2IS.js';
30
- import './chunk-726AR6Q7.js';
31
- import { GatewayClient } from './chunk-SPRG6G6G.js';
32
- import './chunk-FZRODKIN.js';
33
- export { layer_exports as Layer } from './chunk-STWFX5E2.js';
34
- import './chunk-VFCMR5GX.js';
35
- import { ContextManager } from './chunk-RZOFS2BQ.js';
36
- export { ContextManager } from './chunk-RZOFS2BQ.js';
37
- import { GatewayError, GatewayErrorType } from './chunk-QWNNFE4P.js';
38
- import { GraphModule } from './chunk-OQDSAOG3.js';
39
- export { graph_exports as Graph, GraphModule } from './chunk-OQDSAOG3.js';
40
- import './chunk-PN6GIF3R.js';
41
- import { EventsModule } from './chunk-JS52ZHTK.js';
42
- export { event_queue_exports as EventQueue, EventsModule } from './chunk-JS52ZHTK.js';
43
- import './chunk-Z77BTSOK.js';
44
- import { QueueType, EventQueueFactory } from './chunk-HTLEGD3Q.js';
45
- import { resolveEventStreamsUrl } from './chunk-KS2HQCJR.js';
46
- export { graphql_exports as GraphQL } from './chunk-ZZK3WEDI.js';
47
- import './chunk-MWPYA2HD.js';
48
- import './chunk-6XEXJATV.js';
49
- export { ai_credits_exports as AiCredits } from './chunk-MESLAC5W.js';
50
- import { AuthModule } from './chunk-4XIBXZ6J.js';
51
- export { AuthModule } from './chunk-4XIBXZ6J.js';
52
- export { utils_exports as Utils } from './chunk-LA5KPWZ2.js';
53
- export { cache_exports as Cache } from './chunk-XOJORS75.js';
54
- import './chunk-A5F6Z5UE.js';
55
- import { disposeAll } from './chunk-KO2ZXZ7W.js';
56
- export { lifecycle_exports as Lifecycle, disposeAll, getRegisteredDisposableCount, registerDisposable, unregisterDisposable } from './chunk-KO2ZXZ7W.js';
57
- export { captcha_exports as Captcha, isCaptchaEnabled, verifyCaptcha, verifyCaptchaIfEnabled } from './chunk-YMZEUTD2.js';
58
- export { createInternalClient, createInternalClientForTenant, createInternalClientForWorkspaces } from './chunk-KJOSPVB2.js';
59
- export { crypto_exports as Crypto } from './chunk-SBS4S2PJ.js';
60
- import { DatabaseModule } from './chunk-ID3WR4JS.js';
61
- export { DatabaseModule } from './chunk-ID3WR4JS.js';
62
- import { APIError, NetworkError, TimeoutError, ValidationError } from './chunk-I3KOWRT3.js';
63
- export { DEFAULT_CIRCUIT_BREAKER_CONFIG, DEFAULT_GATEWAY_RETRY_CONFIG, DEFAULT_GATEWAY_ROUTING, DEFAULT_LAYER_RESOURCES, DEFAULT_LAYER_STREAMS } from './chunk-5CAFHK2Z.js';
64
- import { logger } from './chunk-RU266375.js';
65
- export { logger_exports as Logger } from './chunk-RU266375.js';
66
- import { __name } from './chunk-XE4OXN2W.js';
67
- import { GraphQLClient } from 'graphql-request';
1
+ import { t as GatewayClient } from "./client-sAJTrb4i.js";
2
+ import { a as DEFAULT_LAYER_STREAMS, i as DEFAULT_LAYER_RESOURCES, n as DEFAULT_GATEWAY_RETRY_CONFIG, r as DEFAULT_GATEWAY_ROUTING, t as DEFAULT_CIRCUIT_BREAKER_CONFIG } from "./layer-Bcix-WCl.js";
3
+ import { n as GatewayError, r as GatewayErrorType } from "./types-BYMYND1L.js";
4
+ import { APIError, NetworkError, TimeoutError } from "./types/index.js";
5
+ import { a as logger, o as logger_exports } from "./logger-B6rCpb7D.js";
6
+ import { ContextManager } from "./context/index.js";
7
+ import { t as AuthModule } from "./auth-C5ctwSLp.js";
8
+ import { c as tenant_notifications_exports, r as NotificationsModule, s as TenantNotificationsModule } from "./notifications-DY_i37WN.js";
9
+ import { a as createRBACDirectiveForLayer, i as createRBACDirective, o as createRBACDirectiveFromEnv, t as RBACModule } from "./rbac-Dvz0YzEt.js";
10
+ import { ActivityModule, ActivityOperationUnsupportedError } from "./activity/index.js";
11
+ import { a as UsageModule, c as BillingUsageClient } from "./usage-BRqVP3CJ.js";
12
+ import { t as TrackerModule } from "./tracker-PQztSlhJ.js";
13
+ import { DatabaseModule } from "./database/index.js";
14
+ import { T as EventsModule, t as event_queue_exports } from "./event-queue-Cw-YJPY_.js";
15
+ import { a as unregisterDisposable, i as registerDisposable, n as disposeAll, r as getRegisteredDisposableCount, t as lifecycle_exports } from "./lifecycle-DeoLSX0U.js";
16
+ import { n as graph_exports, t as GraphModule } from "./graph-CR7u4lpl.js";
17
+ import { l as QueueType, t as EventQueueFactory } from "./EventQueueFactory-9NGZV9jl.js";
18
+ import { SearchModule } from "./search/index.js";
19
+ import { a as resolveEventStreamsUrl } from "./env-DdaoGjIt.js";
20
+ import { TranslationModule } from "./translation/index.js";
21
+ import { PaymentsModule } from "./payments/index.js";
22
+ import { BootstrapModule, createBootstrap } from "./bootstrap/index.js";
23
+ import { createInternalClient, createInternalClientForTenant, createInternalClientForWorkspaces } from "./client/internal-client.js";
24
+ import { RESOURCE_CAP_DEFAULTS, ResourceCapExceededError, ResourceCapsModule, configureResourceCaps, getResourceCaps } from "./resource-caps/index.js";
25
+ import { t as sharing_exports } from "./sharing-CflDsSJ-.js";
26
+ import { t as tags_exports } from "./tags-CbijgoqR.js";
27
+ import { t as files_exports } from "./files-h5U-D2AF.js";
28
+ import { t as ai_credits_exports } from "./ai-credits-xxfwGpHS.js";
29
+ import { a as TemporalClient, i as TemporalWorkerManager, n as TemporalWorker, o as TemporalClientFactory, r as TemporalWorkerFactory, t as TemporalModule } from "./temporal-B534uYK8.js";
30
+ import { t as cache_exports } from "./cache-CU0uLwcS.js";
31
+ import { t as middleware_exports } from "./middleware-Cq0zFMGp.js";
32
+ import { t as observability_exports } from "./observability-DBDXipTU.js";
33
+ import { t as graphql_exports } from "./graphql-DHAHHcww.js";
34
+ import { t as prisma_exports } from "./prisma-BzOOdt79.js";
35
+ import { _ as utils_exports } from "./utils-DL85Tnbn.js";
36
+ import { a as getLanguage, c as t, i as createTranslator, o as getLocale, r as i18n_exports, s as hasI18n } from "./i18n-BBMYFd0P.js";
37
+ import { t as export_exports } from "./export-DJXE3Osa.js";
38
+ import { n as init_exports } from "./init-CQPFmOOe.js";
39
+ import { s as dataloader_exports } from "./dataloader-DwpT3YoS.js";
40
+ import { r as instrumentation_exports } from "./instrumentation-xkkmDgJ0.js";
41
+ import { a as layer_exports } from "./layer-CEKy6cm8.js";
42
+ import { t as crypto_exports } from "./crypto-DO9fM0FO.js";
43
+ import { t as gateway_exports } from "./gateway-ByVo-n37.js";
44
+ import { t as feature_flags_exports } from "./feature-flags-CP1KRgwD.js";
45
+ import { i as verifyCaptchaIfEnabled, n as isCaptchaEnabled, r as verifyCaptcha, t as captcha_exports } from "./captcha-BT7yh1YS.js";
46
+ import { t as platform_exports } from "./platform-DZwczW7v.js";
47
+ import { C as NAME_MIN_LENGTH, S as NAME_MAX_LENGTH, T as validateName, b as USERNAME_MIN_LENGTH, f as RbacCoverageError, m as assertRbacCoverage, p as analyzeRbacCoverage, t as validation_exports, v as validateUserFields, w as lengthInCodePoints, x as validateUsername, y as USERNAME_MAX_LENGTH } from "./validation-CPUITdMk.js";
48
+ import { A as rbacResourceVariants, C as normalizeProductSlug, D as productSlugVariants, E as normalizeTemplateKey, M as templateKeyVariants, N as toCurrentName, O as product_alias_exports, P as toLegacyName, S as normalizeGraphQLName, T as normalizeRbacResource, _ as isSameQuotaKey, a as billingIdVariants, b as nameVariants, c as emitProductSlug, d as emitTemplateKey, f as isLegacyName, g as isSameProductSlug, h as isSameName, i as RENAME_CONCERNS, j as readRenamedEnv, k as quotaKeyVariants, l as emitQuotaKey, m as isSameGraphQLName, n as PRODUCT_RENAME_EMIT, o as emitBillingId, p as isSameBillingId, r as PRODUCT_SLUG_ALIASES, s as emitName, t as PRODUCT_RENAMES, u as emitRbacResource, v as isSameRbacResource, w as normalizeQuotaKey, x as normalizeBillingId, y as isSameTemplateKey } from "./product-alias-BPqtskMq.js";
49
+ import { GraphQLClient } from "graphql-request";
68
50
 
51
+ // src/client/graphql.ts
69
52
  function isServiceLayer(value) {
70
- return value === "wspace" || value === "global";
53
+ return value === "wspace" || value === "global";
71
54
  }
72
- __name(isServiceLayer, "isServiceLayer");
55
+ /**
56
+ * GraphQL client wrapper with retry logic and error handling
57
+ */
73
58
  var BurdenoffGraphQLClient = class {
74
- static {
75
- __name(this, "BurdenoffGraphQLClient");
76
- }
77
- workspacesClient;
78
- /**
79
- * Cross-layer (tenant) calls go through the unified GatewayClient, which
80
- * targets the peer layer's PUBLIC gateway and mints a short-lived `service`
81
- * actor JWT (via signServiceJwt) so the gateway admits the M2M call and the
82
- * subgraph sees a trusted service context. This is the same mechanism used by
83
- * `GatewayClient.crossLayerQuery` everywhere else — kept consistent here so
84
- * tenant SDK calls (notifications, tenant lookups) authenticate identically.
85
- */
86
- tenantGateway;
87
- config;
88
- defaultContext;
89
- constructor(config, defaultContext = {}) {
90
- this.config = config;
91
- this.defaultContext = defaultContext;
92
- this.workspacesClient = new GraphQLClient(config.workspacesApiUrl, {
93
- headers: this.getHeaders(defaultContext)
94
- });
95
- if (config.tenantApiUrl) {
96
- this.tenantGateway = new GatewayClient({
97
- layer: config.serviceLayer ?? (isServiceLayer(process.env["SERVICE_LAYER"]) ? process.env["SERVICE_LAYER"] : "wspace"),
98
- serviceName: config.serviceName ?? process.env["SERVICE_NAME"] ?? "burdenoff-be-sdk",
99
- crossLayerGatewayUrl: config.tenantApiUrl,
100
- timeout: config.timeout,
101
- // Honor the SDK's retry config (same field shape) so callers that lower
102
- // maxAttempts for non-idempotent tenant mutations (e.g. notification
103
- // sends) are respected instead of falling back to the gateway default.
104
- retry: config.retry
105
- });
106
- }
107
- }
108
- /**
109
- * Get headers for GraphQL request
110
- * Includes actor context headers for RBAC authorization
111
- */
112
- getHeaders(context) {
113
- const headers = {
114
- "Content-Type": "application/json"
115
- };
116
- if (context.token) {
117
- headers["Authorization"] = `Bearer ${context.token}`;
118
- }
119
- if (context.actorId) {
120
- headers["x-actor-id"] = context.actorId;
121
- }
122
- if (context.actorType) {
123
- headers["x-actor-type"] = context.actorType;
124
- }
125
- if (context.workspaceId) {
126
- headers["x-workspace-id"] = context.workspaceId;
127
- }
128
- if (context.productId) {
129
- headers["x-product-id"] = context.productId;
130
- }
131
- return headers;
132
- }
133
- /**
134
- * Update context for future requests
135
- */
136
- updateContext(context) {
137
- this.defaultContext = {
138
- ...this.defaultContext,
139
- ...context
140
- };
141
- this.workspacesClient.setHeaders(this.getHeaders(this.defaultContext));
142
- }
143
- /**
144
- * Execute GraphQL query/mutation against workspaces API
145
- */
146
- async query(query, variables, context) {
147
- return this.executeWithRetry(() => this.executeQuery(this.workspacesClient, query, variables, context), "workspaces");
148
- }
149
- /**
150
- * Execute GraphQL query/mutation against the tenant (cross-layer) API.
151
- *
152
- * Routed through GatewayClient.crossLayerQuery: targets the peer layer's
153
- * PUBLIC gateway and mints a short-lived `service` actor JWT. Only routing
154
- * context (workspace / product) is forwarded — the end-user identity is not,
155
- * because cross-layer tenant operations are service-to-service M2M. Retry and
156
- * circuit-breaking are handled inside GatewayClient.
157
- */
158
- async tenantQuery(query, variables, context) {
159
- if (!this.tenantGateway) {
160
- throw new APIError("Tenant API URL not configured", {
161
- operation: "tenantQuery"
162
- });
163
- }
164
- const mergedContext = {
165
- ...this.defaultContext,
166
- ...context
167
- };
168
- const headers = {};
169
- if (mergedContext.workspaceId) {
170
- headers["x-workspace-id"] = mergedContext.workspaceId;
171
- }
172
- if (mergedContext.productId) {
173
- headers["x-product-id"] = mergedContext.productId;
174
- }
175
- if (mergedContext.organizationId) {
176
- headers["x-org-id"] = mergedContext.organizationId;
177
- }
178
- try {
179
- const response = await this.tenantGateway.crossLayerQuery({
180
- query,
181
- variables,
182
- headers
183
- });
184
- if (response.data == null) {
185
- throw new APIError("Tenant query returned no data", {
186
- api: "tenant"
187
- });
188
- }
189
- return response.data;
190
- } catch (error) {
191
- throw this.mapTenantError(error);
192
- }
193
- }
194
- /**
195
- * Map a GatewayClient failure back to the SDK's APIError contract so existing
196
- * tenant callers (which inspect `error.message` / extensions, e.g. "Forbidden")
197
- * keep working unchanged.
198
- */
199
- mapTenantError(error) {
200
- if (error instanceof APIError) {
201
- return error;
202
- }
203
- if (error instanceof GatewayError) {
204
- const first = error.graphqlErrors?.[0];
205
- if (first) {
206
- return new APIError(first.message, {
207
- graphqlErrors: error.graphqlErrors,
208
- extensions: first.extensions
209
- });
210
- }
211
- if (error.type === GatewayErrorType.NETWORK_ERROR) {
212
- return new NetworkError(error.message, {
213
- gatewayErrorType: error.type
214
- });
215
- }
216
- if (error.type === GatewayErrorType.TIMEOUT_ERROR) {
217
- return new TimeoutError(error.message, {
218
- gatewayErrorType: error.type
219
- });
220
- }
221
- return new APIError(error.message, {
222
- gatewayErrorType: error.type
223
- });
224
- }
225
- return this.handleError(error);
226
- }
227
- /**
228
- * Execute GraphQL request
229
- */
230
- async executeQuery(client, query, variables, context) {
231
- try {
232
- if (!context) {
233
- return await client.request(query, variables);
234
- }
235
- const mergedContext = {
236
- ...this.defaultContext,
237
- ...context
238
- };
239
- return await client.request({
240
- document: query,
241
- variables,
242
- requestHeaders: this.getHeaders(mergedContext)
243
- });
244
- } catch (error) {
245
- throw this.handleError(error);
246
- }
247
- }
248
- /**
249
- * Execute with retry logic
250
- */
251
- async executeWithRetry(operation, api) {
252
- const maxAttempts = this.config.retry?.maxAttempts || 3;
253
- const initialDelay = this.config.retry?.initialDelay || 1e3;
254
- const maxDelay = this.config.retry?.maxDelay || 1e4;
255
- const backoffMultiplier = this.config.retry?.backoffMultiplier || 2;
256
- let lastError;
257
- let delay = initialDelay;
258
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
259
- try {
260
- return await operation();
261
- } catch (error) {
262
- lastError = error;
263
- if (error instanceof APIError && !this.shouldRetry(error)) {
264
- throw error;
265
- }
266
- if (attempt === maxAttempts) {
267
- break;
268
- }
269
- await this.sleep(Math.min(delay, maxDelay));
270
- delay *= backoffMultiplier;
271
- }
272
- }
273
- throw new APIError(`GraphQL request failed after ${maxAttempts} attempts`, {
274
- api,
275
- lastError: lastError?.message
276
- });
277
- }
278
- /**
279
- * Determine if error should be retried
280
- */
281
- shouldRetry(error) {
282
- if (error instanceof NetworkError || error instanceof TimeoutError) {
283
- return true;
284
- }
285
- if (error.code === "SERVER_ERROR") {
286
- return true;
287
- }
288
- return false;
289
- }
290
- /**
291
- * Handle GraphQL errors
292
- */
293
- handleError(error) {
294
- if (error instanceof Error) {
295
- if (error.message.includes("fetch failed") || error.message.includes("ECONNREFUSED")) {
296
- return new NetworkError("Network error while connecting to API", {
297
- originalError: error.message
298
- });
299
- }
300
- if (error.message.includes("timeout") || error.message.includes("ETIMEDOUT")) {
301
- return new TimeoutError("Request timed out", {
302
- originalError: error.message
303
- });
304
- }
305
- if ("response" in error && error.response) {
306
- const response = error.response;
307
- if (response.errors && response.errors.length > 0) {
308
- const firstError = response.errors[0];
309
- if (firstError) {
310
- return new APIError(firstError.message, {
311
- graphqlErrors: response.errors,
312
- extensions: firstError.extensions
313
- });
314
- }
315
- }
316
- }
317
- return new APIError(error.message, {
318
- originalError: error.message
319
- });
320
- }
321
- return new APIError("Unknown error occurred", {
322
- error: String(error)
323
- });
324
- }
325
- /**
326
- * Sleep utility for retry delays
327
- */
328
- sleep(ms) {
329
- return new Promise((resolve) => setTimeout(resolve, ms));
330
- }
331
- /**
332
- * Get current context
333
- */
334
- getContext() {
335
- return {
336
- ...this.defaultContext
337
- };
338
- }
339
- };
340
-
341
- // src/search/index.ts
342
- var SearchModule = class {
343
- static {
344
- __name(this, "SearchModule");
345
- }
346
- client;
347
- context;
348
- constructor(client, context) {
349
- this.client = client;
350
- this.context = context;
351
- }
352
- /**
353
- * Search across all resources
354
- */
355
- async search(options) {
356
- if (!options.query || options.query.trim().length === 0) {
357
- throw new ValidationError("Search query is required");
358
- }
359
- logger.debug("[Search] Searching", {
360
- query: options.query,
361
- resourceTypes: options.resourceTypes
362
- });
363
- const query = `
364
- query Search($input: SearchInput!) {
365
- search(input: $input) {
366
- results {
367
- id
368
- type
369
- title
370
- description
371
- data
372
- workspaceId
373
- organizationId
374
- projectId
375
- score
376
- highlights
377
- createdAt
378
- updatedAt
379
- }
380
- total
381
- took
382
- aggregations
383
- }
384
- }
385
- `;
386
- const variables = {
387
- input: {
388
- query: options.query,
389
- resourceTypes: options.resourceTypes,
390
- workspaceId: options.workspaceId || this.context.workspaceId,
391
- organizationId: options.organizationId,
392
- projectId: options.projectId || this.context.projectId,
393
- fields: options.fields,
394
- fuzziness: options.fuzziness || 0.8,
395
- boosts: options.boosts,
396
- filters: options.filters,
397
- sort: options.sort,
398
- limit: options.limit || 20,
399
- offset: options.offset || 0,
400
- highlight: options.highlight !== false
401
- }
402
- };
403
- const response = await this.client.query(query, variables, this.context);
404
- logger.info("[Search] Search completed", {
405
- total: response.search.total,
406
- took: response.search.took
407
- });
408
- return response.search;
409
- }
410
- /**
411
- * Index document for search
412
- */
413
- async indexDocument(options) {
414
- if (!options.id) {
415
- throw new ValidationError("Document ID is required");
416
- }
417
- if (!options.type) {
418
- throw new ValidationError("Document type is required");
419
- }
420
- if (!options.title) {
421
- throw new ValidationError("Document title is required");
422
- }
423
- logger.debug("[Search] Indexing document", {
424
- id: options.id,
425
- type: options.type
426
- });
427
- const mutation = `
428
- mutation IndexDocument($input: IndexDocumentInput!) {
429
- indexDocument(input: $input) {
430
- id
431
- indexed
432
- }
433
- }
434
- `;
435
- const variables = {
436
- input: {
437
- id: options.id,
438
- type: options.type,
439
- title: options.title,
440
- description: options.description,
441
- content: options.content,
442
- data: options.data,
443
- workspaceId: options.workspaceId || this.context.workspaceId,
444
- organizationId: options.organizationId,
445
- projectId: options.projectId || this.context.projectId,
446
- tags: options.tags,
447
- metadata: options.metadata
448
- }
449
- };
450
- const response = await this.client.query(mutation, variables, this.context);
451
- logger.info("[Search] Document indexed", {
452
- id: response.indexDocument.id
453
- });
454
- return response.indexDocument;
455
- }
456
- /**
457
- * Remove document from search index
458
- */
459
- async removeDocument(id, type) {
460
- logger.debug("[Search] Removing document", {
461
- id,
462
- type
463
- });
464
- const mutation = `
465
- mutation RemoveDocument($id: ID!, $type: String!) {
466
- removeDocument(id: $id, type: $type) {
467
- success
468
- }
469
- }
470
- `;
471
- await this.client.query(mutation, {
472
- id,
473
- type
474
- }, this.context);
475
- logger.info("[Search] Document removed", {
476
- id
477
- });
478
- return true;
479
- }
480
- /**
481
- * Update document in search index
482
- */
483
- async updateDocument(id, type, updates) {
484
- logger.debug("[Search] Updating document", {
485
- id,
486
- type
487
- });
488
- const mutation = `
489
- mutation UpdateDocument($id: ID!, $type: String!, $updates: JSON!) {
490
- updateDocument(id: $id, type: $type, updates: $updates) {
491
- id
492
- updated
493
- }
494
- }
495
- `;
496
- const response = await this.client.query(mutation, {
497
- id,
498
- type,
499
- updates
500
- }, this.context);
501
- logger.info("[Search] Document updated", {
502
- id
503
- });
504
- return response.updateDocument;
505
- }
506
- /**
507
- * Bulk index documents
508
- */
509
- async indexDocumentsBulk(documents) {
510
- logger.debug("[Search] Bulk indexing documents", {
511
- count: documents.length
512
- });
513
- const mutation = `
514
- mutation IndexDocumentsBulk($documents: [IndexDocumentInput!]!) {
515
- indexDocumentsBulk(documents: $documents) {
516
- indexed
517
- failed
518
- errors
519
- }
520
- }
521
- `;
522
- const response = await this.client.query(mutation, {
523
- documents
524
- }, this.context);
525
- logger.info("[Search] Bulk indexing completed", {
526
- indexed: response.indexDocumentsBulk.indexed,
527
- failed: response.indexDocumentsBulk.failed
528
- });
529
- return response.indexDocumentsBulk;
530
- }
531
- /**
532
- * Get search suggestions (autocomplete)
533
- */
534
- async suggest(prefix, options) {
535
- if (!prefix || prefix.trim().length === 0) {
536
- throw new ValidationError("Prefix is required for suggestions");
537
- }
538
- logger.debug("[Search] Getting suggestions", {
539
- prefix
540
- });
541
- const query = `
542
- query GetSuggestions($prefix: String!, $resourceTypes: [String!], $limit: Int) {
543
- getSuggestions(prefix: $prefix, resourceTypes: $resourceTypes, limit: $limit) {
544
- text
545
- score
546
- type
547
- }
548
- }
549
- `;
550
- const response = await this.client.query(query, {
551
- prefix,
552
- resourceTypes: options?.resourceTypes,
553
- limit: options?.limit || 10
554
- }, this.context);
555
- return response.getSuggestions;
556
- }
557
- /**
558
- * Get related documents
559
- */
560
- async getRelated(documentId, options) {
561
- logger.debug("[Search] Getting related documents", {
562
- documentId
563
- });
564
- const query = `
565
- query GetRelatedDocuments($documentId: ID!, $limit: Int, $minScore: Float) {
566
- getRelatedDocuments(documentId: $documentId, limit: $limit, minScore: $minScore) {
567
- id
568
- type
569
- title
570
- description
571
- data
572
- score
573
- createdAt
574
- updatedAt
575
- }
576
- }
577
- `;
578
- const response = await this.client.query(query, {
579
- documentId,
580
- limit: options?.limit || 10,
581
- minScore: options?.minScore || 0.5
582
- }, this.context);
583
- return response.getRelatedDocuments;
584
- }
585
- /**
586
- * Get search aggregations
587
- */
588
- async aggregate(query, aggregations) {
589
- logger.debug("[Search] Getting aggregations", {
590
- query
591
- });
592
- const gqlQuery = `
593
- query GetAggregations($query: String!, $aggregations: [AggregationInput!]!) {
594
- getAggregations(query: $query, aggregations: $aggregations) {
595
- aggregations
596
- }
597
- }
598
- `;
599
- const response = await this.client.query(gqlQuery, {
600
- query,
601
- aggregations
602
- }, this.context);
603
- return response.getAggregations.aggregations;
604
- }
605
- /**
606
- * Clear search index for workspace
607
- */
608
- async clearIndex(workspaceId) {
609
- logger.debug("[Search] Clearing index", {
610
- workspaceId
611
- });
612
- const mutation = `
613
- mutation ClearSearchIndex($workspaceId: ID) {
614
- clearSearchIndex(workspaceId: $workspaceId) {
615
- deletedCount
616
- }
617
- }
618
- `;
619
- const response = await this.client.query(mutation, {
620
- workspaceId: workspaceId || this.context.workspaceId
621
- }, this.context);
622
- logger.info("[Search] Index cleared", {
623
- deletedCount: response.clearSearchIndex.deletedCount
624
- });
625
- return response.clearSearchIndex;
626
- }
627
- /**
628
- * Reindex all documents
629
- */
630
- async reindex(options) {
631
- logger.debug("[Search] Reindexing", options);
632
- const mutation = `
633
- mutation ReindexDocuments($workspaceId: ID, $resourceTypes: [String!]) {
634
- reindexDocuments(workspaceId: $workspaceId, resourceTypes: $resourceTypes) {
635
- indexed
636
- failed
637
- }
638
- }
639
- `;
640
- const response = await this.client.query(mutation, {
641
- workspaceId: options?.workspaceId || this.context.workspaceId,
642
- resourceTypes: options?.resourceTypes
643
- }, this.context);
644
- logger.info("[Search] Reindexing completed", response.reindexDocuments);
645
- return response.reindexDocuments;
646
- }
59
+ workspacesClient;
60
+ /**
61
+ * Cross-layer (tenant) calls go through the unified GatewayClient, which
62
+ * targets the peer layer's PUBLIC gateway and mints a short-lived `service`
63
+ * actor JWT (via signServiceJwt) so the gateway admits the M2M call and the
64
+ * subgraph sees a trusted service context. This is the same mechanism used by
65
+ * `GatewayClient.crossLayerQuery` everywhere else — kept consistent here so
66
+ * tenant SDK calls (notifications, tenant lookups) authenticate identically.
67
+ */
68
+ tenantGateway;
69
+ config;
70
+ defaultContext;
71
+ constructor(config, defaultContext = {}) {
72
+ this.config = config;
73
+ this.defaultContext = defaultContext;
74
+ this.workspacesClient = new GraphQLClient(config.workspacesApiUrl, { headers: this.getHeaders(defaultContext) });
75
+ if (config.tenantApiUrl) this.tenantGateway = new GatewayClient({
76
+ layer: config.serviceLayer ?? (isServiceLayer(process.env["SERVICE_LAYER"]) ? process.env["SERVICE_LAYER"] : "wspace"),
77
+ serviceName: config.serviceName ?? process.env["SERVICE_NAME"] ?? "burdenoff-be-sdk",
78
+ crossLayerGatewayUrl: config.tenantApiUrl,
79
+ timeout: config.timeout,
80
+ retry: config.retry
81
+ });
82
+ }
83
+ /**
84
+ * Get headers for GraphQL request
85
+ * Includes actor context headers for RBAC authorization
86
+ */
87
+ getHeaders(context) {
88
+ const headers = { "Content-Type": "application/json" };
89
+ if (context.token) headers["Authorization"] = `Bearer ${context.token}`;
90
+ if (context.actorId) headers["x-actor-id"] = context.actorId;
91
+ if (context.actorType) headers["x-actor-type"] = context.actorType;
92
+ if (context.workspaceId) headers["x-workspace-id"] = context.workspaceId;
93
+ if (context.productId) headers["x-product-id"] = context.productId;
94
+ return headers;
95
+ }
96
+ /**
97
+ * Update context for future requests
98
+ */
99
+ updateContext(context) {
100
+ this.defaultContext = {
101
+ ...this.defaultContext,
102
+ ...context
103
+ };
104
+ this.workspacesClient.setHeaders(this.getHeaders(this.defaultContext));
105
+ }
106
+ /**
107
+ * Execute GraphQL query/mutation against workspaces API
108
+ */
109
+ async query(query, variables, context) {
110
+ return this.executeWithRetry(() => this.executeQuery(this.workspacesClient, query, variables, context), "workspaces");
111
+ }
112
+ /**
113
+ * Execute GraphQL query/mutation against the tenant (cross-layer) API.
114
+ *
115
+ * Routed through GatewayClient.crossLayerQuery: targets the peer layer's
116
+ * PUBLIC gateway and mints a short-lived `service` actor JWT. Only routing
117
+ * context (workspace / product) is forwarded — the end-user identity is not,
118
+ * because cross-layer tenant operations are service-to-service M2M. Retry and
119
+ * circuit-breaking are handled inside GatewayClient.
120
+ */
121
+ async tenantQuery(query, variables, context) {
122
+ if (!this.tenantGateway) throw new APIError("Tenant API URL not configured", { operation: "tenantQuery" });
123
+ const mergedContext = {
124
+ ...this.defaultContext,
125
+ ...context
126
+ };
127
+ const headers = {};
128
+ if (mergedContext.workspaceId) headers["x-workspace-id"] = mergedContext.workspaceId;
129
+ if (mergedContext.productId) headers["x-product-id"] = mergedContext.productId;
130
+ if (mergedContext.organizationId) headers["x-org-id"] = mergedContext.organizationId;
131
+ try {
132
+ const response = await this.tenantGateway.crossLayerQuery({
133
+ query,
134
+ variables,
135
+ headers
136
+ });
137
+ if (response.data == null) throw new APIError("Tenant query returned no data", { api: "tenant" });
138
+ return response.data;
139
+ } catch (error) {
140
+ throw this.mapTenantError(error);
141
+ }
142
+ }
143
+ /**
144
+ * Map a GatewayClient failure back to the SDK's APIError contract so existing
145
+ * tenant callers (which inspect `error.message` / extensions, e.g. "Forbidden")
146
+ * keep working unchanged.
147
+ */
148
+ mapTenantError(error) {
149
+ if (error instanceof APIError) return error;
150
+ if (error instanceof GatewayError) {
151
+ const first = error.graphqlErrors?.[0];
152
+ if (first) return new APIError(first.message, {
153
+ graphqlErrors: error.graphqlErrors,
154
+ extensions: first.extensions
155
+ });
156
+ if (error.type === "NETWORK_ERROR") return new NetworkError(error.message, { gatewayErrorType: error.type });
157
+ if (error.type === "TIMEOUT_ERROR") return new TimeoutError(error.message, { gatewayErrorType: error.type });
158
+ return new APIError(error.message, { gatewayErrorType: error.type });
159
+ }
160
+ return this.handleError(error);
161
+ }
162
+ /**
163
+ * Execute GraphQL request
164
+ */
165
+ async executeQuery(client, query, variables, context) {
166
+ try {
167
+ if (!context) return await client.request(query, variables);
168
+ const mergedContext = {
169
+ ...this.defaultContext,
170
+ ...context
171
+ };
172
+ return await client.request({
173
+ document: query,
174
+ variables,
175
+ requestHeaders: this.getHeaders(mergedContext)
176
+ });
177
+ } catch (error) {
178
+ throw this.handleError(error);
179
+ }
180
+ }
181
+ /**
182
+ * Execute with retry logic
183
+ */
184
+ async executeWithRetry(operation, api) {
185
+ const maxAttempts = this.config.retry?.maxAttempts || 3;
186
+ const initialDelay = this.config.retry?.initialDelay || 1e3;
187
+ const maxDelay = this.config.retry?.maxDelay || 1e4;
188
+ const backoffMultiplier = this.config.retry?.backoffMultiplier || 2;
189
+ let lastError;
190
+ let delay = initialDelay;
191
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) try {
192
+ return await operation();
193
+ } catch (error) {
194
+ lastError = error;
195
+ if (error instanceof APIError && !this.shouldRetry(error)) throw error;
196
+ if (attempt === maxAttempts) break;
197
+ await this.sleep(Math.min(delay, maxDelay));
198
+ delay *= backoffMultiplier;
199
+ }
200
+ throw new APIError(`GraphQL request failed after ${maxAttempts} attempts`, {
201
+ api,
202
+ lastError: lastError?.message
203
+ });
204
+ }
205
+ /**
206
+ * Determine if error should be retried
207
+ */
208
+ shouldRetry(error) {
209
+ if (error instanceof NetworkError || error instanceof TimeoutError) return true;
210
+ if (error.code === "SERVER_ERROR") return true;
211
+ return false;
212
+ }
213
+ /**
214
+ * Handle GraphQL errors
215
+ */
216
+ handleError(error) {
217
+ if (error instanceof Error) {
218
+ if (error.message.includes("fetch failed") || error.message.includes("ECONNREFUSED")) return new NetworkError("Network error while connecting to API", { originalError: error.message });
219
+ if (error.message.includes("timeout") || error.message.includes("ETIMEDOUT")) return new TimeoutError("Request timed out", { originalError: error.message });
220
+ if ("response" in error && error.response) {
221
+ const response = error.response;
222
+ if (response.errors && response.errors.length > 0) {
223
+ const firstError = response.errors[0];
224
+ if (firstError) return new APIError(firstError.message, {
225
+ graphqlErrors: response.errors,
226
+ extensions: firstError.extensions
227
+ });
228
+ }
229
+ }
230
+ return new APIError(error.message, { originalError: error.message });
231
+ }
232
+ return new APIError("Unknown error occurred", { error: String(error) });
233
+ }
234
+ /**
235
+ * Sleep utility for retry delays
236
+ */
237
+ sleep(ms) {
238
+ return new Promise((resolve) => setTimeout(resolve, ms));
239
+ }
240
+ /**
241
+ * Get current context
242
+ */
243
+ getContext() {
244
+ return { ...this.defaultContext };
245
+ }
647
246
  };
648
247
 
649
- // src/translation/index.ts
650
- var TranslationModule = class {
651
- static {
652
- __name(this, "TranslationModule");
653
- }
654
- client;
655
- context;
656
- constructor(client, context) {
657
- this.client = client;
658
- this.context = context;
659
- }
660
- /**
661
- * Translate text
662
- */
663
- async translate(options) {
664
- if (!options.text || options.text.trim().length === 0) {
665
- throw new ValidationError("Text to translate is required");
666
- }
667
- if (!options.targetLanguage) {
668
- throw new ValidationError("Target language is required");
669
- }
670
- logger.debug("[Translation] Translating text", {
671
- sourceLanguage: options.sourceLanguage || "auto",
672
- targetLanguage: options.targetLanguage,
673
- textLength: options.text.length
674
- });
675
- const query = `
676
- query Translate($input: TranslateInput!) {
677
- translate(input: $input) {
678
- original
679
- translated
680
- sourceLanguage
681
- targetLanguage
682
- confidence
683
- }
684
- }
685
- `;
686
- const variables = {
687
- input: {
688
- text: options.text,
689
- sourceLanguage: options.sourceLanguage,
690
- targetLanguage: options.targetLanguage,
691
- context: options.context
692
- }
693
- };
694
- const response = await this.client.query(query, variables, this.context);
695
- let translated = response.translate.translated;
696
- if (options.variables) {
697
- translated = this.interpolate(translated, options.variables);
698
- }
699
- logger.info("[Translation] Text translated", {
700
- sourceLanguage: response.translate.sourceLanguage,
701
- targetLanguage: response.translate.targetLanguage
702
- });
703
- return {
704
- ...response.translate,
705
- translated
706
- };
707
- }
708
- /**
709
- * Get translations for keys
710
- */
711
- async getTranslations(options) {
712
- if (!options.keys || options.keys.length === 0) {
713
- throw new ValidationError("Translation keys are required");
714
- }
715
- if (!options.language) {
716
- throw new ValidationError("Language is required");
717
- }
718
- logger.debug("[Translation] Getting translations", {
719
- language: options.language,
720
- count: options.keys.length
721
- });
722
- const query = `
723
- query GetTranslations(
724
- $keys: [String!]!
725
- $language: String!
726
- $namespace: String
727
- $fallbackLanguage: String
728
- ) {
729
- getTranslations(
730
- keys: $keys
731
- language: $language
732
- namespace: $namespace
733
- fallbackLanguage: $fallbackLanguage
734
- ) {
735
- translations
736
- }
737
- }
738
- `;
739
- const response = await this.client.query(query, {
740
- keys: options.keys,
741
- language: options.language,
742
- namespace: options.namespace,
743
- fallbackLanguage: options.fallbackLanguage || "en"
744
- }, this.context);
745
- return response.getTranslations.translations;
746
- }
747
- /**
748
- * Get single translation
749
- */
750
- async get(key, language, variables) {
751
- const translations = await this.getTranslations({
752
- keys: [
753
- key
754
- ],
755
- language
756
- });
757
- let translation = translations[key] || key;
758
- if (variables) {
759
- translation = this.interpolate(translation, variables);
760
- }
761
- return translation;
762
- }
763
- /**
764
- * Set translation
765
- */
766
- async setTranslation(options) {
767
- if (!options.key) {
768
- throw new ValidationError("Translation key is required");
769
- }
770
- if (!options.value) {
771
- throw new ValidationError("Translation value is required");
772
- }
773
- if (!options.language) {
774
- throw new ValidationError("Language is required");
775
- }
776
- logger.debug("[Translation] Setting translation", {
777
- key: options.key,
778
- language: options.language
779
- });
780
- const mutation = `
781
- mutation SetTranslation($input: SetTranslationInput!) {
782
- setTranslation(input: $input) {
783
- key
784
- value
785
- language
786
- namespace
787
- description
788
- variables
789
- }
790
- }
791
- `;
792
- const variables = {
793
- input: {
794
- key: options.key,
795
- value: options.value,
796
- language: options.language,
797
- namespace: options.namespace,
798
- description: options.description,
799
- variables: options.variables
800
- }
801
- };
802
- const response = await this.client.query(mutation, variables, this.context);
803
- logger.info("[Translation] Translation set", {
804
- key: options.key,
805
- language: options.language
806
- });
807
- return response.setTranslation;
808
- }
809
- /**
810
- * Delete translation
811
- */
812
- async deleteTranslation(key, language, namespace) {
813
- logger.debug("[Translation] Deleting translation", {
814
- key,
815
- language
816
- });
817
- const mutation = `
818
- mutation DeleteTranslation($key: String!, $language: String!, $namespace: String) {
819
- deleteTranslation(key: $key, language: $language, namespace: $namespace) {
820
- success
821
- }
822
- }
823
- `;
824
- await this.client.query(mutation, {
825
- key,
826
- language,
827
- namespace
828
- }, this.context);
829
- logger.info("[Translation] Translation deleted", {
830
- key,
831
- language
832
- });
833
- return true;
834
- }
835
- /**
836
- * Batch set translations
837
- */
838
- async setTranslationsBatch(translations) {
839
- logger.debug("[Translation] Batch setting translations", {
840
- count: translations.length
841
- });
842
- const mutation = `
843
- mutation SetTranslationsBatch($translations: [SetTranslationInput!]!) {
844
- setTranslationsBatch(translations: $translations) {
845
- key
846
- value
847
- language
848
- namespace
849
- description
850
- variables
851
- }
852
- }
853
- `;
854
- const response = await this.client.query(mutation, {
855
- translations
856
- }, this.context);
857
- logger.info("[Translation] Batch translations set", {
858
- count: response.setTranslationsBatch.length
859
- });
860
- return response.setTranslationsBatch;
861
- }
862
- /**
863
- * Get all translations for language
864
- */
865
- async getAllTranslations(language, namespace) {
866
- logger.debug("[Translation] Getting all translations", {
867
- language,
868
- namespace
869
- });
870
- const query = `
871
- query GetAllTranslations($language: String!, $namespace: String) {
872
- getAllTranslations(language: $language, namespace: $namespace) {
873
- key
874
- value
875
- language
876
- namespace
877
- description
878
- variables
879
- }
880
- }
881
- `;
882
- const response = await this.client.query(query, {
883
- language,
884
- namespace
885
- }, this.context);
886
- return response.getAllTranslations;
887
- }
888
- /**
889
- * Detect language
890
- */
891
- async detectLanguage(text) {
892
- if (!text || text.trim().length === 0) {
893
- throw new ValidationError("Text is required for language detection");
894
- }
895
- logger.debug("[Translation] Detecting language");
896
- const query = `
897
- query DetectLanguage($text: String!) {
898
- detectLanguage(text: $text) {
899
- language
900
- confidence
901
- }
902
- }
903
- `;
904
- const response = await this.client.query(query, {
905
- text
906
- }, this.context);
907
- return response.detectLanguage;
908
- }
909
- /**
910
- * Get supported languages
911
- */
912
- async getSupportedLanguages() {
913
- logger.debug("[Translation] Getting supported languages");
914
- const query = `
915
- query GetSupportedLanguages {
916
- getSupportedLanguages {
917
- code
918
- name
919
- nativeName
920
- }
921
- }
922
- `;
923
- const response = await this.client.query(query, {}, this.context);
924
- return response.getSupportedLanguages;
925
- }
926
- /**
927
- * Import translations from file
928
- */
929
- async importTranslations(language, translations, namespace) {
930
- logger.debug("[Translation] Importing translations", {
931
- language,
932
- count: Object.keys(translations).length
933
- });
934
- const mutation = `
935
- mutation ImportTranslations($language: String!, $translations: JSON!, $namespace: String) {
936
- importTranslations(language: $language, translations: $translations, namespace: $namespace) {
937
- imported
938
- failed
939
- }
940
- }
941
- `;
942
- const response = await this.client.query(mutation, {
943
- language,
944
- translations,
945
- namespace
946
- }, this.context);
947
- logger.info("[Translation] Translations imported", response.importTranslations);
948
- return response.importTranslations;
949
- }
950
- /**
951
- * Export translations to JSON
952
- */
953
- async exportTranslations(language, namespace) {
954
- logger.debug("[Translation] Exporting translations", {
955
- language,
956
- namespace
957
- });
958
- const query = `
959
- query ExportTranslations($language: String!, $namespace: String) {
960
- exportTranslations(language: $language, namespace: $namespace) {
961
- translations
962
- }
963
- }
964
- `;
965
- const response = await this.client.query(query, {
966
- language,
967
- namespace
968
- }, this.context);
969
- logger.info("[Translation] Translations exported", {
970
- language,
971
- count: Object.keys(response.exportTranslations.translations).length
972
- });
973
- return response.exportTranslations.translations;
974
- }
975
- /**
976
- * Export product translations from global i18n service (federated schema).
977
- *
978
- * This uses the modern i18n GraphQL contract:
979
- * - i18nProductByName
980
- * - exportTranslations(productId, languageCode, format)
981
- */
982
- async exportProductTranslations(options) {
983
- const productId = await this.resolveProductId(options.productId, options.productName);
984
- const languageCode = options.languageCode ?? "en";
985
- const format = options.format ?? "JSON";
986
- const query = `
987
- query ExportProductTranslations(
988
- $productId: String!
989
- $languageCode: String!
990
- $format: ImportJobFormat!
991
- ) {
992
- exportTranslations(productId: $productId, languageCode: $languageCode, format: $format) {
993
- format
994
- url
995
- }
996
- }
997
- `;
998
- const response = await this.client.query(query, {
999
- productId,
1000
- languageCode,
1001
- format
1002
- }, this.context);
1003
- const result = {
1004
- format: response.exportTranslations.format,
1005
- url: response.exportTranslations.url
1006
- };
1007
- if ((options.decodeJson ?? true) && format === "JSON") {
1008
- result.translations = this.decodeDataUrlJson(response.exportTranslations.url);
1009
- }
1010
- return result;
1011
- }
1012
- /**
1013
- * Upsert product translations in global i18n service.
1014
- *
1015
- * Behavior:
1016
- * - Ensures translation keys exist (create if missing)
1017
- * - Optionally updates translation key defaultValue
1018
- * - Creates/updates language translation entries
1019
- * - Optionally publishes translations
1020
- */
1021
- async upsertProductTranslations(options) {
1022
- if (!options.languageCode) {
1023
- throw new ValidationError("languageCode is required");
1024
- }
1025
- const flatTranslations = this.flattenTranslationTree(options.translations);
1026
- if (Object.keys(flatTranslations).length === 0) {
1027
- throw new ValidationError("translations cannot be empty");
1028
- }
1029
- const flatDefaults = options.defaultValues ? this.flattenTranslationTree(options.defaultValues) : flatTranslations;
1030
- const productId = await this.resolveProductId(options.productId, options.productName);
1031
- const publish = options.publish ?? true;
1032
- const updateExisting = options.updateExisting ?? true;
1033
- const result = {
1034
- productId,
1035
- languageCode: options.languageCode,
1036
- keysProcessed: 0,
1037
- createdKeys: 0,
1038
- updatedKeyDefaults: 0,
1039
- createdTranslations: 0,
1040
- updatedTranslations: 0
1041
- };
1042
- const entries = Object.entries(flatTranslations);
1043
- const existingKeysMap = /* @__PURE__ */ new Map();
1044
- for (const [key] of entries) {
1045
- const keyRow = await this.findTranslationKeyByKey(productId, key);
1046
- if (keyRow) {
1047
- existingKeysMap.set(key, keyRow);
1048
- }
1049
- }
1050
- for (const [key, value] of entries) {
1051
- const defaultValue = flatDefaults[key] ?? value;
1052
- let keyId = "";
1053
- const keyRow = existingKeysMap.get(key);
1054
- if (!keyRow) {
1055
- const createdKey = await this.createTranslationKey(productId, key, defaultValue);
1056
- keyId = createdKey.id;
1057
- result.createdKeys += 1;
1058
- } else {
1059
- keyId = keyRow.id;
1060
- if (defaultValue && keyRow.defaultValue !== defaultValue) {
1061
- await this.updateTranslationKeyDefaultValue(keyId, defaultValue);
1062
- result.updatedKeyDefaults += 1;
1063
- }
1064
- }
1065
- const translationRow = await this.findGlobalTranslation(keyId, options.languageCode);
1066
- if (!translationRow) {
1067
- const createdTranslation = await this.createLanguageTranslation(keyId, options.languageCode, value);
1068
- result.createdTranslations += 1;
1069
- if (publish && createdTranslation.status !== "PUBLISHED") {
1070
- await this.updateLanguageTranslation(createdTranslation.id, value, "PUBLISHED");
1071
- }
1072
- } else {
1073
- const shouldUpdateValue = updateExisting && translationRow.value !== value;
1074
- const shouldPublish = publish && translationRow.status !== "PUBLISHED";
1075
- if (shouldUpdateValue || shouldPublish) {
1076
- await this.updateLanguageTranslation(translationRow.id, shouldUpdateValue ? value : translationRow.value, publish ? "PUBLISHED" : translationRow.status);
1077
- if (shouldUpdateValue) {
1078
- result.updatedTranslations += 1;
1079
- }
1080
- }
1081
- }
1082
- result.keysProcessed += 1;
1083
- }
1084
- logger.info("[Translation] Product translations upsert completed", {
1085
- productId,
1086
- languageCode: options.languageCode,
1087
- keysProcessed: result.keysProcessed,
1088
- createdKeys: result.createdKeys,
1089
- createdTranslations: result.createdTranslations,
1090
- updatedTranslations: result.updatedTranslations
1091
- });
1092
- return result;
1093
- }
1094
- flattenTranslationTree(input, prefix = "") {
1095
- const out = {};
1096
- for (const [key, rawValue] of Object.entries(input)) {
1097
- const nextKey = prefix ? `${prefix}.${key}` : key;
1098
- if (typeof rawValue === "string") {
1099
- out[nextKey] = rawValue;
1100
- continue;
1101
- }
1102
- if (rawValue && typeof rawValue === "object") {
1103
- Object.assign(out, this.flattenTranslationTree(rawValue, nextKey));
1104
- }
1105
- }
1106
- return out;
1107
- }
1108
- decodeDataUrlJson(url) {
1109
- if (!url.startsWith("data:")) {
1110
- throw new ValidationError("Expected exportTranslations URL to be a data URL");
1111
- }
1112
- const commaIdx = url.indexOf(",");
1113
- if (commaIdx === -1) {
1114
- throw new ValidationError("Invalid data URL: missing comma separator");
1115
- }
1116
- const header = url.slice(0, commaIdx);
1117
- const payload = url.slice(commaIdx + 1);
1118
- if (!payload) {
1119
- throw new ValidationError("Invalid data URL payload");
1120
- }
1121
- try {
1122
- const decoded = header.includes("base64") ? Buffer.from(payload, "base64").toString("utf8") : decodeURIComponent(payload);
1123
- return JSON.parse(decoded);
1124
- } catch (error) {
1125
- logger.error("[Translation] Failed to decode data URL JSON", {
1126
- error,
1127
- isBase64: header.includes("base64")
1128
- });
1129
- throw new ValidationError("Failed to decode JSON translation payload");
1130
- }
1131
- }
1132
- async resolveProductId(productId, productName) {
1133
- if (productId) {
1134
- return productId;
1135
- }
1136
- if (!productName) {
1137
- throw new ValidationError("Either productId or productName is required");
1138
- }
1139
- const query = `
1140
- query GetI18nProductByName($name: String!) {
1141
- i18nProductByName(name: $name) {
1142
- id
1143
- }
1144
- }
1145
- `;
1146
- const response = await this.client.query(query, {
1147
- name: productName
1148
- }, this.context);
1149
- if (!response.i18nProductByName?.id) {
1150
- throw new ValidationError(`i18n product not found: ${productName}`);
1151
- }
1152
- return response.i18nProductByName.id;
1153
- }
1154
- async findTranslationKeyByKey(productId, key) {
1155
- const query = `
1156
- query FindTranslationKey($productId: String!, $key: String!) {
1157
- translationKeyByKey(productId: $productId, key: $key) {
1158
- id
1159
- defaultValue
1160
- }
1161
- }
1162
- `;
1163
- const response = await this.client.query(query, {
1164
- productId,
1165
- key
1166
- }, this.context);
1167
- return response.translationKeyByKey;
1168
- }
1169
- async createTranslationKey(productId, key, defaultValue) {
1170
- const mutation = `
1171
- mutation CreateTranslationKey($input: CreateTranslationKeyInput!) {
1172
- createTranslationKey(input: $input) {
1173
- id
1174
- }
1175
- }
1176
- `;
1177
- const response = await this.client.query(mutation, {
1178
- input: {
1179
- productId,
1180
- key,
1181
- defaultValue
1182
- }
1183
- }, this.context);
1184
- return response.createTranslationKey;
1185
- }
1186
- async updateTranslationKeyDefaultValue(id, defaultValue) {
1187
- const mutation = `
1188
- mutation UpdateTranslationKeyDefault($id: ID!, $input: UpdateTranslationKeyInput!) {
1189
- updateTranslationKey(id: $id, input: $input) {
1190
- id
1191
- }
1192
- }
1193
- `;
1194
- await this.client.query(mutation, {
1195
- id,
1196
- input: {
1197
- defaultValue
1198
- }
1199
- }, this.context);
1200
- }
1201
- async findGlobalTranslation(keyId, languageCode) {
1202
- const query = `
1203
- query FindTranslation($filter: TranslationFilterInput) {
1204
- translations(filter: $filter, limit: 50, offset: 0) {
1205
- items {
1206
- id
1207
- value
1208
- status
1209
- tenantId
1210
- }
1211
- }
1212
- }
1213
- `;
1214
- const response = await this.client.query(query, {
1215
- filter: {
1216
- keyId,
1217
- languageCode
1218
- }
1219
- }, this.context);
1220
- const globalTranslation = response.translations.items.find((item) => item.tenantId === null);
1221
- if (!globalTranslation) {
1222
- return null;
1223
- }
1224
- return {
1225
- id: globalTranslation.id,
1226
- value: globalTranslation.value,
1227
- status: globalTranslation.status
1228
- };
1229
- }
1230
- async createLanguageTranslation(keyId, languageCode, value) {
1231
- const mutation = `
1232
- mutation CreateTranslation($input: CreateTranslationInput!) {
1233
- createTranslation(input: $input) {
1234
- id
1235
- status
1236
- }
1237
- }
1238
- `;
1239
- const response = await this.client.query(mutation, {
1240
- input: {
1241
- keyId,
1242
- languageCode,
1243
- value
1244
- }
1245
- }, this.context);
1246
- return response.createTranslation;
1247
- }
1248
- async updateLanguageTranslation(id, value, status) {
1249
- const mutation = `
1250
- mutation UpdateTranslation($id: ID!, $input: UpdateTranslationInput!) {
1251
- updateTranslation(id: $id, input: $input) {
1252
- id
1253
- status
1254
- }
1255
- }
1256
- `;
1257
- await this.client.query(mutation, {
1258
- id,
1259
- input: {
1260
- value,
1261
- status
1262
- }
1263
- }, this.context);
1264
- }
1265
- /**
1266
- * Escape regex special characters in a string
1267
- */
1268
- escapeRegex(str) {
1269
- return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1270
- }
1271
- /**
1272
- * Interpolate variables in translation string
1273
- */
1274
- interpolate(text, variables) {
1275
- let result = text;
1276
- for (const [key, value] of Object.entries(variables)) {
1277
- const escapedKey = this.escapeRegex(key);
1278
- const regex = new RegExp(`{{\\s*${escapedKey}\\s*}}`, "g");
1279
- result = result.replace(regex, String(value));
1280
- }
1281
- return result;
1282
- }
1283
- /**
1284
- * Format translation with pluralization
1285
- */
1286
- formatPlural(_language, count, translations) {
1287
- if (count === 0 && translations.zero) {
1288
- return translations.zero;
1289
- }
1290
- if (count === 1) {
1291
- return translations.one;
1292
- }
1293
- return translations.other;
1294
- }
1295
- /**
1296
- * Format date/time for locale
1297
- */
1298
- formatDateTime(date, language, options) {
1299
- const dateObj = typeof date === "string" ? new Date(date) : date;
1300
- return new Intl.DateTimeFormat(language, options).format(dateObj);
1301
- }
1302
- /**
1303
- * Format number for locale
1304
- */
1305
- formatNumber(number, language, options) {
1306
- return new Intl.NumberFormat(language, options).format(number);
1307
- }
1308
- /**
1309
- * Format currency for locale
1310
- */
1311
- formatCurrency(amount, currency, language) {
1312
- return new Intl.NumberFormat(language, {
1313
- style: "currency",
1314
- currency
1315
- }).format(amount);
1316
- }
1317
- };
1318
-
1319
- // src/payments/index.ts
1320
- var PaymentsModule = class {
1321
- static {
1322
- __name(this, "PaymentsModule");
1323
- }
1324
- client;
1325
- context;
1326
- constructor(client, context) {
1327
- this.client = client;
1328
- this.context = context;
1329
- }
1330
- /**
1331
- * Create payment
1332
- */
1333
- async createPayment(options) {
1334
- if (typeof options.amount !== "number" || options.amount <= 0) {
1335
- throw new ValidationError("Amount must be a positive number");
1336
- }
1337
- if (!options.currency) {
1338
- throw new ValidationError("Currency is required");
1339
- }
1340
- if (!options.paymentMethod) {
1341
- throw new ValidationError("Payment method is required");
1342
- }
1343
- if (!options.customerId) {
1344
- throw new ValidationError("Customer ID is required");
1345
- }
1346
- logger.debug("[Payments] Creating payment", {
1347
- amount: options.amount,
1348
- currency: options.currency,
1349
- customerId: options.customerId
1350
- });
1351
- const mutation = `
1352
- mutation CreatePayment($input: CreatePaymentInput!) {
1353
- createPayment(input: $input) {
1354
- id
1355
- amount
1356
- currency
1357
- status
1358
- paymentMethod
1359
- customerId
1360
- description
1361
- metadata
1362
- workspaceId
1363
- organizationId
1364
- transactionId
1365
- failureReason
1366
- createdAt
1367
- updatedAt
1368
- }
1369
- }
1370
- `;
1371
- const variables = {
1372
- input: {
1373
- amount: options.amount,
1374
- currency: options.currency,
1375
- paymentMethod: options.paymentMethod,
1376
- customerId: options.customerId,
1377
- description: options.description,
1378
- metadata: options.metadata,
1379
- workspaceId: options.workspaceId || this.context.workspaceId,
1380
- organizationId: options.organizationId
1381
- }
1382
- };
1383
- const response = await this.client.query(mutation, variables, this.context);
1384
- logger.info("[Payments] Payment created", {
1385
- paymentId: response.createPayment.id
1386
- });
1387
- return response.createPayment;
1388
- }
1389
- /**
1390
- * Get payment by ID
1391
- */
1392
- async getPayment(paymentId) {
1393
- logger.debug("[Payments] Getting payment", {
1394
- paymentId
1395
- });
1396
- const query = `
1397
- query GetPayment($paymentId: ID!) {
1398
- getPayment(paymentId: $paymentId) {
1399
- id
1400
- amount
1401
- currency
1402
- status
1403
- paymentMethod
1404
- customerId
1405
- description
1406
- metadata
1407
- workspaceId
1408
- organizationId
1409
- transactionId
1410
- failureReason
1411
- createdAt
1412
- updatedAt
1413
- }
1414
- }
1415
- `;
1416
- const response = await this.client.query(query, {
1417
- paymentId
1418
- }, this.context);
1419
- return response.getPayment;
1420
- }
1421
- /**
1422
- * Get payments with filters
1423
- */
1424
- async getPayments(options) {
1425
- logger.debug("[Payments] Getting payments", options);
1426
- const query = `
1427
- query GetPayments(
1428
- $customerId: ID
1429
- $status: PaymentStatus
1430
- $workspaceId: ID
1431
- $organizationId: ID
1432
- $startDate: DateTime
1433
- $endDate: DateTime
1434
- $limit: Int
1435
- $offset: Int
1436
- ) {
1437
- getPayments(
1438
- customerId: $customerId
1439
- status: $status
1440
- workspaceId: $workspaceId
1441
- organizationId: $organizationId
1442
- startDate: $startDate
1443
- endDate: $endDate
1444
- limit: $limit
1445
- offset: $offset
1446
- ) {
1447
- payments {
1448
- id
1449
- amount
1450
- currency
1451
- status
1452
- paymentMethod
1453
- customerId
1454
- description
1455
- transactionId
1456
- createdAt
1457
- updatedAt
1458
- }
1459
- total
1460
- }
1461
- }
1462
- `;
1463
- const variables = {
1464
- customerId: options.customerId,
1465
- status: options.status,
1466
- workspaceId: options.workspaceId || this.context.workspaceId,
1467
- organizationId: options.organizationId,
1468
- startDate: options.startDate,
1469
- endDate: options.endDate,
1470
- limit: options.limit || 50,
1471
- offset: options.offset || 0
1472
- };
1473
- const response = await this.client.query(query, variables, this.context);
1474
- return response.getPayments;
1475
- }
1476
- /**
1477
- * Refund payment
1478
- */
1479
- async refundPayment(paymentId, amount, reason) {
1480
- logger.debug("[Payments] Refunding payment", {
1481
- paymentId,
1482
- amount
1483
- });
1484
- const mutation = `
1485
- mutation RefundPayment($paymentId: ID!, $amount: Int, $reason: String) {
1486
- refundPayment(paymentId: $paymentId, amount: $amount, reason: $reason) {
1487
- id
1488
- amount
1489
- currency
1490
- status
1491
- paymentMethod
1492
- customerId
1493
- failureReason
1494
- updatedAt
1495
- }
1496
- }
1497
- `;
1498
- const response = await this.client.query(mutation, {
1499
- paymentId,
1500
- amount,
1501
- reason
1502
- }, this.context);
1503
- logger.info("[Payments] Payment refunded", {
1504
- paymentId
1505
- });
1506
- return response.refundPayment;
1507
- }
1508
- /**
1509
- * Verify payment
1510
- */
1511
- async verifyPayment(paymentId, verificationData) {
1512
- logger.debug("[Payments] Verifying payment", {
1513
- paymentId
1514
- });
1515
- const mutation = `
1516
- mutation VerifyPayment($paymentId: ID!, $verificationData: JSON!) {
1517
- verifyPayment(paymentId: $paymentId, verificationData: $verificationData) {
1518
- verified
1519
- status
1520
- }
1521
- }
1522
- `;
1523
- const response = await this.client.query(mutation, {
1524
- paymentId,
1525
- verificationData
1526
- }, this.context);
1527
- logger.info("[Payments] Payment verified", {
1528
- paymentId,
1529
- verified: response.verifyPayment.verified
1530
- });
1531
- return response.verifyPayment;
1532
- }
1533
- /**
1534
- * Create subscription
1535
- */
1536
- async createSubscription(options) {
1537
- if (!options.customerId) {
1538
- throw new ValidationError("Customer ID is required");
1539
- }
1540
- if (!options.planId) {
1541
- throw new ValidationError("Plan ID is required");
1542
- }
1543
- if (!options.paymentMethod) {
1544
- throw new ValidationError("Payment method is required");
1545
- }
1546
- logger.debug("[Payments] Creating subscription", {
1547
- customerId: options.customerId,
1548
- planId: options.planId
1549
- });
1550
- const mutation = `
1551
- mutation CreateSubscription($input: CreateSubscriptionInput!) {
1552
- createSubscription(input: $input) {
1553
- id
1554
- customerId
1555
- planId
1556
- status
1557
- currentPeriodStart
1558
- currentPeriodEnd
1559
- trialEnd
1560
- cancelledAt
1561
- endedAt
1562
- metadata
1563
- workspaceId
1564
- organizationId
1565
- createdAt
1566
- updatedAt
1567
- }
1568
- }
1569
- `;
1570
- const variables = {
1571
- input: {
1572
- customerId: options.customerId,
1573
- planId: options.planId,
1574
- paymentMethod: options.paymentMethod,
1575
- trialDays: options.trialDays,
1576
- metadata: options.metadata,
1577
- workspaceId: options.workspaceId || this.context.workspaceId,
1578
- organizationId: options.organizationId
1579
- }
1580
- };
1581
- const response = await this.client.query(mutation, variables, this.context);
1582
- logger.info("[Payments] Subscription created", {
1583
- subscriptionId: response.createSubscription.id
1584
- });
1585
- return response.createSubscription;
1586
- }
1587
- /**
1588
- * Get subscription
1589
- */
1590
- async getSubscription(subscriptionId) {
1591
- logger.debug("[Payments] Getting subscription", {
1592
- subscriptionId
1593
- });
1594
- const query = `
1595
- query GetSubscription($subscriptionId: ID!) {
1596
- getSubscription(subscriptionId: $subscriptionId) {
1597
- id
1598
- customerId
1599
- planId
1600
- status
1601
- currentPeriodStart
1602
- currentPeriodEnd
1603
- trialEnd
1604
- cancelledAt
1605
- endedAt
1606
- metadata
1607
- workspaceId
1608
- organizationId
1609
- createdAt
1610
- updatedAt
1611
- }
1612
- }
1613
- `;
1614
- const response = await this.client.query(query, {
1615
- subscriptionId
1616
- }, this.context);
1617
- return response.getSubscription;
1618
- }
1619
- /**
1620
- * Cancel subscription
1621
- */
1622
- async cancelSubscription(subscriptionId, cancelAtPeriodEnd = false) {
1623
- logger.debug("[Payments] Cancelling subscription", {
1624
- subscriptionId,
1625
- cancelAtPeriodEnd
1626
- });
1627
- const mutation = `
1628
- mutation CancelSubscription($subscriptionId: ID!, $cancelAtPeriodEnd: Boolean!) {
1629
- cancelSubscription(subscriptionId: $subscriptionId, cancelAtPeriodEnd: $cancelAtPeriodEnd) {
1630
- id
1631
- status
1632
- cancelledAt
1633
- endedAt
1634
- updatedAt
1635
- }
1636
- }
1637
- `;
1638
- const response = await this.client.query(mutation, {
1639
- subscriptionId,
1640
- cancelAtPeriodEnd
1641
- }, this.context);
1642
- logger.info("[Payments] Subscription cancelled", {
1643
- subscriptionId
1644
- });
1645
- return response.cancelSubscription;
1646
- }
1647
- /**
1648
- * Get customer subscriptions
1649
- */
1650
- async getCustomerSubscriptions(customerId) {
1651
- logger.debug("[Payments] Getting customer subscriptions", {
1652
- customerId
1653
- });
1654
- const query = `
1655
- query GetCustomerSubscriptions($customerId: ID!) {
1656
- getCustomerSubscriptions(customerId: $customerId) {
1657
- id
1658
- customerId
1659
- planId
1660
- status
1661
- currentPeriodStart
1662
- currentPeriodEnd
1663
- trialEnd
1664
- cancelledAt
1665
- createdAt
1666
- }
1667
- }
1668
- `;
1669
- const response = await this.client.query(query, {
1670
- customerId
1671
- }, this.context);
1672
- return response.getCustomerSubscriptions;
1673
- }
1674
- /**
1675
- * Get plans
1676
- */
1677
- async getPlans(activeOnly = true) {
1678
- logger.debug("[Payments] Getting plans", {
1679
- activeOnly
1680
- });
1681
- const query = `
1682
- query GetPlans($activeOnly: Boolean!) {
1683
- getPlans(activeOnly: $activeOnly) {
1684
- id
1685
- name
1686
- description
1687
- amount
1688
- currency
1689
- interval
1690
- intervalCount
1691
- features
1692
- metadata
1693
- active
1694
- createdAt
1695
- }
1696
- }
1697
- `;
1698
- const response = await this.client.query(query, {
1699
- activeOnly
1700
- }, this.context);
1701
- return response.getPlans;
1702
- }
1703
- /**
1704
- * Create payment intent
1705
- */
1706
- async createPaymentIntent(options) {
1707
- logger.debug("[Payments] Creating payment intent", {
1708
- amount: options.amount,
1709
- currency: options.currency
1710
- });
1711
- const mutation = `
1712
- mutation CreatePaymentIntent($input: CreatePaymentIntentInput!) {
1713
- createPaymentIntent(input: $input) {
1714
- clientSecret
1715
- paymentIntentId
1716
- }
1717
- }
1718
- `;
1719
- const response = await this.client.query(mutation, {
1720
- input: options
1721
- }, this.context);
1722
- logger.info("[Payments] Payment intent created", {
1723
- paymentIntentId: response.createPaymentIntent.paymentIntentId
1724
- });
1725
- return response.createPaymentIntent;
1726
- }
1727
- /**
1728
- * Get payment statistics
1729
- */
1730
- async getPaymentStats(options) {
1731
- logger.debug("[Payments] Getting payment statistics", options);
1732
- const query = `
1733
- query GetPaymentStats($startDate: DateTime, $endDate: DateTime, $workspaceId: ID) {
1734
- getPaymentStats(startDate: $startDate, endDate: $endDate, workspaceId: $workspaceId) {
1735
- totalRevenue
1736
- totalPayments
1737
- successfulPayments
1738
- failedPayments
1739
- refundedAmount
1740
- averagePaymentAmount
1741
- }
1742
- }
1743
- `;
1744
- const response = await this.client.query(query, {
1745
- startDate: options?.startDate,
1746
- endDate: options?.endDate,
1747
- workspaceId: options?.workspaceId || this.context.workspaceId
1748
- }, this.context);
1749
- return response.getPaymentStats;
1750
- }
1751
- };
1752
-
1753
- // src/bootstrap/index.ts
1754
- var BootstrapModule = class {
1755
- static {
1756
- __name(this, "BootstrapModule");
1757
- }
1758
- config;
1759
- startTime;
1760
- healthCheckInterval;
1761
- constructor(config) {
1762
- this.config = config;
1763
- this.startTime = /* @__PURE__ */ new Date();
1764
- }
1765
- /**
1766
- * Bootstrap the application
1767
- */
1768
- async bootstrap() {
1769
- logger.info("[Bootstrap] Starting application bootstrap", {
1770
- serviceName: this.config.serviceName,
1771
- environment: this.config.environment || "development"
1772
- });
1773
- try {
1774
- await this.validateConfiguration();
1775
- const databaseConnected = await this.connectDatabase();
1776
- const loadedModules = await this.loadModules();
1777
- if (this.config.healthCheck) {
1778
- await this.setupHealthChecks();
1779
- }
1780
- this.setupSignalHandlers();
1781
- const result = {
1782
- success: true,
1783
- serviceName: this.config.serviceName || "burdenoff-service",
1784
- serviceVersion: this.config.serviceVersion || "1.0.0",
1785
- environment: this.config.environment || "development",
1786
- startedAt: this.startTime.toISOString(),
1787
- modules: loadedModules,
1788
- databaseConnected,
1789
- healthCheckEnabled: this.config.healthCheck || false
1790
- };
1791
- logger.info("[Bootstrap] Application bootstrapped successfully", result);
1792
- return result;
1793
- } catch (error) {
1794
- logger.error("[Bootstrap] Failed to bootstrap application", {
1795
- error
1796
- });
1797
- throw error;
1798
- }
1799
- }
1800
- /**
1801
- * Validate configuration
1802
- */
1803
- async validateConfiguration() {
1804
- logger.debug("[Bootstrap] Validating configuration");
1805
- if (!this.config.workspacesApiUrl) {
1806
- throw new Error("Workspaces API URL is required");
1807
- }
1808
- if (this.config.database?.url && !DatabaseModule.validateDatabaseUrl(this.config.database.url)) {
1809
- throw new Error("Invalid database URL");
1810
- }
1811
- logger.debug("[Bootstrap] Configuration validated");
1812
- }
1813
- /**
1814
- * Connect to database
1815
- */
1816
- async connectDatabase() {
1817
- if (!this.config.database) {
1818
- logger.debug("[Bootstrap] No database configuration provided, skipping");
1819
- return false;
1820
- }
1821
- logger.info("[Bootstrap] Connecting to database");
1822
- try {
1823
- const sanitizedUrl = DatabaseModule.sanitizeDatabaseUrl(this.config.database.url);
1824
- logger.info("[Bootstrap] Database connection configured", {
1825
- url: sanitizedUrl
1826
- });
1827
- return true;
1828
- } catch (error) {
1829
- logger.error("[Bootstrap] Failed to connect to database", {
1830
- error
1831
- });
1832
- return false;
1833
- }
1834
- }
1835
- /**
1836
- * Load modules
1837
- */
1838
- async loadModules() {
1839
- const modules = this.config.modules || [];
1840
- if (modules.length === 0) {
1841
- logger.debug("[Bootstrap] No modules to load");
1842
- return [];
1843
- }
1844
- logger.info("[Bootstrap] Loading modules", {
1845
- modules
1846
- });
1847
- const loadedModules = [];
1848
- for (const moduleName of modules) {
1849
- try {
1850
- logger.debug(`[Bootstrap] Loading module: ${moduleName}`);
1851
- loadedModules.push(moduleName);
1852
- } catch (error) {
1853
- logger.error(`[Bootstrap] Failed to load module: ${moduleName}`, {
1854
- error
1855
- });
1856
- }
1857
- }
1858
- logger.info("[Bootstrap] Modules loaded", {
1859
- loaded: loadedModules
1860
- });
1861
- return loadedModules;
1862
- }
1863
- /**
1864
- * Setup health checks
1865
- */
1866
- async setupHealthChecks() {
1867
- logger.info("[Bootstrap] Setting up health checks");
1868
- const interval = this.config.healthCheckInterval || 3e4;
1869
- this.healthCheckInterval = setInterval(() => {
1870
- void (async () => {
1871
- const health = await this.performHealthCheck();
1872
- if (!health.healthy) {
1873
- logger.warn("[Bootstrap] Health check failed", health);
1874
- } else {
1875
- logger.debug("[Bootstrap] Health check passed", health);
1876
- }
1877
- })();
1878
- }, interval);
1879
- logger.info("[Bootstrap] Health checks configured", {
1880
- interval
1881
- });
1882
- }
1883
- /**
1884
- * Perform health check
1885
- */
1886
- async performHealthCheck() {
1887
- const checks = {};
1888
- const memUsage = process.memoryUsage();
1889
- checks.memory = {
1890
- used: memUsage.heapUsed,
1891
- total: memUsage.heapTotal,
1892
- percentage: memUsage.heapUsed / memUsage.heapTotal * 100
1893
- };
1894
- checks.uptime = Math.floor((Date.now() - this.startTime.getTime()) / 1e3);
1895
- const healthy = checks.memory.percentage < 90 && // Less than 90% memory usage
1896
- checks.uptime > 0;
1897
- return {
1898
- healthy,
1899
- checks,
1900
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
1901
- };
1902
- }
1903
- /**
1904
- * Setup signal handlers for graceful shutdown
1905
- */
1906
- setupSignalHandlers() {
1907
- logger.debug("[Bootstrap] Setting up signal handlers");
1908
- const gracefulShutdown = /* @__PURE__ */ __name(async (signal) => {
1909
- logger.info(`[Bootstrap] Received ${signal}, shutting down gracefully`);
1910
- if (this.healthCheckInterval) {
1911
- clearInterval(this.healthCheckInterval);
1912
- }
1913
- await this.cleanup();
1914
- process.exit(0);
1915
- }, "gracefulShutdown");
1916
- process.on("SIGTERM", () => {
1917
- void gracefulShutdown("SIGTERM");
1918
- });
1919
- process.on("SIGINT", () => {
1920
- void gracefulShutdown("SIGINT");
1921
- });
1922
- process.on("unhandledRejection", (reason, promise) => {
1923
- logger.error("[Bootstrap] Unhandled rejection", {
1924
- reason,
1925
- promise
1926
- });
1927
- });
1928
- process.on("uncaughtException", (error) => {
1929
- logger.error("[Bootstrap] Uncaught exception", {
1930
- error
1931
- });
1932
- process.exit(1);
1933
- });
1934
- }
1935
- /**
1936
- * Cleanup on shutdown
1937
- */
1938
- async cleanup() {
1939
- logger.info("[Bootstrap] Performing cleanup");
1940
- await disposeAll();
1941
- ContextManager.clearContext();
1942
- logger.info("[Bootstrap] Cleanup completed");
1943
- }
1944
- /**
1945
- * Get application info
1946
- */
1947
- getInfo() {
1948
- return {
1949
- serviceName: this.config.serviceName || "burdenoff-service",
1950
- serviceVersion: this.config.serviceVersion || "1.0.0",
1951
- environment: this.config.environment || "development",
1952
- uptime: Math.floor((Date.now() - this.startTime.getTime()) / 1e3),
1953
- startedAt: this.startTime.toISOString()
1954
- };
1955
- }
1956
- /**
1957
- * Setup default context
1958
- */
1959
- setupDefaultContext(context) {
1960
- logger.debug("[Bootstrap] Setting up default context", context);
1961
- ContextManager.setContext(context);
1962
- }
1963
- /**
1964
- * Create context middleware (for Elysia/HTTP frameworks)
1965
- */
1966
- createContextMiddleware() {
1967
- return async (req, _res, next) => {
1968
- const context = this.extractContextFromRequest(req);
1969
- ContextManager.setContext(context);
1970
- next();
1971
- };
1972
- }
1973
- /**
1974
- * Extract context from request
1975
- */
1976
- extractContextFromRequest(req) {
1977
- const context = {};
1978
- if (req.user) {
1979
- context.actorId = req.user.user_id;
1980
- context.workspaceId = req.user.workspace_id;
1981
- context.tenantId = req.user.tenant_endpoint;
1982
- }
1983
- const getHeader = /* @__PURE__ */ __name((key) => {
1984
- const value = req.headers[key.toLowerCase()];
1985
- return Array.isArray(value) ? value[0] : value;
1986
- }, "getHeader");
1987
- const authHeader = getHeader("authorization");
1988
- if (authHeader) {
1989
- context.token = authHeader.replace("Bearer ", "");
1990
- }
1991
- const workspaceId = getHeader("x-workspace-id");
1992
- if (workspaceId && !context.workspaceId) {
1993
- context.workspaceId = workspaceId;
1994
- }
1995
- const productId = getHeader("x-product-id");
1996
- if (productId) {
1997
- context.productId = productId;
1998
- }
1999
- const projectId = getHeader("x-project-id");
2000
- if (projectId) {
2001
- context.projectId = projectId;
2002
- }
2003
- const appId = getHeader("x-app-id");
2004
- if (appId) {
2005
- context.appId = appId;
2006
- }
2007
- const cfAccessClientId = getHeader("cf-access-client-id");
2008
- if (cfAccessClientId) {
2009
- context.cfAccessClientId = cfAccessClientId;
2010
- }
2011
- const cfAccessClientSecret = getHeader("cf-access-client-secret");
2012
- if (cfAccessClientSecret) {
2013
- context.cfAccessClientSecret = cfAccessClientSecret;
2014
- }
2015
- const cfAuthorization = getHeader("x-cf-authorization");
2016
- if (cfAuthorization) {
2017
- context.cfAuthorization = cfAuthorization;
2018
- }
2019
- return context;
2020
- }
2021
- /**
2022
- * Load GraphQL schema
2023
- */
2024
- async loadSchema(schemaPath) {
2025
- logger.info("[Bootstrap] Loading GraphQL schema", {
2026
- schemaPath
2027
- });
2028
- try {
2029
- logger.info("[Bootstrap] Schema loaded successfully");
2030
- return true;
2031
- } catch (error) {
2032
- logger.error("[Bootstrap] Failed to load schema", {
2033
- error
2034
- });
2035
- return false;
2036
- }
2037
- }
2038
- /**
2039
- * Register shutdown hook
2040
- */
2041
- onShutdown(callback) {
2042
- const originalHandler = process.listeners("SIGTERM")[0];
2043
- process.removeAllListeners("SIGTERM");
2044
- process.on("SIGTERM", () => {
2045
- void (async () => {
2046
- await callback();
2047
- if (typeof originalHandler === "function") {
2048
- originalHandler();
2049
- }
2050
- })();
2051
- });
2052
- }
2053
- /**
2054
- * Check if application is ready
2055
- */
2056
- async isReady() {
2057
- const health = await this.performHealthCheck();
2058
- return health.healthy;
2059
- }
2060
- /**
2061
- * Get metrics
2062
- */
2063
- getMetrics() {
2064
- return {
2065
- memory: process.memoryUsage(),
2066
- uptime: Math.floor((Date.now() - this.startTime.getTime()) / 1e3),
2067
- cpu: process.cpuUsage()
2068
- };
2069
- }
2070
- };
2071
- function createBootstrap(config) {
2072
- return new BootstrapModule(config);
2073
- }
2074
- __name(createBootstrap, "createBootstrap");
2075
-
2076
248
  // src/client/tenant-backend.ts
249
+ /**
250
+ * Tenant Backend Client
251
+ * Centralized client for accessing tenant-backend services (notifications, auth, etc.)
252
+ *
253
+ * This is a reusable utility that can be used by any backend to communicate with tenant-backend.
254
+ */
255
+ /**
256
+ * Tenant Backend Client
257
+ * Provides access to centralized tenant-backend services using be-sdk
258
+ *
259
+ * @example
260
+ * ```typescript
261
+ * import { TenantBackendClient } from '@burdenoff/be-sdk';
262
+ *
263
+ * const client = new TenantBackendClient({
264
+ * tenantBackendUrl: process.env.GLOBAL_INT_GATEWAY_URL!,
265
+ * workspacesBackendUrl: process.env.WORKSPACES_BACKEND_URL,
266
+ * apiKey: process.env.TENANT_BACKEND_API_KEY,
267
+ * });
268
+ *
269
+ * // Send notification
270
+ * await client.notifications.sendWithTemplate({
271
+ * templateSlug: 'user-welcome',
272
+ * recipients: ['user@example.com'],
273
+ * variables: { userName: 'John' },
274
+ * });
275
+ *
276
+ * // Execute raw query
277
+ * const result = await client.query(`
278
+ * query GetUser($id: ID!) {
279
+ * user(id: $id) { id name email }
280
+ * }
281
+ * `, { id: 'user-123' });
282
+ * ```
283
+ */
2077
284
  var TenantBackendClient = class {
2078
- static {
2079
- __name(this, "TenantBackendClient");
2080
- }
2081
- graphqlClient;
2082
- config;
2083
- /** Notifications module for sending notifications via tenant backend */
2084
- notifications;
2085
- constructor(config) {
2086
- this.config = config;
2087
- const sdkConfig = {
2088
- workspacesApiUrl: config.workspacesBackendUrl || "http://localhost:4000/graphql",
2089
- tenantApiUrl: config.tenantBackendUrl
2090
- };
2091
- this.graphqlClient = new BurdenoffGraphQLClient(sdkConfig, {});
2092
- this.notifications = new TenantNotificationsModule(this.graphqlClient, {});
2093
- logger.info("[TenantBackend] Client initialized using be-sdk", {
2094
- tenantUrl: config.tenantBackendUrl,
2095
- workspacesUrl: config.workspacesBackendUrl,
2096
- hasApiKey: !!config.apiKey
2097
- });
2098
- }
2099
- /**
2100
- * Update authentication token
2101
- *
2102
- * @param token - JWT token for authentication
2103
- */
2104
- setAuthToken(token) {
2105
- this.graphqlClient.updateContext({
2106
- token
2107
- });
2108
- logger.debug("[TenantBackend] Authentication token updated");
2109
- }
2110
- /**
2111
- * Execute raw GraphQL query against tenant backend
2112
- *
2113
- * @param query - GraphQL query string
2114
- * @param variables - Query variables
2115
- * @returns Query result
2116
- *
2117
- * @example
2118
- * ```typescript
2119
- * const result = await client.query(`
2120
- * query GetTemplate($slug: String!) {
2121
- * notificationTemplate(slug: $slug) {
2122
- * id
2123
- * slug
2124
- * subject
2125
- * }
2126
- * }
2127
- * `, { slug: 'user-welcome' });
2128
- * ```
2129
- */
2130
- async query(query, variables) {
2131
- return this.graphqlClient.tenantQuery(query, variables);
2132
- }
2133
- /**
2134
- * Health check
2135
- *
2136
- * @returns True if tenant backend is reachable, false otherwise
2137
- */
2138
- async healthCheck() {
2139
- try {
2140
- const query = `
285
+ graphqlClient;
286
+ config;
287
+ /** Notifications module for sending notifications via tenant backend */
288
+ notifications;
289
+ constructor(config) {
290
+ this.config = config;
291
+ const sdkConfig = {
292
+ workspacesApiUrl: config.workspacesBackendUrl || "http://localhost:4000/graphql",
293
+ tenantApiUrl: config.tenantBackendUrl
294
+ };
295
+ this.graphqlClient = new BurdenoffGraphQLClient(sdkConfig, {});
296
+ this.notifications = new TenantNotificationsModule(this.graphqlClient, {});
297
+ logger.info("[TenantBackend] Client initialized using be-sdk", {
298
+ tenantUrl: config.tenantBackendUrl,
299
+ workspacesUrl: config.workspacesBackendUrl,
300
+ hasApiKey: !!config.apiKey
301
+ });
302
+ }
303
+ /**
304
+ * Update authentication token
305
+ *
306
+ * @param token - JWT token for authentication
307
+ */
308
+ setAuthToken(token) {
309
+ this.graphqlClient.updateContext({ token });
310
+ logger.debug("[TenantBackend] Authentication token updated");
311
+ }
312
+ /**
313
+ * Execute raw GraphQL query against tenant backend
314
+ *
315
+ * @param query - GraphQL query string
316
+ * @param variables - Query variables
317
+ * @returns Query result
318
+ *
319
+ * @example
320
+ * ```typescript
321
+ * const result = await client.query(`
322
+ * query GetTemplate($slug: String!) {
323
+ * notificationTemplate(slug: $slug) {
324
+ * id
325
+ * slug
326
+ * subject
327
+ * }
328
+ * }
329
+ * `, { slug: 'user-welcome' });
330
+ * ```
331
+ */
332
+ async query(query, variables) {
333
+ return this.graphqlClient.tenantQuery(query, variables);
334
+ }
335
+ /**
336
+ * Health check
337
+ *
338
+ * @returns True if tenant backend is reachable, false otherwise
339
+ */
340
+ async healthCheck() {
341
+ try {
342
+ await this.graphqlClient.tenantQuery(`
2141
343
  query HealthCheck {
2142
344
  __typename
2143
345
  }
2144
- `;
2145
- await this.graphqlClient.tenantQuery(query);
2146
- return true;
2147
- } catch (error) {
2148
- logger.error("[TenantBackend] Health check failed", {
2149
- error: error instanceof Error ? error.message : "Unknown error"
2150
- });
2151
- return false;
2152
- }
2153
- }
2154
- /**
2155
- * Get GraphQL client for advanced usage
2156
- *
2157
- * @returns Underlying BurdenoffGraphQLClient
2158
- */
2159
- getClient() {
2160
- return this.graphqlClient;
2161
- }
2162
- /**
2163
- * Get client configuration
2164
- *
2165
- * @returns Client configuration
2166
- */
2167
- getConfig() {
2168
- return {
2169
- ...this.config
2170
- };
2171
- }
346
+ `);
347
+ return true;
348
+ } catch (error) {
349
+ logger.error("[TenantBackend] Health check failed", { error: error instanceof Error ? error.message : "Unknown error" });
350
+ return false;
351
+ }
352
+ }
353
+ /**
354
+ * Get GraphQL client for advanced usage
355
+ *
356
+ * @returns Underlying BurdenoffGraphQLClient
357
+ */
358
+ getClient() {
359
+ return this.graphqlClient;
360
+ }
361
+ /**
362
+ * Get client configuration
363
+ *
364
+ * @returns Client configuration
365
+ */
366
+ getConfig() {
367
+ return { ...this.config };
368
+ }
2172
369
  };
370
+ /**
371
+ * Create a TenantBackendClient instance
372
+ *
373
+ * @param config - Client configuration
374
+ * @returns TenantBackendClient instance
375
+ *
376
+ * @example
377
+ * ```typescript
378
+ * import { createTenantBackendClient } from '@burdenoff/be-sdk';
379
+ *
380
+ * const client = createTenantBackendClient({
381
+ * tenantBackendUrl: process.env.GLOBAL_INT_GATEWAY_URL!,
382
+ * });
383
+ * ```
384
+ */
2173
385
  function createTenantBackendClient(config) {
2174
- return new TenantBackendClient(config);
386
+ return new TenantBackendClient(config);
2175
387
  }
2176
- __name(createTenantBackendClient, "createTenantBackendClient");
2177
388
 
2178
389
  // src/index.ts
390
+ /**
391
+ * Burdenoff Backend SDK
392
+ * Comprehensive SDK for all Burdenoff products
393
+ *
394
+ * @packageDocumentation
395
+ */
396
+ /**
397
+ * Main Burdenoff SDK class
398
+ *
399
+ * @example
400
+ * ```typescript
401
+ * import { BurdenoffSDK } from '@burdenoff/be-sdk';
402
+ *
403
+ * const sdk = new BurdenoffSDK({
404
+ * workspacesApiUrl: 'https://api.burdenoff.com/graphql',
405
+ * timeout: 30000,
406
+ * });
407
+ *
408
+ * // Use the unified tracker (most common use case)
409
+ * const result = await sdk.tracker.track({
410
+ * userId: 'user123',
411
+ * action: 'create_project',
412
+ * resourceType: 'project',
413
+ * workspaceId: 'ws123',
414
+ * usage: {
415
+ * quotaName: 'myproduct.projects.count',
416
+ * productId: 'myproduct',
417
+ * amount: 1,
418
+ * },
419
+ * });
420
+ * ```
421
+ */
2179
422
  var BurdenoffSDK = class {
2180
- static {
2181
- __name(this, "BurdenoffSDK");
2182
- }
2183
- client;
2184
- defaultContext;
2185
- // Event queue publisher state (Redis Streams)
2186
- eventPublisher = null;
2187
- eventPublisherInitPromise = null;
2188
- eventQueueConfig = null;
2189
- // Initialization state
2190
- initializationPromise = null;
2191
- isShuttingDown = false;
2192
- /** Authentication module */
2193
- auth;
2194
- /** Notifications module (workspaces-backend) */
2195
- notifications;
2196
- /** Tenant Notifications module (tenant-backend - RECOMMENDED) */
2197
- tenantNotifications;
2198
- /** RBAC module */
2199
- rbac;
2200
- /** Activity tracking module */
2201
- activity;
2202
- /** Usage & Quota module */
2203
- usage;
2204
- /** Unified Tracker module (MOST IMPORTANT - use this for most operations) */
2205
- tracker;
2206
- /** Database helpers module */
2207
- database;
2208
- /** Events/Queue module */
2209
- events;
2210
- /** Graph integration module */
2211
- graph;
2212
- /** Search module */
2213
- search;
2214
- /** Translation module */
2215
- translation;
2216
- /** Payments module */
2217
- payments;
2218
- /** Temporal workflow orchestration module (lazy-loaded) */
2219
- _temporal = null;
2220
- _temporalPromise = null;
2221
- _temporalConfig = null;
2222
- /**
2223
- * Get Temporal workflow orchestration module (lazy-loaded)
2224
- * Only loads @temporalio/client when this method is called
2225
- *
2226
- * @returns Promise resolving to TemporalModule
2227
- * @example
2228
- * ```typescript
2229
- * const temporal = await sdk.getTemporalModule();
2230
- * await temporal.startWorkflow('myWorkflow', { ... });
2231
- * ```
2232
- */
2233
- async getTemporalModule() {
2234
- if (this._temporal) {
2235
- return this._temporal;
2236
- }
2237
- if (!this._temporalPromise) {
2238
- this._temporalPromise = this.loadTemporalModule();
2239
- }
2240
- return this._temporalPromise;
2241
- }
2242
- /**
2243
- * Load temporal module dynamically
2244
- * @private
2245
- */
2246
- async loadTemporalModule() {
2247
- const { TemporalModule: TM } = await import('./temporal/index.js');
2248
- this._temporal = this._temporalConfig?.moduleType ? new TM({
2249
- moduleType: this._temporalConfig.moduleType,
2250
- address: this._temporalConfig.address,
2251
- namespace: this._temporalConfig.namespace,
2252
- taskQueue: this._temporalConfig.taskQueue
2253
- }) : TM.fromEnv();
2254
- return this._temporal;
2255
- }
2256
- /** Logger instance */
2257
- logger;
2258
- /** Context manager */
2259
- context;
2260
- /**
2261
- * Create SDK instance
2262
- */
2263
- constructor(config, defaultContext = {}) {
2264
- this.client = new BurdenoffGraphQLClient(config, defaultContext);
2265
- this.defaultContext = defaultContext;
2266
- this.logger = logger;
2267
- if (config.logger) {
2268
- this.logger.setLevel(config.logger.level);
2269
- this.logger.setConsoleEnabled(config.logger.console);
2270
- if (config.logger.transport) {
2271
- this.logger.addTransport(config.logger.transport);
2272
- }
2273
- }
2274
- this.context = ContextManager;
2275
- if (Object.keys(defaultContext).length > 0) {
2276
- ContextManager.setContext(defaultContext);
2277
- }
2278
- this.auth = new AuthModule(this.client, defaultContext);
2279
- this.notifications = new NotificationsModule(this.client, defaultContext);
2280
- this.tenantNotifications = new TenantNotificationsModule(this.client, defaultContext);
2281
- this.rbac = new RBACModule(this.client, defaultContext);
2282
- this.activity = new ActivityModule(this.client, defaultContext);
2283
- this.usage = new UsageModule(this.client, defaultContext);
2284
- this.tracker = new TrackerModule(this.client, defaultContext);
2285
- this.database = DatabaseModule;
2286
- this.events = new EventsModule(this.client, defaultContext);
2287
- this.graph = new GraphModule(this.client, defaultContext);
2288
- this.search = new SearchModule(this.client, defaultContext);
2289
- this.translation = new TranslationModule(this.client, defaultContext);
2290
- this.payments = new PaymentsModule(this.client, defaultContext);
2291
- if (config.temporalModuleType) {
2292
- this._temporalConfig = {
2293
- moduleType: config.temporalModuleType,
2294
- address: config.temporalAddress,
2295
- namespace: config.temporalNamespace,
2296
- taskQueue: config.temporalTaskQueue
2297
- };
2298
- }
2299
- if (config.eventQueue || resolveEventStreamsUrl()) {
2300
- this.eventQueueConfig = {
2301
- autoConnect: true,
2302
- maxReconnectAttempts: -1,
2303
- reconnectTimeWait: 2e3,
2304
- ...config.eventQueue
2305
- };
2306
- }
2307
- logger.info("[SDK] Burdenoff SDK initialized", {
2308
- workspacesApiUrl: config.workspacesApiUrl,
2309
- tenantApiUrl: config.tenantApiUrl,
2310
- hasDefaultContext: Object.keys(defaultContext).length > 0,
2311
- hasEventQueueConfig: !!this.eventQueueConfig,
2312
- hasTemporalConfig: !!config.temporalModuleType
2313
- });
2314
- this.scheduleBackgroundInit();
2315
- }
2316
- /**
2317
- * Schedule background initialization outside constructor
2318
- * Uses queueMicrotask to defer async work while maintaining initialization order
2319
- * @private
2320
- */
2321
- scheduleBackgroundInit() {
2322
- queueMicrotask(() => {
2323
- this.initializationPromise = this.initializeAsync();
2324
- });
2325
- }
2326
- /**
2327
- * Update SDK context
2328
- */
2329
- setContext(context) {
2330
- this.defaultContext = {
2331
- ...this.defaultContext,
2332
- ...context
2333
- };
2334
- this.client.updateContext(context);
2335
- ContextManager.setContext(this.defaultContext);
2336
- }
2337
- /**
2338
- * Get current context
2339
- */
2340
- getContext() {
2341
- return ContextManager.getContext();
2342
- }
2343
- /**
2344
- * Run function with specific context
2345
- */
2346
- async withContext(context, fn) {
2347
- return ContextManager.withContext(context, fn);
2348
- }
2349
- /**
2350
- * Background initialization for event queue and other async resources
2351
- * @private
2352
- */
2353
- async initializeAsync() {
2354
- const promises = [];
2355
- if (this.eventQueueConfig?.autoConnect) {
2356
- promises.push(this.initializeEventQueue().catch((error) => {
2357
- logger.warn("[SDK] Failed to auto-connect to Redis Streams", {
2358
- error
2359
- });
2360
- }));
2361
- }
2362
- await Promise.allSettled(promises);
2363
- }
2364
- /**
2365
- * Initialize the Redis Streams event publisher
2366
- * @private
2367
- */
2368
- async initializeEventQueue() {
2369
- if (!this.eventQueueConfig || this.eventPublisher) return;
2370
- const url = this.eventQueueConfig.url || resolveEventStreamsUrl();
2371
- if (!url) {
2372
- logger.warn("[SDK] No REDIS_STREAMS_URL / REDIS_URL available \u2014 event publisher disabled");
2373
- return;
2374
- }
2375
- const publisherConfig = {
2376
- type: QueueType.REDIS_STREAMS,
2377
- url,
2378
- password: this.eventQueueConfig.password,
2379
- name: this.eventQueueConfig.name || "burdenoff-sdk-publisher",
2380
- maxReconnectAttempts: this.eventQueueConfig.maxReconnectAttempts ?? -1,
2381
- reconnectTimeWait: this.eventQueueConfig.reconnectTimeWait ?? 2e3
2382
- };
2383
- this.eventPublisher = EventQueueFactory.createPublisher(publisherConfig);
2384
- await this.eventPublisher.connect();
2385
- logger.info("[SDK] Redis Streams event publisher initialized", {
2386
- url,
2387
- name: this.eventQueueConfig.name
2388
- });
2389
- }
2390
- /**
2391
- * Get the event publisher instance (lazy initialization).
2392
- *
2393
- * @example
2394
- * ```typescript
2395
- * const publisher = await sdk.getEventPublisher();
2396
- * await publisher.publish({
2397
- * subject: 'events.user.created',
2398
- * data: { userId: 'user-123' }
2399
- * });
2400
- * ```
2401
- */
2402
- async getEventPublisher() {
2403
- if (this.eventPublisher) return this.eventPublisher;
2404
- if (!this.eventQueueConfig) {
2405
- throw new Error("[SDK] Event queue not configured - set REDIS_STREAMS_URL / REDIS_URL or provide config.eventQueue");
2406
- }
2407
- if (!this.eventPublisherInitPromise) {
2408
- this.eventPublisherInitPromise = this.initializeEventQueue();
2409
- }
2410
- await this.eventPublisherInitPromise;
2411
- if (!this.eventPublisher) {
2412
- throw new Error("[SDK] Event publisher initialization failed");
2413
- }
2414
- return this.eventPublisher;
2415
- }
2416
- /**
2417
- * Wait for SDK initialization to complete
2418
- *
2419
- * @example
2420
- * ```typescript
2421
- * await sdk.waitForReady();
2422
- * ```
2423
- */
2424
- async waitForReady() {
2425
- if (this.initializationPromise) {
2426
- await this.initializationPromise;
2427
- }
2428
- }
2429
- /**
2430
- * Check event queue (Redis Streams) health status
2431
- *
2432
- * @example
2433
- * ```typescript
2434
- * const health = await sdk.isEventQueueHealthy();
2435
- * if (health.status === 'healthy') {
2436
- * console.log('Event queue is connected');
2437
- * }
2438
- * ```
2439
- */
2440
- async isEventQueueHealthy() {
2441
- if (!this.eventQueueConfig) {
2442
- return {
2443
- status: "not_configured",
2444
- connected: false
2445
- };
2446
- }
2447
- if (!this.eventPublisher) {
2448
- return {
2449
- status: "unhealthy",
2450
- connected: false,
2451
- url: this.eventQueueConfig.url,
2452
- details: {
2453
- reason: "Not initialized"
2454
- }
2455
- };
2456
- }
2457
- try {
2458
- const healthCheck = await this.eventPublisher.healthCheck();
2459
- return {
2460
- status: healthCheck.status,
2461
- connected: this.eventPublisher.isConnected(),
2462
- url: this.eventQueueConfig.url,
2463
- details: healthCheck.details
2464
- };
2465
- } catch (error) {
2466
- return {
2467
- status: "unhealthy",
2468
- connected: false,
2469
- url: this.eventQueueConfig.url,
2470
- details: {
2471
- error: error instanceof Error ? error.message : String(error)
2472
- }
2473
- };
2474
- }
2475
- }
2476
- /**
2477
- * Check Temporal health status
2478
- *
2479
- * @example
2480
- * ```typescript
2481
- * const health = await sdk.isTemporalHealthy();
2482
- * if (health.status === 'healthy') {
2483
- * console.log('Temporal is connected');
2484
- * }
2485
- * ```
2486
- */
2487
- async isTemporalHealthy() {
2488
- if (!this._temporal) {
2489
- return {
2490
- status: "not_configured",
2491
- connected: false
2492
- };
2493
- }
2494
- const config = this._temporal.getConfig();
2495
- if (!config.address) {
2496
- return {
2497
- status: "not_configured",
2498
- connected: false
2499
- };
2500
- }
2501
- try {
2502
- const client = this._temporal.getClient();
2503
- const connected = client.isClientConnected();
2504
- return {
2505
- status: connected ? "healthy" : "unhealthy",
2506
- connected,
2507
- address: config.address,
2508
- namespace: config.namespace,
2509
- details: {
2510
- taskQueue: config.taskQueue
2511
- }
2512
- };
2513
- } catch (error) {
2514
- return {
2515
- status: "unhealthy",
2516
- connected: false,
2517
- address: config.address,
2518
- namespace: config.namespace,
2519
- details: {
2520
- error: error instanceof Error ? error.message : String(error)
2521
- }
2522
- };
2523
- }
2524
- }
2525
- /**
2526
- * Get overall SDK health status
2527
- *
2528
- * @example
2529
- * ```typescript
2530
- * const health = await sdk.getHealthStatus();
2531
- * console.log('Event Queue:', health.eventQueue.status);
2532
- * console.log('Temporal:', health.temporal.status);
2533
- * ```
2534
- */
2535
- async getHealthStatus() {
2536
- const [eventQueue, temporal] = await Promise.all([
2537
- this.isEventQueueHealthy(),
2538
- this.isTemporalHealthy()
2539
- ]);
2540
- return {
2541
- eventQueue,
2542
- temporal
2543
- };
2544
- }
2545
- /**
2546
- * Graceful shutdown - disconnect all resources
2547
- *
2548
- * @example
2549
- * ```typescript
2550
- * // On application shutdown
2551
- * await sdk.shutdown({ timeout: 5000, force: true });
2552
- * ```
2553
- */
2554
- async shutdown(options = {}) {
2555
- if (this.isShuttingDown) {
2556
- logger.warn("[SDK] Shutdown already in progress");
2557
- return;
2558
- }
2559
- this.isShuttingDown = true;
2560
- const timeout = options.timeout ?? 5e3;
2561
- const force = options.force ?? true;
2562
- logger.info("[SDK] Starting graceful shutdown", {
2563
- timeout,
2564
- force
2565
- });
2566
- const shutdownPromises = [];
2567
- if (this.eventPublisher) {
2568
- shutdownPromises.push(this.eventPublisher.disconnect().catch((error) => {
2569
- logger.error("[SDK] Error disconnecting event publisher", {
2570
- error
2571
- });
2572
- }));
2573
- }
2574
- if (this._temporal) {
2575
- shutdownPromises.push(this._temporal.disconnect().catch((error) => {
2576
- logger.error("[SDK] Error disconnecting Temporal", {
2577
- error
2578
- });
2579
- }));
2580
- }
2581
- shutdownPromises.push(disposeAll(timeout));
2582
- try {
2583
- await Promise.race([
2584
- Promise.allSettled(shutdownPromises),
2585
- new Promise((_, reject) => setTimeout(() => reject(new Error("[SDK] Shutdown timeout exceeded")), timeout))
2586
- ]);
2587
- logger.info("[SDK] Shutdown completed successfully");
2588
- } catch (error) {
2589
- if (!force) {
2590
- throw error;
2591
- }
2592
- logger.warn("[SDK] Shutdown timeout exceeded, forcing shutdown", {
2593
- error
2594
- });
2595
- }
2596
- }
2597
- /**
2598
- * Create bootstrap instance
2599
- */
2600
- static createBootstrap(config) {
2601
- return createBootstrap(config);
2602
- }
423
+ client;
424
+ defaultContext;
425
+ eventPublisher = null;
426
+ eventPublisherInitPromise = null;
427
+ eventQueueConfig = null;
428
+ initializationPromise = null;
429
+ isShuttingDown = false;
430
+ /** Authentication module */
431
+ auth;
432
+ /** Notifications module (workspaces-backend) */
433
+ notifications;
434
+ /** Tenant Notifications module (tenant-backend - RECOMMENDED) */
435
+ tenantNotifications;
436
+ /** RBAC module */
437
+ rbac;
438
+ /** Activity tracking module */
439
+ activity;
440
+ /** Usage & Quota module */
441
+ usage;
442
+ /** Unified Tracker module (MOST IMPORTANT - use this for most operations) */
443
+ tracker;
444
+ /** Database helpers module */
445
+ database;
446
+ /** Events/Queue module */
447
+ events;
448
+ /** Graph integration module */
449
+ graph;
450
+ /** Search module */
451
+ search;
452
+ /** Translation module */
453
+ translation;
454
+ /** Payments module */
455
+ payments;
456
+ /** Temporal workflow orchestration module (lazy-loaded) */
457
+ _temporal = null;
458
+ _temporalPromise = null;
459
+ _temporalConfig = null;
460
+ /**
461
+ * Get Temporal workflow orchestration module (lazy-loaded)
462
+ * Only loads @temporalio/client when this method is called
463
+ *
464
+ * @returns Promise resolving to TemporalModule
465
+ * @example
466
+ * ```typescript
467
+ * const temporal = await sdk.getTemporalModule();
468
+ * await temporal.startWorkflow('myWorkflow', { ... });
469
+ * ```
470
+ */
471
+ async getTemporalModule() {
472
+ if (this._temporal) return this._temporal;
473
+ if (!this._temporalPromise) this._temporalPromise = this.loadTemporalModule();
474
+ return this._temporalPromise;
475
+ }
476
+ /**
477
+ * Load temporal module dynamically
478
+ * @private
479
+ */
480
+ async loadTemporalModule() {
481
+ const { TemporalModule: TM } = await import("./temporal/index.js");
482
+ this._temporal = this._temporalConfig?.moduleType ? new TM({
483
+ moduleType: this._temporalConfig.moduleType,
484
+ address: this._temporalConfig.address,
485
+ namespace: this._temporalConfig.namespace,
486
+ taskQueue: this._temporalConfig.taskQueue
487
+ }) : TM.fromEnv();
488
+ return this._temporal;
489
+ }
490
+ /** Logger instance */
491
+ logger;
492
+ /** Context manager */
493
+ context;
494
+ /**
495
+ * Create SDK instance
496
+ */
497
+ constructor(config, defaultContext = {}) {
498
+ this.client = new BurdenoffGraphQLClient(config, defaultContext);
499
+ this.defaultContext = defaultContext;
500
+ this.logger = logger;
501
+ if (config.logger) {
502
+ this.logger.setLevel(config.logger.level);
503
+ this.logger.setConsoleEnabled(config.logger.console);
504
+ if (config.logger.transport) this.logger.addTransport(config.logger.transport);
505
+ }
506
+ this.context = ContextManager;
507
+ if (Object.keys(defaultContext).length > 0) ContextManager.setContext(defaultContext);
508
+ this.auth = new AuthModule(this.client, defaultContext);
509
+ this.notifications = new NotificationsModule(this.client, defaultContext);
510
+ this.tenantNotifications = new TenantNotificationsModule(this.client, defaultContext);
511
+ this.rbac = new RBACModule(this.client, defaultContext);
512
+ this.activity = new ActivityModule(this.client, defaultContext);
513
+ this.usage = new UsageModule(this.client, defaultContext);
514
+ this.tracker = new TrackerModule(this.client, defaultContext);
515
+ this.database = DatabaseModule;
516
+ this.events = new EventsModule(this.client, defaultContext);
517
+ this.graph = new GraphModule(this.client, defaultContext);
518
+ this.search = new SearchModule(this.client, defaultContext);
519
+ this.translation = new TranslationModule(this.client, defaultContext);
520
+ this.payments = new PaymentsModule(this.client, defaultContext);
521
+ if (config.temporalModuleType) this._temporalConfig = {
522
+ moduleType: config.temporalModuleType,
523
+ address: config.temporalAddress,
524
+ namespace: config.temporalNamespace,
525
+ taskQueue: config.temporalTaskQueue
526
+ };
527
+ if (config.eventQueue || resolveEventStreamsUrl()) this.eventQueueConfig = {
528
+ autoConnect: true,
529
+ maxReconnectAttempts: -1,
530
+ reconnectTimeWait: 2e3,
531
+ ...config.eventQueue
532
+ };
533
+ logger.info("[SDK] Burdenoff SDK initialized", {
534
+ workspacesApiUrl: config.workspacesApiUrl,
535
+ tenantApiUrl: config.tenantApiUrl,
536
+ hasDefaultContext: Object.keys(defaultContext).length > 0,
537
+ hasEventQueueConfig: !!this.eventQueueConfig,
538
+ hasTemporalConfig: !!config.temporalModuleType
539
+ });
540
+ this.scheduleBackgroundInit();
541
+ }
542
+ /**
543
+ * Schedule background initialization outside constructor
544
+ * Uses queueMicrotask to defer async work while maintaining initialization order
545
+ * @private
546
+ */
547
+ scheduleBackgroundInit() {
548
+ queueMicrotask(() => {
549
+ this.initializationPromise = this.initializeAsync();
550
+ });
551
+ }
552
+ /**
553
+ * Update SDK context
554
+ */
555
+ setContext(context) {
556
+ this.defaultContext = {
557
+ ...this.defaultContext,
558
+ ...context
559
+ };
560
+ this.client.updateContext(context);
561
+ ContextManager.setContext(this.defaultContext);
562
+ }
563
+ /**
564
+ * Get current context
565
+ */
566
+ getContext() {
567
+ return ContextManager.getContext();
568
+ }
569
+ /**
570
+ * Run function with specific context
571
+ */
572
+ async withContext(context, fn) {
573
+ return ContextManager.withContext(context, fn);
574
+ }
575
+ /**
576
+ * Background initialization for event queue and other async resources
577
+ * @private
578
+ */
579
+ async initializeAsync() {
580
+ const promises = [];
581
+ if (this.eventQueueConfig?.autoConnect) promises.push(this.initializeEventQueue().catch((error) => {
582
+ logger.warn("[SDK] Failed to auto-connect to Redis Streams", { error });
583
+ }));
584
+ await Promise.allSettled(promises);
585
+ }
586
+ /**
587
+ * Initialize the Redis Streams event publisher
588
+ * @private
589
+ */
590
+ async initializeEventQueue() {
591
+ if (!this.eventQueueConfig || this.eventPublisher) return;
592
+ const url = this.eventQueueConfig.url || resolveEventStreamsUrl();
593
+ if (!url) {
594
+ logger.warn("[SDK] No REDIS_STREAMS_URL / REDIS_URL available — event publisher disabled");
595
+ return;
596
+ }
597
+ const publisherConfig = {
598
+ type: "redis-streams",
599
+ url,
600
+ password: this.eventQueueConfig.password,
601
+ name: this.eventQueueConfig.name || "burdenoff-sdk-publisher",
602
+ maxReconnectAttempts: this.eventQueueConfig.maxReconnectAttempts ?? -1,
603
+ reconnectTimeWait: this.eventQueueConfig.reconnectTimeWait ?? 2e3
604
+ };
605
+ this.eventPublisher = EventQueueFactory.createPublisher(publisherConfig);
606
+ await this.eventPublisher.connect();
607
+ logger.info("[SDK] Redis Streams event publisher initialized", {
608
+ url,
609
+ name: this.eventQueueConfig.name
610
+ });
611
+ }
612
+ /**
613
+ * Get the event publisher instance (lazy initialization).
614
+ *
615
+ * @example
616
+ * ```typescript
617
+ * const publisher = await sdk.getEventPublisher();
618
+ * await publisher.publish({
619
+ * subject: 'events.user.created',
620
+ * data: { userId: 'user-123' }
621
+ * });
622
+ * ```
623
+ */
624
+ async getEventPublisher() {
625
+ if (this.eventPublisher) return this.eventPublisher;
626
+ if (!this.eventQueueConfig) throw new Error("[SDK] Event queue not configured - set REDIS_STREAMS_URL / REDIS_URL or provide config.eventQueue");
627
+ if (!this.eventPublisherInitPromise) this.eventPublisherInitPromise = this.initializeEventQueue();
628
+ await this.eventPublisherInitPromise;
629
+ if (!this.eventPublisher) throw new Error("[SDK] Event publisher initialization failed");
630
+ return this.eventPublisher;
631
+ }
632
+ /**
633
+ * Wait for SDK initialization to complete
634
+ *
635
+ * @example
636
+ * ```typescript
637
+ * await sdk.waitForReady();
638
+ * ```
639
+ */
640
+ async waitForReady() {
641
+ if (this.initializationPromise) await this.initializationPromise;
642
+ }
643
+ /**
644
+ * Check event queue (Redis Streams) health status
645
+ *
646
+ * @example
647
+ * ```typescript
648
+ * const health = await sdk.isEventQueueHealthy();
649
+ * if (health.status === 'healthy') {
650
+ * console.log('Event queue is connected');
651
+ * }
652
+ * ```
653
+ */
654
+ async isEventQueueHealthy() {
655
+ if (!this.eventQueueConfig) return {
656
+ status: "not_configured",
657
+ connected: false
658
+ };
659
+ if (!this.eventPublisher) return {
660
+ status: "unhealthy",
661
+ connected: false,
662
+ url: this.eventQueueConfig.url,
663
+ details: { reason: "Not initialized" }
664
+ };
665
+ try {
666
+ const healthCheck = await this.eventPublisher.healthCheck();
667
+ return {
668
+ status: healthCheck.status,
669
+ connected: this.eventPublisher.isConnected(),
670
+ url: this.eventQueueConfig.url,
671
+ details: healthCheck.details
672
+ };
673
+ } catch (error) {
674
+ return {
675
+ status: "unhealthy",
676
+ connected: false,
677
+ url: this.eventQueueConfig.url,
678
+ details: { error: error instanceof Error ? error.message : String(error) }
679
+ };
680
+ }
681
+ }
682
+ /**
683
+ * Check Temporal health status
684
+ *
685
+ * @example
686
+ * ```typescript
687
+ * const health = await sdk.isTemporalHealthy();
688
+ * if (health.status === 'healthy') {
689
+ * console.log('Temporal is connected');
690
+ * }
691
+ * ```
692
+ */
693
+ async isTemporalHealthy() {
694
+ if (!this._temporal) return {
695
+ status: "not_configured",
696
+ connected: false
697
+ };
698
+ const config = this._temporal.getConfig();
699
+ if (!config.address) return {
700
+ status: "not_configured",
701
+ connected: false
702
+ };
703
+ try {
704
+ const connected = this._temporal.getClient().isClientConnected();
705
+ return {
706
+ status: connected ? "healthy" : "unhealthy",
707
+ connected,
708
+ address: config.address,
709
+ namespace: config.namespace,
710
+ details: { taskQueue: config.taskQueue }
711
+ };
712
+ } catch (error) {
713
+ return {
714
+ status: "unhealthy",
715
+ connected: false,
716
+ address: config.address,
717
+ namespace: config.namespace,
718
+ details: { error: error instanceof Error ? error.message : String(error) }
719
+ };
720
+ }
721
+ }
722
+ /**
723
+ * Get overall SDK health status
724
+ *
725
+ * @example
726
+ * ```typescript
727
+ * const health = await sdk.getHealthStatus();
728
+ * console.log('Event Queue:', health.eventQueue.status);
729
+ * console.log('Temporal:', health.temporal.status);
730
+ * ```
731
+ */
732
+ async getHealthStatus() {
733
+ const [eventQueue, temporal] = await Promise.all([this.isEventQueueHealthy(), this.isTemporalHealthy()]);
734
+ return {
735
+ eventQueue,
736
+ temporal
737
+ };
738
+ }
739
+ /**
740
+ * Graceful shutdown - disconnect all resources
741
+ *
742
+ * @example
743
+ * ```typescript
744
+ * // On application shutdown
745
+ * await sdk.shutdown({ timeout: 5000, force: true });
746
+ * ```
747
+ */
748
+ async shutdown(options = {}) {
749
+ if (this.isShuttingDown) {
750
+ logger.warn("[SDK] Shutdown already in progress");
751
+ return;
752
+ }
753
+ this.isShuttingDown = true;
754
+ const timeout = options.timeout ?? 5e3;
755
+ const force = options.force ?? true;
756
+ logger.info("[SDK] Starting graceful shutdown", {
757
+ timeout,
758
+ force
759
+ });
760
+ const shutdownPromises = [];
761
+ if (this.eventPublisher) shutdownPromises.push(this.eventPublisher.disconnect().catch((error) => {
762
+ logger.error("[SDK] Error disconnecting event publisher", { error });
763
+ }));
764
+ if (this._temporal) shutdownPromises.push(this._temporal.disconnect().catch((error) => {
765
+ logger.error("[SDK] Error disconnecting Temporal", { error });
766
+ }));
767
+ shutdownPromises.push(disposeAll(timeout));
768
+ try {
769
+ await Promise.race([Promise.allSettled(shutdownPromises), new Promise((_, reject) => setTimeout(() => reject(/* @__PURE__ */ new Error("[SDK] Shutdown timeout exceeded")), timeout))]);
770
+ logger.info("[SDK] Shutdown completed successfully");
771
+ } catch (error) {
772
+ if (!force) throw error;
773
+ logger.warn("[SDK] Shutdown timeout exceeded, forcing shutdown", { error });
774
+ }
775
+ }
776
+ /**
777
+ * Create bootstrap instance
778
+ */
779
+ static createBootstrap(config) {
780
+ return createBootstrap(config);
781
+ }
2603
782
  };
2604
- var index_default = BurdenoffSDK;
783
+ /**
784
+ * Create SDK instance (convenience function)
785
+ */
2605
786
  function createSDK(config, context) {
2606
- return new BurdenoffSDK(config, context);
787
+ return new BurdenoffSDK(config, context);
2607
788
  }
2608
- __name(createSDK, "createSDK");
2609
789
 
2610
- export { BootstrapModule, BurdenoffGraphQLClient, BurdenoffSDK, PaymentsModule, SearchModule, TenantBackendClient, TranslationModule, createBootstrap, createSDK, createTenantBackendClient, index_default as default };
2611
- //# sourceMappingURL=index.js.map
790
+ export { ActivityModule, ActivityOperationUnsupportedError, ai_credits_exports as AiCredits, AuthModule, BillingUsageClient, BootstrapModule, BurdenoffGraphQLClient, BurdenoffSDK, BurdenoffSDK as default, cache_exports as Cache, captcha_exports as Captcha, ContextManager, crypto_exports as Crypto, DEFAULT_CIRCUIT_BREAKER_CONFIG, DEFAULT_GATEWAY_RETRY_CONFIG, DEFAULT_GATEWAY_ROUTING, DEFAULT_LAYER_RESOURCES, DEFAULT_LAYER_STREAMS, dataloader_exports as DataLoader, DatabaseModule, event_queue_exports as EventQueue, EventsModule, export_exports as Export, feature_flags_exports as FeatureFlags, files_exports as Files, gateway_exports as Gateway, graph_exports as Graph, GraphModule, graphql_exports as GraphQL, i18n_exports as I18n, init_exports as Init, instrumentation_exports as Instrumentation, layer_exports as Layer, lifecycle_exports as Lifecycle, logger_exports as Logger, middleware_exports as Middleware, NAME_MAX_LENGTH, NAME_MIN_LENGTH, tenant_notifications_exports as Notifications, NotificationsModule, observability_exports as Observability, PRODUCT_RENAMES, PRODUCT_RENAME_EMIT, PRODUCT_SLUG_ALIASES, PaymentsModule, platform_exports as Platform, prisma_exports as Prisma, product_alias_exports as ProductAlias, RBACModule, RENAME_CONCERNS, RESOURCE_CAP_DEFAULTS, RbacCoverageError, ResourceCapExceededError, ResourceCapsModule, SearchModule, sharing_exports as Sharing, tags_exports as Tags, TemporalClient, TemporalClientFactory, TemporalModule, TemporalWorker, TemporalWorkerFactory, TemporalWorkerManager, TenantBackendClient, TrackerModule, TranslationModule, USERNAME_MAX_LENGTH, USERNAME_MIN_LENGTH, UsageModule, utils_exports as Utils, validation_exports as Validation, analyzeRbacCoverage, assertRbacCoverage, billingIdVariants, configureResourceCaps, createBootstrap, createInternalClient, createInternalClientForTenant, createInternalClientForWorkspaces, createRBACDirective, createRBACDirectiveForLayer, createRBACDirectiveFromEnv, createSDK, createTenantBackendClient, createTranslator, disposeAll, emitBillingId, emitName, emitProductSlug, emitQuotaKey, emitRbacResource, emitTemplateKey, getLanguage, getLocale, getRegisteredDisposableCount, getResourceCaps, hasI18n, isCaptchaEnabled, isLegacyName, isSameBillingId, isSameGraphQLName, isSameName, isSameProductSlug, isSameQuotaKey, isSameRbacResource, isSameTemplateKey, lengthInCodePoints, nameVariants, normalizeBillingId, normalizeGraphQLName, normalizeProductSlug, normalizeQuotaKey, normalizeRbacResource, normalizeTemplateKey, productSlugVariants, quotaKeyVariants, rbacResourceVariants, readRenamedEnv, registerDisposable, t, templateKeyVariants, toCurrentName, toLegacyName, unregisterDisposable, validateName, validateUserFields, validateUsername, verifyCaptcha, verifyCaptchaIfEnabled };
2612
791
  //# sourceMappingURL=index.js.map