@burdenoff/be-sdk 2026.1110.2 → 2026.1110.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (497) hide show
  1. package/configs/eslint/index.js +1 -1
  2. package/configs/tsconfig/tsconfig.json +1 -1
  3. package/dist/EventQueueFactory-9NGZV9jl.js +1457 -0
  4. package/dist/EventQueueFactory-9NGZV9jl.js.map +1 -0
  5. package/dist/RedisStreamsConnection-CY8WySJy.js +283 -0
  6. package/dist/RedisStreamsConnection-CY8WySJy.js.map +1 -0
  7. package/dist/activity/index.d.ts +165 -0
  8. package/dist/activity/index.js +389 -0
  9. package/dist/activity/index.js.map +1 -0
  10. package/dist/ai-credits/index.d.ts +2 -3
  11. package/dist/ai-credits/index.js +3 -4
  12. package/dist/ai-credits/index.js.map +1 -1
  13. package/dist/ai-credits-xxfwGpHS.js +546 -0
  14. package/dist/ai-credits-xxfwGpHS.js.map +1 -0
  15. package/dist/{assistant-session-CJZhF4D6.d.ts → assistant-session-DA5ZKJOr.d.ts} +4 -5
  16. package/dist/auth/index.d.ts +2 -77
  17. package/dist/auth/index.js +3 -7
  18. package/dist/auth/index.js.map +1 -1
  19. package/dist/auth-C5ctwSLp.js +228 -0
  20. package/dist/auth-C5ctwSLp.js.map +1 -0
  21. package/dist/bootstrap/index.d.ts +74 -0
  22. package/dist/bootstrap/index.js +282 -0
  23. package/dist/bootstrap/index.js.map +1 -0
  24. package/dist/cache/index.d.ts +2 -3
  25. package/dist/cache/index.js +3 -7
  26. package/dist/cache/index.js.map +1 -1
  27. package/dist/cache-CU0uLwcS.js +1837 -0
  28. package/dist/cache-CU0uLwcS.js.map +1 -0
  29. package/dist/captcha/index.d.ts +2 -1
  30. package/dist/captcha/index.js +3 -3
  31. package/dist/captcha/index.js.map +1 -1
  32. package/dist/captcha-BT7yh1YS.js +77 -0
  33. package/dist/captcha-BT7yh1YS.js.map +1 -0
  34. package/dist/client/internal-client.d.ts +4 -7
  35. package/dist/client/internal-client.js +172 -4
  36. package/dist/client/internal-client.js.map +1 -1
  37. package/dist/client-BgAEvDC2.d.ts +86 -0
  38. package/dist/client-sAJTrb4i.js +565 -0
  39. package/dist/client-sAJTrb4i.js.map +1 -0
  40. package/dist/collector-endpoint-iyQYeI50.js +50 -0
  41. package/dist/collector-endpoint-iyQYeI50.js.map +1 -0
  42. package/dist/context/index.d.ts +35 -0
  43. package/dist/context/index.js +283 -0
  44. package/dist/context/index.js.map +1 -0
  45. package/dist/crypto/index.d.ts +2 -1
  46. package/dist/crypto/index.js +3 -3
  47. package/dist/crypto/index.js.map +1 -1
  48. package/dist/crypto-DO9fM0FO.js +145 -0
  49. package/dist/crypto-DO9fM0FO.js.map +1 -0
  50. package/dist/database/index.d.ts +104 -108
  51. package/dist/database/index.js +468 -6
  52. package/dist/database/index.js.map +1 -1
  53. package/dist/dataloader/index.d.ts +2 -1
  54. package/dist/dataloader/index.js +3 -3
  55. package/dist/dataloader/index.js.map +1 -1
  56. package/dist/dataloader-DwpT3YoS.js +294 -0
  57. package/dist/dataloader-DwpT3YoS.js.map +1 -0
  58. package/dist/deployed-environment-p_Tdl3sT.js +38 -0
  59. package/dist/deployed-environment-p_Tdl3sT.js.map +1 -0
  60. package/dist/dist-BGKdXVy3.js +1718 -0
  61. package/dist/dist-BGKdXVy3.js.map +1 -0
  62. package/dist/env-DdaoGjIt.js +74 -0
  63. package/dist/env-DdaoGjIt.js.map +1 -0
  64. package/dist/event-queue/index.d.ts +2 -7
  65. package/dist/event-queue/index.js +7 -9
  66. package/dist/event-queue/index.js.map +1 -1
  67. package/dist/event-queue-Cw-YJPY_.js +1384 -0
  68. package/dist/event-queue-Cw-YJPY_.js.map +1 -0
  69. package/dist/{explicit-activity-scope-CCoxVwAr.d.ts → explicit-activity-scope-D8VeGGpt.d.ts} +1 -2
  70. package/dist/explicit-activity-scope-DikJ7NAE.js +57 -0
  71. package/dist/explicit-activity-scope-DikJ7NAE.js.map +1 -0
  72. package/dist/export/index.d.ts +2 -2
  73. package/dist/export/index.js +3 -14
  74. package/dist/export/index.js.map +1 -1
  75. package/dist/export-DJXE3Osa.js +642 -0
  76. package/dist/export-DJXE3Osa.js.map +1 -0
  77. package/dist/feature-flags/index.d.ts +2 -10
  78. package/dist/feature-flags/index.js +3 -6
  79. package/dist/feature-flags/index.js.map +1 -1
  80. package/dist/feature-flags-CP1KRgwD.js +422 -0
  81. package/dist/feature-flags-CP1KRgwD.js.map +1 -0
  82. package/dist/files/index.d.ts +2 -3
  83. package/dist/files/index.js +3 -4
  84. package/dist/files/index.js.map +1 -1
  85. package/dist/files-h5U-D2AF.js +830 -0
  86. package/dist/files-h5U-D2AF.js.map +1 -0
  87. package/dist/gateway/index.d.ts +4 -6
  88. package/dist/gateway/index.js +7 -13
  89. package/dist/gateway/index.js.map +1 -1
  90. package/dist/gateway/security/index.d.ts +2 -2
  91. package/dist/gateway/security/index.js +3 -5
  92. package/dist/gateway/security/index.js.map +1 -1
  93. package/dist/gateway-ByVo-n37.js +50 -0
  94. package/dist/gateway-ByVo-n37.js.map +1 -0
  95. package/dist/graph/index.d.ts +3 -10
  96. package/dist/graph/index.js +4 -13
  97. package/dist/graph/index.js.map +1 -1
  98. package/dist/graph-CR7u4lpl.js +2152 -0
  99. package/dist/graph-CR7u4lpl.js.map +1 -0
  100. package/dist/graph-emitter-CdOXP7Tn.js +621 -0
  101. package/dist/graph-emitter-CdOXP7Tn.js.map +1 -0
  102. package/dist/graphql/index.d.ts +3 -2
  103. package/dist/graphql/index.js +4 -6
  104. package/dist/graphql/index.js.map +1 -1
  105. package/dist/graphql/services/index.d.ts +2 -24
  106. package/dist/graphql/services/index.js +3 -4
  107. package/dist/graphql/services/index.js.map +1 -1
  108. package/dist/graphql-CUDyhibV.d.ts +21 -0
  109. package/dist/graphql-DHAHHcww.js +161 -0
  110. package/dist/graphql-DHAHHcww.js.map +1 -0
  111. package/dist/i18n/index.d.ts +3 -3
  112. package/dist/i18n/index.js +3 -4
  113. package/dist/i18n/index.js.map +1 -1
  114. package/dist/i18n-BBMYFd0P.js +860 -0
  115. package/dist/i18n-BBMYFd0P.js.map +1 -0
  116. package/dist/import-optional-peer-B82VYxeX.js +18 -0
  117. package/dist/import-optional-peer-B82VYxeX.js.map +1 -0
  118. package/dist/index-3KOZ1zN9.d.ts +233 -0
  119. package/dist/index-ADmsX0BI.d.ts +646 -0
  120. package/dist/index-B2LCaK0R.d.ts +500 -0
  121. package/dist/index-BBqooJ52.d.ts +45 -0
  122. package/dist/index-BGzMYJsm.d.ts +209 -0
  123. package/dist/index-BMIMnp6T.d.ts +8 -0
  124. package/dist/index-BVOL7458.d.ts +10 -0
  125. package/dist/index-BcqQs-Uq.d.ts +69 -0
  126. package/dist/index-BeVtqGO-.d.ts +208 -0
  127. package/dist/index-BiTzGUZP.d.ts +114 -0
  128. package/dist/index-C0qLquY0.d.ts +150 -0
  129. package/dist/index-C5uEKchX.d.ts +60 -0
  130. package/dist/index-CDOqxSIi.d.ts +37 -0
  131. package/dist/index-CG6wj66Y.d.ts +148 -0
  132. package/dist/index-CHwMhK6v.d.ts +63 -0
  133. package/dist/index-CIgoeobA.d.ts +145 -0
  134. package/dist/index-CPQDMSFS.d.ts +103 -0
  135. package/dist/index-CSRcgkVi.d.ts +23 -0
  136. package/dist/index-CTTwo9av.d.ts +102 -0
  137. package/dist/index-CVCyKzhB.d.ts +207 -0
  138. package/dist/index-C_GXXF32.d.ts +704 -0
  139. package/dist/index-CaM9JUcc.d.ts +144 -0
  140. package/dist/index-CliOgq6L.d.ts +203 -0
  141. package/dist/index-Cot73bdh.d.ts +63 -0
  142. package/dist/index-DGgh9DWn.d.ts +59 -0
  143. package/dist/index-DY3dNhMN.d.ts +420 -0
  144. package/dist/index-DqbGqfAy.d.ts +127 -0
  145. package/dist/index-Dt1HJPTX.d.ts +12 -0
  146. package/dist/index-DtI6aBtB.d.ts +22 -0
  147. package/dist/index-FKohsiex.d.ts +38 -0
  148. package/dist/index-FRRaa6h2.d.ts +999 -0
  149. package/dist/index-FbXPfen7.d.ts +132 -0
  150. package/dist/index-MArCb8Aq.d.ts +306 -0
  151. package/dist/index-U_tu3zUl.d.ts +303 -0
  152. package/dist/index-YOShAwkq.d.ts +45 -0
  153. package/dist/index-cmR9k9ga.d.ts +26 -0
  154. package/dist/index-yBSjMY32.d.ts +24 -0
  155. package/dist/index-zd_NPGJo.d.ts +206 -0
  156. package/dist/index.d.ts +106 -609
  157. package/dist/index.js +769 -2590
  158. package/dist/index.js.map +1 -1
  159. package/dist/init/index.d.ts +2 -2
  160. package/dist/init/index.js +3 -16
  161. package/dist/init/index.js.map +1 -1
  162. package/dist/init-CQPFmOOe.js +325 -0
  163. package/dist/init-CQPFmOOe.js.map +1 -0
  164. package/dist/instrumentation/index.d.ts +3 -4
  165. package/dist/instrumentation/index.js +5 -5
  166. package/dist/instrumentation/index.js.map +1 -1
  167. package/dist/instrumentation-xkkmDgJ0.js +1678 -0
  168. package/dist/instrumentation-xkkmDgJ0.js.map +1 -0
  169. package/dist/lake/index.d.ts +50 -54
  170. package/dist/lake/index.js +169 -193
  171. package/dist/lake/index.js.map +1 -1
  172. package/dist/layer/index.d.ts +3 -2
  173. package/dist/layer/index.js +4 -5
  174. package/dist/layer/index.js.map +1 -1
  175. package/dist/layer-BZBZZWeV.d.ts +69 -0
  176. package/dist/layer-Bcix-WCl.js +105 -0
  177. package/dist/layer-Bcix-WCl.js.map +1 -0
  178. package/dist/layer-CEKy6cm8.js +252 -0
  179. package/dist/layer-CEKy6cm8.js.map +1 -0
  180. package/dist/lifecycle/index.d.ts +2 -1
  181. package/dist/lifecycle/index.js +3 -4
  182. package/dist/lifecycle/index.js.map +1 -1
  183. package/dist/lifecycle-DeoLSX0U.js +76 -0
  184. package/dist/lifecycle-DeoLSX0U.js.map +1 -0
  185. package/dist/logger/index.d.ts +2 -3
  186. package/dist/logger/index.js +3 -3
  187. package/dist/logger/index.js.map +1 -1
  188. package/dist/logger-B6rCpb7D.js +290 -0
  189. package/dist/logger-B6rCpb7D.js.map +1 -0
  190. package/dist/metrics/index.d.ts +13 -14
  191. package/dist/metrics/index.js +3 -4
  192. package/dist/metrics/index.js.map +1 -1
  193. package/dist/metrics-BrLwNUrb.js +52 -0
  194. package/dist/metrics-BrLwNUrb.js.map +1 -0
  195. package/dist/metrics-collector-C2eShrlW.js +922 -0
  196. package/dist/metrics-collector-C2eShrlW.js.map +1 -0
  197. package/dist/middleware/index.d.ts +3 -3
  198. package/dist/middleware/index.js +3 -4
  199. package/dist/middleware/index.js.map +1 -1
  200. package/dist/middleware-CUxJVUpD.js +1243 -0
  201. package/dist/middleware-CUxJVUpD.js.map +1 -0
  202. package/dist/middleware-Cq0zFMGp.js +253 -0
  203. package/dist/middleware-Cq0zFMGp.js.map +1 -0
  204. package/dist/notifications/index.d.ts +2 -5
  205. package/dist/notifications/index.js +3 -6
  206. package/dist/notifications/index.js.map +1 -1
  207. package/dist/notifications-DY_i37WN.js +869 -0
  208. package/dist/notifications-DY_i37WN.js.map +1 -0
  209. package/dist/observability/index.d.ts +2 -3
  210. package/dist/observability/index.js +3 -4
  211. package/dist/observability/index.js.map +1 -1
  212. package/dist/observability-DBDXipTU.js +272 -0
  213. package/dist/observability-DBDXipTU.js.map +1 -0
  214. package/dist/payments/index.d.ts +144 -0
  215. package/dist/payments/index.js +404 -0
  216. package/dist/payments/index.js.map +1 -0
  217. package/dist/platform/index.d.ts +2 -1
  218. package/dist/platform/index.js +3 -5
  219. package/dist/platform/index.js.map +1 -1
  220. package/dist/platform-DZwczW7v.js +1510 -0
  221. package/dist/platform-DZwczW7v.js.map +1 -0
  222. package/dist/prisma/generator/index.d.ts +1 -1
  223. package/dist/prisma/generator/index.js +97 -84
  224. package/dist/prisma/generator/index.js.map +1 -1
  225. package/dist/prisma/index.d.ts +4 -7
  226. package/dist/prisma/index.js +5 -12
  227. package/dist/prisma/index.js.map +1 -1
  228. package/dist/prisma-BzOOdt79.js +863 -0
  229. package/dist/prisma-BzOOdt79.js.map +1 -0
  230. package/dist/prisma-extension-Cfl09swM.d.ts +172 -0
  231. package/dist/product-alias/index.d.ts +2 -1
  232. package/dist/product-alias/index.js +3 -3
  233. package/dist/product-alias/index.js.map +1 -1
  234. package/dist/product-alias-BPqtskMq.js +273 -0
  235. package/dist/product-alias-BPqtskMq.js.map +1 -0
  236. package/dist/rate-limit-CBrK_U5H.js +142 -0
  237. package/dist/rate-limit-CBrK_U5H.js.map +1 -0
  238. package/dist/rbac/index.d.ts +2 -122
  239. package/dist/rbac/index.js +3 -6
  240. package/dist/rbac/index.js.map +1 -1
  241. package/dist/rbac-Dvz0YzEt.js +1486 -0
  242. package/dist/rbac-Dvz0YzEt.js.map +1 -0
  243. package/dist/resource-caps/index.d.ts +66 -72
  244. package/dist/resource-caps/index.js +430 -5
  245. package/dist/resource-caps/index.js.map +1 -1
  246. package/dist/rolldown-runtime-ad2WFvuA.js +17 -0
  247. package/dist/sdk-Dju9o-sq.js +124 -0
  248. package/dist/sdk-Dju9o-sq.js.map +1 -0
  249. package/dist/search/index.d.ts +112 -0
  250. package/dist/search/index.js +266 -0
  251. package/dist/search/index.js.map +1 -0
  252. package/dist/security/index.d.ts +2 -0
  253. package/dist/security/index.js +4 -0
  254. package/dist/security/index.js.map +1 -0
  255. package/dist/security/rate-limit/index.d.ts +2 -0
  256. package/dist/security/rate-limit/index.js +4 -0
  257. package/dist/security/rate-limit/index.js.map +1 -0
  258. package/dist/security-DIG-95Ic.js +1647 -0
  259. package/dist/security-DIG-95Ic.js.map +1 -0
  260. package/dist/server/index.d.ts +7 -164
  261. package/dist/server/index.js +2001 -1507
  262. package/dist/server/index.js.map +1 -1
  263. package/dist/service-jwt-Bu-WNA_-.js +80 -0
  264. package/dist/service-jwt-Bu-WNA_-.js.map +1 -0
  265. package/dist/services-BWzfz7vG.js +102 -0
  266. package/dist/services-BWzfz7vG.js.map +1 -0
  267. package/dist/sharding/index.d.ts +41 -44
  268. package/dist/sharding/index.js +156 -137
  269. package/dist/sharding/index.js.map +1 -1
  270. package/dist/sharing/index.d.ts +2 -1
  271. package/dist/sharing/index.js +3 -4
  272. package/dist/sharing/index.js.map +1 -1
  273. package/dist/sharing-CflDsSJ-.js +911 -0
  274. package/dist/sharing-CflDsSJ-.js.map +1 -0
  275. package/dist/stub-BUnfMiAS.js +577 -0
  276. package/dist/stub-BUnfMiAS.js.map +1 -0
  277. package/dist/tags/index.d.ts +2 -3
  278. package/dist/tags/index.js +3 -4
  279. package/dist/tags/index.js.map +1 -1
  280. package/dist/tags-CbijgoqR.js +868 -0
  281. package/dist/{chunk-PBZFAAOM.js.map → tags-CbijgoqR.js.map} +1 -1
  282. package/dist/telemetry/index.d.ts +64 -76
  283. package/dist/telemetry/index.js +369 -201
  284. package/dist/telemetry/index.js.map +1 -1
  285. package/dist/temporal/index.d.ts +2 -148
  286. package/dist/temporal/index.js +3 -5
  287. package/dist/temporal/index.js.map +1 -1
  288. package/dist/temporal-B534uYK8.js +706 -0
  289. package/dist/temporal-B534uYK8.js.map +1 -0
  290. package/dist/tracker/index.d.ts +5 -11
  291. package/dist/tracker/index.js +7 -20
  292. package/dist/tracker/index.js.map +1 -1
  293. package/dist/tracker-PQztSlhJ.js +458 -0
  294. package/dist/tracker-PQztSlhJ.js.map +1 -0
  295. package/dist/translation/index.d.ts +120 -0
  296. package/dist/translation/index.js +573 -0
  297. package/dist/translation/index.js.map +1 -0
  298. package/dist/types/index.d.ts +3 -0
  299. package/dist/types/index.js +90 -0
  300. package/dist/types/index.js.map +1 -0
  301. package/dist/types-BYMYND1L.js +44 -0
  302. package/dist/types-BYMYND1L.js.map +1 -0
  303. package/dist/types-C6EKaS3V.d.ts +106 -0
  304. package/dist/types-CWybW61E.d.ts +323 -0
  305. package/dist/types-C_yfu3XK.d.ts +34 -0
  306. package/dist/types-DgaQqvxo.d.ts +70 -0
  307. package/dist/usage/index.d.ts +2 -213
  308. package/dist/usage/index.js +3 -15
  309. package/dist/usage/index.js.map +1 -1
  310. package/dist/usage-BRqVP3CJ.js +682 -0
  311. package/dist/usage-BRqVP3CJ.js.map +1 -0
  312. package/dist/utils/index.d.ts +2 -1
  313. package/dist/utils/index.js +3 -3
  314. package/dist/utils/index.js.map +1 -1
  315. package/dist/utils-DL85Tnbn.js +500 -0
  316. package/dist/utils-DL85Tnbn.js.map +1 -0
  317. package/dist/validation/index.d.ts +2 -2
  318. package/dist/validation/index.js +3 -3
  319. package/dist/validation/index.js.map +1 -1
  320. package/dist/validation-CPUITdMk.js +762 -0
  321. package/dist/validation-CPUITdMk.js.map +1 -0
  322. package/dist/workspace-extension-COrC0dYi.js +979 -0
  323. package/dist/workspace-extension-COrC0dYi.js.map +1 -0
  324. package/dist/{workspace-extension-BGwTOV_r.d.ts → workspace-extension-DTFTdGVF.d.ts} +43 -45
  325. package/package.json +7 -10
  326. package/dist/EventQueueFactory-GXC3A7DH.js +0 -8
  327. package/dist/EventQueueFactory-GXC3A7DH.js.map +0 -1
  328. package/dist/chunk-4XIBXZ6J.js +0 -276
  329. package/dist/chunk-4XIBXZ6J.js.map +0 -1
  330. package/dist/chunk-554Z4C2K.js +0 -1006
  331. package/dist/chunk-554Z4C2K.js.map +0 -1
  332. package/dist/chunk-5CAFHK2Z.js +0 -107
  333. package/dist/chunk-5CAFHK2Z.js.map +0 -1
  334. package/dist/chunk-63ZXJ42X.js +0 -451
  335. package/dist/chunk-63ZXJ42X.js.map +0 -1
  336. package/dist/chunk-6XEXJATV.js +0 -304
  337. package/dist/chunk-6XEXJATV.js.map +0 -1
  338. package/dist/chunk-726AR6Q7.js +0 -1532
  339. package/dist/chunk-726AR6Q7.js.map +0 -1
  340. package/dist/chunk-A5F6Z5UE.js +0 -21
  341. package/dist/chunk-A5F6Z5UE.js.map +0 -1
  342. package/dist/chunk-A6DE32ZS.js +0 -1507
  343. package/dist/chunk-A6DE32ZS.js.map +0 -1
  344. package/dist/chunk-AXJDGQPE.js +0 -690
  345. package/dist/chunk-AXJDGQPE.js.map +0 -1
  346. package/dist/chunk-BJQOGOVW.js +0 -602
  347. package/dist/chunk-BJQOGOVW.js.map +0 -1
  348. package/dist/chunk-CFXWH2IS.js +0 -52
  349. package/dist/chunk-CFXWH2IS.js.map +0 -1
  350. package/dist/chunk-DRWH5XCJ.js +0 -876
  351. package/dist/chunk-DRWH5XCJ.js.map +0 -1
  352. package/dist/chunk-E4QNLVY4.js +0 -909
  353. package/dist/chunk-E4QNLVY4.js.map +0 -1
  354. package/dist/chunk-EBDHIL7V.js +0 -774
  355. package/dist/chunk-EBDHIL7V.js.map +0 -1
  356. package/dist/chunk-ELU7VL3E.js +0 -245
  357. package/dist/chunk-ELU7VL3E.js.map +0 -1
  358. package/dist/chunk-FZRODKIN.js +0 -31
  359. package/dist/chunk-FZRODKIN.js.map +0 -1
  360. package/dist/chunk-GCIB76AJ.js +0 -882
  361. package/dist/chunk-GCIB76AJ.js.map +0 -1
  362. package/dist/chunk-HC6MPUIH.js +0 -1571
  363. package/dist/chunk-HC6MPUIH.js.map +0 -1
  364. package/dist/chunk-HNMHPSAM.js +0 -272
  365. package/dist/chunk-HNMHPSAM.js.map +0 -1
  366. package/dist/chunk-HTLEGD3Q.js +0 -1480
  367. package/dist/chunk-HTLEGD3Q.js.map +0 -1
  368. package/dist/chunk-I3KOWRT3.js +0 -89
  369. package/dist/chunk-I3KOWRT3.js.map +0 -1
  370. package/dist/chunk-ID3WR4JS.js +0 -509
  371. package/dist/chunk-ID3WR4JS.js.map +0 -1
  372. package/dist/chunk-JS52ZHTK.js +0 -1346
  373. package/dist/chunk-JS52ZHTK.js.map +0 -1
  374. package/dist/chunk-JVMAQOA3.js +0 -521
  375. package/dist/chunk-JVMAQOA3.js.map +0 -1
  376. package/dist/chunk-KH4TRQCO.js +0 -1063
  377. package/dist/chunk-KH4TRQCO.js.map +0 -1
  378. package/dist/chunk-KJOSPVB2.js +0 -57
  379. package/dist/chunk-KJOSPVB2.js.map +0 -1
  380. package/dist/chunk-KO2ZXZ7W.js +0 -61
  381. package/dist/chunk-KO2ZXZ7W.js.map +0 -1
  382. package/dist/chunk-KS2HQCJR.js +0 -56
  383. package/dist/chunk-KS2HQCJR.js.map +0 -1
  384. package/dist/chunk-LA5KPWZ2.js +0 -413
  385. package/dist/chunk-LA5KPWZ2.js.map +0 -1
  386. package/dist/chunk-MESLAC5W.js +0 -574
  387. package/dist/chunk-MESLAC5W.js.map +0 -1
  388. package/dist/chunk-MWPYA2HD.js +0 -94
  389. package/dist/chunk-MWPYA2HD.js.map +0 -1
  390. package/dist/chunk-NUB5GQTU.js +0 -270
  391. package/dist/chunk-NUB5GQTU.js.map +0 -1
  392. package/dist/chunk-OBBCR6WY.js +0 -277
  393. package/dist/chunk-OBBCR6WY.js.map +0 -1
  394. package/dist/chunk-OQDSAOG3.js +0 -1908
  395. package/dist/chunk-OQDSAOG3.js.map +0 -1
  396. package/dist/chunk-OXNCBE7P.js +0 -971
  397. package/dist/chunk-OXNCBE7P.js.map +0 -1
  398. package/dist/chunk-PBZFAAOM.js +0 -941
  399. package/dist/chunk-PN6GIF3R.js +0 -1185
  400. package/dist/chunk-PN6GIF3R.js.map +0 -1
  401. package/dist/chunk-PYD44IHJ.js +0 -728
  402. package/dist/chunk-PYD44IHJ.js.map +0 -1
  403. package/dist/chunk-QVPIACWD.js +0 -679
  404. package/dist/chunk-QVPIACWD.js.map +0 -1
  405. package/dist/chunk-QWNNFE4P.js +0 -41
  406. package/dist/chunk-QWNNFE4P.js.map +0 -1
  407. package/dist/chunk-RU266375.js +0 -327
  408. package/dist/chunk-RU266375.js.map +0 -1
  409. package/dist/chunk-RYTSVGGA.js +0 -1624
  410. package/dist/chunk-RYTSVGGA.js.map +0 -1
  411. package/dist/chunk-RZOFS2BQ.js +0 -225
  412. package/dist/chunk-RZOFS2BQ.js.map +0 -1
  413. package/dist/chunk-SBS4S2PJ.js +0 -100
  414. package/dist/chunk-SBS4S2PJ.js.map +0 -1
  415. package/dist/chunk-SPRG6G6G.js +0 -530
  416. package/dist/chunk-SPRG6G6G.js.map +0 -1
  417. package/dist/chunk-STWFX5E2.js +0 -233
  418. package/dist/chunk-STWFX5E2.js.map +0 -1
  419. package/dist/chunk-UNASM5VJ.js +0 -419
  420. package/dist/chunk-UNASM5VJ.js.map +0 -1
  421. package/dist/chunk-VAT66FJA.js +0 -245
  422. package/dist/chunk-VAT66FJA.js.map +0 -1
  423. package/dist/chunk-VFCMR5GX.js +0 -49
  424. package/dist/chunk-VFCMR5GX.js.map +0 -1
  425. package/dist/chunk-VGAHZKNJ.js +0 -66
  426. package/dist/chunk-VGAHZKNJ.js.map +0 -1
  427. package/dist/chunk-VTJTAAXC.js +0 -627
  428. package/dist/chunk-VTJTAAXC.js.map +0 -1
  429. package/dist/chunk-VXVLKRU6.js +0 -758
  430. package/dist/chunk-VXVLKRU6.js.map +0 -1
  431. package/dist/chunk-WWUU5ETI.js +0 -163
  432. package/dist/chunk-WWUU5ETI.js.map +0 -1
  433. package/dist/chunk-XE4OXN2W.js +0 -10
  434. package/dist/chunk-XE4OXN2W.js.map +0 -1
  435. package/dist/chunk-XOJORS75.js +0 -1853
  436. package/dist/chunk-XOJORS75.js.map +0 -1
  437. package/dist/chunk-YMZEUTD2.js +0 -110
  438. package/dist/chunk-YMZEUTD2.js.map +0 -1
  439. package/dist/chunk-Z77BTSOK.js +0 -617
  440. package/dist/chunk-Z77BTSOK.js.map +0 -1
  441. package/dist/chunk-ZZK3WEDI.js +0 -181
  442. package/dist/chunk-ZZK3WEDI.js.map +0 -1
  443. package/dist/client-CCXpAZ2r.d.ts +0 -89
  444. package/dist/client-DSI_760t.d.ts +0 -36
  445. package/dist/client-JU6T3UPB.js +0 -11
  446. package/dist/client-JU6T3UPB.js.map +0 -1
  447. package/dist/dist-2X4Q7PJA.js +0 -1491
  448. package/dist/dist-2X4Q7PJA.js.map +0 -1
  449. package/dist/env-4UWSUS64.js +0 -4
  450. package/dist/env-4UWSUS64.js.map +0 -1
  451. package/dist/graph-emitter-r5TylDBm.d.ts +0 -47
  452. package/dist/graphql-CMHMQjvd.d.ts +0 -23
  453. package/dist/i18n-Qm2AkPC-.d.ts +0 -33
  454. package/dist/index--yvpa6ay.d.ts +0 -83
  455. package/dist/index-4gKQKZ2B.d.ts +0 -71
  456. package/dist/index-5x0XMKXN.d.ts +0 -149
  457. package/dist/index-B70b5mYS.d.ts +0 -33
  458. package/dist/index-B8KrxO4j.d.ts +0 -755
  459. package/dist/index-BOuDKnqD.d.ts +0 -201
  460. package/dist/index-BTMt4OjA.d.ts +0 -201
  461. package/dist/index-BejbszA7.d.ts +0 -39
  462. package/dist/index-BkeOYZye.d.ts +0 -198
  463. package/dist/index-BuAj5nXg.d.ts +0 -83
  464. package/dist/index-BvkVcW8I.d.ts +0 -349
  465. package/dist/index-CWmH_-RZ.d.ts +0 -247
  466. package/dist/index-CbgWNcus.d.ts +0 -258
  467. package/dist/index-CmfPeQza.d.ts +0 -166
  468. package/dist/index-CmpG-zak.d.ts +0 -607
  469. package/dist/index-CoMKgL-p.d.ts +0 -12
  470. package/dist/index-D8HGwglK.d.ts +0 -541
  471. package/dist/index-DCaVm66D.d.ts +0 -1101
  472. package/dist/index-DE2w7E0d.d.ts +0 -83
  473. package/dist/index-DSOpj8DI.d.ts +0 -17
  474. package/dist/index-DW9q22GH.d.ts +0 -75
  475. package/dist/index-DnjJ9CwI.d.ts +0 -347
  476. package/dist/index-DwMJZ8PP.d.ts +0 -317
  477. package/dist/index-PaojfSdd.d.ts +0 -71
  478. package/dist/index-aHtYvc3i.d.ts +0 -284
  479. package/dist/index-e_18DzAg.d.ts +0 -18
  480. package/dist/index-ffmipXSA.d.ts +0 -55
  481. package/dist/index-joONjwLt.d.ts +0 -33
  482. package/dist/index-kssw5ziY.d.ts +0 -250
  483. package/dist/index-lFffh5-G.d.ts +0 -125
  484. package/dist/index-pxYge_6k.d.ts +0 -79
  485. package/dist/layer-Cv9vSwBx.d.ts +0 -70
  486. package/dist/pino-logger-H4HPW5P6.js +0 -5
  487. package/dist/pino-logger-H4HPW5P6.js.map +0 -1
  488. package/dist/prisma-extension-gYhYriA0.d.ts +0 -174
  489. package/dist/sdk-L75WWUP3.js +0 -156
  490. package/dist/sdk-L75WWUP3.js.map +0 -1
  491. package/dist/shutdown-registry-CW9LryO8.d.ts +0 -10
  492. package/dist/types-Bo2wkjSP.d.ts +0 -35
  493. package/dist/types-DVpvrAhd.d.ts +0 -71
  494. package/dist/types-DgJ4lDYA.d.ts +0 -108
  495. package/dist/types-USOv09qy.d.ts +0 -327
  496. package/dist/workspace-guard-NXVYYBVJ.js +0 -5
  497. package/dist/workspace-guard-NXVYYBVJ.js.map +0 -1
@@ -0,0 +1,1837 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-ad2WFvuA.js";
2
+ import { a as logger } from "./logger-B6rCpb7D.js";
3
+ import { n as currentEnvironment, t as DEPLOYED_ENVIRONMENTS } from "./deployed-environment-p_Tdl3sT.js";
4
+ import { i as DEFAULT_LAYER_RESOURCES } from "./layer-Bcix-WCl.js";
5
+ import { a as unregisterDisposable, i as registerDisposable } from "./lifecycle-DeoLSX0U.js";
6
+
7
+ // src/cache/endpoint.ts
8
+ /**
9
+ * Cache endpoint configuration guard.
10
+ *
11
+ * Every cache entry point in this package resolves its connection the same way:
12
+ * take `VALKEY_URL`, else `REDIS_URL`, else fall back to `VALKEY_HOST ||
13
+ * 'localhost'` on port 6379 with whatever `VALKEY_PASSWORD` happens to hold.
14
+ * That last step is the problem. It succeeds at configuration time no matter
15
+ * what, so a service with no cache endpoint at all starts cleanly and looks
16
+ * healthy; the misconfiguration only surfaces later, as a connect that hangs on
17
+ * GLIDE's reconnect backoff long enough to starve the event loop and saturate
18
+ * the pg pool — 500s under load, with nothing in the boot log pointing at the
19
+ * cause.
20
+ *
21
+ * That failure has now been reached three separate ways, each time diagnosed
22
+ * from the symptom rather than the config:
23
+ *
24
+ * 1. `VALKEY_URL` present but set to the empty string.
25
+ * 2. `VALKEY_URL` blank where only the canonical `REDIS_URL` was populated —
26
+ * the fallback documented in CacheFactory.createCache.
27
+ * 3. `VALKEY_URL` absent entirely, with no `REDIS_URL` and no `VALKEY_HOST`
28
+ * (`boff/dev/global/tenant` and `boff/dev/wspace/files`, 2026-08-25).
29
+ *
30
+ * A presence check finds none of these reliably — "absent", "empty" and
31
+ * "present but pointing somewhere useless" are three different shapes. What
32
+ * they share is that the fallback is taken, so that is what this guards.
33
+ *
34
+ * In a deployed environment the fallback is never correct: nothing listens on
35
+ * the pod's own localhost:6379, so the only outcomes are a hang and a 500.
36
+ * There it throws, naming the keys it looked for. In development it logs at
37
+ * error level and continues, because a laptop running `bun run dev` against a
38
+ * local Valkey on the default port is a legitimate setup.
39
+ *
40
+ * Verified before shipping: of the be-sdk service bundles in Secrets Manager,
41
+ * 76 of 76 in alpha and 75 of 75 in prod already carry a cache endpoint, so the
42
+ * throw changes no current behaviour — it only catches the next one.
43
+ */
44
+ /** Environments where falling back to localhost is always a misconfiguration. */
45
+ /** Hosts that mean "no endpoint was configured" rather than a deliberate choice. */
46
+ const LOOPBACK_HOSTS = /* @__PURE__ */ new Set([
47
+ "localhost",
48
+ "127.0.0.1",
49
+ "::1"
50
+ ]);
51
+ /**
52
+ * Throw (deployed) or log loudly (development) when a cache client is about to
53
+ * be built with no configured endpoint.
54
+ *
55
+ * Returns normally — and silently — whenever an endpoint *was* configured,
56
+ * which is the overwhelmingly common case, so this costs nothing on the happy
57
+ * path.
58
+ *
59
+ * @throws when no endpoint is configured and DEPLOY_ENV/NODE_ENV is a deployed environment.
60
+ */
61
+ function assertCacheEndpointConfigured(check) {
62
+ if (check.url?.trim()) return;
63
+ const host = check.host?.trim();
64
+ if (host && !LOOPBACK_HOSTS.has(host.toLowerCase())) return;
65
+ const port = check.port ?? 6379;
66
+ const target = `${host || "localhost"}:${port}`;
67
+ const credentials = check.password ? "a password" : "NO password";
68
+ const detail = `[cache] ${check.context}: no cache endpoint is configured — none of ${check.keysTried.join(", ")} is set. Falling back to ${target} with ${credentials}. That fallback is silent at startup and surfaces later as a connect that hangs on GLIDE reconnect backoff, starving the event loop and returning 500s under load.`;
69
+ const environment = currentEnvironment();
70
+ if (DEPLOYED_ENVIRONMENTS.has(environment)) throw new Error(`${detail} Refusing to continue with DEPLOY_ENV=${environment}: set VALKEY_URL (or REDIS_URL) in this service's Secrets Manager bundle, boff/${environment}/{layer}/{module}.`);
71
+ logger.error(detail);
72
+ }
73
+ /**
74
+ * Flag a deployed service that fell through to a layer default rather than its
75
+ * own configuration. The defaults in `DEFAULT_LAYER_RESOURCES` are local-dev
76
+ * compose hostnames — `wspace-shared-valkey` and friends — which resolve to
77
+ * nothing inside a cluster. This does not throw: unlike the localhost fallback,
78
+ * a layer default is a real hostname and could conceivably be routable, so the
79
+ * call is the operator's to make.
80
+ */
81
+ function warnOnLayerDefaultEndpoint(context, url, layerDefault) {
82
+ if (url !== layerDefault) return;
83
+ const environment = currentEnvironment();
84
+ if (!DEPLOYED_ENVIRONMENTS.has(environment)) return;
85
+ logger.error(`[cache] ${context}: falling back to the local-dev layer default ${layerDefault} with DEPLOY_ENV=${environment}. That hostname does not resolve in a cluster. Set VALKEY_URL or REDIS_URL for this service.`);
86
+ }
87
+
88
+ // src/cache/implementations/memory/MemoryCacheProvider.ts
89
+ /**
90
+ * Memory Cache Provider
91
+ * In-memory cache implementation (for testing and fallback)
92
+ */
93
+ /**
94
+ * Sentinel `expiresAt` for a key with NO expiry (persistent), mirroring a
95
+ * Redis key that has never been given a TTL. `increment`/`decrement` create
96
+ * keys in this state (Redis INCR never sets a TTL), and `expireNX` applies a
97
+ * TTL only to keys in this state.
98
+ */
99
+ const NO_EXPIRY = Number.POSITIVE_INFINITY;
100
+ /**
101
+ * Memory cache provider implementation (LRU-based)
102
+ */
103
+ var MemoryCacheProvider = class {
104
+ cache = /* @__PURE__ */ new Map();
105
+ namespace;
106
+ defaultTTL;
107
+ maxSize;
108
+ enableLogging;
109
+ connected = false;
110
+ stats = {
111
+ hits: 0,
112
+ misses: 0,
113
+ sets: 0,
114
+ deletes: 0,
115
+ evictions: 0
116
+ };
117
+ constructor(config, namespace = "default") {
118
+ this.namespace = namespace;
119
+ this.defaultTTL = config.defaultTTL || 300;
120
+ this.maxSize = config.maxSize || 1e3;
121
+ this.enableLogging = config.enableLogging ?? false;
122
+ this.startCleanupInterval();
123
+ }
124
+ /**
125
+ * Connect (no-op for memory cache)
126
+ */
127
+ async connect() {
128
+ await Promise.resolve();
129
+ this.connected = true;
130
+ if (this.enableLogging) logger.info(`[MemoryCacheProvider:${this.namespace}] Connected (in-memory)`);
131
+ }
132
+ /**
133
+ * Disconnect (cleanup)
134
+ */
135
+ async disconnect() {
136
+ await Promise.resolve();
137
+ this.connected = false;
138
+ this.cache.clear();
139
+ if (this.enableLogging) logger.info(`[MemoryCacheProvider:${this.namespace}] Disconnected`);
140
+ }
141
+ /**
142
+ * Check if connected
143
+ */
144
+ isConnected() {
145
+ return this.connected;
146
+ }
147
+ /**
148
+ * Health check
149
+ */
150
+ async healthCheck() {
151
+ await Promise.resolve();
152
+ return {
153
+ status: "healthy",
154
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
155
+ connected: this.connected,
156
+ latencyMs: 0,
157
+ details: {
158
+ provider: "memory",
159
+ cacheSize: this.cache.size,
160
+ maxSize: this.maxSize
161
+ }
162
+ };
163
+ }
164
+ /**
165
+ * Get statistics
166
+ */
167
+ async getStatistics() {
168
+ await Promise.resolve();
169
+ const totalOperations = this.stats.hits + this.stats.misses;
170
+ const hitRate = totalOperations > 0 ? this.stats.hits / totalOperations : 0;
171
+ const memoryUsed = this.cache.size * 500;
172
+ return {
173
+ hits: this.stats.hits,
174
+ misses: this.stats.misses,
175
+ hitRate,
176
+ keyCount: this.cache.size,
177
+ memoryUsed,
178
+ totalOperations,
179
+ details: {
180
+ sets: this.stats.sets,
181
+ deletes: this.stats.deletes,
182
+ evictions: this.stats.evictions,
183
+ maxSize: this.maxSize
184
+ }
185
+ };
186
+ }
187
+ /**
188
+ * Build cache key with namespace
189
+ */
190
+ buildKey(key) {
191
+ return `${this.namespace}:${key}`;
192
+ }
193
+ /**
194
+ * Check if entry is expired
195
+ */
196
+ isExpired(expiresAt) {
197
+ return Date.now() > expiresAt;
198
+ }
199
+ /**
200
+ * Evict LRU entry if cache is full
201
+ */
202
+ evictIfNeeded() {
203
+ if (this.cache.size >= this.maxSize) {
204
+ const firstKey = this.cache.keys().next().value;
205
+ if (firstKey) {
206
+ this.cache.delete(firstKey);
207
+ this.stats.evictions++;
208
+ }
209
+ }
210
+ }
211
+ /**
212
+ * Cleanup expired entries
213
+ */
214
+ cleanup() {
215
+ let cleaned = 0;
216
+ for (const [key, value] of this.cache.entries()) if (this.isExpired(value.expiresAt)) {
217
+ this.cache.delete(key);
218
+ cleaned++;
219
+ }
220
+ if (cleaned > 0 && this.enableLogging) logger.debug(`[MemoryCacheProvider:${this.namespace}] Cleaned up ${cleaned} expired entries`);
221
+ }
222
+ /**
223
+ * Start cleanup interval
224
+ */
225
+ startCleanupInterval() {
226
+ setInterval(() => this.cleanup(), 6e4);
227
+ }
228
+ /**
229
+ * Get value from cache
230
+ */
231
+ async get(key, _options) {
232
+ await Promise.resolve();
233
+ const cacheKey = this.buildKey(key);
234
+ const cached = this.cache.get(cacheKey);
235
+ if (!cached) {
236
+ this.stats.misses++;
237
+ if (this.enableLogging) logger.debug(`[MemoryCacheProvider:${this.namespace}] Cache miss`, { key });
238
+ return null;
239
+ }
240
+ if (this.isExpired(cached.expiresAt)) {
241
+ this.cache.delete(cacheKey);
242
+ this.stats.misses++;
243
+ if (this.enableLogging) logger.debug(`[MemoryCacheProvider:${this.namespace}] Cache miss (expired)`, { key });
244
+ return null;
245
+ }
246
+ this.stats.hits++;
247
+ if (this.enableLogging) logger.debug(`[MemoryCacheProvider:${this.namespace}] Cache hit`, { key });
248
+ this.cache.delete(cacheKey);
249
+ this.cache.set(cacheKey, cached);
250
+ return cached.entry.data;
251
+ }
252
+ /**
253
+ * Set value in cache
254
+ */
255
+ async set(key, value, options) {
256
+ await Promise.resolve();
257
+ const cacheKey = this.buildKey(key);
258
+ const ttlSeconds = options?.ttl || this.defaultTTL;
259
+ this.evictIfNeeded();
260
+ const entry = {
261
+ data: value,
262
+ timestamp: Date.now(),
263
+ ttl: ttlSeconds,
264
+ metadata: options?.metadata
265
+ };
266
+ this.cache.set(cacheKey, {
267
+ entry,
268
+ expiresAt: Date.now() + ttlSeconds * 1e3
269
+ });
270
+ this.stats.sets++;
271
+ if (this.enableLogging) logger.debug(`[MemoryCacheProvider:${this.namespace}] Cache set`, {
272
+ key,
273
+ ttl: ttlSeconds
274
+ });
275
+ return true;
276
+ }
277
+ /**
278
+ * Delete value from cache
279
+ */
280
+ async delete(key) {
281
+ await Promise.resolve();
282
+ const cacheKey = this.buildKey(key);
283
+ const deleted = this.cache.delete(cacheKey);
284
+ if (deleted) {
285
+ this.stats.deletes++;
286
+ if (this.enableLogging) logger.debug(`[MemoryCacheProvider:${this.namespace}] Cache delete`, { key });
287
+ }
288
+ return deleted;
289
+ }
290
+ /**
291
+ * Check if key exists
292
+ */
293
+ async has(key) {
294
+ await Promise.resolve();
295
+ const cacheKey = this.buildKey(key);
296
+ const cached = this.cache.get(cacheKey);
297
+ if (!cached) return false;
298
+ if (this.isExpired(cached.expiresAt)) {
299
+ this.cache.delete(cacheKey);
300
+ return false;
301
+ }
302
+ return true;
303
+ }
304
+ /**
305
+ * Get TTL for key
306
+ */
307
+ async ttl(key) {
308
+ await Promise.resolve();
309
+ const cacheKey = this.buildKey(key);
310
+ const cached = this.cache.get(cacheKey);
311
+ if (!cached) return -2;
312
+ if (cached.expiresAt === NO_EXPIRY) return -1;
313
+ const remaining = Math.floor((cached.expiresAt - Date.now()) / 1e3);
314
+ if (remaining <= 0) {
315
+ this.cache.delete(cacheKey);
316
+ return -2;
317
+ }
318
+ return remaining;
319
+ }
320
+ /**
321
+ * Update TTL for key
322
+ */
323
+ async expire(key, ttl) {
324
+ await Promise.resolve();
325
+ const cacheKey = this.buildKey(key);
326
+ const cached = this.cache.get(cacheKey);
327
+ if (!cached) return false;
328
+ cached.expiresAt = Date.now() + ttl * 1e3;
329
+ cached.entry.ttl = ttl;
330
+ return true;
331
+ }
332
+ /**
333
+ * Set TTL for key only if it currently has no TTL (Redis `EXPIRE key ttl NX`).
334
+ * Returns true only when the expiry was applied — i.e. the key exists (and is
335
+ * not expired) and had no TTL. A key that already has a TTL is left untouched.
336
+ */
337
+ async expireNX(key, ttlSeconds) {
338
+ await Promise.resolve();
339
+ const cacheKey = this.buildKey(key);
340
+ const cached = this.cache.get(cacheKey);
341
+ if (!cached || this.isExpired(cached.expiresAt)) return false;
342
+ if (cached.expiresAt !== NO_EXPIRY) return false;
343
+ cached.expiresAt = Date.now() + ttlSeconds * 1e3;
344
+ cached.entry.ttl = ttlSeconds;
345
+ return true;
346
+ }
347
+ /**
348
+ * Get multiple values (batch operation)
349
+ */
350
+ async mget(keys, _options) {
351
+ const result = /* @__PURE__ */ new Map();
352
+ for (const key of keys) {
353
+ const value = await this.get(key);
354
+ if (value !== null) result.set(key, value);
355
+ }
356
+ return result;
357
+ }
358
+ /**
359
+ * Set multiple values (batch operation)
360
+ */
361
+ async mset(entries, options) {
362
+ for (const [key, value] of entries) await this.set(key, value, options);
363
+ return true;
364
+ }
365
+ /**
366
+ * Delete multiple keys (batch operation)
367
+ */
368
+ async mdel(keys) {
369
+ let deleted = 0;
370
+ for (const key of keys) if (await this.delete(key)) deleted++;
371
+ return deleted;
372
+ }
373
+ /**
374
+ * Match key against pattern (supports * wildcard)
375
+ */
376
+ matchPattern(key, pattern) {
377
+ if (!pattern.includes("*")) return key === pattern;
378
+ const parts = pattern.split("*");
379
+ let position = 0;
380
+ for (let i = 0; i < parts.length; i++) {
381
+ const part = parts[i];
382
+ if (!part || part === "") continue;
383
+ const index = key.indexOf(part, position);
384
+ if (index === -1) return false;
385
+ if (i === 0 && index !== 0) return false;
386
+ position = index + part.length;
387
+ }
388
+ const lastPart = parts[parts.length - 1];
389
+ return !lastPart || lastPart === "" || key.endsWith(lastPart);
390
+ }
391
+ /**
392
+ * Clear keys by pattern
393
+ */
394
+ async clearPattern(pattern) {
395
+ await Promise.resolve();
396
+ const searchPattern = this.buildKey(pattern);
397
+ let deleted = 0;
398
+ for (const key of this.cache.keys()) if (this.matchPattern(key, searchPattern)) {
399
+ this.cache.delete(key);
400
+ deleted++;
401
+ }
402
+ if (this.enableLogging) logger.debug(`[MemoryCacheProvider:${this.namespace}] Pattern cleared`, {
403
+ pattern,
404
+ deleted
405
+ });
406
+ return deleted;
407
+ }
408
+ /**
409
+ * Get keys by pattern
410
+ */
411
+ async keys(options) {
412
+ await Promise.resolve();
413
+ const searchPattern = this.buildKey(options.pattern);
414
+ const matchedKeys = [];
415
+ const prefix = `${this.namespace}:`;
416
+ for (const key of this.cache.keys()) if (this.matchPattern(key, searchPattern)) matchedKeys.push(key.replace(prefix, ""));
417
+ return {
418
+ keys: options.limit ? matchedKeys.slice(0, options.limit) : matchedKeys,
419
+ nextCursor: null,
420
+ totalCount: matchedKeys.length
421
+ };
422
+ }
423
+ /**
424
+ * Clear all keys in namespace
425
+ */
426
+ async clear() {
427
+ await Promise.resolve();
428
+ const prefix = `${this.namespace}:`;
429
+ let cleared = 0;
430
+ for (const key of Array.from(this.cache.keys())) if (key.startsWith(prefix)) {
431
+ this.cache.delete(key);
432
+ cleared++;
433
+ }
434
+ if (this.enableLogging) logger.info(`[MemoryCacheProvider:${this.namespace}] Cleared ${cleared} keys`);
435
+ return true;
436
+ }
437
+ /**
438
+ * Increment numeric value.
439
+ *
440
+ * Mirrors Redis `INCRBY`: a missing key is created with NO expiry
441
+ * (persistent), and an existing key's TTL is preserved (never reset). This
442
+ * keeps the `increment` + `expireNX` fixed-window pattern behaving
443
+ * identically to the valkey-glide provider.
444
+ */
445
+ async increment(key, amount = 1) {
446
+ return this.applyDelta(key, amount);
447
+ }
448
+ /**
449
+ * Decrement numeric value. Mirrors Redis `DECRBY` (see {@link increment}).
450
+ */
451
+ async decrement(key, amount = 1) {
452
+ return this.applyDelta(key, -amount);
453
+ }
454
+ /**
455
+ * Shared INCRBY/DECRBY core: preserve an existing key's TTL, create a missing
456
+ * key with no expiry.
457
+ */
458
+ async applyDelta(key, delta) {
459
+ await Promise.resolve();
460
+ const cacheKey = this.buildKey(key);
461
+ const existing = this.cache.get(cacheKey);
462
+ const alive = existing && !this.isExpired(existing.expiresAt) ? existing : void 0;
463
+ const parsed = alive ? Number(alive.entry.data) : 0;
464
+ const newValue = (Number.isFinite(parsed) ? parsed : 0) + delta;
465
+ if (alive) {
466
+ alive.entry.data = newValue;
467
+ alive.entry.timestamp = Date.now();
468
+ } else {
469
+ if (existing) this.cache.delete(cacheKey);
470
+ this.evictIfNeeded();
471
+ this.cache.set(cacheKey, {
472
+ entry: {
473
+ data: newValue,
474
+ timestamp: Date.now(),
475
+ ttl: 0
476
+ },
477
+ expiresAt: NO_EXPIRY
478
+ });
479
+ }
480
+ this.stats.sets++;
481
+ return newValue;
482
+ }
483
+ /**
484
+ * Get or set value
485
+ */
486
+ async getOrSet(key, fetcher, options) {
487
+ const cached = await this.get(key, options);
488
+ if (cached !== null) return cached;
489
+ const value = await fetcher();
490
+ await this.set(key, value, options);
491
+ return value;
492
+ }
493
+ /**
494
+ * Invalidate by tags
495
+ */
496
+ async invalidateTags(tags) {
497
+ let totalDeleted = 0;
498
+ for (const tag of tags) {
499
+ const pattern = `*:tag:${tag}:*`;
500
+ const deleted = await this.clearPattern(pattern);
501
+ totalDeleted += deleted;
502
+ }
503
+ return totalDeleted;
504
+ }
505
+ };
506
+
507
+ // src/cache/implementations/valkey/ValkeyGlideProvider.ts
508
+ /**
509
+ * Valkey Glide Cache Provider
510
+ *
511
+ * Implements ICacheProvider using @valkey/valkey-glide client.
512
+ * Provides a modern, high-performance Valkey/Redis client implementation.
513
+ *
514
+ * @module cache/implementations/valkey/ValkeyGlideProvider
515
+ * @category Cache
516
+ *
517
+ * @example
518
+ * ```typescript
519
+ * import { ValkeyGlideProvider } from '@burdenoff/be-sdk/cache';
520
+ *
521
+ * const cache = new ValkeyGlideProvider({
522
+ * type: 'valkey-glide',
523
+ * url: 'valkey://localhost:6379',
524
+ * defaultTTL: 300,
525
+ * }, 'my-namespace');
526
+ *
527
+ * await cache.connect();
528
+ * await cache.set('key', 'value', { ttl: 60 });
529
+ * const value = await cache.get('key');
530
+ * ```
531
+ */
532
+ /**
533
+ * Read a positive-integer override from the environment, falling back to a
534
+ * default. Every timeout below is env-tunable so an operator can adapt to a
535
+ * given Redis/network profile without a code change.
536
+ */
537
+ function readPositiveIntEnv(name, fallback) {
538
+ const raw = process.env[name];
539
+ if (!raw) return fallback;
540
+ const parsed = parseInt(raw, 10);
541
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
542
+ }
543
+ /**
544
+ * After a failed connect, fail subsequent ops fast (treated as a cache miss by
545
+ * callers) for this cooldown instead of issuing a fresh `createClient` on every
546
+ * operation. Per-operation connect hammering is what turned a brief Redis
547
+ * hiccup into thousands of "Failed to connect" log lines/min and a
548
+ * self-amplifying reconnect storm across the platform.
549
+ */
550
+ const CONNECT_RETRY_COOLDOWN_MS = readPositiveIntEnv("VALKEY_CONNECT_RETRY_COOLDOWN_MS", 8e3);
551
+ /**
552
+ * Hard wall-clock budget for a single request-path connect attempt. GLIDE's
553
+ * `connectionBackoff` (exponential, seeded by `reconnectTimeWait`) means a
554
+ * `createClient` against an unreachable/misconfigured endpoint can stay pending
555
+ * for tens of seconds. Because cache ops run inline in resolvers — often while a
556
+ * Postgres connection is checked out — a connect that hangs that long starves
557
+ * the event loop and saturates the pg pool, surfacing as 10s "connect timeout"
558
+ * 500s. Bounding the attempt turns any connect stall into a fast cache-miss +
559
+ * an armed circuit-breaker instead of a request-blocking hang.
560
+ *
561
+ * Sized to sit just above {@link CONNECTION_TIMEOUT_MS} so GLIDE's own (cleaner,
562
+ * typed) connect timeout normally fires first, with this race as the backstop
563
+ * for when GLIDE ignores it. The previous 2.5s default was too tight for a cold
564
+ * TLS handshake to Azure Managed Redis, so a healthy-but-slow connect tripped
565
+ * the circuit-breaker and produced the observed connect flapping.
566
+ */
567
+ const CONNECT_ATTEMPT_TIMEOUT_MS = readPositiveIntEnv("VALKEY_CONNECT_ATTEMPT_TIMEOUT_MS", 4500);
568
+ /**
569
+ * GLIDE's own per-connect budget (initial connect AND every internal
570
+ * reconnect), passed via `advancedConfiguration.connectionTimeout`. In GLIDE 2.x
571
+ * a TOP-LEVEL `connectionTimeout` is silently ignored — it must live under
572
+ * `advancedConfiguration` — so connects previously ran with GLIDE's built-in
573
+ * default. Overridable per instance via config.connectionTimeout.
574
+ */
575
+ const CONNECTION_TIMEOUT_MS = readPositiveIntEnv("VALKEY_CONNECTION_TIMEOUT_MS", 4e3);
576
+ /**
577
+ * GLIDE `requestTimeout`: the hard ceiling for a single command, which per
578
+ * GLIDE's docs "encompasses sending the request, awaiting a response, AND any
579
+ * required reconnection or retries." This is the fix for the cache HANG: without
580
+ * it, a `get`/`set` issued while the socket is dropping or GLIDE is mid-reconnect
581
+ * waits GLIDE's effectively-unbounded default, blocking the calling resolver
582
+ * (and any pg connection it holds) — which upstream surfaced as RBAC checks
583
+ * exceeding the gateway's 5s budget and fail-closing. With it, such a command
584
+ * throws TimeoutError fast and the provider returns a cache miss.
585
+ */
586
+ const REQUEST_TIMEOUT_MS = readPositiveIntEnv("VALKEY_REQUEST_TIMEOUT_MS", 2e3);
587
+ /**
588
+ * Consecutive connection-level operation failures after which the provider tears
589
+ * its client down and lets the next op build a fresh one. GLIDE reconnects a
590
+ * dropped socket on its own indefinitely, but a client whose TLS/keepalive state
591
+ * wedges (observed against Azure Managed Redis: connect flaps, redis-cli to the
592
+ * same endpoint is healthy) would otherwise stay broken until the process
593
+ * restarts — which is why a pod restart used to be the only fix. A brand-new
594
+ * client means a new socket + TLS session, which recovers where the wedged one
595
+ * could not.
596
+ */
597
+ const MAX_CONSECUTIVE_OP_FAILURES = readPositiveIntEnv("VALKEY_MAX_CONSECUTIVE_OP_FAILURES", 3);
598
+ /**
599
+ * Minimum interval between logged cooldown fast-fails, per provider instance.
600
+ * While the connect circuit-breaker is armed, EVERY cache op fast-fails with
601
+ * the same "connect in cooldown" error; logging each one at error level buried
602
+ * prod logs in dozens of identical stack traces per second (observed on
603
+ * global-tenant-svc) and drowned out the one log line that matters — the
604
+ * underlying connect failure. Real (non-cooldown) op errors are never throttled.
605
+ */
606
+ const COOLDOWN_LOG_INTERVAL_MS = readPositiveIntEnv("VALKEY_COOLDOWN_LOG_INTERVAL_MS", 3e4);
607
+ /**
608
+ * True when an error indicates the connection (not the command) is the problem,
609
+ * so it should count toward the client-teardown threshold. Matches GLIDE's error
610
+ * class names (ClosingError / ConnectionError / TimeoutError) and, as a fallback
611
+ * for wrapped/plain errors, connection-shaped messages. Deliberately excludes
612
+ * the provider's own "connect in cooldown" fast-fail (that is the breaker
613
+ * already working, not a fresh failure) and the connect-budget message.
614
+ */
615
+ function isConnectionLevelError(error) {
616
+ if (!(error instanceof Error)) return false;
617
+ const name = error.name;
618
+ if (name === "ClosingError" || name === "ConnectionError" || name === "TimeoutError") return true;
619
+ const message = error.message.toLowerCase();
620
+ if (message.includes("cooldown") || message.includes("budget")) return false;
621
+ return /connection|closing|closed|timed out|timeout|disconnect|socket|econnreset|broken pipe|not connected/.test(message);
622
+ }
623
+ /**
624
+ * Valkey Glide cache provider implementation
625
+ */
626
+ var ValkeyGlideProvider = class {
627
+ client = null;
628
+ clusterScanCursor = null;
629
+ clientIsCluster = false;
630
+ connected = false;
631
+ connectPromise = null;
632
+ lastConnectFailureAt = 0;
633
+ consecutiveOpFailures = 0;
634
+ lastCooldownLogAt = 0;
635
+ config;
636
+ namespace;
637
+ dbNamespaceSuffixApplied = false;
638
+ defaultTTL;
639
+ enableLogging;
640
+ stats = {
641
+ hits: 0,
642
+ misses: 0,
643
+ sets: 0,
644
+ deletes: 0,
645
+ errors: 0
646
+ };
647
+ constructor(config, namespace = "default") {
648
+ this.config = config;
649
+ this.namespace = namespace;
650
+ this.defaultTTL = config.defaultTTL || 300;
651
+ this.enableLogging = config.enableLogging ?? process.env["NODE_ENV"] === "development";
652
+ }
653
+ async serverReportsCluster(client) {
654
+ try {
655
+ const info = await client.info("cluster");
656
+ return /(?:^|\n)cluster_enabled:1(?:\r?\n|$)/.test(info);
657
+ } catch {
658
+ return false;
659
+ }
660
+ }
661
+ async scanClusterKeys(pattern) {
662
+ if (!this.client || !this.clientIsCluster || !this.clusterScanCursor) return [];
663
+ const clusterClient = this.client;
664
+ let cursor = new this.clusterScanCursor();
665
+ const keys = [];
666
+ do {
667
+ const [nextCursor, batch] = await clusterClient.scan(cursor, {
668
+ match: pattern,
669
+ count: 1e3
670
+ });
671
+ keys.push(...batch);
672
+ cursor = nextCursor;
673
+ } while (!cursor.isFinished());
674
+ return keys;
675
+ }
676
+ async getKeys(pattern) {
677
+ const client = await this.ensureConnected();
678
+ if (this.clientIsCluster) return this.scanClusterKeys(pattern);
679
+ const standaloneClient = client;
680
+ let cursor = "0";
681
+ const keys = /* @__PURE__ */ new Set();
682
+ let pages = 0;
683
+ do {
684
+ const [nextCursor, batch] = await standaloneClient.scan(cursor, {
685
+ match: pattern,
686
+ count: 1e3,
687
+ decoder: 1
688
+ });
689
+ for (const key of batch) {
690
+ if (!key.startsWith(`${this.namespace}:`)) throw new Error("Valkey SCAN returned a key outside the namespace");
691
+ keys.add(key);
692
+ }
693
+ pages++;
694
+ if (pages > 1e4 || keys.size > 1e5) throw new Error("Valkey namespace SCAN exceeded its safety budget");
695
+ cursor = nextCursor;
696
+ } while (cursor !== "0");
697
+ return [...keys];
698
+ }
699
+ /**
700
+ * Connect to Valkey server using @valkey/valkey-glide
701
+ */
702
+ /**
703
+ * Lazy-connect helper used by every public operation so callers can just do
704
+ * `const cache = createCache('x'); await cache.set(...)` without an explicit
705
+ * `await cache.connect()`. Multiple concurrent ops share the same in-flight
706
+ * connect promise.
707
+ */
708
+ async ensureConnected() {
709
+ if (!(this.connected && this.client)) {
710
+ if (!this.connectPromise && this.lastConnectFailureAt > 0) {
711
+ if (Date.now() - this.lastConnectFailureAt < CONNECT_RETRY_COOLDOWN_MS) throw new Error("Valkey connect in cooldown after a recent failure");
712
+ }
713
+ if (!this.connectPromise) this.connectPromise = this.connect().finally(() => {
714
+ this.connectPromise = null;
715
+ });
716
+ await this.connectPromise;
717
+ }
718
+ if (!this.client) throw new Error("Valkey client connect failed");
719
+ return this.client;
720
+ }
721
+ /**
722
+ * Race a GLIDE `createClient` promise against {@link CONNECT_ATTEMPT_TIMEOUT_MS}
723
+ * so a stalled connect can never block the calling resolver (and the pg
724
+ * connection it may be holding) longer than the budget. On timeout the
725
+ * underlying connect is abandoned but not left dangling: if it later resolves
726
+ * we close the orphaned client to avoid leaking a socket. The thrown error
727
+ * propagates to `connect()`'s catch, which arms the circuit-breaker so
728
+ * subsequent ops fast-fail (cache miss) during the cooldown.
729
+ */
730
+ async withConnectBudget(pending) {
731
+ let timer;
732
+ const timeout = new Promise((_, reject) => {
733
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`Valkey connect exceeded ${String(CONNECT_ATTEMPT_TIMEOUT_MS)}ms budget`)), CONNECT_ATTEMPT_TIMEOUT_MS);
734
+ });
735
+ try {
736
+ return await Promise.race([pending, timeout]);
737
+ } catch (error) {
738
+ pending.then((client) => {
739
+ client.close().catch(() => void 0);
740
+ }, () => void 0);
741
+ throw error;
742
+ } finally {
743
+ if (timer) clearTimeout(timer);
744
+ }
745
+ }
746
+ async connect() {
747
+ if (this.connected && this.client) return;
748
+ try {
749
+ let glideModule;
750
+ try {
751
+ glideModule = await import("@valkey/valkey-glide");
752
+ } catch (importError) {
753
+ throw new Error(`@valkey/valkey-glide is not installed — the Valkey cache is DISABLED and every cache op degrades to a miss (import failed: ${importError instanceof Error ? importError.message : String(importError)})`);
754
+ }
755
+ const GlideClient = glideModule.GlideClient || glideModule.default;
756
+ const GlideClusterClient = glideModule.GlideClusterClient;
757
+ this.clusterScanCursor = glideModule.ClusterScanCursor ?? null;
758
+ if (!GlideClient) throw new Error("Valkey GLIDE standalone client is unavailable");
759
+ let host = this.config.host || "localhost";
760
+ let port = this.config.port || 6379;
761
+ let password = this.config.password;
762
+ let username = this.config.username;
763
+ let useTLSFromUrl;
764
+ let databaseFromUrl;
765
+ if (this.config.url) {
766
+ const rawUrl = this.config.url;
767
+ useTLSFromUrl = /^(rediss|valkeys):\/\//i.test(rawUrl);
768
+ const url = new URL(rawUrl.replace(/^valkey:\/\//i, "redis://").replace(/^valkeys:\/\//i, "rediss://"));
769
+ host = url.hostname;
770
+ port = parseInt(url.port || "6379", 10);
771
+ if (!password && url.password) try {
772
+ password = decodeURIComponent(url.password);
773
+ } catch {
774
+ password = url.password;
775
+ }
776
+ if (!username && url.username) try {
777
+ username = decodeURIComponent(url.username);
778
+ } catch {
779
+ username = url.username;
780
+ }
781
+ const dbMatch = /^\/(\d+)$/.exec(url.pathname);
782
+ if (dbMatch && dbMatch[1]) {
783
+ databaseFromUrl = parseInt(dbMatch[1], 10);
784
+ if (/\.redis\.azure\.net$/i.test(host) && databaseFromUrl > 0) {
785
+ if (!this.dbNamespaceSuffixApplied) {
786
+ logger.warn(`[ValkeyGlideProvider] Azure Managed Redis only supports DB 0; ignoring /${String(databaseFromUrl)} in URL and folding it into namespace.`);
787
+ this.namespace = `${this.namespace}:db${String(databaseFromUrl)}`;
788
+ this.dbNamespaceSuffixApplied = true;
789
+ }
790
+ databaseFromUrl = 0;
791
+ }
792
+ }
793
+ }
794
+ const baseClientConfig = {
795
+ addresses: this.config.clusterNodes?.length ? this.config.clusterNodes : [{
796
+ host,
797
+ port
798
+ }],
799
+ useTLS: this.config.useTLS ?? useTLSFromUrl,
800
+ credentials: password || username ? {
801
+ password,
802
+ username
803
+ } : void 0,
804
+ clientName: this.config.name || `valkey-glide-${this.namespace}`,
805
+ databaseId: this.config.db ?? databaseFromUrl,
806
+ requestTimeout: REQUEST_TIMEOUT_MS,
807
+ connectionBackoff: {
808
+ numberOfRetries: this.config.maxReconnectAttempts && this.config.maxReconnectAttempts > 0 ? this.config.maxReconnectAttempts : 5,
809
+ factor: this.config.reconnectTimeWait ?? 1e3,
810
+ exponentBase: 2
811
+ },
812
+ readFrom: "primary",
813
+ advancedConfiguration: { connectionTimeout: this.config.connectionTimeout ?? CONNECTION_TIMEOUT_MS }
814
+ };
815
+ if (this.config.cluster === true) {
816
+ if (!GlideClusterClient) throw new Error("Valkey GLIDE cluster client is unavailable");
817
+ this.client = await this.withConnectBudget(GlideClusterClient.createClient({
818
+ ...baseClientConfig,
819
+ periodicChecks: { duration_in_sec: 30 },
820
+ advancedConfiguration: {
821
+ ...baseClientConfig.advancedConfiguration,
822
+ refreshTopologyFromInitialNodes: true
823
+ }
824
+ }));
825
+ this.clientIsCluster = true;
826
+ } else {
827
+ const standaloneClient = await this.withConnectBudget(GlideClient.createClient(baseClientConfig));
828
+ if (this.config.cluster !== false && await this.serverReportsCluster(standaloneClient)) {
829
+ if (!GlideClusterClient) throw new Error("Valkey server is clustered but GLIDE cluster client is unavailable");
830
+ await standaloneClient.close();
831
+ this.client = await this.withConnectBudget(GlideClusterClient.createClient({
832
+ ...baseClientConfig,
833
+ periodicChecks: { duration_in_sec: 30 },
834
+ advancedConfiguration: {
835
+ ...baseClientConfig.advancedConfiguration,
836
+ refreshTopologyFromInitialNodes: true
837
+ }
838
+ }));
839
+ this.clientIsCluster = true;
840
+ } else {
841
+ this.client = standaloneClient;
842
+ this.clientIsCluster = false;
843
+ }
844
+ }
845
+ this.connected = true;
846
+ this.lastConnectFailureAt = 0;
847
+ this.consecutiveOpFailures = 0;
848
+ registerDisposable(this);
849
+ if (this.enableLogging) logger.info(`[ValkeyGlideProvider:${this.namespace}] Connected to Valkey`, {
850
+ host,
851
+ port,
852
+ cluster: this.clientIsCluster
853
+ });
854
+ } catch (error) {
855
+ this.stats.errors++;
856
+ this.lastConnectFailureAt = Date.now();
857
+ const normalized = error instanceof Error ? error : new Error(String(error));
858
+ logger.error(`[ValkeyGlideProvider:${this.namespace}] Failed to connect:`, normalized);
859
+ throw normalized;
860
+ }
861
+ }
862
+ /**
863
+ * Disconnect from Valkey server
864
+ */
865
+ /** Label for the graceful-shutdown registry. */
866
+ get shutdownName() {
867
+ return `valkey-cache:${this.namespace}`;
868
+ }
869
+ /** Close the client on graceful shutdown. */
870
+ dispose() {
871
+ return this.disconnect();
872
+ }
873
+ async disconnect() {
874
+ unregisterDisposable(this);
875
+ if (this.client) {
876
+ await this.client.close();
877
+ this.client = null;
878
+ this.clientIsCluster = false;
879
+ this.connected = false;
880
+ this.lastConnectFailureAt = 0;
881
+ if (this.enableLogging) logger.info(`[ValkeyGlideProvider:${this.namespace}] Disconnected`);
882
+ }
883
+ }
884
+ /**
885
+ * A command completed — the connection is proven alive, so clear the
886
+ * teardown counter. Called from every command's success path.
887
+ */
888
+ recordOpSuccess() {
889
+ if (this.consecutiveOpFailures !== 0) this.consecutiveOpFailures = 0;
890
+ }
891
+ /**
892
+ * Record an operation error and, if the client looks wedged (enough
893
+ * consecutive connection-level failures), tear it down so the next op builds a
894
+ * fresh one. Non-connection errors (bad command, serialization) are ignored so
895
+ * they never trip the teardown.
896
+ */
897
+ noteOpError(error) {
898
+ if (!isConnectionLevelError(error)) return;
899
+ this.consecutiveOpFailures += 1;
900
+ if (this.consecutiveOpFailures >= MAX_CONSECUTIVE_OP_FAILURES) this.resetClientForReconnect();
901
+ }
902
+ /**
903
+ * Log an operation error, throttling the breaker's own cooldown fast-fail.
904
+ * While the connect circuit-breaker is armed every op fails with the same
905
+ * "connect in cooldown" error; those are expected (the op has already
906
+ * degraded to a cache miss) and are summarized at most once per
907
+ * COOLDOWN_LOG_INTERVAL_MS instead of stack-traced per call. Any other error
908
+ * logs at error level unthrottled.
909
+ */
910
+ logOpError(what, error) {
911
+ if (error instanceof Error && error.message.includes("connect in cooldown")) {
912
+ const now = Date.now();
913
+ if (now - this.lastCooldownLogAt < COOLDOWN_LOG_INTERVAL_MS) return;
914
+ this.lastCooldownLogAt = now;
915
+ logger.warn(`[ValkeyGlideProvider:${this.namespace}] Valkey unavailable (connect circuit-breaker armed); ops are degrading to cache misses. Further cooldown fast-fails are suppressed for ${String(COOLDOWN_LOG_INTERVAL_MS)}ms — see the preceding "Failed to connect" log for the root cause.`);
916
+ return;
917
+ }
918
+ logger.error(`[ValkeyGlideProvider:${this.namespace}] ${what}:`, error);
919
+ }
920
+ /**
921
+ * Drop the current client so the next ensureConnected() creates a new one.
922
+ * Arms the connect circuit-breaker so ops fast-fail (cache miss) during the
923
+ * cooldown rather than racing a fresh connect on every call, and closes the
924
+ * dead client in the background so its socket is not leaked.
925
+ */
926
+ resetClientForReconnect() {
927
+ const dead = this.client;
928
+ this.client = null;
929
+ this.connected = false;
930
+ this.consecutiveOpFailures = 0;
931
+ this.lastConnectFailureAt = Date.now();
932
+ logger.warn(`[ValkeyGlideProvider:${this.namespace}] Tearing down wedged client after ${String(MAX_CONSECUTIVE_OP_FAILURES)} consecutive connection failures; rebuilding on next op`);
933
+ if (dead) dead.close().catch(() => void 0);
934
+ }
935
+ /**
936
+ * Check if connected
937
+ */
938
+ isConnected() {
939
+ return this.connected && this.client !== null;
940
+ }
941
+ /**
942
+ * Health check
943
+ */
944
+ async healthCheck() {
945
+ const startTime = Date.now();
946
+ try {
947
+ if (!this.client) return {
948
+ status: "unhealthy",
949
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
950
+ connected: false,
951
+ error: "Not connected"
952
+ };
953
+ const result = await this.client.ping();
954
+ const latencyMs = Date.now() - startTime;
955
+ if (result === "PONG") return {
956
+ status: "healthy",
957
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
958
+ connected: true,
959
+ latencyMs
960
+ };
961
+ return {
962
+ status: "unhealthy",
963
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
964
+ connected: false,
965
+ error: "Unexpected ping response"
966
+ };
967
+ } catch (error) {
968
+ return {
969
+ status: "unhealthy",
970
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
971
+ connected: false,
972
+ error: error instanceof Error ? error.message : "Unknown error",
973
+ latencyMs: Date.now() - startTime
974
+ };
975
+ }
976
+ }
977
+ /**
978
+ * Get statistics
979
+ */
980
+ async getStatistics() {
981
+ const totalOperations = this.stats.hits + this.stats.misses;
982
+ const hitRate = totalOperations > 0 ? this.stats.hits / totalOperations : 0;
983
+ try {
984
+ const client = await this.ensureConnected();
985
+ const info = await client.info("memory");
986
+ const memoryMatch = /used_memory:(\d+)/.exec(info);
987
+ const memoryUsed = memoryMatch && memoryMatch[1] ? parseInt(memoryMatch[1], 10) : void 0;
988
+ const keyCount = await client.dbsize();
989
+ this.recordOpSuccess();
990
+ return {
991
+ hits: this.stats.hits,
992
+ misses: this.stats.misses,
993
+ hitRate,
994
+ keyCount,
995
+ memoryUsed,
996
+ totalOperations,
997
+ details: {
998
+ sets: this.stats.sets,
999
+ deletes: this.stats.deletes,
1000
+ errors: this.stats.errors
1001
+ }
1002
+ };
1003
+ } catch (error) {
1004
+ this.noteOpError(error);
1005
+ this.logOpError("Failed to get statistics", error);
1006
+ return {
1007
+ hits: this.stats.hits,
1008
+ misses: this.stats.misses,
1009
+ hitRate,
1010
+ totalOperations,
1011
+ details: {
1012
+ sets: this.stats.sets,
1013
+ deletes: this.stats.deletes,
1014
+ errors: this.stats.errors
1015
+ }
1016
+ };
1017
+ }
1018
+ }
1019
+ /**
1020
+ * Build cache key with namespace
1021
+ */
1022
+ buildKey(key) {
1023
+ return `${this.namespace}:${key}`;
1024
+ }
1025
+ buildPattern(pattern) {
1026
+ return `${this.namespace.replace(/[\\*?[\]]/g, "\\$&")}:${pattern}`;
1027
+ }
1028
+ /**
1029
+ * Get value from cache
1030
+ */
1031
+ async get(key, _options) {
1032
+ try {
1033
+ const client = await this.ensureConnected();
1034
+ const cacheKey = this.buildKey(key);
1035
+ const value = await client.get(cacheKey);
1036
+ this.recordOpSuccess();
1037
+ if (value === null) {
1038
+ this.stats.misses++;
1039
+ if (this.enableLogging) logger.debug(`[ValkeyGlideProvider:${this.namespace}] Cache miss`, { key });
1040
+ return null;
1041
+ }
1042
+ this.stats.hits++;
1043
+ if (this.enableLogging) logger.debug(`[ValkeyGlideProvider:${this.namespace}] Cache hit`, { key });
1044
+ return JSON.parse(value).data;
1045
+ } catch (error) {
1046
+ this.stats.errors++;
1047
+ this.noteOpError(error);
1048
+ this.logOpError("Error getting cache key", error);
1049
+ return null;
1050
+ }
1051
+ }
1052
+ /**
1053
+ * Set value in cache
1054
+ */
1055
+ async set(key, value, options) {
1056
+ try {
1057
+ const client = await this.ensureConnected();
1058
+ const cacheKey = this.buildKey(key);
1059
+ const ttlSeconds = options?.ttl || this.defaultTTL;
1060
+ const entry = {
1061
+ data: value,
1062
+ timestamp: Date.now(),
1063
+ ttl: ttlSeconds,
1064
+ metadata: options?.metadata
1065
+ };
1066
+ await client.set(cacheKey, JSON.stringify(entry), { expiry: {
1067
+ type: "EX",
1068
+ count: ttlSeconds
1069
+ } });
1070
+ this.recordOpSuccess();
1071
+ this.stats.sets++;
1072
+ if (this.enableLogging) logger.debug(`[ValkeyGlideProvider:${this.namespace}] Cache set`, {
1073
+ key,
1074
+ ttl: ttlSeconds
1075
+ });
1076
+ return true;
1077
+ } catch (error) {
1078
+ this.stats.errors++;
1079
+ this.noteOpError(error);
1080
+ this.logOpError("Error setting cache key", error);
1081
+ return false;
1082
+ }
1083
+ }
1084
+ /**
1085
+ * Delete value from cache
1086
+ */
1087
+ async delete(key) {
1088
+ try {
1089
+ const client = await this.ensureConnected();
1090
+ const cacheKey = this.buildKey(key);
1091
+ const result = await client.del([cacheKey]);
1092
+ this.recordOpSuccess();
1093
+ this.stats.deletes++;
1094
+ if (this.enableLogging) logger.debug(`[ValkeyGlideProvider:${this.namespace}] Cache delete`, {
1095
+ key,
1096
+ deleted: result > 0
1097
+ });
1098
+ return result > 0;
1099
+ } catch (error) {
1100
+ this.stats.errors++;
1101
+ this.noteOpError(error);
1102
+ this.logOpError("Error deleting cache key", error);
1103
+ return false;
1104
+ }
1105
+ }
1106
+ /**
1107
+ * Check if key exists
1108
+ */
1109
+ async has(key) {
1110
+ try {
1111
+ const client = await this.ensureConnected();
1112
+ const cacheKey = this.buildKey(key);
1113
+ const exists = await client.exists([cacheKey]);
1114
+ this.recordOpSuccess();
1115
+ return exists === 1;
1116
+ } catch (error) {
1117
+ this.stats.errors++;
1118
+ this.noteOpError(error);
1119
+ this.logOpError("Error checking cache key", error);
1120
+ return false;
1121
+ }
1122
+ }
1123
+ /**
1124
+ * Get TTL for key
1125
+ */
1126
+ async ttl(key) {
1127
+ try {
1128
+ const client = await this.ensureConnected();
1129
+ const cacheKey = this.buildKey(key);
1130
+ const result = await client.ttl(cacheKey);
1131
+ this.recordOpSuccess();
1132
+ return result;
1133
+ } catch (error) {
1134
+ this.stats.errors++;
1135
+ this.noteOpError(error);
1136
+ this.logOpError("Error getting TTL", error);
1137
+ return -2;
1138
+ }
1139
+ }
1140
+ /**
1141
+ * Update TTL for key
1142
+ */
1143
+ async expire(key, ttl) {
1144
+ try {
1145
+ const client = await this.ensureConnected();
1146
+ const cacheKey = this.buildKey(key);
1147
+ const result = await client.expire(cacheKey, ttl);
1148
+ this.recordOpSuccess();
1149
+ return result;
1150
+ } catch (error) {
1151
+ this.stats.errors++;
1152
+ this.noteOpError(error);
1153
+ this.logOpError("Error setting expiration", error);
1154
+ return false;
1155
+ }
1156
+ }
1157
+ /**
1158
+ * Set TTL for a key only if it currently has no TTL (`EXPIRE key ttl NX`).
1159
+ * Atomic server-side. Returns true only when the expiry was applied.
1160
+ */
1161
+ async expireNX(key, ttlSeconds) {
1162
+ try {
1163
+ const client = await this.ensureConnected();
1164
+ const cacheKey = this.buildKey(key);
1165
+ const result = await client.expire(cacheKey, ttlSeconds, { expireOption: "NX" });
1166
+ this.recordOpSuccess();
1167
+ return result === true;
1168
+ } catch (error) {
1169
+ this.stats.errors++;
1170
+ this.noteOpError(error);
1171
+ this.logOpError("Error setting NX expiration", error);
1172
+ return false;
1173
+ }
1174
+ }
1175
+ /**
1176
+ * Get multiple values (batch operation)
1177
+ */
1178
+ async mget(keys, _options) {
1179
+ const result = /* @__PURE__ */ new Map();
1180
+ if (keys.length === 0) return result;
1181
+ try {
1182
+ const client = await this.ensureConnected();
1183
+ const cacheKeys = keys.map((key) => this.buildKey(key));
1184
+ const values = await client.mget(cacheKeys);
1185
+ this.recordOpSuccess();
1186
+ for (let i = 0; i < keys.length; i++) {
1187
+ const key = keys[i];
1188
+ if (!key) continue;
1189
+ if (values[i] !== null) {
1190
+ const entry = JSON.parse(values[i]);
1191
+ result.set(key, entry.data);
1192
+ this.stats.hits++;
1193
+ } else this.stats.misses++;
1194
+ }
1195
+ if (this.enableLogging) logger.debug(`[ValkeyGlideProvider:${this.namespace}] Batch get`, {
1196
+ requested: keys.length,
1197
+ found: result.size
1198
+ });
1199
+ return result;
1200
+ } catch (error) {
1201
+ this.stats.errors++;
1202
+ this.noteOpError(error);
1203
+ this.logOpError("Error in batch get", error);
1204
+ return result;
1205
+ }
1206
+ }
1207
+ /**
1208
+ * Set multiple values (batch operation)
1209
+ */
1210
+ async mset(entries, options) {
1211
+ if (entries.size === 0) return true;
1212
+ try {
1213
+ const client = await this.ensureConnected();
1214
+ const ttlSeconds = options?.ttl || this.defaultTTL;
1215
+ const keyValuePairs = {};
1216
+ for (const [key, value] of entries) {
1217
+ const cacheKey = this.buildKey(key);
1218
+ const entry = {
1219
+ data: value,
1220
+ timestamp: Date.now(),
1221
+ ttl: ttlSeconds,
1222
+ metadata: options?.metadata
1223
+ };
1224
+ keyValuePairs[cacheKey] = JSON.stringify(entry);
1225
+ }
1226
+ await client.mset(keyValuePairs);
1227
+ this.recordOpSuccess();
1228
+ for (const cacheKey of Object.keys(keyValuePairs)) await client.expire(cacheKey, ttlSeconds);
1229
+ this.stats.sets += entries.size;
1230
+ if (this.enableLogging) logger.debug(`[ValkeyGlideProvider:${this.namespace}] Batch set`, {
1231
+ count: entries.size,
1232
+ ttl: ttlSeconds
1233
+ });
1234
+ return true;
1235
+ } catch (error) {
1236
+ this.stats.errors++;
1237
+ this.noteOpError(error);
1238
+ this.logOpError("Error in batch set", error);
1239
+ return false;
1240
+ }
1241
+ }
1242
+ /**
1243
+ * Delete multiple keys (batch operation)
1244
+ */
1245
+ async mdel(keys) {
1246
+ if (keys.length === 0) return 0;
1247
+ try {
1248
+ const client = await this.ensureConnected();
1249
+ const cacheKeys = keys.map((key) => this.buildKey(key));
1250
+ const result = await client.del(cacheKeys);
1251
+ this.recordOpSuccess();
1252
+ this.stats.deletes += result;
1253
+ if (this.enableLogging) logger.debug(`[ValkeyGlideProvider:${this.namespace}] Batch delete`, {
1254
+ requested: keys.length,
1255
+ deleted: result
1256
+ });
1257
+ return result;
1258
+ } catch (error) {
1259
+ this.stats.errors++;
1260
+ this.noteOpError(error);
1261
+ this.logOpError("Error in batch delete", error);
1262
+ return 0;
1263
+ }
1264
+ }
1265
+ /**
1266
+ * Clear keys by pattern
1267
+ */
1268
+ async clearPattern(pattern) {
1269
+ try {
1270
+ const client = await this.ensureConnected();
1271
+ const searchPattern = this.buildPattern(pattern);
1272
+ const keys = await this.getKeys(searchPattern);
1273
+ if (keys.length === 0) {
1274
+ this.recordOpSuccess();
1275
+ return 0;
1276
+ }
1277
+ let result = 0;
1278
+ const uniqueKeys = [...new Set(keys)];
1279
+ for (let offset = 0; offset < uniqueKeys.length; offset += 1e3) result += await client.del(uniqueKeys.slice(offset, offset + 1e3));
1280
+ this.recordOpSuccess();
1281
+ if (this.enableLogging) logger.debug(`[ValkeyGlideProvider:${this.namespace}] Pattern cleared`, {
1282
+ pattern,
1283
+ deleted: result
1284
+ });
1285
+ return result;
1286
+ } catch (error) {
1287
+ this.stats.errors++;
1288
+ this.noteOpError(error);
1289
+ this.logOpError("Error clearing pattern", error);
1290
+ throw error;
1291
+ }
1292
+ }
1293
+ /**
1294
+ * Get keys by pattern
1295
+ */
1296
+ async keys(options) {
1297
+ try {
1298
+ await this.ensureConnected();
1299
+ const searchPattern = this.buildPattern(options.pattern);
1300
+ const keys = await this.getKeys(searchPattern);
1301
+ this.recordOpSuccess();
1302
+ const prefix = `${this.namespace}:`;
1303
+ const cleanKeys = keys.map((key) => key.replace(prefix, ""));
1304
+ return {
1305
+ keys: options.limit ? cleanKeys.slice(0, options.limit) : cleanKeys,
1306
+ nextCursor: null,
1307
+ totalCount: cleanKeys.length
1308
+ };
1309
+ } catch (error) {
1310
+ this.stats.errors++;
1311
+ this.noteOpError(error);
1312
+ this.logOpError("Error getting keys", error);
1313
+ return {
1314
+ keys: [],
1315
+ nextCursor: null,
1316
+ totalCount: 0
1317
+ };
1318
+ }
1319
+ }
1320
+ /**
1321
+ * Clear all keys in namespace
1322
+ */
1323
+ async clear() {
1324
+ try {
1325
+ const client = await this.ensureConnected();
1326
+ const pattern = this.buildPattern("*");
1327
+ const keys = await this.getKeys(pattern);
1328
+ this.recordOpSuccess();
1329
+ if (keys.length > 0) {
1330
+ await client.del(keys);
1331
+ if (this.enableLogging) logger.info(`[ValkeyGlideProvider:${this.namespace}] Cleared ${keys.length} keys`);
1332
+ }
1333
+ return true;
1334
+ } catch (error) {
1335
+ this.stats.errors++;
1336
+ this.noteOpError(error);
1337
+ this.logOpError("Error clearing cache", error);
1338
+ return false;
1339
+ }
1340
+ }
1341
+ /**
1342
+ * Increment numeric value
1343
+ */
1344
+ async increment(key, amount = 1) {
1345
+ try {
1346
+ const client = await this.ensureConnected();
1347
+ const cacheKey = this.buildKey(key);
1348
+ const result = await client.incrBy(cacheKey, amount);
1349
+ this.recordOpSuccess();
1350
+ return result;
1351
+ } catch (error) {
1352
+ this.stats.errors++;
1353
+ this.noteOpError(error);
1354
+ this.logOpError("Error incrementing", error);
1355
+ throw error;
1356
+ }
1357
+ }
1358
+ /**
1359
+ * Decrement numeric value
1360
+ */
1361
+ async decrement(key, amount = 1) {
1362
+ try {
1363
+ const client = await this.ensureConnected();
1364
+ const cacheKey = this.buildKey(key);
1365
+ const result = await client.decrBy(cacheKey, amount);
1366
+ this.recordOpSuccess();
1367
+ return result;
1368
+ } catch (error) {
1369
+ this.stats.errors++;
1370
+ this.noteOpError(error);
1371
+ this.logOpError("Error decrementing", error);
1372
+ throw error;
1373
+ }
1374
+ }
1375
+ /**
1376
+ * Get or set value
1377
+ */
1378
+ async getOrSet(key, fetcher, options) {
1379
+ const cached = await this.get(key, options);
1380
+ if (cached !== null) return cached;
1381
+ const value = await fetcher();
1382
+ await this.set(key, value, options);
1383
+ return value;
1384
+ }
1385
+ /**
1386
+ * Invalidate by tags
1387
+ */
1388
+ async invalidateTags(tags) {
1389
+ try {
1390
+ let totalDeleted = 0;
1391
+ for (const tag of tags) {
1392
+ const pattern = `*:tag:${tag}:*`;
1393
+ const deleted = await this.clearPattern(pattern);
1394
+ totalDeleted += deleted;
1395
+ }
1396
+ if (this.enableLogging) logger.debug(`[ValkeyGlideProvider:${this.namespace}] Tags invalidated`, {
1397
+ tags,
1398
+ deleted: totalDeleted
1399
+ });
1400
+ return totalDeleted;
1401
+ } catch (error) {
1402
+ this.stats.errors++;
1403
+ this.logOpError("Error invalidating tags", error);
1404
+ return 0;
1405
+ }
1406
+ }
1407
+ };
1408
+
1409
+ // src/cache/factory/CacheFactory.ts
1410
+ /**
1411
+ * Cache Factory
1412
+ * Creates appropriate cache provider instances based on configuration
1413
+ */
1414
+ /**
1415
+ * Factory for creating cache instances
1416
+ */
1417
+ var CacheFactory = class CacheFactory {
1418
+ static instances = /* @__PURE__ */ new Map();
1419
+ static parseBoolean(value) {
1420
+ if (value === void 0) return void 0;
1421
+ const normalized = value.trim().toLowerCase();
1422
+ if ([
1423
+ "1",
1424
+ "true",
1425
+ "yes",
1426
+ "on"
1427
+ ].includes(normalized)) return true;
1428
+ if ([
1429
+ "0",
1430
+ "false",
1431
+ "no",
1432
+ "off"
1433
+ ].includes(normalized)) return false;
1434
+ }
1435
+ static parseClusterNodes(value) {
1436
+ if (!value) return void 0;
1437
+ const nodes = value.split(",").map((node) => node.trim()).filter(Boolean).map((node) => {
1438
+ const [host, rawPort] = node.replace(/^redis:\/\//, "").replace(/^valkey:\/\//, "").split(":");
1439
+ if (!host) return null;
1440
+ return {
1441
+ host,
1442
+ port: rawPort ? parseInt(rawPort, 10) : 6379
1443
+ };
1444
+ }).filter((node) => node !== null && Number.isFinite(node.port));
1445
+ return nodes.length > 0 ? nodes : void 0;
1446
+ }
1447
+ /**
1448
+ * Resolve port from multiple environment variable sources
1449
+ * @param layerPort - Layer-specific port environment variable value
1450
+ * @param genericPort - Generic port environment variable value
1451
+ * @param defaultPort - Default port if none provided
1452
+ * @returns Resolved port number
1453
+ */
1454
+ static resolvePort(layerPort, genericPort, defaultPort = 6379) {
1455
+ if (layerPort) return parseInt(layerPort, 10);
1456
+ if (genericPort) return parseInt(genericPort, 10);
1457
+ return defaultPort;
1458
+ }
1459
+ /**
1460
+ * Create a cache provider based on configuration
1461
+ */
1462
+ static createCache(config, namespace = "default") {
1463
+ logger.info("[CacheFactory] Creating cache provider", {
1464
+ type: config.type,
1465
+ namespace
1466
+ });
1467
+ switch (config.type) {
1468
+ case "valkey":
1469
+ case "redis": return new ValkeyGlideProvider({
1470
+ type: "valkey-glide",
1471
+ url: config.url,
1472
+ host: config.host,
1473
+ port: config.port,
1474
+ password: config.password,
1475
+ username: config.username,
1476
+ db: config.db,
1477
+ keyPrefix: config.keyPrefix,
1478
+ defaultTTL: config.defaultTTL,
1479
+ enableLogging: config.enableLogging,
1480
+ maxReconnectAttempts: config.maxReconnectAttempts,
1481
+ reconnectTimeWait: config.reconnectTimeWait,
1482
+ connectionTimeout: config.connectionTimeout,
1483
+ name: config.name,
1484
+ useTLS: config.tls?.enabled,
1485
+ cluster: config.cluster,
1486
+ clusterNodes: config.clusterNodes
1487
+ }, namespace);
1488
+ case "memory": return new MemoryCacheProvider(config, namespace);
1489
+ default: throw new Error(`Unsupported cache provider type: ${config.type}`);
1490
+ }
1491
+ }
1492
+ /**
1493
+ * Create a cache from environment variables
1494
+ */
1495
+ static createCacheFromEnv(namespace = "default") {
1496
+ const type = process.env["CACHE_PROVIDER_TYPE"] === "memory" ? "memory" : "valkey";
1497
+ if (type === "valkey") assertCacheEndpointConfigured({
1498
+ url: process.env["VALKEY_URL"] || process.env["REDIS_URL"],
1499
+ host: process.env["VALKEY_HOST"],
1500
+ password: process.env["VALKEY_PASSWORD"],
1501
+ port: process.env["VALKEY_PORT"] ? parseInt(process.env["VALKEY_PORT"], 10) : void 0,
1502
+ context: "CacheFactory.createCache",
1503
+ keysTried: [
1504
+ "VALKEY_URL",
1505
+ "REDIS_URL",
1506
+ "VALKEY_HOST"
1507
+ ]
1508
+ });
1509
+ const config = type === "valkey" ? {
1510
+ type: "valkey",
1511
+ url: process.env["VALKEY_URL"] || process.env["REDIS_URL"],
1512
+ host: process.env["VALKEY_HOST"] || "localhost",
1513
+ port: process.env["VALKEY_PORT"] ? parseInt(process.env["VALKEY_PORT"], 10) : 6379,
1514
+ password: process.env["VALKEY_PASSWORD"],
1515
+ db: process.env["VALKEY_DB"] ? parseInt(process.env["VALKEY_DB"], 10) : 0,
1516
+ username: process.env["VALKEY_USERNAME"],
1517
+ keyPrefix: process.env["CACHE_KEY_PREFIX"] || "cache",
1518
+ defaultTTL: process.env["CACHE_DEFAULT_TTL"] ? parseInt(process.env["CACHE_DEFAULT_TTL"], 10) : 300,
1519
+ enableLogging: process.env["CACHE_ENABLE_LOGGING"] === "true",
1520
+ maxReconnectAttempts: process.env["VALKEY_MAX_RECONNECT_ATTEMPTS"] ? parseInt(process.env["VALKEY_MAX_RECONNECT_ATTEMPTS"], 10) : -1,
1521
+ reconnectTimeWait: process.env["VALKEY_RECONNECT_TIME_WAIT"] ? parseInt(process.env["VALKEY_RECONNECT_TIME_WAIT"], 10) : 2e3,
1522
+ connectionTimeout: process.env["VALKEY_CONNECTION_TIMEOUT"] ? parseInt(process.env["VALKEY_CONNECTION_TIMEOUT"], 10) : 1e4,
1523
+ name: process.env["CACHE_CLIENT_NAME"] || `cache-${namespace}`,
1524
+ cluster: CacheFactory.parseBoolean(process.env["VALKEY_CLUSTER"] || process.env["CACHE_CLUSTER"]),
1525
+ clusterNodes: CacheFactory.parseClusterNodes(process.env["VALKEY_CLUSTER_NODES"] || process.env["CACHE_CLUSTER_NODES"])
1526
+ } : {
1527
+ type: "memory",
1528
+ maxSize: process.env["CACHE_MAX_SIZE"] ? parseInt(process.env["CACHE_MAX_SIZE"], 10) : 1e3,
1529
+ defaultTTL: process.env["CACHE_DEFAULT_TTL"] ? parseInt(process.env["CACHE_DEFAULT_TTL"], 10) : 300,
1530
+ enableLogging: process.env["CACHE_ENABLE_LOGGING"] === "true",
1531
+ keyPrefix: process.env["CACHE_KEY_PREFIX"] || "cache"
1532
+ };
1533
+ return CacheFactory.createCache(config, namespace);
1534
+ }
1535
+ /**
1536
+ * Get or create a singleton cache instance for a namespace
1537
+ */
1538
+ static getInstance(namespace = "default", config) {
1539
+ const instanceKey = `${config?.type || "default"}:${namespace}`;
1540
+ if (!CacheFactory.instances.has(instanceKey)) {
1541
+ const cache = config ? CacheFactory.createCache(config, namespace) : CacheFactory.createCacheFromEnv(namespace);
1542
+ CacheFactory.instances.set(instanceKey, cache);
1543
+ }
1544
+ return CacheFactory.instances.get(instanceKey);
1545
+ }
1546
+ /**
1547
+ * Close a specific cache instance
1548
+ */
1549
+ static async closeInstance(namespace) {
1550
+ for (const [key, cache] of CacheFactory.instances.entries()) if (key.endsWith(`:${namespace}`)) {
1551
+ await cache.disconnect();
1552
+ CacheFactory.instances.delete(key);
1553
+ logger.info("[CacheFactory] Closed cache instance", { namespace });
1554
+ }
1555
+ }
1556
+ /**
1557
+ * Close all cache instances
1558
+ * Call this during application shutdown
1559
+ */
1560
+ static async closeAll() {
1561
+ const promises = Array.from(CacheFactory.instances.values()).map(async (cache) => cache.disconnect());
1562
+ await Promise.all(promises);
1563
+ CacheFactory.instances.clear();
1564
+ logger.info("[CacheFactory] All cache instances closed");
1565
+ }
1566
+ /**
1567
+ * Create a cache provider for a specific layer
1568
+ *
1569
+ * @param layer - Service layer ('wspace' or 'global')
1570
+ * @param serviceName - Service name for identification
1571
+ * @param namespace - Cache namespace (default: 'default')
1572
+ * @returns Cache provider configured for the layer
1573
+ *
1574
+ * @example
1575
+ * ```typescript
1576
+ * const cache = CacheFactory.createCacheForLayer('wspace', 'wspace-tags-svc');
1577
+ * await cache.connect();
1578
+ * await cache.set('key', { data: 'value' });
1579
+ * ```
1580
+ */
1581
+ static createCacheForLayer(layer, serviceName, namespace = "default") {
1582
+ const envPrefix = layer.toUpperCase();
1583
+ const defaults = DEFAULT_LAYER_RESOURCES[layer];
1584
+ const url = process.env[`${envPrefix}_VALKEY_URL`] || process.env["VALKEY_URL"] || process.env["REDIS_URL"] || defaults.valkeyUrl;
1585
+ warnOnLayerDefaultEndpoint(`CacheFactory.createCacheForLayer(${layer}, ${serviceName})`, url, defaults.valkeyUrl);
1586
+ const resolvedPort = CacheFactory.resolvePort(process.env[`${envPrefix}_VALKEY_PORT`], process.env["VALKEY_PORT"]);
1587
+ const config = {
1588
+ type: "valkey",
1589
+ url,
1590
+ host: process.env[`${envPrefix}_VALKEY_HOST`] || process.env["VALKEY_HOST"] || "localhost",
1591
+ port: resolvedPort,
1592
+ password: process.env["VALKEY_PASSWORD"],
1593
+ db: process.env["VALKEY_DB"] ? parseInt(process.env["VALKEY_DB"], 10) : 0,
1594
+ username: process.env["VALKEY_USERNAME"],
1595
+ keyPrefix: process.env["CACHE_KEY_PREFIX"] || `${layer}-cache`,
1596
+ defaultTTL: process.env["CACHE_DEFAULT_TTL"] ? parseInt(process.env["CACHE_DEFAULT_TTL"], 10) : 300,
1597
+ enableLogging: process.env["CACHE_ENABLE_LOGGING"] === "true",
1598
+ maxReconnectAttempts: process.env["VALKEY_MAX_RECONNECT_ATTEMPTS"] ? parseInt(process.env["VALKEY_MAX_RECONNECT_ATTEMPTS"], 10) : -1,
1599
+ reconnectTimeWait: process.env["VALKEY_RECONNECT_TIME_WAIT"] ? parseInt(process.env["VALKEY_RECONNECT_TIME_WAIT"], 10) : 2e3,
1600
+ connectionTimeout: process.env["VALKEY_CONNECTION_TIMEOUT"] ? parseInt(process.env["VALKEY_CONNECTION_TIMEOUT"], 10) : 1e4,
1601
+ name: serviceName,
1602
+ cluster: CacheFactory.parseBoolean(process.env[`${envPrefix}_VALKEY_CLUSTER`] || process.env["VALKEY_CLUSTER"] || process.env["CACHE_CLUSTER"]),
1603
+ clusterNodes: CacheFactory.parseClusterNodes(process.env[`${envPrefix}_VALKEY_CLUSTER_NODES`] || process.env["VALKEY_CLUSTER_NODES"] || process.env["CACHE_CLUSTER_NODES"])
1604
+ };
1605
+ logger.info("[CacheFactory] Creating layer cache", {
1606
+ layer,
1607
+ serviceName,
1608
+ namespace,
1609
+ url: config.url
1610
+ });
1611
+ return CacheFactory.createCache(config, namespace);
1612
+ }
1613
+ /**
1614
+ * Get or create a singleton cache instance for a layer
1615
+ *
1616
+ * @param layer - Service layer ('wspace' or 'global')
1617
+ * @param serviceName - Service name for identification
1618
+ * @param namespace - Cache namespace (default: 'default')
1619
+ * @returns Singleton cache provider for the layer
1620
+ */
1621
+ static getInstanceForLayer(layer, serviceName, namespace = "default") {
1622
+ const instanceKey = `${layer}:${serviceName}:${namespace}`;
1623
+ if (!CacheFactory.instances.has(instanceKey)) {
1624
+ const cache = CacheFactory.createCacheForLayer(layer, serviceName, namespace);
1625
+ CacheFactory.instances.set(instanceKey, cache);
1626
+ }
1627
+ return CacheFactory.instances.get(instanceKey);
1628
+ }
1629
+ };
1630
+
1631
+ // src/cache/types/config.ts
1632
+ /**
1633
+ * Cache Configuration Types
1634
+ */
1635
+ /**
1636
+ * Cache provider type enum
1637
+ */
1638
+ let CacheProviderType = /* @__PURE__ */ function(CacheProviderType) {
1639
+ CacheProviderType["VALKEY"] = "valkey";
1640
+ CacheProviderType["MEMORY"] = "memory";
1641
+ CacheProviderType["MEMCACHED"] = "memcached";
1642
+ return CacheProviderType;
1643
+ }({});
1644
+
1645
+ // src/cache/index.ts
1646
+ /**
1647
+ * Cache - Public API
1648
+ *
1649
+ * This module provides a complete abstraction over caching systems (Valkey, Memory, etc.)
1650
+ * allowing the application to cache data without direct dependency on any specific caching implementation.
1651
+ *
1652
+ * Usage:
1653
+ *
1654
+ * // Create cache from environment variables (workspaces-backend)
1655
+ * import { createCache } from '@burdenoff/be-sdk/cache';
1656
+ *
1657
+ * const cache = createCache('my-module');
1658
+ * await cache.connect();
1659
+ *
1660
+ * // Set value
1661
+ * await cache.set('user:123', { name: 'John', email: 'john@example.com' }, { ttl: 3600 });
1662
+ *
1663
+ * // Get value
1664
+ * const user = await cache.get<User>('user:123');
1665
+ *
1666
+ * // Delete value
1667
+ * await cache.delete('user:123');
1668
+ *
1669
+ * // Disconnect when done
1670
+ * await cache.disconnect();
1671
+ */
1672
+ var cache_exports = /* @__PURE__ */ __exportAll({
1673
+ CacheFactory: () => CacheFactory,
1674
+ CacheProviderType: () => CacheProviderType,
1675
+ MemoryCacheProvider: () => MemoryCacheProvider,
1676
+ ValkeyGlideProvider: () => ValkeyGlideProvider,
1677
+ assertCacheEndpointConfigured: () => assertCacheEndpointConfigured,
1678
+ closeAllCaches: () => closeAllCaches,
1679
+ createCache: () => createCache,
1680
+ getCache: () => getCache,
1681
+ getValkeyClient: () => getValkeyClient,
1682
+ warnOnLayerDefaultEndpoint: () => warnOnLayerDefaultEndpoint
1683
+ });
1684
+ /**
1685
+ * Create a cache instance from environment configuration
1686
+ * Convenience function for creating a cache without manual config
1687
+ *
1688
+ * @param namespace - Cache namespace (e.g., 'analytics', 'files', 'users')
1689
+ * @returns Cache provider instance
1690
+ */
1691
+ function createCache(namespace = "default") {
1692
+ return CacheFactory.createCacheFromEnv(namespace);
1693
+ }
1694
+ /**
1695
+ * Get or create a singleton cache instance
1696
+ * Convenience function for getting/creating a singleton cache
1697
+ *
1698
+ * @param namespace - Cache namespace
1699
+ * @param config - Optional cache configuration
1700
+ * @returns Singleton cache provider instance
1701
+ */
1702
+ function getCache(namespace = "default", config) {
1703
+ return CacheFactory.getInstance(namespace, config);
1704
+ }
1705
+ /**
1706
+ * Process-wide GLIDE client shared by every env-configured `getValkeyClient()`
1707
+ * caller.
1708
+ *
1709
+ * This function used to construct a brand-new GLIDE client on every call, and
1710
+ * nothing that calls it ever closes the result — every caller in the SDK and in
1711
+ * the services memoises the promise and keeps the client for the life of the
1712
+ * process. `createServer`'s readiness probe then started calling it on the
1713
+ * Kubernetes readiness interval (every 10s, per pod), so each pod opened a
1714
+ * fresh connection every 10 seconds and never released one.
1715
+ *
1716
+ * On alpha that walked the shared ElastiCache node from ~140 to its 20,003
1717
+ * `maxclients` cap, at which point it refused every new connection mid-TLS
1718
+ * handshake and the cache was effectively dead fleet-wide — taking a workspace
1719
+ * subgraph out of the gateway's endpoint list with it. Sharing one client is
1720
+ * both the fix and what every caller already assumed was happening.
1721
+ */
1722
+ const sharedValkeyClients = /* @__PURE__ */ new Map();
1723
+ const sharedValkeyConnects = /* @__PURE__ */ new Map();
1724
+ /**
1725
+ * Identity of the endpoint the env currently points at.
1726
+ *
1727
+ * Keying the shared client by endpoint rather than holding a single global
1728
+ * means a process whose configuration genuinely changes gets a client for the
1729
+ * new endpoint instead of a stale one. In a deployed service the env is fixed,
1730
+ * so this resolves to exactly one entry — a true singleton.
1731
+ */
1732
+ function envEndpointKey() {
1733
+ return [
1734
+ process.env["VALKEY_URL"] || process.env["REDIS_URL"] || "",
1735
+ process.env["VALKEY_HOST"] || "",
1736
+ process.env["VALKEY_PORT"] || "",
1737
+ process.env["VALKEY_DB"] || "",
1738
+ process.env["VALKEY_USERNAME"] || ""
1739
+ ].join("|");
1740
+ }
1741
+ /**
1742
+ * Get direct access to Valkey client via @valkey/valkey-glide
1743
+ * Useful for cases where you need raw Valkey operations beyond caching
1744
+ *
1745
+ * The env-configured client (no `config` argument) is a process-wide singleton:
1746
+ * repeated calls reuse one connection rather than opening a new one each time.
1747
+ *
1748
+ * @param config - Optional Valkey configuration. If not provided, uses environment variables
1749
+ * @returns ValkeyGlideClient instance from @valkey/valkey-glide
1750
+ *
1751
+ * @example
1752
+ * ```typescript
1753
+ * import { getValkeyClient } from '@burdenoff/be-sdk';
1754
+ *
1755
+ * const valkey = await getValkeyClient();
1756
+ * await valkey.lpush('mylist', 'value');
1757
+ * ```
1758
+ */
1759
+ async function getValkeyClient(config) {
1760
+ if (config) return createValkeyClient(config);
1761
+ const key = envEndpointKey();
1762
+ const existing = sharedValkeyClients.get(key);
1763
+ if (existing) return existing;
1764
+ const inFlight = sharedValkeyConnects.get(key);
1765
+ if (inFlight) return inFlight;
1766
+ const pending = (async () => {
1767
+ try {
1768
+ const client = await createValkeyClient();
1769
+ sharedValkeyClients.set(key, client);
1770
+ return client;
1771
+ } finally {
1772
+ sharedValkeyConnects.delete(key);
1773
+ }
1774
+ })();
1775
+ sharedValkeyConnects.set(key, pending);
1776
+ return pending;
1777
+ }
1778
+ async function createValkeyClient(config) {
1779
+ const glideModule = await import("@valkey/valkey-glide");
1780
+ const GlideClient = glideModule.GlideClient || glideModule.default;
1781
+ if (!config) assertCacheEndpointConfigured({
1782
+ url: process.env["VALKEY_URL"] || process.env["REDIS_URL"],
1783
+ host: process.env["VALKEY_HOST"],
1784
+ password: process.env["VALKEY_PASSWORD"],
1785
+ port: process.env["VALKEY_PORT"] ? parseInt(process.env["VALKEY_PORT"], 10) : void 0,
1786
+ context: "getValkeyClient",
1787
+ keysTried: [
1788
+ "VALKEY_URL",
1789
+ "REDIS_URL",
1790
+ "VALKEY_HOST"
1791
+ ]
1792
+ });
1793
+ const valkeyConfig = config || {
1794
+ type: "valkey",
1795
+ url: process.env["VALKEY_URL"] || process.env["REDIS_URL"],
1796
+ host: process.env["VALKEY_HOST"] || "localhost",
1797
+ port: process.env["VALKEY_PORT"] ? parseInt(process.env["VALKEY_PORT"], 10) : 6379,
1798
+ password: process.env["VALKEY_PASSWORD"],
1799
+ db: process.env["VALKEY_DB"] ? parseInt(process.env["VALKEY_DB"], 10) : 0,
1800
+ username: process.env["VALKEY_USERNAME"]
1801
+ };
1802
+ let host = valkeyConfig.host || "localhost";
1803
+ let port = valkeyConfig.port || 6379;
1804
+ if (valkeyConfig.url) {
1805
+ const url = new URL(valkeyConfig.url.replace("valkey://", "redis://"));
1806
+ host = url.hostname;
1807
+ port = parseInt(url.port || "6379", 10);
1808
+ }
1809
+ const useTLS = valkeyConfig.useTLS ?? (valkeyConfig.url ? /^(rediss|valkeys):\/\//i.test(valkeyConfig.url) : void 0);
1810
+ return GlideClient.createClient({
1811
+ addresses: [{
1812
+ host,
1813
+ port
1814
+ }],
1815
+ useTLS,
1816
+ credentials: valkeyConfig.password ? {
1817
+ password: valkeyConfig.password,
1818
+ username: valkeyConfig.username
1819
+ } : void 0,
1820
+ clientName: valkeyConfig.name || "valkey-glide-client",
1821
+ readFrom: "primary"
1822
+ });
1823
+ }
1824
+ /**
1825
+ * Close all cache connections
1826
+ * Call this during application shutdown
1827
+ */
1828
+ async function closeAllCaches() {
1829
+ await CacheFactory.closeAll();
1830
+ const shared = [...sharedValkeyClients.values()];
1831
+ sharedValkeyClients.clear();
1832
+ sharedValkeyConnects.clear();
1833
+ await Promise.all(shared.map((client) => Promise.resolve(client.close()).catch(() => void 0)));
1834
+ }
1835
+
1836
+ export { getValkeyClient as a, ValkeyGlideProvider as c, warnOnLayerDefaultEndpoint as d, getCache as i, MemoryCacheProvider as l, closeAllCaches as n, CacheProviderType as o, createCache as r, CacheFactory as s, cache_exports as t, assertCacheEndpointConfigured as u };
1837
+ //# sourceMappingURL=cache-CU0uLwcS.js.map