@keboola/api-client 39.0.0 → 41.0.0

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 (522) hide show
  1. package/AGENTS.md +121 -100
  2. package/API-SURFACE.md +27 -2
  3. package/CHANGELOG.md +129 -0
  4. package/README.md +3 -3
  5. package/dist/{ManagementClientAuthError-FcfMJNhr.cjs → ManagementClientAuthError-DE7lNGZQ.cjs} +2 -2
  6. package/dist/{ManagementClientAuthError-FcfMJNhr.cjs.map → ManagementClientAuthError-DE7lNGZQ.cjs.map} +1 -1
  7. package/dist/{ManagementClientAuthError-Cr9IOsnJ.js → ManagementClientAuthError-H30lti_Q.js} +2 -2
  8. package/dist/{ManagementClientAuthError-Cr9IOsnJ.js.map → ManagementClientAuthError-H30lti_Q.js.map} +1 -1
  9. package/dist/{ValidationError-CLVJCCwH.cjs → ValidationError-D65QU0uq.cjs} +10 -16
  10. package/dist/ValidationError-D65QU0uq.cjs.map +1 -0
  11. package/dist/ValidationError-DjhtNMfZ.js +42 -0
  12. package/dist/ValidationError-DjhtNMfZ.js.map +1 -0
  13. package/dist/ai/index.cjs +2 -2
  14. package/dist/ai/index.d.cts +2 -2
  15. package/dist/ai/index.d.ts +2 -2
  16. package/dist/ai/index.js +2 -2
  17. package/dist/ai/types.d.cts +1 -1
  18. package/dist/ai/types.d.ts +1 -1
  19. package/dist/{appLogs-C_zP0lpv.cjs → appLogs-B9zFJIuy.cjs} +2 -2
  20. package/dist/{appLogs-C_zP0lpv.cjs.map → appLogs-B9zFJIuy.cjs.map} +1 -1
  21. package/dist/{appLogs-Cl7Q_MR9.js → appLogs-BBkkUOW1.js} +2 -2
  22. package/dist/{appLogs-Cl7Q_MR9.js.map → appLogs-BBkkUOW1.js.map} +1 -1
  23. package/dist/{appLogs-Ch7DYpzx.d.ts → appLogs-BS6ViVGR.d.ts} +2 -2
  24. package/dist/{appLogs-D5A13Y0y.d.cts → appLogs-C9YlJ2g8.d.cts} +2 -2
  25. package/dist/apps/index.cjs +30 -56
  26. package/dist/apps/index.cjs.map +1 -1
  27. package/dist/apps/index.d.cts +8 -13
  28. package/dist/apps/index.d.ts +8 -13
  29. package/dist/apps/index.js +30 -56
  30. package/dist/apps/index.js.map +1 -1
  31. package/dist/apps/types.d.cts +2 -2
  32. package/dist/apps/types.d.ts +2 -2
  33. package/dist/assets/index.cjs +1 -1
  34. package/dist/assets/index.d.cts +1 -1
  35. package/dist/assets/index.d.ts +1 -1
  36. package/dist/assets/index.js +1 -1
  37. package/dist/auth/index.cjs +8 -4
  38. package/dist/auth/index.d.cts +2 -2
  39. package/dist/auth/index.d.ts +2 -2
  40. package/dist/auth/index.js +2 -2
  41. package/dist/auth/types.d.cts +2 -2
  42. package/dist/auth/types.d.ts +2 -2
  43. package/dist/{auth-DLWnl18b.cjs → auth-Dm0F2rOh.cjs} +2 -2
  44. package/dist/{auth-DLWnl18b.cjs.map → auth-Dm0F2rOh.cjs.map} +1 -1
  45. package/dist/{auth-BjmkFOgd.js → auth-DworfoPy.js} +2 -2
  46. package/dist/{auth-BjmkFOgd.js.map → auth-DworfoPy.js.map} +1 -1
  47. package/dist/{authClient-8yU1last.cjs → authClient-BmuUo0J4.cjs} +141 -48
  48. package/dist/authClient-BmuUo0J4.cjs.map +1 -0
  49. package/dist/{authClient-CTHNs6Tq.d.cts → authClient-CHXWJ9x3.d.ts} +109 -76
  50. package/dist/{authClient-BTo4Afm6.js → authClient-CgcDGd30.js} +108 -39
  51. package/dist/authClient-CgcDGd30.js.map +1 -0
  52. package/dist/{authClient-D8i3JTM-.d.ts → authClient-vEt_7_uk.d.cts} +109 -76
  53. package/dist/billing/index.cjs +2 -2
  54. package/dist/billing/index.d.cts +1 -1
  55. package/dist/billing/index.d.ts +1 -1
  56. package/dist/billing/index.js +2 -2
  57. package/dist/billing/types.d.cts +1 -1
  58. package/dist/billing/types.d.ts +1 -1
  59. package/dist/businessWorkspaceApi/index.cjs +1 -1
  60. package/dist/businessWorkspaceApi/index.d.cts +1 -1
  61. package/dist/businessWorkspaceApi/index.d.ts +1 -1
  62. package/dist/businessWorkspaceApi/index.js +1 -1
  63. package/dist/businessWorkspaceApi/types.d.cts +1 -1
  64. package/dist/businessWorkspaceApi/types.d.ts +1 -1
  65. package/dist/{businessWorkspaceApi-wyBdbpIJ.cjs → businessWorkspaceApi-6tCDdpnY.cjs} +3 -3
  66. package/dist/{businessWorkspaceApi-wyBdbpIJ.cjs.map → businessWorkspaceApi-6tCDdpnY.cjs.map} +1 -1
  67. package/dist/{businessWorkspaceApi-BD-iUj07.js → businessWorkspaceApi-BLUdefRF.js} +3 -3
  68. package/dist/{businessWorkspaceApi-BD-iUj07.js.map → businessWorkspaceApi-BLUdefRF.js.map} +1 -1
  69. package/dist/{businessWorkspaceApiClient-CRM1U8b-.d.cts → businessWorkspaceApiClient-BHDJlHFo.d.cts} +3 -3
  70. package/dist/{businessWorkspaceApiClient-C2WyWN3b.d.ts → businessWorkspaceApiClient-DI-z1VIH.d.ts} +3 -3
  71. package/dist/chat/index.cjs +7 -3
  72. package/dist/chat/index.cjs.map +1 -1
  73. package/dist/chat/index.d.cts +2 -2
  74. package/dist/chat/index.d.ts +2 -2
  75. package/dist/chat/index.js +7 -3
  76. package/dist/chat/index.js.map +1 -1
  77. package/dist/chat/types.cjs +1 -3
  78. package/dist/chat/types.cjs.map +1 -1
  79. package/dist/chat/types.d.cts +2 -2
  80. package/dist/chat/types.d.ts +2 -2
  81. package/dist/chat/types.js +1 -3
  82. package/dist/chat/types.js.map +1 -1
  83. package/dist/{componentId-vJz-kWs6.js → componentId-BJLfnaGc.js} +6 -2
  84. package/dist/componentId-BJLfnaGc.js.map +1 -0
  85. package/dist/{componentId-DkyQ8PM0.cjs → componentId-_IKXxICq.cjs} +6 -2
  86. package/dist/componentId-_IKXxICq.cjs.map +1 -0
  87. package/dist/{concurrent-CH9fbNr3.js → concurrent-BacWxPwi.js} +5 -7
  88. package/dist/concurrent-BacWxPwi.js.map +1 -0
  89. package/dist/{concurrent-tbiIa0UL.cjs → concurrent-CdVfR1N5.cjs} +5 -7
  90. package/dist/concurrent-CdVfR1N5.cjs.map +1 -0
  91. package/dist/{configurations-CyFF9Dtu.cjs → configurations-BTRHVSRq.cjs} +20 -53
  92. package/dist/configurations-BTRHVSRq.cjs.map +1 -0
  93. package/dist/{configurations-VtNE0nrT.js → configurations-CF3xz7RB.js} +14 -22
  94. package/dist/configurations-CF3xz7RB.js.map +1 -0
  95. package/dist/{configurations-BVvcimzo.js → configurations-Chg_JwJ1.js} +20 -53
  96. package/dist/configurations-Chg_JwJ1.js.map +1 -0
  97. package/dist/{configurations-zkNjr73Q.cjs → configurations-VlfQ_37Y.cjs} +14 -22
  98. package/dist/configurations-VlfQ_37Y.cjs.map +1 -0
  99. package/dist/constants/index.cjs +1 -1
  100. package/dist/constants/index.d.cts +1 -1
  101. package/dist/constants/index.d.ts +1 -1
  102. package/dist/constants/index.js +1 -1
  103. package/dist/{createFetchClient-BlgPbjFj.cjs → createFetchClient-Cwp8max9.cjs} +11 -4
  104. package/dist/createFetchClient-Cwp8max9.cjs.map +1 -0
  105. package/dist/{createFetchClient-C-cadpBx.js → createFetchClient-DXHQK63w.js} +11 -4
  106. package/dist/createFetchClient-DXHQK63w.js.map +1 -0
  107. package/dist/{createGenericFetchClient-Bnf1QK9W.js → createGenericFetchClient-Dg1rgzmG.js} +2 -2
  108. package/dist/{createGenericFetchClient-Bnf1QK9W.js.map → createGenericFetchClient-Dg1rgzmG.js.map} +1 -1
  109. package/dist/{createGenericFetchClient-lcozzwk2.cjs → createGenericFetchClient-Dl9cqTvR.cjs} +2 -2
  110. package/dist/{createGenericFetchClient-lcozzwk2.cjs.map → createGenericFetchClient-Dl9cqTvR.cjs.map} +1 -1
  111. package/dist/{createOpenapiFetchClient-C3UmDXpe.cjs → createOpenapiFetchClient-BYqW-9tm.cjs} +2 -2
  112. package/dist/{createOpenapiFetchClient-C3UmDXpe.cjs.map → createOpenapiFetchClient-BYqW-9tm.cjs.map} +1 -1
  113. package/dist/{createOpenapiFetchClient-COaPeeQ0.js → createOpenapiFetchClient-DZUOVupy.js} +2 -2
  114. package/dist/{createOpenapiFetchClient-COaPeeQ0.js.map → createOpenapiFetchClient-DZUOVupy.js.map} +1 -1
  115. package/dist/dataScience/index.cjs +2 -2
  116. package/dist/dataScience/index.d.cts +2 -2
  117. package/dist/dataScience/index.d.ts +2 -2
  118. package/dist/dataScience/index.js +2 -2
  119. package/dist/dataScience/types.d.cts +2 -2
  120. package/dist/dataScience/types.d.ts +2 -2
  121. package/dist/{dataScience-D-hyc4GY.cjs → dataScience-B5QxZnvW.cjs} +5 -5
  122. package/dist/{dataScience-D-hyc4GY.cjs.map → dataScience-B5QxZnvW.cjs.map} +1 -1
  123. package/dist/{dataScience-B_BmnB1m.js → dataScience-OXcwdk1p.js} +5 -5
  124. package/dist/{dataScience-B_BmnB1m.js.map → dataScience-OXcwdk1p.js.map} +1 -1
  125. package/dist/dedupe-Cky1gSUu.js +21 -0
  126. package/dist/dedupe-Cky1gSUu.js.map +1 -0
  127. package/dist/dedupe-OSnnst2u.cjs +26 -0
  128. package/dist/dedupe-OSnnst2u.cjs.map +1 -0
  129. package/dist/developerPortal/index.cjs +1 -1
  130. package/dist/developerPortal/index.d.cts +2 -2
  131. package/dist/developerPortal/index.d.ts +2 -2
  132. package/dist/developerPortal/index.js +1 -1
  133. package/dist/developerPortal/types.d.cts +1 -1
  134. package/dist/developerPortal/types.d.ts +1 -1
  135. package/dist/{developerPortalClient-yHFTkKPb.js → developerPortalClient-B1QZ1rYi.js} +6 -8
  136. package/dist/{developerPortalClient-yHFTkKPb.js.map → developerPortalClient-B1QZ1rYi.js.map} +1 -1
  137. package/dist/{developerPortalClient-CutPqoAa.cjs → developerPortalClient-CLPpBksD.cjs} +6 -8
  138. package/dist/{developerPortalClient-CutPqoAa.cjs.map → developerPortalClient-CLPpBksD.cjs.map} +1 -1
  139. package/dist/domain/permissions/index.cjs +9 -30
  140. package/dist/domain/permissions/index.cjs.map +1 -1
  141. package/dist/domain/permissions/index.d.cts +29 -102
  142. package/dist/domain/permissions/index.d.ts +29 -102
  143. package/dist/domain/permissions/index.js +9 -30
  144. package/dist/domain/permissions/index.js.map +1 -1
  145. package/dist/domain/storageTable/index.d.cts +1 -1
  146. package/dist/domain/storageTable/index.d.ts +1 -1
  147. package/dist/editor/index.cjs +2 -2
  148. package/dist/editor/index.cjs.map +1 -1
  149. package/dist/editor/index.d.cts +2 -2
  150. package/dist/editor/index.d.ts +2 -2
  151. package/dist/editor/index.js +2 -2
  152. package/dist/editor/index.js.map +1 -1
  153. package/dist/editor/types.d.cts +1 -1
  154. package/dist/editor/types.d.ts +1 -1
  155. package/dist/encryption/index.cjs +2 -22
  156. package/dist/encryption/index.cjs.map +1 -1
  157. package/dist/encryption/index.d.cts +1 -1
  158. package/dist/encryption/index.d.ts +1 -1
  159. package/dist/encryption/index.js +2 -22
  160. package/dist/encryption/index.js.map +1 -1
  161. package/dist/encryption/types.d.cts +1 -1
  162. package/dist/encryption/types.d.ts +1 -1
  163. package/dist/import/index.cjs +1 -1
  164. package/dist/import/index.d.cts +3 -3
  165. package/dist/import/index.d.ts +3 -3
  166. package/dist/import/index.js +1 -1
  167. package/dist/{import-7YyyD_U_.cjs → import-CNk89mqy.cjs} +3 -3
  168. package/dist/{import-7YyyD_U_.cjs.map → import-CNk89mqy.cjs.map} +1 -1
  169. package/dist/{import-xliONVib.js → import-DiMQCzLa.js} +3 -3
  170. package/dist/{import-xliONVib.js.map → import-DiMQCzLa.js.map} +1 -1
  171. package/dist/{index-1r_CskjU.d.ts → index--ZpnE3YT.d.cts} +3 -3
  172. package/dist/{index-DBklbaTp.d.cts → index-B5w7WlaU.d.cts} +5 -1
  173. package/dist/{index-DBklbaTp.d.ts → index-B5w7WlaU.d.ts} +5 -1
  174. package/dist/{index-C77vTm2K.d.ts → index-BDZvaRud.d.ts} +6 -6
  175. package/dist/{index-KuQ79Mnz.d.ts → index-BVhHt5lx.d.cts} +18 -26
  176. package/dist/{index-NC1dXRTD.d.ts → index-BfqkgPGI.d.cts} +7 -13
  177. package/dist/{index-NC1dXRTD.d.cts → index-BfqkgPGI.d.ts} +7 -13
  178. package/dist/{index-V7XKUQm9.d.cts → index-BgR5zcjJ.d.ts} +18 -26
  179. package/dist/{index-BK-qHT39.d.ts → index-ByRpNVcs.d.cts} +83 -17
  180. package/dist/{index-pXN4LWUX.d.ts → index-C11JSxBY.d.ts} +8 -11
  181. package/dist/{index-GjcJTCbz.d.cts → index-C4TNAA8-.d.cts} +8 -11
  182. package/dist/{index-BMqLPS6S.d.ts → index-CXcWpZQ2.d.cts} +4 -12
  183. package/dist/{index-BMqLPS6S.d.cts → index-CXcWpZQ2.d.ts} +4 -12
  184. package/dist/{index-GfKzh267.d.ts → index-CaaTOANF.d.ts} +395 -297
  185. package/dist/{index-Dx52hNLP.d.cts → index-CcMHJcuP.d.cts} +3 -3
  186. package/dist/{index-DVw4Av4b.d.cts → index-Cvbjp3jx.d.cts} +6 -6
  187. package/dist/{index-DppA4k3b.d.cts → index-Cz0MXhzs.d.cts} +5 -5
  188. package/dist/{index-6Xe81qN3.d.ts → index-D-VMgpGc.d.ts} +5 -5
  189. package/dist/{index-DWf6FXOr.d.cts → index-D7-o-oGa.d.ts} +3 -3
  190. package/dist/{index-CWoEnDJ_.d.cts → index-DCRKjihs.d.ts} +83 -17
  191. package/dist/{kaiAgentClient-CHpULyeG.d.cts → index-DNThyEej.d.cts} +14 -5
  192. package/dist/{index-DXSmFkol.d.cts → index-DOAZmWvh.d.cts} +6 -6
  193. package/dist/{index-BuegqrS1.d.ts → index-D_-4uQF8.d.ts} +3 -3
  194. package/dist/index-DbLFwXgb.d.cts +116 -0
  195. package/dist/{index-De5qUWhp.d.ts → index-DnQTuc6t.d.ts} +6 -6
  196. package/dist/{kaiAgentClient-B5L4gbQ1.d.ts → index-Qb7X6-ph.d.ts} +14 -5
  197. package/dist/{index-CHXnJQ9s.d.cts → index-cWp_V6K5.d.cts} +395 -297
  198. package/dist/index-rwK7GcB2.d.ts +116 -0
  199. package/dist/index.cjs +1498 -901
  200. package/dist/index.cjs.map +1 -1
  201. package/dist/index.d.cts +7 -7
  202. package/dist/index.d.ts +7 -7
  203. package/dist/index.js +1497 -902
  204. package/dist/index.js.map +1 -1
  205. package/dist/isLoginPageRedirect-XPwAOKK3.js +14 -0
  206. package/dist/isLoginPageRedirect-XPwAOKK3.js.map +1 -0
  207. package/dist/isLoginPageRedirect-jQHiLrG7.cjs +19 -0
  208. package/dist/isLoginPageRedirect-jQHiLrG7.cjs.map +1 -0
  209. package/dist/{jobStatus-0_Y3Sr4i.cjs → jobStatus-BMlsyXWI.cjs} +19 -45
  210. package/dist/jobStatus-BMlsyXWI.cjs.map +1 -0
  211. package/dist/{jobStatus-PSZJMTiA.js → jobStatus-CfRtsIpv.js} +19 -45
  212. package/dist/jobStatus-CfRtsIpv.js.map +1 -0
  213. package/dist/kaiAgent/index.cjs +1 -1
  214. package/dist/kaiAgent/index.d.cts +3 -2
  215. package/dist/kaiAgent/index.d.ts +3 -2
  216. package/dist/kaiAgent/index.js +1 -1
  217. package/dist/kaiAgent/types.d.cts +2 -2
  218. package/dist/kaiAgent/types.d.ts +2 -2
  219. package/dist/{kaiAgent-CcT2oNip.js → kaiAgent-Dp20HLTh.js} +32 -11
  220. package/dist/kaiAgent-Dp20HLTh.js.map +1 -0
  221. package/dist/{kaiAgent-DaB6UCsh.cjs → kaiAgent-QNoeVKPs.cjs} +32 -11
  222. package/dist/kaiAgent-QNoeVKPs.cjs.map +1 -0
  223. package/dist/kaiMemory-CClSPInt.cjs +289 -0
  224. package/dist/kaiMemory-CClSPInt.cjs.map +1 -0
  225. package/dist/kaiMemory-D0Y_16U4.js +260 -0
  226. package/dist/kaiMemory-D0Y_16U4.js.map +1 -0
  227. package/dist/management/index.cjs +1 -1
  228. package/dist/management/index.d.cts +1 -1
  229. package/dist/management/index.d.ts +1 -1
  230. package/dist/management/index.js +1 -1
  231. package/dist/management/types.d.cts +2 -2
  232. package/dist/management/types.d.ts +2 -2
  233. package/dist/{management-DeZiQSlw.cjs → management-CCY0IYnq.cjs} +59 -24
  234. package/dist/management-CCY0IYnq.cjs.map +1 -0
  235. package/dist/{management-ckdnu1dA.js → management-DvmPiG64.js} +59 -24
  236. package/dist/management-DvmPiG64.js.map +1 -0
  237. package/dist/metastore/index.cjs +1 -1
  238. package/dist/metastore/index.d.cts +1 -1
  239. package/dist/metastore/index.d.ts +1 -1
  240. package/dist/metastore/index.js +1 -1
  241. package/dist/metastore/types.d.cts +2 -2
  242. package/dist/metastore/types.d.ts +2 -2
  243. package/dist/{metastore-B0PolCjQ.js → metastore-BycJxe7A.js} +14 -8
  244. package/dist/metastore-BycJxe7A.js.map +1 -0
  245. package/dist/{metastore-9AGrwjmN.cjs → metastore-XtWciCZT.cjs} +14 -8
  246. package/dist/metastore-XtWciCZT.cjs.map +1 -0
  247. package/dist/microsoftGraph/index.cjs +2 -2
  248. package/dist/microsoftGraph/index.d.cts +2 -2
  249. package/dist/microsoftGraph/index.d.ts +2 -2
  250. package/dist/microsoftGraph/index.js +2 -2
  251. package/dist/microsoftGraph/types.d.cts +1 -1
  252. package/dist/microsoftGraph/types.d.ts +1 -1
  253. package/dist/middleware-CBwrtgQd.js +34 -0
  254. package/dist/middleware-CBwrtgQd.js.map +1 -0
  255. package/dist/middleware-IjYx3d5u.cjs +45 -0
  256. package/dist/middleware-IjYx3d5u.cjs.map +1 -0
  257. package/dist/notifications/index.cjs +4 -4
  258. package/dist/notifications/index.d.cts +2 -2
  259. package/dist/notifications/index.d.ts +2 -2
  260. package/dist/notifications/index.js +4 -4
  261. package/dist/notifications/types.d.cts +1 -1
  262. package/dist/notifications/types.d.ts +1 -1
  263. package/dist/oauth/index.cjs +1 -1
  264. package/dist/oauth/index.d.cts +2 -2
  265. package/dist/oauth/index.d.ts +2 -2
  266. package/dist/oauth/index.js +1 -1
  267. package/dist/oauth/types.d.cts +1 -1
  268. package/dist/oauth/types.d.ts +1 -1
  269. package/dist/{oauth-DNtv4Ihb.cjs → oauth--2p8jkJf.cjs} +5 -5
  270. package/dist/{oauth-DNtv4Ihb.cjs.map → oauth--2p8jkJf.cjs.map} +1 -1
  271. package/dist/{oauth-BnHVf4cB.js → oauth-l5zE39cD.js} +5 -5
  272. package/dist/{oauth-BnHVf4cB.js.map → oauth-l5zE39cD.js.map} +1 -1
  273. package/dist/omnisearch/index.cjs +6 -14
  274. package/dist/omnisearch/index.cjs.map +1 -1
  275. package/dist/omnisearch/index.d.cts +6 -14
  276. package/dist/omnisearch/index.d.ts +6 -14
  277. package/dist/omnisearch/index.js +6 -14
  278. package/dist/omnisearch/index.js.map +1 -1
  279. package/dist/omnisearch/types.d.cts +1 -1
  280. package/dist/omnisearch/types.d.ts +1 -1
  281. package/dist/{project-DCHOxRWd.d.ts → project-B15gStbM.d.ts} +2 -2
  282. package/dist/{project-BRpzv3yE.d.cts → project-cHKuGvqJ.d.cts} +2 -2
  283. package/dist/queryService/index.cjs +1 -1
  284. package/dist/queryService/index.d.cts +1 -1
  285. package/dist/queryService/index.d.ts +1 -1
  286. package/dist/queryService/index.js +1 -1
  287. package/dist/queryService/types.d.cts +1 -1
  288. package/dist/queryService/types.d.ts +1 -1
  289. package/dist/{queryService-j3XZ2mX6.js → queryService-CCOYbRbw.js} +6 -6
  290. package/dist/{queryService-j3XZ2mX6.js.map → queryService-CCOYbRbw.js.map} +1 -1
  291. package/dist/{queryService-BVwD6Vmc.cjs → queryService-CQzclHdL.cjs} +6 -6
  292. package/dist/{queryService-BVwD6Vmc.cjs.map → queryService-CQzclHdL.cjs.map} +1 -1
  293. package/dist/queue/index.cjs +1 -1
  294. package/dist/queue/index.d.cts +3 -3
  295. package/dist/queue/index.d.ts +3 -3
  296. package/dist/queue/index.js +1 -1
  297. package/dist/queue/types.d.cts +1 -1
  298. package/dist/queue/types.d.ts +1 -1
  299. package/dist/{queue-Dagl0sdP.js → queue-Cowbg6bR.js} +8 -11
  300. package/dist/queue-Cowbg6bR.js.map +1 -0
  301. package/dist/{queue-e3rMWbmK.cjs → queue-UG_BWKIC.cjs} +8 -11
  302. package/dist/queue-UG_BWKIC.cjs.map +1 -0
  303. package/dist/scheduler/index.cjs +4 -4
  304. package/dist/scheduler/index.d.cts +2 -2
  305. package/dist/scheduler/index.d.ts +2 -2
  306. package/dist/scheduler/index.js +4 -4
  307. package/dist/scheduler/types.d.cts +1 -1
  308. package/dist/scheduler/types.d.ts +1 -1
  309. package/dist/sdk/configurations/index.cjs +1 -1
  310. package/dist/sdk/configurations/index.d.cts +11 -11
  311. package/dist/sdk/configurations/index.d.ts +11 -11
  312. package/dist/sdk/configurations/index.js +1 -1
  313. package/dist/sdk/developerPortal/index.cjs +10 -18
  314. package/dist/sdk/developerPortal/index.cjs.map +1 -1
  315. package/dist/sdk/developerPortal/index.d.cts +7 -15
  316. package/dist/sdk/developerPortal/index.d.ts +7 -15
  317. package/dist/sdk/developerPortal/index.js +7 -15
  318. package/dist/sdk/developerPortal/index.js.map +1 -1
  319. package/dist/sdk/kaiMemory/index.cjs +7 -0
  320. package/dist/sdk/kaiMemory/index.d.cts +41 -0
  321. package/dist/sdk/kaiMemory/index.d.ts +41 -0
  322. package/dist/sdk/kaiMemory/index.js +2 -0
  323. package/dist/sdk/kaiMemory/types.cjs +0 -0
  324. package/dist/sdk/kaiMemory/types.d.cts +2 -0
  325. package/dist/sdk/kaiMemory/types.d.ts +2 -0
  326. package/dist/sdk/kaiMemory/types.js +1 -0
  327. package/dist/sdk/queryService/index.cjs +2 -2
  328. package/dist/sdk/queryService/index.d.cts +1 -1
  329. package/dist/sdk/queryService/index.d.ts +1 -1
  330. package/dist/sdk/queryService/index.js +2 -2
  331. package/dist/sdk/semanticLayer/index.cjs +1 -1
  332. package/dist/sdk/semanticLayer/index.d.cts +16 -40
  333. package/dist/sdk/semanticLayer/index.d.ts +16 -40
  334. package/dist/sdk/semanticLayer/index.js +1 -1
  335. package/dist/sdk/semanticLayer/types.d.cts +1 -1
  336. package/dist/sdk/semanticLayer/types.d.ts +1 -1
  337. package/dist/sdk/storage/index.cjs +0 -5
  338. package/dist/sdk/storage/index.cjs.map +1 -1
  339. package/dist/sdk/storage/index.d.cts +2 -2
  340. package/dist/sdk/storage/index.d.ts +2 -2
  341. package/dist/sdk/storage/index.js +1 -5
  342. package/dist/sdk/storage/index.js.map +1 -1
  343. package/dist/sdk/tag/index.cjs +1 -1
  344. package/dist/sdk/tag/index.d.cts +3 -3
  345. package/dist/sdk/tag/index.d.ts +3 -3
  346. package/dist/sdk/tag/index.js +1 -1
  347. package/dist/sdk/tag/types.d.cts +1 -1
  348. package/dist/sdk/tag/types.d.ts +1 -1
  349. package/dist/sdk/vault/index.cjs +1 -1
  350. package/dist/sdk/vault/index.d.cts +1 -1
  351. package/dist/sdk/vault/index.d.ts +1 -1
  352. package/dist/sdk/vault/index.js +1 -1
  353. package/dist/{semanticLayer-9uTaU7UT.cjs → semanticLayer-CKDVkU56.cjs} +62 -183
  354. package/dist/semanticLayer-CKDVkU56.cjs.map +1 -0
  355. package/dist/{semanticLayer-6_gtFxDu.js → semanticLayer-pYy082Ju.js} +62 -183
  356. package/dist/semanticLayer-pYy082Ju.js.map +1 -0
  357. package/dist/status/index.cjs +1 -1
  358. package/dist/status/index.d.cts +1 -1
  359. package/dist/status/index.d.ts +1 -1
  360. package/dist/status/index.js +1 -1
  361. package/dist/storage/index.cjs +5 -5
  362. package/dist/storage/index.d.cts +2 -2
  363. package/dist/storage/index.d.ts +2 -2
  364. package/dist/storage/index.js +5 -5
  365. package/dist/storage/types.d.cts +2 -2
  366. package/dist/storage/types.d.ts +2 -2
  367. package/dist/{storage-Ob1LUIDq.js → storage-CZQHZcXG.js} +109 -302
  368. package/dist/storage-CZQHZcXG.js.map +1 -0
  369. package/dist/{storage-HFUdEy7P.cjs → storage-JinL1y1s.cjs} +109 -302
  370. package/dist/storage-JinL1y1s.cjs.map +1 -0
  371. package/dist/stream/index.cjs +3 -3
  372. package/dist/stream/index.d.cts +2 -2
  373. package/dist/stream/index.d.ts +2 -2
  374. package/dist/stream/index.js +3 -3
  375. package/dist/stream/types.d.cts +1 -1
  376. package/dist/stream/types.d.ts +1 -1
  377. package/dist/syncActions/index.cjs +1 -1
  378. package/dist/syncActions/index.d.cts +1 -1
  379. package/dist/syncActions/index.d.ts +1 -1
  380. package/dist/syncActions/index.js +1 -1
  381. package/dist/syncActions/types.d.cts +2 -2
  382. package/dist/syncActions/types.d.ts +2 -2
  383. package/dist/{syncActions-B3NS5a0g.js → syncActions-ChNWuhYA.js} +260 -111
  384. package/dist/syncActions-ChNWuhYA.js.map +1 -0
  385. package/dist/{syncActions-D2DhY6pP.cjs → syncActions-mFlF16cl.cjs} +260 -111
  386. package/dist/syncActions-mFlF16cl.cjs.map +1 -0
  387. package/dist/{tag-CsoOZWB_.cjs → tag-DHS_soa7.cjs} +2 -2
  388. package/dist/{tag-CsoOZWB_.cjs.map → tag-DHS_soa7.cjs.map} +1 -1
  389. package/dist/{tag-DCsoewjL.js → tag-hh-1nhNr.js} +2 -2
  390. package/dist/{tag-DCsoewjL.js.map → tag-hh-1nhNr.js.map} +1 -1
  391. package/dist/telemetry/index.cjs +7 -11
  392. package/dist/telemetry/index.cjs.map +1 -1
  393. package/dist/telemetry/index.d.cts +5 -9
  394. package/dist/telemetry/index.d.ts +5 -9
  395. package/dist/telemetry/index.js +7 -11
  396. package/dist/telemetry/index.js.map +1 -1
  397. package/dist/telemetry/types.d.cts +1 -1
  398. package/dist/telemetry/types.d.ts +1 -1
  399. package/dist/{types-DqxIx9Pi.d.cts → types-6kuMW4JW.d.cts} +2 -2
  400. package/dist/{types-Ct0YPy2w.d.ts → types-B2w2TtSA.d.ts} +3 -3
  401. package/dist/{types-M46WuBSm.d.cts → types-B61aCifg.d.cts} +2 -2
  402. package/dist/{types-COL1kVEB.d.cts → types-B8N_k79M.d.cts} +2 -2
  403. package/dist/{types-Jw10xuOW.d.cts → types-BIECJYun.d.ts} +171 -44
  404. package/dist/{types-DZk3XHiN.d.cts → types-BLNB882w.d.cts} +3 -3
  405. package/dist/{types-BEe50G2r.d.cts → types-BPy5Ozee.d.cts} +2 -2
  406. package/dist/{types-gi4Eay19.d.ts → types-BS4jwuMi.d.ts} +7 -15
  407. package/dist/{types-BrYkBQo4.d.ts → types-BTK7Bv3n.d.cts} +171 -44
  408. package/dist/{types-D6UmMa6E.d.ts → types-BZDV8DZk.d.ts} +3 -3
  409. package/dist/{types-Cz83RiVu.d.cts → types-B_iLJlp4.d.ts} +255 -12
  410. package/dist/{types-CmF3pR2n.d.cts → types-BiMahEK8.d.cts} +91 -237
  411. package/dist/{types-BH5LLeJy.d.ts → types-Bl03Cg2n.d.cts} +255 -12
  412. package/dist/{types-bGQb4Jtl.d.cts → types-ByLH46Dt.d.cts} +13 -8
  413. package/dist/{types-g3vU7hcg.d.cts → types-Bydx6ga_.d.cts} +2 -2
  414. package/dist/{types-B95uNQ9o.d.ts → types-CKmTZSPG.d.ts} +91 -237
  415. package/dist/{types-D_j2Uq5X.d.cts → types-CMzQSHAQ.d.cts} +3 -3
  416. package/dist/{types-N3EChotg.d.cts → types-CP_LBmw3.d.cts} +2 -2
  417. package/dist/{types-CW6lCqrC.d.cts → types-CQFOCQzk.d.ts} +230 -43
  418. package/dist/{types-zZBxJ0P-.d.ts → types-CWyXTMwy.d.ts} +2 -2
  419. package/dist/{types-CPB-eF82.d.ts → types-CZJlLCbA.d.ts} +2 -2
  420. package/dist/{types-l9o4gFsI.d.ts → types-CZXPu3gn.d.ts} +2 -2
  421. package/dist/{types-BztF4HeB.d.ts → types-CaOtNjSZ.d.ts} +6 -13
  422. package/dist/{types-BTWIPEiU.d.ts → types-CfwqVkEA.d.ts} +2 -2
  423. package/dist/types-Cg14ncdV.d.ts +63 -0
  424. package/dist/{types-BsxLGDoC.d.cts → types-CoJVrRAD.d.ts} +2 -2
  425. package/dist/{types-DYzJ6K2e.d.ts → types-CqwHP7mN.d.cts} +230 -43
  426. package/dist/{types-CKiW3n6v.d.ts → types-D3wcs4tp.d.ts} +2 -2
  427. package/dist/{types-DOyNe7oe.d.cts → types-DDOa07rU.d.cts} +7 -15
  428. package/dist/{types-BW2BXUB4.d.cts → types-DE9hgr7i.d.cts} +2 -2
  429. package/dist/{types-BOqD3Hqy.d.cts → types-DEzW1CfI.d.cts} +3 -3
  430. package/dist/{types-OaD-cbbl.d.ts → types-DIiOMV-t.d.ts} +3 -3
  431. package/dist/{types-B-P4vQe0.d.cts → types-DKc1gmd9.d.ts} +857 -131
  432. package/dist/{types-BrPlv-NS.d.ts → types-DRCMBt89.d.ts} +3 -3
  433. package/dist/{types-BQvv4RaI.d.cts → types-DUMal2E-.d.cts} +5 -8
  434. package/dist/types-DWiLcrxt.d.cts +63 -0
  435. package/dist/{types-DNxOHnZI.d.cts → types-Dd31Lw4S.d.cts} +2 -2
  436. package/dist/{types-Dmu-8g4O.d.ts → types-DekYAlA-.d.ts} +3 -3
  437. package/dist/{types-B2U9cFcx.d.ts → types-DgJeO9Nd.d.ts} +2 -2
  438. package/dist/{types-nrviNdzZ.d.ts → types-DicSaNwq.d.ts} +2 -2
  439. package/dist/{types-Crhy0c9m.d.cts → types-DinIJ1D_.d.cts} +40 -11
  440. package/dist/{types-DhDNS-5B.d.ts → types-DlQw6FCi.d.ts} +13 -8
  441. package/dist/{types-_RhBCj4_.d.cts → types-DoZtE9tz.d.cts} +3 -3
  442. package/dist/{types-Bxhh2SJr.d.ts → types-DrvKfXXd.d.cts} +2 -2
  443. package/dist/{types-DPl8pZsY.d.ts → types-Dtuvhm3K.d.cts} +857 -131
  444. package/dist/{types-CcrvrAJX.d.ts → types-DwVSj-Da.d.ts} +5 -8
  445. package/dist/{types-C2vefB4D.d.ts → types-FwRmjsNN.d.ts} +10 -34
  446. package/dist/{types-C0_2KZ-A.d.ts → types-RbrfiY8T.d.ts} +2 -2
  447. package/dist/{types-DfvdbRPL.d.ts → types-WZBztugL.d.ts} +2 -2
  448. package/dist/{types-52irAt99.d.cts → types-YHUEArkR.d.cts} +2 -2
  449. package/dist/{types-fX4gbxfV.d.cts → types-bc-4z_gc.d.cts} +10 -34
  450. package/dist/{types-3eUgOA7I.d.cts → types-ePSqbXRr.d.cts} +6 -13
  451. package/dist/{types-DrqKICcK.d.ts → types-n4PTnLii.d.ts} +40 -11
  452. package/dist/{types-DXskkNp8.d.cts → types-pvQzbgNE.d.cts} +3 -3
  453. package/dist/{types-DajzGOKB.d.ts → types-q-1r_9d1.d.ts} +2 -2
  454. package/dist/{types-D8Rrz51O.d.cts → types-tKkeLa2B.d.cts} +2 -2
  455. package/dist/{validateConnectionStatus-828HV8WL.js → validateConnectionStatus-BEGu8wXT.js} +6 -10
  456. package/dist/validateConnectionStatus-BEGu8wXT.js.map +1 -0
  457. package/dist/{validateConnectionStatus-CvBKyeDO.cjs → validateConnectionStatus-BEYkQpu9.cjs} +6 -10
  458. package/dist/validateConnectionStatus-BEYkQpu9.cjs.map +1 -0
  459. package/dist/vault/index.cjs +4 -4
  460. package/dist/vault/index.d.cts +1 -1
  461. package/dist/vault/index.d.ts +1 -1
  462. package/dist/vault/index.js +4 -4
  463. package/dist/vault/types.d.cts +1 -1
  464. package/dist/vault/types.d.ts +1 -1
  465. package/package.json +32 -4
  466. package/surface/apps.md +3 -3
  467. package/surface/auth.md +13 -6
  468. package/surface/chat.md +6 -6
  469. package/surface/kaiAgent.md +9 -8
  470. package/surface/management.md +14 -5
  471. package/surface/metastore.md +2 -2
  472. package/surface/queue.md +3 -3
  473. package/surface/sdk.md +13 -3
  474. package/surface/storage.md +6 -6
  475. package/surface/syncActions.md +16 -0
  476. package/dist/ValidationError-BekhphAq.js +0 -48
  477. package/dist/ValidationError-BekhphAq.js.map +0 -1
  478. package/dist/ValidationError-CLVJCCwH.cjs.map +0 -1
  479. package/dist/authClient-8yU1last.cjs.map +0 -1
  480. package/dist/authClient-BTo4Afm6.js.map +0 -1
  481. package/dist/componentId-DkyQ8PM0.cjs.map +0 -1
  482. package/dist/componentId-vJz-kWs6.js.map +0 -1
  483. package/dist/concurrent-CH9fbNr3.js.map +0 -1
  484. package/dist/concurrent-tbiIa0UL.cjs.map +0 -1
  485. package/dist/configurations-BVvcimzo.js.map +0 -1
  486. package/dist/configurations-CyFF9Dtu.cjs.map +0 -1
  487. package/dist/configurations-VtNE0nrT.js.map +0 -1
  488. package/dist/configurations-zkNjr73Q.cjs.map +0 -1
  489. package/dist/createFetchClient-BlgPbjFj.cjs.map +0 -1
  490. package/dist/createFetchClient-C-cadpBx.js.map +0 -1
  491. package/dist/credential-CAulvfZ-.cjs +0 -47
  492. package/dist/credential-CAulvfZ-.cjs.map +0 -1
  493. package/dist/credential-DWXbo4IX.js +0 -36
  494. package/dist/credential-DWXbo4IX.js.map +0 -1
  495. package/dist/dedupe-CiskLkGR.cjs +0 -30
  496. package/dist/dedupe-CiskLkGR.cjs.map +0 -1
  497. package/dist/dedupe-DYIHgZoG.js +0 -25
  498. package/dist/dedupe-DYIHgZoG.js.map +0 -1
  499. package/dist/index-3LUk2rpD.d.ts +0 -65
  500. package/dist/index-CW3Pj7DY.d.cts +0 -65
  501. package/dist/isLoginPageRedirect-Cm6Pn8Pj.cjs +0 -25
  502. package/dist/isLoginPageRedirect-Cm6Pn8Pj.cjs.map +0 -1
  503. package/dist/isLoginPageRedirect-hyPqyWNX.js +0 -20
  504. package/dist/isLoginPageRedirect-hyPqyWNX.js.map +0 -1
  505. package/dist/jobStatus-0_Y3Sr4i.cjs.map +0 -1
  506. package/dist/jobStatus-PSZJMTiA.js.map +0 -1
  507. package/dist/kaiAgent-CcT2oNip.js.map +0 -1
  508. package/dist/kaiAgent-DaB6UCsh.cjs.map +0 -1
  509. package/dist/management-DeZiQSlw.cjs.map +0 -1
  510. package/dist/management-ckdnu1dA.js.map +0 -1
  511. package/dist/metastore-9AGrwjmN.cjs.map +0 -1
  512. package/dist/metastore-B0PolCjQ.js.map +0 -1
  513. package/dist/queue-Dagl0sdP.js.map +0 -1
  514. package/dist/queue-e3rMWbmK.cjs.map +0 -1
  515. package/dist/semanticLayer-6_gtFxDu.js.map +0 -1
  516. package/dist/semanticLayer-9uTaU7UT.cjs.map +0 -1
  517. package/dist/storage-HFUdEy7P.cjs.map +0 -1
  518. package/dist/storage-Ob1LUIDq.js.map +0 -1
  519. package/dist/syncActions-B3NS5a0g.js.map +0 -1
  520. package/dist/syncActions-D2DhY6pP.cjs.map +0 -1
  521. package/dist/validateConnectionStatus-828HV8WL.js.map +0 -1
  522. package/dist/validateConnectionStatus-CvBKyeDO.cjs.map +0 -1
package/dist/index.js CHANGED
@@ -1,51 +1,52 @@
1
1
  import { t as createProject } from "./project-DWwZv66D.js";
2
- import { a as poller, c as Result, d as delay, i as poll, l as asError, n as emitter, o as clamp, r as failureOf, s as finiteOr, t as jobStatus, u as lazy } from "./jobStatus-PSZJMTiA.js";
3
- import { n as collect, t as createQueueClient } from "./queue-Dagl0sdP.js";
4
- import { t as concurrent } from "./concurrent-CH9fbNr3.js";
5
- import { t as dedupe } from "./dedupe-DYIHgZoG.js";
2
+ import { a as poller, c as Result, d as delay, i as poll, l as asError, n as emitter, o as clamp, r as failureOf, s as finiteOr, t as jobStatus, u as lazy } from "./jobStatus-CfRtsIpv.js";
3
+ import { n as collect, t as createQueueClient } from "./queue-Cowbg6bR.js";
4
+ import { t as concurrent } from "./concurrent-BacWxPwi.js";
5
+ import { t as dedupe } from "./dedupe-Cky1gSUu.js";
6
6
  import { n as createEmitter, t as createStore } from "./store-C9FQCHGe.js";
7
- import { a as readableReason, i as ServiceUnavailableError, o as series, t as createStorageClient } from "./storage-Ob1LUIDq.js";
8
- import { n as keboolaUID, t as createTagSdk } from "./tag-DCsoewjL.js";
7
+ import { a as readableReason, i as ServiceUnavailableError, o as series, t as createStorageClient } from "./storage-CZQHZcXG.js";
8
+ import { n as keboolaUID, t as createTagSdk } from "./tag-hh-1nhNr.js";
9
9
  import { t as generateUUID } from "./generateUUID-Dr8l-aoc.js";
10
10
  import { t as isPlainObject } from "./isPlainObject-LYW-03uB.js";
11
- import { n as schemaGuidedMerge, r as isEmptyDeep, t as createConfigurationSdk } from "./configurations-VtNE0nrT.js";
11
+ import { n as schemaGuidedMerge, r as isEmptyDeep, t as createConfigurationSdk } from "./configurations-CF3xz7RB.js";
12
12
  import { t as UserError } from "./UserError-By_Zckmc.js";
13
- import { a as isTimeoutError, d as normalizeBaseUrl, g as ApiError, h as KeboolaHttpHeader, i as isFetchClientError, m as HttpStatus, n as isAbortError, o as HttpContentType, r as isApiError, s as HttpHeader } from "./createFetchClient-C-cadpBx.js";
14
- import { n as HtmlResponseError, r as isHtmlResponseError } from "./validateConnectionStatus-828HV8WL.js";
15
- import { t as ManagementClientAuthError } from "./ManagementClientAuthError-Cr9IOsnJ.js";
13
+ import { a as isTimeoutError, d as normalizeBaseUrl, g as ApiError, h as KeboolaHttpHeader, i as isFetchClientError, m as HttpStatus, n as isAbortError, o as HttpContentType, r as isApiError, s as HttpHeader } from "./createFetchClient-DXHQK63w.js";
14
+ import { n as HtmlResponseError, r as isHtmlResponseError } from "./validateConnectionStatus-BEGu8wXT.js";
15
+ import { t as ManagementClientAuthError } from "./ManagementClientAuthError-H30lti_Q.js";
16
16
  import { i as isQueryJobError, n as isQueryJobTimeoutError, r as QueryJobError, t as QueryJobTimeoutError } from "./QueryJobTimeoutError-C7JbNGOM.js";
17
17
  import { n as isSyncActionError, t as SyncActionError } from "./SyncActionError-CoZFsdUk.js";
18
- import { i as parseOrThrow, n as formatValidationIssues, r as isValidationError, t as ValidationError } from "./ValidationError-BekhphAq.js";
19
- import { t as createGenericFetchClient } from "./createGenericFetchClient-Bnf1QK9W.js";
20
- import { t as createImportClient } from "./import-xliONVib.js";
21
- import { t as createAuthClient } from "./authClient-BTo4Afm6.js";
22
- import { n as isManagementClientAuthError, t as createManagementClient } from "./management-ckdnu1dA.js";
18
+ import { i as parseOrThrow, n as formatValidationIssues, r as isValidationError, t as ValidationError } from "./ValidationError-DjhtNMfZ.js";
19
+ import { t as createGenericFetchClient } from "./createGenericFetchClient-Dg1rgzmG.js";
20
+ import { t as createImportClient } from "./import-DiMQCzLa.js";
21
+ import { t as createAuthClient } from "./authClient-CgcDGd30.js";
22
+ import { n as isManagementClientAuthError, t as createManagementClient } from "./management-DvmPiG64.js";
23
23
  import { s as ProjectFeature } from "./constants-C2tYAJSj.js";
24
24
  import { t as createStorageTable } from "./storageTable-DslXtqNL.js";
25
- import { a as createSemanticLayerSdk } from "./semanticLayer-6_gtFxDu.js";
25
+ import { i as createKaiMemorySdk } from "./kaiMemory-D0Y_16U4.js";
26
+ import { a as createSemanticLayerSdk } from "./semanticLayer-pYy082Ju.js";
26
27
  import { createStorageSdk } from "./sdk/storage/index.js";
27
28
  import { createVaultSdk } from "./sdk/vault/index.js";
28
29
  import { createAiClient } from "./ai/index.js";
29
- import { t as parseLogLines } from "./appLogs-Cl7Q_MR9.js";
30
+ import { t as parseLogLines } from "./appLogs-BBkkUOW1.js";
30
31
  import { createAppsClient } from "./apps/index.js";
31
32
  import { createBillingClient } from "./billing/index.js";
32
- import { t as createBusinessWorkspaceApiClient } from "./businessWorkspaceApi-BD-iUj07.js";
33
+ import { t as createBusinessWorkspaceApiClient } from "./businessWorkspaceApi-BLUdefRF.js";
33
34
  import { createChatClient } from "./chat/index.js";
34
- import { t as createDataScienceClient } from "./dataScience-B_BmnB1m.js";
35
+ import { t as createDataScienceClient } from "./dataScience-OXcwdk1p.js";
35
36
  import { createEditorClient } from "./editor/index.js";
36
37
  import { createEncryptionClient } from "./encryption/index.js";
37
- import { t as createKaiAgentClient } from "./kaiAgent-CcT2oNip.js";
38
- import { t as createMetastoreClient } from "./metastore-B0PolCjQ.js";
38
+ import { t as createKaiAgentClient } from "./kaiAgent-Dp20HLTh.js";
39
+ import { t as createMetastoreClient } from "./metastore-BycJxe7A.js";
39
40
  import { createNotificationsClient } from "./notifications/index.js";
40
- import { t as createOauthClient } from "./oauth-BnHVf4cB.js";
41
+ import { t as createOauthClient } from "./oauth-l5zE39cD.js";
41
42
  import { createOmnisearchClient } from "./omnisearch/index.js";
42
- import { t as createQueryServiceClient } from "./queryService-j3XZ2mX6.js";
43
+ import { t as createQueryServiceClient } from "./queryService-CCOYbRbw.js";
43
44
  import { createSchedulerClient } from "./scheduler/index.js";
44
45
  import { createStreamClient } from "./stream/index.js";
45
- import { t as createSyncActionsClient } from "./syncActions-B3NS5a0g.js";
46
+ import { t as createSyncActionsClient } from "./syncActions-ChNWuhYA.js";
46
47
  import { createTelemetryClient } from "./telemetry/index.js";
47
48
  import { createVaultClient } from "./vault/index.js";
48
- import { n as isUnauthorized, t as createBearerCredential } from "./credential-DWXbo4IX.js";
49
+ import { n as isUnauthorized, t as createBearerAuthMiddleware } from "./middleware-CBwrtgQd.js";
49
50
  import { createQueryServiceSdk } from "./sdk/queryService/index.js";
50
51
  import * as z$1 from "zod";
51
52
  //#region src/utils/assert.ts
@@ -53,22 +54,29 @@ function assert(value, message) {
53
54
  if (value == null) throw new Error(message);
54
55
  }
55
56
  //#endregion
57
+ //#region src/utils/ensure.ts
58
+ /**
59
+ * Read a key, or build its value and keep it.
60
+ *
61
+ * `Map.prototype.getOrInsertComputed` is this natively — swap to it once it clears the app's
62
+ * `baseline-widely-available` build target. Vite transpiles syntax, not methods, so adopting it
63
+ * early fails in the browser rather than at build.
64
+ */
65
+ const ensure = (map, key, build) => {
66
+ const existing = map.get(key);
67
+ if (existing !== void 0) return existing;
68
+ const created = build();
69
+ map.set(key, created);
70
+ return created;
71
+ };
72
+ //#endregion
56
73
  //#region src/utils/async/coalesce.ts
57
74
  /**
58
75
  * Coalesces concurrent triggers onto a single, never-parallel run of `task`.
59
- * Triggers fired while a run is busy collapse into one trailing run, and each
60
- * resolves with the first run that started after it — so it never sees stale state.
61
- *
62
- * Example — A triggers, then B and C trigger while A's run is still going:
63
- * 1. trigger A → run #1 starts
64
- * 2. trigger B, C → run #1 busy, so they wait
65
- * 3. run #1 done → A resolves
66
- * 4. run #2 starts → covers B and C together (one trailing run, not two)
67
- * 5. run #2 done → B and C resolve
68
76
  *
69
- * @returns a trigger; each call returns a promise of the task result.
70
- * @throws The returned promise rejects with whatever `task` throws or rejects
71
- * with — the caller handles it (try/catch, or `.catch` on `void trigger()`).
77
+ * - Triggers fired while a run is busy collapse into one trailing run.
78
+ * - Each trigger resolves with the first run started after it, so it never sees stale state.
79
+ * - The returned promise rejects with whatever `task` throws.
72
80
  */
73
81
  const coalesce = (task) => {
74
82
  let running = false;
@@ -388,8 +396,7 @@ const createProjectRefreshMiddleware = (shouldRefresh, requestRefresh) => (next)
388
396
  return response;
389
397
  };
390
398
  /**
391
- * The live project store: seeded from the verified token, re-verified (coalesced) after a
392
- * token-mutating request or an explicit re-scope. Its `middleware` drives the auto re-verify.
399
+ * The live project store, re-verified (coalesced) after a token-mutating request or a re-scope.
393
400
  */
394
401
  const createLiveProject = ({ initialToken, verify }) => {
395
402
  const store = createStore(createProject({ sapiToken: initialToken }));
@@ -412,24 +419,30 @@ const createLiveProject = ({ initialToken, verify }) => {
412
419
  const KeboolaErrorType = {
413
420
  Unconfigured: "unconfigured",
414
421
  NotAuthenticated: "not-authenticated",
422
+ SignInEnded: "sign-in-ended",
415
423
  AlreadyAuthenticated: "already-authenticated",
416
424
  NoStorageToken: "no-storage-token",
417
425
  NoManagementToken: "no-management-token",
418
426
  MissingProject: "missing-project",
419
427
  NotBearer: "not-bearer",
420
428
  NotReady: "not-ready",
421
- InvalidBuildTransition: "invalid-build-transition"
429
+ InvalidBuildTransition: "invalid-build-transition",
430
+ StackActive: "stack-active",
431
+ CredentialKindMismatch: "credential-kind-mismatch"
422
432
  };
423
433
  const MESSAGES = {
424
434
  [KeboolaErrorType.Unconfigured]: "The session is not configured — set a baseUrl first.",
425
435
  [KeboolaErrorType.NotAuthenticated]: "The session is not authenticated — sign in first.",
436
+ [KeboolaErrorType.SignInEnded]: "The sign-in this operation started under has ended — its result belongs to nobody.",
426
437
  [KeboolaErrorType.AlreadyAuthenticated]: "The session is already authenticated — reset before authenticating again.",
427
438
  [KeboolaErrorType.NoStorageToken]: "No storage token — authenticate the storage realm first.",
428
439
  [KeboolaErrorType.NoManagementToken]: "No management token — authenticate the management realm first.",
429
440
  [KeboolaErrorType.MissingProject]: "A bearer storage session requires a project — call setProject(projectId) first.",
430
441
  [KeboolaErrorType.NotBearer]: "This operation requires a bearer (OAuth) session.",
431
442
  [KeboolaErrorType.NotReady]: "The client is not ready — authenticate the storage realm first.",
432
- [KeboolaErrorType.InvalidBuildTransition]: "Invalid storage build transition — the build goes idle → initializing → ready | failed."
443
+ [KeboolaErrorType.InvalidBuildTransition]: "Invalid storage build transition — the build goes idle → initializing → ready | failed.",
444
+ [KeboolaErrorType.StackActive]: "The active stack cannot be closed — select another first.",
445
+ [KeboolaErrorType.CredentialKindMismatch]: "This client renews the other credential kind — log in the way its `credentials` mode expects."
433
446
  };
434
447
  var KeboolaError = class KeboolaError extends Error {
435
448
  type;
@@ -446,168 +459,6 @@ function assert$1(value, type) {
446
459
  if (value == null) throw new KeboolaError(type);
447
460
  }
448
461
  //#endregion
449
- //#region src/middlewares/loggingMiddleware.ts
450
- const CORRELATION_ID_HEADER = "X-Correlation-ID";
451
- const ALWAYS_REDACTED_HEADERS = [
452
- KeboolaHttpHeader.MANAGEMENT_API_TOKEN,
453
- KeboolaHttpHeader.STORAGE_API_TOKEN,
454
- "authorization",
455
- "cookie",
456
- "set-cookie"
457
- ];
458
- const ALWAYS_REDACTED_QUERY_PARAMS = /* @__PURE__ */ new Set([
459
- "token",
460
- "apikey",
461
- "api_key",
462
- "access_token",
463
- "refresh_token",
464
- "code",
465
- "state",
466
- "signature",
467
- "sig",
468
- "x-amz-signature",
469
- "x-amz-credential",
470
- "x-amz-security-token",
471
- "password",
472
- "secret"
473
- ]);
474
- const REDACTED = "[REDACTED]";
475
- const getRedactedUrl = (rawUrl) => {
476
- const url = new URL(rawUrl);
477
- if (url.username) url.username = REDACTED;
478
- if (url.password) url.password = REDACTED;
479
- url.searchParams.forEach((_value, key) => {
480
- if (ALWAYS_REDACTED_QUERY_PARAMS.has(key.toLowerCase())) url.searchParams.set(key, REDACTED);
481
- });
482
- return url.toString();
483
- };
484
- const ensureCorrelationId = (request) => {
485
- const correlationId = request.headers.get(CORRELATION_ID_HEADER) ?? generateUUID();
486
- request.headers.set(CORRELATION_ID_HEADER, correlationId);
487
- return correlationId;
488
- };
489
- const getRedactedHeaders = (headers, redacted) => {
490
- const redactedSet = new Set([...ALWAYS_REDACTED_HEADERS, ...redacted].map((h) => h.toLowerCase()));
491
- const result = {};
492
- headers.forEach((value, name) => {
493
- result[name] = redactedSet.has(name.toLowerCase()) ? REDACTED : value;
494
- });
495
- return result;
496
- };
497
- const getRequestLog = (request, redactedHeaders) => ({
498
- url: getRedactedUrl(request.url),
499
- headers: getRedactedHeaders(request.headers, redactedHeaders)
500
- });
501
- const getResponseLog = (response, redactedHeaders) => ({
502
- status: response.status,
503
- statusText: response.statusText,
504
- headers: getRedactedHeaders(response.headers, redactedHeaders)
505
- });
506
- const redactApiError = (error, redactedHeaders) => new ApiError({
507
- request: new Request(getRedactedUrl(error.request.url), {
508
- method: error.request.method,
509
- headers: getRedactedHeaders(error.request.headers, redactedHeaders)
510
- }),
511
- response: new Response(null, {
512
- status: error.response.status,
513
- statusText: error.response.statusText,
514
- headers: getRedactedHeaders(error.response.headers, redactedHeaders)
515
- }),
516
- data: error.data
517
- });
518
- const formatLog = (level, log) => {
519
- const parts = [
520
- `[${level.toUpperCase()}]`,
521
- `${Math.round(log.durationMs)}ms`,
522
- log.method
523
- ];
524
- parts.push(log.request.url);
525
- if ("response" in log) parts.push(String(log.response.status));
526
- return parts.join(" ");
527
- };
528
- const createSafeLogger = (logger, level = "error-only") => {
529
- return {
530
- info: (log) => {
531
- if (level !== "all") return;
532
- try {
533
- if (logger?.info) {
534
- logger.info(log);
535
- return;
536
- }
537
- console.info(formatLog("info", log));
538
- } catch {}
539
- },
540
- error: (log) => {
541
- try {
542
- if (logger?.error) {
543
- logger.error(log);
544
- return;
545
- }
546
- console.error(formatLog("error", log));
547
- } catch {}
548
- }
549
- };
550
- };
551
- const createLoggingMiddleware = (options = {}) => {
552
- const safeLogger = createSafeLogger(options.logger, options.level);
553
- const redactHeaders = options.redactHeaders ?? [];
554
- return (next) => async (fetchRequest) => {
555
- const correlationId = ensureCorrelationId(fetchRequest.request);
556
- const start = performance.now();
557
- const method = fetchRequest.request.method.toLowerCase();
558
- const requestLog = getRequestLog(fetchRequest.request, redactHeaders);
559
- try {
560
- const result = await next(fetchRequest);
561
- safeLogger.info({
562
- correlationId,
563
- method,
564
- durationMs: performance.now() - start,
565
- request: requestLog,
566
- response: getResponseLog(result.response, redactHeaders)
567
- });
568
- return result;
569
- } catch (error) {
570
- if (error instanceof Error) safeLogger.error({
571
- correlationId,
572
- method,
573
- durationMs: performance.now() - start,
574
- request: requestLog,
575
- error: isApiError(error) ? redactApiError(error, redactHeaders) : error
576
- });
577
- throw error;
578
- }
579
- };
580
- };
581
- //#endregion
582
- //#region src/middlewares/retryMiddleware.ts
583
- const DEFAULT_MAX_RETRIES = 5;
584
- const DEFAULT_RETRYABLE_STATUSES = [
585
- HttpStatus.INTERNAL_SERVER_ERROR,
586
- HttpStatus.BAD_GATEWAY,
587
- HttpStatus.SERVICE_UNAVAILABLE,
588
- HttpStatus.GATEWAY_TIMEOUT
589
- ];
590
- const DEFAULT_BACKOFF_FACTOR = .3;
591
- const defaultShouldRetry = (error) => error instanceof ApiError && DEFAULT_RETRYABLE_STATUSES.includes(error.response.status);
592
- const createRetryMiddleware = (options) => {
593
- const { maxRetries = DEFAULT_MAX_RETRIES, backoffFactor = DEFAULT_BACKOFF_FACTOR, shouldRetry = defaultShouldRetry } = options ?? {};
594
- if (!Number.isInteger(maxRetries) || maxRetries < 0) throw new RangeError("maxRetries must be a non-negative integer");
595
- if (!Number.isFinite(backoffFactor) || backoffFactor < 0) throw new RangeError("backoffFactor must be a finite non-negative number");
596
- return (next) => async (request) => {
597
- for (let attempt = 0; attempt <= maxRetries; attempt++) try {
598
- return await next({
599
- ...request,
600
- request: request.request.clone()
601
- });
602
- } catch (error) {
603
- if (attempt === maxRetries || !shouldRetry(error, attempt)) throw error;
604
- const delayMs = backoffFactor * 1e3 * Math.pow(2, attempt);
605
- await delay(delayMs, request.request.signal ?? void 0);
606
- }
607
- throw new Error("unreachable");
608
- };
609
- };
610
- //#endregion
611
462
  //#region src/serviceClientRegistry/utils.ts
612
463
  const isBuiltInProperty = (property) => typeof property === "symbol" || property === "then" || property === "constructor" || property === "toString" || property === "valueOf";
613
464
  /**
@@ -696,146 +547,40 @@ const createMiddlewareFor = (middlewares) => {
696
547
  };
697
548
  };
698
549
  //#endregion
699
- //#region src/keboola/bearer/createConfig.ts
700
- const INITIAL = {
701
- status: "anonymous",
702
- baseUrl: null
703
- };
704
- const stamp = (tokens) => ({
705
- ...tokens,
706
- issuedAt: Date.now()
707
- });
708
- const createConfig$1 = (initial = INITIAL) => {
709
- const store = createStore(initial);
710
- let expiredNotified = false;
711
- let epoch = 0;
550
+ //#region src/keboola/legacy/createConfig.ts
551
+ const createConfig = () => {
552
+ const store = createStore({
553
+ baseUrl: null,
554
+ sapiToken: null,
555
+ managementToken: null
556
+ });
712
557
  const setBaseUrl = (baseUrl) => {
713
- if (store.get().status !== "anonymous") throw new KeboolaError(KeboolaErrorType.AlreadyAuthenticated);
714
558
  store.set({
715
- status: "anonymous",
559
+ ...store.get(),
716
560
  baseUrl
717
561
  });
718
562
  };
719
563
  const authenticate = (tokens) => {
720
- const state = store.get();
721
- if (state.status !== "anonymous") throw new KeboolaError(KeboolaErrorType.AlreadyAuthenticated);
722
- if (!state.baseUrl) throw new KeboolaError(KeboolaErrorType.Unconfigured);
723
- expiredNotified = false;
724
- epoch += 1;
725
- store.set({
726
- status: "authenticated",
727
- baseUrl: state.baseUrl,
728
- credential: stamp(tokens)
729
- });
730
- };
731
- const setProjectId = (projectId) => {
732
- const state = store.get();
733
- if (state.status === "anonymous") throw new KeboolaError(KeboolaErrorType.NotAuthenticated);
734
- store.set({
735
- status: "scoped",
736
- baseUrl: state.baseUrl,
737
- credential: state.credential,
738
- projectId
739
- });
740
- };
741
- /**
742
- * Drop the project scope, keeping the credential — the inverse of `setProjectId`, for leaving a
743
- * project without signing out. The project clients are keyed on the scope, so they tear down and
744
- * the storage build returns to `idle`; the session stays usable for `auth` and `management`.
745
- * No-op unless currently scoped.
746
- */
747
- const clearProjectId = () => {
748
- const state = store.get();
749
- if (state.status !== "scoped") return;
750
- store.set({
751
- status: "authenticated",
752
- baseUrl: state.baseUrl,
753
- credential: state.credential
754
- });
755
- };
756
- /** Drop the credential (sign out); keeps the configured baseUrl. */
757
- const reset = () => {
758
- epoch += 1;
759
- store.set({
760
- status: "anonymous",
761
- baseUrl: store.get().baseUrl
762
- });
763
- };
764
- /** Apply a token refresh: replace the credential (fresh tokens, new issue time); no-op before auth. */
765
- const applyRefresh = (tokens) => {
766
- const state = store.get();
767
- if (state.status === "anonymous") return;
768
- store.set({
769
- ...state,
770
- credential: stamp(tokens)
771
- });
772
- };
773
- /**
774
- * Dev/test lever: backdate the current token's issue time by a full lifetime so it reads as
775
- * expired, making the refresh policy rotate it on the next request. No-op before auth.
776
- */
777
- const forceExpire = () => {
778
- const state = store.get();
779
- if (state.status === "anonymous") return;
780
- const issuedAt = Date.now() - state.credential.expiresIn * 1e3;
564
+ const current = store.get();
781
565
  store.set({
782
- ...state,
783
- credential: {
784
- ...state.credential,
785
- issuedAt
786
- }
566
+ ...current,
567
+ sapiToken: tokens.sapiToken ?? current.sapiToken,
568
+ managementToken: tokens.managementToken ?? current.managementToken
787
569
  });
788
570
  };
789
- /**
790
- * The current credential, asserting the session is authenticated (or scoped). Single point for that
791
- * check so callers (token attach, refresh) don't each re-narrow the state.
792
- */
793
- const requireCredential = () => {
794
- const state = store.get();
795
- if (state.status === "anonymous") throw new KeboolaError(KeboolaErrorType.NotAuthenticated);
796
- return state.credential;
797
- };
798
- const getBaseUrl = () => store.get().baseUrl;
799
- /**
800
- * Which sign-in this is — a counter, bumped by `authenticate` and `reset`.
801
- *
802
- * - For anything long-lived that must not outlive the credential it was built against: capture it,
803
- * compare it later. A rotation does not move it; only a new session or a sign-out does.
804
- * - Distinct from `notifyExpired`'s latch, which answers "report this death once" rather than
805
- * "which session are we in".
806
- */
807
- const getEpoch = () => epoch;
808
- /**
809
- * Session-expiry latch (fire-once):
810
- * - why: concurrent 401s all report expiry, but the app must sign out once; and the credential /
811
- * auth middleware are long-lived singletons, so the latch can't live in them — it must reset
812
- * per session.
813
- * - how: returns `true` only for the first call since the last `authenticate` (which re-arms it),
814
- * so the caller runs its sign-out exactly once per session death.
815
- */
816
- const notifyExpired = () => {
817
- if (expiredNotified) return false;
818
- expiredNotified = true;
819
- return true;
820
- };
571
+ const getStorageToken = () => store.get().sapiToken ?? "";
572
+ const setStorageToken = (sapiToken) => store.set({
573
+ ...store.get(),
574
+ sapiToken
575
+ });
576
+ /** Current state, for diagnostics. */
821
577
  const debug = () => store.get();
822
578
  return {
823
- store: {
824
- get: store.get,
825
- subscribe: store.subscribe,
826
- dispose: store.dispose
827
- },
579
+ store,
828
580
  setBaseUrl,
829
581
  authenticate,
830
- setProjectId,
831
- clearProjectId,
832
- reset,
833
- applyRefresh,
834
- forceExpire,
835
- requireCredential,
836
- getBaseUrl,
837
- getEpoch,
838
- notifyExpired,
582
+ getStorageToken,
583
+ setStorageToken,
839
584
  debug
840
585
  };
841
586
  };
@@ -976,6 +721,7 @@ const createVariablesSdk = ({ storageClient }) => {
976
721
  };
977
722
  //#endregion
978
723
  //#region src/keboola/createServiceClients.ts
724
+ const withPath = (serviceBaseUrl, path) => typeof serviceBaseUrl === "string" ? `${serviceBaseUrl}${path}` : async () => `${await serviceBaseUrl()}${path}`;
979
725
  const createServiceClients = ({ baseUrl, auth, getServiceBaseUrl, middlewareFor, attachTokenMiddleware }) => createServiceClientRegistry()({
980
726
  getServiceBaseUrl,
981
727
  onUnavailable: ({ serviceId, path, clientName }) => {
@@ -1001,7 +747,7 @@ const createServiceClients = ({ baseUrl, auth, getServiceBaseUrl, middlewareFor,
1001
747
  serviceId: "data-science",
1002
748
  clientName: "apps",
1003
749
  clientFn: (serviceBaseUrl) => createAppsClient({
1004
- baseUrl: `${serviceBaseUrl}/v2`,
750
+ baseUrl: withPath(serviceBaseUrl, "/v2"),
1005
751
  middlewares: middlewareFor("apps", [attachTokenMiddleware]),
1006
752
  auth
1007
753
  })
@@ -1073,7 +819,7 @@ const createServiceClients = ({ baseUrl, auth, getServiceBaseUrl, middlewareFor,
1073
819
  serviceId: "ai",
1074
820
  clientName: "omnisearch",
1075
821
  clientFn: (serviceBaseUrl) => createOmnisearchClient({
1076
- baseUrl: `${serviceBaseUrl}/omnisearch`,
822
+ baseUrl: withPath(serviceBaseUrl, "/omnisearch"),
1077
823
  middlewares: middlewareFor("omnisearch", [attachTokenMiddleware]),
1078
824
  auth
1079
825
  })
@@ -1152,35 +898,26 @@ const createServiceClients = ({ baseUrl, auth, getServiceBaseUrl, middlewareFor,
1152
898
  })
1153
899
  }).build();
1154
900
  //#endregion
1155
- //#region src/keboola/bearer/createProjectClients.ts
1156
- /**
1157
- * Bearer (OAuth) project surface. Same handshake + assembly as the legacy build. The
1158
- * `Authorization: Bearer` header + transparent refresh come from the engine-shared `authMiddleware`
1159
- * (one instance for management + every project client). This build only adds the project-scoped
1160
- * `X-KBC-ProjectId` header, composed *outside* the auth middleware so the header is present
1161
- * before it clones the request for the 401 replay. Bearer has no static token header, so this
1162
- * combined `attach` rides on every client — including the operational storage and the bootstrap reader.
1163
- */
1164
- const createProjectClients$1 = async ({ baseUrl, projectId, authMiddleware, middlewareFor, clientServiceUrls }) => {
901
+ //#region src/keboola/legacy/createProjectClients.ts
902
+ const createAttachStorageToken = (getToken) => (next) => (request) => {
903
+ request.request.headers.set(KeboolaHttpHeader.STORAGE_API_TOKEN, getToken());
904
+ return next(request);
905
+ };
906
+ const createProjectClients = async ({ baseUrl, getStorageToken, onStorageTokenRefreshed, middlewareFor, clientServiceUrls }) => {
1165
907
  const auth = {
1166
- type: "bearer",
1167
- token: "",
1168
- projectId
1169
- };
1170
- const projectIdMiddleware = (next) => (request) => {
1171
- request.request.headers.set(KeboolaHttpHeader.PROJECT_ID, String(projectId));
1172
- return next(request);
908
+ type: "sapi-token",
909
+ token: getStorageToken()
1173
910
  };
1174
- const attach = (next) => projectIdMiddleware(authMiddleware(next));
1175
- const reader = createStorageClient({
911
+ const attach = createAttachStorageToken(getStorageToken);
912
+ const _storage = createStorageClient({
1176
913
  baseUrl,
1177
914
  auth,
1178
915
  middlewares: [attach]
1179
916
  });
1180
917
  const [stackInfo, sapiToken, devBranches] = await Promise.all([
1181
- reader.getStackInfo({ exclude: "componentDetails" }),
1182
- reader.tokens.verify(),
1183
- reader.branches.getDevBranches()
918
+ _storage.getStackInfo({ exclude: "componentDetails" }),
919
+ _storage.tokens.verify(),
920
+ _storage.branches.getDevBranches()
1184
921
  ]);
1185
922
  const stack = createStack({
1186
923
  stackInfo,
@@ -1189,7 +926,7 @@ const createProjectClients$1 = async ({ baseUrl, projectId, authMiddleware, midd
1189
926
  const defaultBranch = createDefaultBranch({ devBranches });
1190
927
  const liveProject = createLiveProject({
1191
928
  initialToken: sapiToken,
1192
- verify: () => reader.tokens.verify()
929
+ verify: () => _storage.tokens.verify()
1193
930
  });
1194
931
  const storageTableStore = createDerivedStore({
1195
932
  source: liveProject.store,
@@ -1214,552 +951,8 @@ const createProjectClients$1 = async ({ baseUrl, projectId, authMiddleware, midd
1214
951
  const storage = createStorageClient({
1215
952
  baseUrl,
1216
953
  auth,
1217
- middlewares: middlewareFor("storage", [attach, liveProject.middleware])
1218
- });
1219
- const { client: services, meta: serviceMeta } = createServiceClients({
1220
- baseUrl,
1221
- auth,
1222
- getServiceBaseUrl: context.stack.getServiceUrl,
1223
- middlewareFor,
1224
- attachTokenMiddleware: attach
1225
- });
1226
- const sdk = {
1227
- configuration: createConfigurationSdk({
1228
- storageClient: storage,
1229
- encryptionClient: services.encryption,
1230
- context
1231
- }),
1232
- tag: createTagSdk({ metastoreClient: services.metastore }),
1233
- semanticLayer: createSemanticLayerSdk({ metastoreClient: services.metastore }),
1234
- storage: createStorageSdk({ storageClient: storage }),
1235
- vault: createVaultSdk({
1236
- vaultClient: services.vault,
1237
- encryptionClient: services.encryption
1238
- }),
1239
- variables: createVariablesSdk({ storageClient: storage })
1240
- };
1241
- return {
1242
- context,
1243
- serviceMeta,
1244
- storage,
1245
- ...services,
1246
- sdk
1247
- };
1248
- };
1249
- //#endregion
1250
- //#region src/keboola/bearer/middleware.ts
1251
- /**
1252
- * Bearer auth for every outgoing request:
1253
- * - Stamps the current access token (from the credential) as the `Authorization` header.
1254
- * - On a 401, force-refreshes the token and replays the request once.
1255
- * - If the replay still 401s, the fresh token is rejected → marks the session expired.
1256
- *
1257
- * When the session is anonymous (`getAccessToken` → `null`) the request is passed through untouched
1258
- * with no 401 dance — so pre-auth calls on the auth client (`login`, `refresh`) work and a failed
1259
- * login is never mistaken for session expiry.
1260
- *
1261
- * Holds no token and never touches config — all token and refresh state lives in the credential.
1262
- */
1263
- const createBearerAuthMiddleware = (credential) => {
1264
- return (next) => async (request) => {
1265
- const token = await credential.getAccessToken({ forceRefresh: false });
1266
- if (token === null) return next(request);
1267
- const retryRequest = request.request.clone();
1268
- request.request.headers.set(HttpHeader.AUTHORIZATION, `Bearer ${token}`);
1269
- try {
1270
- return await next(request);
1271
- } catch (error) {
1272
- if (!isUnauthorized(error)) throw error;
1273
- const refreshed = await credential.getAccessToken({ forceRefresh: true });
1274
- if (refreshed === null) throw error;
1275
- retryRequest.headers.set(HttpHeader.AUTHORIZATION, `Bearer ${refreshed}`);
1276
- try {
1277
- return await next({
1278
- ...request,
1279
- request: retryRequest
1280
- });
1281
- } catch (retryError) {
1282
- if (isUnauthorized(retryError)) credential.notifyExpired();
1283
- throw retryError;
1284
- }
1285
- }
1286
- };
1287
- };
1288
- //#endregion
1289
- //#region src/keboola/bearer/persistor.ts
1290
- const SESSION_KEY = "keboola:bearer-session";
1291
- const persistedSessionSchema = z$1.object({
1292
- baseUrl: z$1.string().nullable(),
1293
- projectId: z$1.number().nullable(),
1294
- refreshToken: z$1.string().nullable()
1295
- });
1296
- const EMPTY_PERSISTED_SESSION = {
1297
- baseUrl: null,
1298
- projectId: null,
1299
- refreshToken: null
1300
- };
1301
- const createSessionPersistor = (storage) => createPersistor({
1302
- storage,
1303
- key: SESSION_KEY,
1304
- schema: persistedSessionSchema,
1305
- defaultValue: EMPTY_PERSISTED_SESSION
1306
- });
1307
- //#endregion
1308
- //#region src/keboola/bearer/keboola.ts
1309
- const createKeboola = (options = {}) => {
1310
- const persistor = createSessionPersistor(options.storage);
1311
- const config = createConfig$1();
1312
- const middlewareFor = createMiddlewareFor(options.middlewares);
1313
- const retryContention = createRetryMiddleware({ shouldRetry: (error) => error instanceof ApiError && error.response.status === HttpStatus.SERVICE_UNAVAILABLE });
1314
- const authClientBare = createDerivedStore({
1315
- source: config.store,
1316
- dependsOn: (state) => state.baseUrl,
1317
- build: (baseUrl) => baseUrl ? createAuthClient({
1318
- baseUrl,
1319
- middlewares: middlewareFor("auth", [retryContention])
1320
- }) : null
1321
- });
1322
- const refresh = async () => {
1323
- const client = authClientBare.get();
1324
- assert$1(client, KeboolaErrorType.NotReady);
1325
- const epoch = config.getEpoch();
1326
- const refreshed = await client.token.refresh(config.requireCredential().refreshToken).catch((error) => {
1327
- if (config.getEpoch() !== epoch) throw new KeboolaError(KeboolaErrorType.NotAuthenticated);
1328
- throw error;
1329
- });
1330
- if (config.getEpoch() !== epoch) throw new KeboolaError(KeboolaErrorType.NotAuthenticated);
1331
- config.applyRefresh(refreshed);
1332
- return refreshed.accessToken;
1333
- };
1334
- const getToken = () => {
1335
- const state = config.store.get();
1336
- if (state.status === "anonymous") return null;
1337
- const { accessToken, issuedAt, expiresIn } = state.credential;
1338
- return {
1339
- accessToken,
1340
- timing: {
1341
- issuedAt,
1342
- expiresIn
1343
- }
1344
- };
1345
- };
1346
- /**
1347
- * The session's state, once it is known to carry a credential.
1348
- *
1349
- * - Returns the state rather than nothing, so the caller reads `baseUrl` and `credential` off a
1350
- * narrowed union instead of re-checking the status to get at them.
1351
- * - `NotAuthenticated`, the same refusal `requireScopedProject` opens with. The two differ only in
1352
- * how far they go: this one stops at "somebody is signed in", which is all a request naming its
1353
- * own project needs.
1354
- */
1355
- const requireAuthenticated = () => {
1356
- const state = config.store.get();
1357
- if (state.status === "anonymous") throw new KeboolaError(KeboolaErrorType.NotAuthenticated);
1358
- return state;
1359
- };
1360
- /**
1361
- * The project this session is scoped to, right now.
1362
- *
1363
- * - Read at every point that stamps a project, never snapshotted across an `await`: the scope moves
1364
- * with `setProject`/`clearProject`, and neither ends the session, so it is not in the epoch and
1365
- * `assertSameSession` cannot see it change.
1366
- * - `NotReady` rather than `NotAuthenticated` when merely unscoped — the credential is fine, the
1367
- * project is what is missing. A credential alone does not authorize a project request: kai-agent
1368
- * reads the project from the header, not the token, and cannot attribute a call that omits it.
1369
- */
1370
- const requireScopedProject = () => {
1371
- const state = requireAuthenticated();
1372
- if (state.status !== "scoped") throw new KeboolaError(KeboolaErrorType.NotReady);
1373
- return state.projectId;
1374
- };
1375
- /**
1376
- * The project client sets `forProject` has handed out, keyed by project id.
1377
- *
1378
- * - Not keyed by stack: `setBaseUrl` throws once authenticated and `signOut` empties this, so one
1379
- * entry can never belong to a different `baseUrl` than the live session.
1380
- * - A `lazy` per key, not a bare promise: concurrent callers share one bootstrap, later ones replay
1381
- * the resolved set, and a rejected build clears only its own slot — so a build orphaned by a
1382
- * sign-out cannot evict the entry that replaced it.
1383
- */
1384
- const extraProjects = /* @__PURE__ */ new Map();
1385
- const signOut = () => {
1386
- config.reset();
1387
- credential.abandonRefresh();
1388
- extraProjects.clear();
1389
- persistor.clear();
1390
- };
1391
- const onSessionExpired = () => {
1392
- if (config.notifyExpired()) signOut();
1393
- };
1394
- const credential = createBearerCredential({
1395
- refresh,
1396
- getToken,
1397
- onSessionExpired
1398
- });
1399
- const sessionGuard = (epoch) => () => {
1400
- if (config.getEpoch() !== epoch) throw new KeboolaError(KeboolaErrorType.NotAuthenticated);
1401
- };
1402
- /**
1403
- * The auth middleware, refusing to carry a request across a change of session.
1404
- *
1405
- * - The middleware holds no token — it reads the credential live — so anything built on it acts as
1406
- * whoever is signed in *at request time*, not whoever built it. Rebuilding a store on sign-out
1407
- * only stops new reads; a request already in flight completes as the next user, still stamped
1408
- * with the old project. `config`'s epoch moves on `authenticate` and `reset` and never on a
1409
- * rotation, so it is exactly "which sign-in is this".
1410
- * - `epochFor` says which sign-in a request answers to, resolved per request:
1411
- * 1. a client set pins to the sign-in that *built* it (`pinToSession`) — a set the caller still
1412
- * holds must not ride the session that replaced it;
1413
- * 2. `api.auth` pins to the sign-in the request *started* on, because its store is keyed on
1414
- * `baseUrl` alone: it is built once, while anonymous, so a build-time pin would freeze at that
1415
- * epoch and refuse every authenticated call.
1416
- * - The guard covers every credential read, not only the wire request, so it wraps the credential
1417
- * rather than sitting beside it. The 401 path rotates the token by calling the credential
1418
- * directly: a straggler from a dead session would otherwise spend the *live* session's
1419
- * single-use refresh token, and sign that session out if the rotation itself came back 401.
1420
- * - `expiresSession` decides whether a 401 that survives a rotation means the session is dead.
1421
- * True for this session's own realms; false where the 401 may be about the project instead of
1422
- * the credential (see `forProject`).
1423
- * - `inner` is for middleware that **re-invokes `next`** — a retry. Composed outside the pin it
1424
- * would re-enter it per attempt, and with a per-request `epochFor` each attempt would re-pin to
1425
- * whoever is signed in by then: a 503 backoff is exactly long enough for a sign-out to land, and
1426
- * the retry then goes out as the next user. Inside, one epoch covers every attempt and each
1427
- * attempt still passes the guard. Anything new that retries belongs here, not in the array.
1428
- */
1429
- const createPinnedAuthMiddleware = (epochFor, { expiresSession = true, inner = [] } = {}) => {
1430
- return (next) => (request) => {
1431
- const assertSameSession = sessionGuard(epochFor());
1432
- const pinnedCredential = {
1433
- ...credential,
1434
- getAccessToken: async (options) => {
1435
- assertSameSession();
1436
- return credential.getAccessToken(options);
1437
- },
1438
- notifyExpired: expiresSession ? credential.notifyExpired : () => {}
1439
- };
1440
- const guarded = (wire) => (repeated) => {
1441
- assertSameSession();
1442
- return wire(repeated);
1443
- };
1444
- const chain = inner.reduceRight((acc, middleware) => middleware(acc), guarded(next));
1445
- return createBearerAuthMiddleware(pinnedCredential)(chain)(request);
1446
- };
1447
- };
1448
- /**
1449
- * Pin something long-lived to the sign-in live right now.
1450
- *
1451
- * - `assertSameSession` is for whatever no middleware chain covers: a bootstrap whose every
1452
- * request passed the guard before the sign-out resolves anyway and must not be handed back, and
1453
- * `getAuthHeaders`, which emits the credential by hand.
1454
- */
1455
- const pinToSession = (options) => {
1456
- const epoch = config.getEpoch();
1457
- return {
1458
- assertSameSession: sessionGuard(epoch),
1459
- pinnedAuthMiddleware: createPinnedAuthMiddleware(() => epoch, options)
1460
- };
1461
- };
1462
- const authClient = createDerivedStore({
1463
- source: config.store,
1464
- dependsOn: (state) => state.baseUrl,
1465
- build: (baseUrl) => baseUrl ? createAuthClient({
1466
- baseUrl,
1467
- middlewares: middlewareFor("auth", [createPinnedAuthMiddleware(config.getEpoch, { inner: [retryContention] })])
1468
- }) : null
1469
- });
1470
- const management = createDerivedStore({
1471
- source: config.store,
1472
- dependsOn: (state) => state.status === "anonymous" ? null : state.baseUrl,
1473
- build: (baseUrl) => baseUrl ? createManagementClient({
1474
- baseUrl,
1475
- auth: {
1476
- type: "bearer",
1477
- token: ""
1478
- },
1479
- middlewares: middlewareFor("management", [pinToSession().pinnedAuthMiddleware])
1480
- }) : null
1481
- });
1482
- const projectClientsAsync = createDerivedAsyncStore({
1483
- source: config.store,
1484
- dependsOn: (state) => state.status === "scoped" ? {
1485
- baseUrl: state.baseUrl,
1486
- projectId: state.projectId
1487
- } : null,
1488
- build: ({ baseUrl, projectId }) => {
1489
- return createProjectClients$1({
1490
- baseUrl,
1491
- authMiddleware: pinToSession().pinnedAuthMiddleware,
1492
- projectId,
1493
- middlewareFor,
1494
- clientServiceUrls: options.clientServiceUrls
1495
- });
1496
- }
1497
- });
1498
- const forProject = async (projectId) => {
1499
- const state = requireAuthenticated();
1500
- const cached = extraProjects.get(projectId);
1501
- if (cached) return cached();
1502
- const { assertSameSession, pinnedAuthMiddleware } = pinToSession({ expiresSession: false });
1503
- const build = lazy(async () => {
1504
- const clients = await createProjectClients$1({
1505
- baseUrl: state.baseUrl,
1506
- authMiddleware: pinnedAuthMiddleware,
1507
- projectId,
1508
- middlewareFor,
1509
- clientServiceUrls: options.clientServiceUrls
1510
- });
1511
- assertSameSession();
1512
- return clients;
1513
- });
1514
- extraProjects.set(projectId, build);
1515
- return build();
1516
- };
1517
- if (options.baseUrl) config.setBaseUrl(options.baseUrl);
1518
- config.store.subscribe((state) => {
1519
- if (state.status === "anonymous") return;
1520
- persistor.persist({
1521
- baseUrl: state.baseUrl,
1522
- projectId: state.status === "scoped" ? state.projectId : null,
1523
- refreshToken: state.credential.refreshToken
1524
- });
1525
- });
1526
- const debug = () => ({
1527
- type: "Bearer",
1528
- config: config.debug(),
1529
- authReady: authClient.get() !== null,
1530
- managementReady: management.get() !== null,
1531
- storage: projectClientsAsync.store.get().state
1532
- });
1533
- const session = {
1534
- hasPersistedValue: persistor.hasPersistedValue,
1535
- setBaseUrl: config.setBaseUrl,
1536
- isStorageReady: () => projectClientsAsync.store.get().state === "ready",
1537
- authenticate: (tokens) => config.authenticate(tokens),
1538
- setProject: config.setProjectId,
1539
- setProjectAsync: async (projectId) => {
1540
- config.setProjectId(projectId);
1541
- await projectClientsAsync.settled();
1542
- },
1543
- /**
1544
- * Leave the current project but stay signed in — the storage build returns to `idle`, so a
1545
- * consumer gating on it falls back to its project picker. The persisted session is rewritten with
1546
- * `projectId: null` by the subscription above, so a reload lands on the picker rather than
1547
- * re-entering the project. Use `reset` to sign out instead.
1548
- */
1549
- clearProject: config.clearProjectId,
1550
- /**
1551
- * The clients for one project, off this session — for reaching a second project without leaving
1552
- * the first.
1553
- *
1554
- * - `setProjectAsync` *moves* the session (and `api`) to another project; this *adds* one. The
1555
- * returned set is the caller's to hold and never appears on `api`.
1556
- * - Every set shares this session's auth middleware, so one rotation serves all of them. A second
1557
- * `createKeboola()` does not: both hold the same single-use refresh token, and the first to
1558
- * rotate invalidates the other's, whose next refresh 401s and signs it out.
1559
- * - Independent of the scope, including for the scoped project itself — asking for that one
1560
- * builds a second set with its own `liveProject`, so prefer `api.*` there.
1561
- */
1562
- forProject,
1563
- reset: signOut,
1564
- /**
1565
- * Dev/test only: mark the current access token as expired so the bearer credential rotates it on
1566
- * the next request. Pair with any authenticated call (e.g. `api.storage.tokens.verify()`) to force
1567
- * the rotation immediately and observe the new credential.
1568
- */
1569
- debugForceRefresh: config.forceExpire,
1570
- /**
1571
- * The headers that authorize one off-client request, resolved fresh each call.
1572
- *
1573
- * - For a transport this package does not own — the chat SSE stream, whose `fetch` the AI SDK
1574
- * holds. Anything with a service client on `api` should use that instead.
1575
- * - Returns the assembled bag, never the bare token: no caller handles the credential as a
1576
- * string, and `X-KBC-ProjectId` is composed here rather than in every consuming app.
1577
- * - Resolved per call, through the credential — so a near-expiry token rotates and a revoked
1578
- * one is never re-sent. A snapshot held by the caller would do neither.
1579
- * - Throws rather than emitting a half-formed `Bearer null`: a session with no credential has
1580
- * nothing to authorize with.
1581
- * - Pinned to the sign-in it was called on, like every client here. This is the one
1582
- * credential-emitting surface with no middleware chain for the guard to sit in, so the check
1583
- * is written out around the `await` that rotates the token.
1584
- *
1585
- * `projectId` names the project the headers authorize, for a caller reaching a project the
1586
- * session is not scoped to:
1587
- *
1588
- * - **Omitted**, the session's own scope answers — unchanged, and re-read *after* the rotation
1589
- * rather than carried across it. The epoch the pin compares moves on a sign-in and a sign-out
1590
- * only, so a project switch mid-rotation is invisible to it.
1591
- * - **Given**, it is what the header says, and the scope is not consulted at all. A caller that
1592
- * names a project has said everything the request needs: the credential is user-level and the
1593
- * project is a header on top of it, so an authenticated session suffices where an unnamed call
1594
- * requires a scoped one. Nothing about the session can change the answer, so there is nothing
1595
- * to re-read after the `await`.
1596
- * - **Not checked against an access set**, because this session cannot acquire one:
1597
- * `forProject` — the only other surface taking a caller-supplied project id — records that
1598
- * connection collapses every bearer failure into a single `invalid_token` 401, so "no access
1599
- * to this project" and "revoked token" are the same response. Whether the caller may reach a
1600
- * project is the caller's own knowledge, from `token.introspect`. What is guaranteed here is
1601
- * that the header names what was asked for and never something else — which is the failure
1602
- * worth preventing: a turn sent somewhere the transcript above it did not come from.
1603
- */
1604
- getAuthHeaders: async (projectId) => {
1605
- const { assertSameSession } = pinToSession();
1606
- if (projectId === void 0) requireScopedProject();
1607
- else requireAuthenticated();
1608
- const accessToken = await credential.getAccessToken();
1609
- assertSameSession();
1610
- const authorizedProjectId = projectId ?? requireScopedProject();
1611
- assert$1(accessToken, KeboolaErrorType.NotAuthenticated);
1612
- return {
1613
- [HttpHeader.AUTHORIZATION]: `Bearer ${accessToken}`,
1614
- [KeboolaHttpHeader.PROJECT_ID]: String(authorizedProjectId)
1615
- };
1616
- },
1617
- restore: async () => {
1618
- const persisted = persistor.hydrate();
1619
- if (!persisted.refreshToken || !persisted.baseUrl) return { status: "empty" };
1620
- const configured = config.getBaseUrl();
1621
- if (configured && configured !== persisted.baseUrl) {
1622
- persistor.clear();
1623
- return { status: "empty" };
1624
- }
1625
- if (!configured) config.setBaseUrl(persisted.baseUrl);
1626
- const client = authClientBare.get();
1627
- assert$1(client, KeboolaErrorType.NotReady);
1628
- const startedOn = config.getEpoch();
1629
- try {
1630
- const refreshed = await client.token.refresh(persisted.refreshToken);
1631
- if (config.getEpoch() !== startedOn) return { status: "empty" };
1632
- config.authenticate(refreshed);
1633
- if (persisted.projectId !== null) {
1634
- config.setProjectId(persisted.projectId);
1635
- await projectClientsAsync.settled();
1636
- }
1637
- return { status: "restored" };
1638
- } catch (err) {
1639
- if (config.getEpoch() !== startedOn) return { status: "empty" };
1640
- if (isUnauthorized(err)) {
1641
- persistor.clear();
1642
- return { status: "expired" };
1643
- }
1644
- throw err;
1645
- }
1646
- },
1647
- subscribe: (listener) => {
1648
- const unsubscribeConfig = config.store.subscribe(() => listener(debug()));
1649
- const unsubscribeBuild = projectClientsAsync.store.subscribe(() => listener(debug()));
1650
- return () => {
1651
- unsubscribeConfig();
1652
- unsubscribeBuild();
1653
- };
1654
- },
1655
- debug
1656
- };
1657
- return {
1658
- api: createApi({
1659
- getAuthClient: () => authClient.get(),
1660
- getManagementClient: () => management.get(),
1661
- getProjectClients: () => {
1662
- const state = projectClientsAsync.store.get();
1663
- return state.state === "ready" ? state.value : null;
1664
- }
1665
- }),
1666
- session
1667
- };
1668
- };
1669
- //#endregion
1670
- //#region src/keboola/legacy/createConfig.ts
1671
- const createConfig = () => {
1672
- const store = createStore({
1673
- baseUrl: null,
1674
- sapiToken: null,
1675
- managementToken: null
1676
- });
1677
- const setBaseUrl = (baseUrl) => {
1678
- store.set({
1679
- ...store.get(),
1680
- baseUrl
1681
- });
1682
- };
1683
- const authenticate = (tokens) => {
1684
- const current = store.get();
1685
- store.set({
1686
- ...current,
1687
- sapiToken: tokens.sapiToken ?? current.sapiToken,
1688
- managementToken: tokens.managementToken ?? current.managementToken
1689
- });
1690
- };
1691
- const getStorageToken = () => store.get().sapiToken ?? "";
1692
- const setStorageToken = (sapiToken) => store.set({
1693
- ...store.get(),
1694
- sapiToken
1695
- });
1696
- /** Current state, for diagnostics. */
1697
- const debug = () => store.get();
1698
- return {
1699
- store,
1700
- setBaseUrl,
1701
- authenticate,
1702
- getStorageToken,
1703
- setStorageToken,
1704
- debug
1705
- };
1706
- };
1707
- //#endregion
1708
- //#region src/keboola/legacy/createProjectClients.ts
1709
- const createAttachStorageToken = (getToken) => (next) => (request) => {
1710
- request.request.headers.set(KeboolaHttpHeader.STORAGE_API_TOKEN, getToken());
1711
- return next(request);
1712
- };
1713
- const createProjectClients = async ({ baseUrl, getStorageToken, onStorageTokenRefreshed, middlewareFor, clientServiceUrls }) => {
1714
- const auth = {
1715
- type: "sapi-token",
1716
- token: getStorageToken()
1717
- };
1718
- const attach = createAttachStorageToken(getStorageToken);
1719
- const _storage = createStorageClient({
1720
- baseUrl,
1721
- auth,
1722
- middlewares: [attach]
1723
- });
1724
- const [stackInfo, sapiToken, devBranches] = await Promise.all([
1725
- _storage.getStackInfo({ exclude: "componentDetails" }),
1726
- _storage.tokens.verify(),
1727
- _storage.branches.getDevBranches()
1728
- ]);
1729
- const stack = createStack({
1730
- stackInfo,
1731
- clientServiceUrls
1732
- });
1733
- const defaultBranch = createDefaultBranch({ devBranches });
1734
- const liveProject = createLiveProject({
1735
- initialToken: sapiToken,
1736
- verify: () => _storage.tokens.verify()
1737
- });
1738
- const storageTableStore = createDerivedStore({
1739
- source: liveProject.store,
1740
- build: createStorageTable,
1741
- dependsOn: (project) => ({
1742
- useLegacyBucketPrefix: !project.hasFeature(ProjectFeature.DisableLegacyBucketPrefix),
1743
- hasProtectedDefaultBranch: project.hasFeature(ProjectFeature.SoxProtectedDefaultBranch),
1744
- hasStorageBranches: project.hasFeature(ProjectFeature.StorageBranches)
1745
- })
1746
- });
1747
- const context = {
1748
- baseUrl: normalizeBaseUrl(baseUrl),
1749
- stack,
1750
- defaultBranch,
1751
- get project() {
1752
- return liveProject.getProject();
1753
- },
1754
- get st() {
1755
- return storageTableStore.get();
1756
- }
1757
- };
1758
- const storage = createStorageClient({
1759
- baseUrl,
1760
- auth,
1761
- middlewares: middlewareFor("storage", [liveProject.middleware]),
1762
- onRefreshToken: onStorageTokenRefreshed
954
+ middlewares: middlewareFor("storage", [liveProject.middleware]),
955
+ onRefreshToken: onStorageTokenRefreshed
1763
956
  });
1764
957
  const { client: services, meta: serviceMeta } = createServiceClients({
1765
958
  baseUrl,
@@ -1776,6 +969,7 @@ const createProjectClients = async ({ baseUrl, getStorageToken, onStorageTokenRe
1776
969
  }),
1777
970
  tag: createTagSdk({ metastoreClient: services.metastore }),
1778
971
  semanticLayer: createSemanticLayerSdk({ metastoreClient: services.metastore }),
972
+ kaiMemory: createKaiMemorySdk({ metastoreClient: services.metastore }),
1779
973
  storage: createStorageSdk({ storageClient: storage }),
1780
974
  vault: createVaultSdk({
1781
975
  vaultClient: services.vault,
@@ -1873,6 +1067,1407 @@ const createLegacyKeboola = (options = {}) => {
1873
1067
  };
1874
1068
  };
1875
1069
  //#endregion
1876
- export { ApiError, HtmlResponseError, HttpContentType, HttpHeader, KeboolaError, KeboolaErrorType, KeboolaHttpHeader, ManagementClientAuthError, QueryJobError, QueryJobTimeoutError, Result, ServiceUnavailableError, SyncActionError, UserError, ValidationError, asError, assert, coalesce, collect, concurrent, createDerivedAsyncStore, createDerivedStore, createEmitter, createGenericFetchClient, createKeboola, createLegacyKeboola, createLocalStorage, createLoggingMiddleware, createMemoryStorage, createNullStorage, createPersistor, createPollRegistry, createQueryServiceSdk, createRetryMiddleware, createSessionStorage, createStorageSdk, createStore, dedupe, deepMerge, delay, emitter, failureOf, formatValidationIssues, generateUUID, isAbortError, isApiError, isEmptyDeep, isFetchClientError, isHtmlResponseError, isKeboolaError, isManagementClientAuthError, isPlainObject, isQueryJobError, isQueryJobTimeoutError, isStorageTokenMutatingRequest, isSyncActionError, isTimeoutError, isValidationError, jobStatus, keboolaUID, lazy, parseLogLines, parseOrThrow, poll, poller, readableReason, schemaGuidedMerge, series, shallowEqual };
1070
+ //#region src/keboola/bearer/credentials/renewal.ts
1071
+ const renewalGrant = (credential) => credential.type === "token" ? {
1072
+ type: "token",
1073
+ refreshToken: credential.refreshToken
1074
+ } : {
1075
+ type: "cookie",
1076
+ sessionId: credential.sessionId
1077
+ };
1078
+ const renew = async (client, grant) => {
1079
+ if (grant.type === "cookie") {
1080
+ const { accessToken, expiresIn, sessionId } = await client.token.refreshWithSession({ sessionId: grant.sessionId });
1081
+ return {
1082
+ type: "cookie",
1083
+ accessToken,
1084
+ expiresIn,
1085
+ sessionId
1086
+ };
1087
+ }
1088
+ const { accessToken, expiresIn, refreshToken } = await client.token.refreshWithToken({ refreshToken: grant.refreshToken });
1089
+ if (!refreshToken) throw new KeboolaError(KeboolaErrorType.NotAuthenticated);
1090
+ return {
1091
+ type: "token",
1092
+ accessToken,
1093
+ expiresIn,
1094
+ refreshToken
1095
+ };
1096
+ };
1097
+ //#endregion
1098
+ //#region src/keboola/bearer/credentials/credentials.ts
1099
+ const DEFAULT_REFRESH_THRESHOLD = .9;
1100
+ const signInEnded = () => new KeboolaError(KeboolaErrorType.SignInEnded);
1101
+ const createCredentials = ({ state, persistor, middlewares, mode = "token", refreshThreshold = DEFAULT_REFRESH_THRESHOLD, onSignedOut }) => {
1102
+ const rotationMap = /* @__PURE__ */ new Map();
1103
+ const generations = /* @__PURE__ */ new Map();
1104
+ const generationOf = (baseUrl) => generations.get(baseUrl) ?? 0;
1105
+ const refresh = async (baseUrl, grant) => {
1106
+ const client = createAuthClient({
1107
+ baseUrl,
1108
+ middlewares
1109
+ });
1110
+ const epochBefore = Result.unwrap(state.auth.getEpoch(baseUrl));
1111
+ const generationBefore = generationOf(baseUrl);
1112
+ const refreshed = await Result.tryCatchAsync(() => renew(client, grant));
1113
+ return Result.unwrapOr(state.auth.getEpoch(baseUrl), -1) === epochBefore && generationOf(baseUrl) === generationBefore ? refreshed : Result.failure(signInEnded());
1114
+ };
1115
+ /**
1116
+ * A stack's teardown, from the credential's side.
1117
+ *
1118
+ * - Bumps the generation, so an in-flight rotation can no longer write.
1119
+ * - Drops the deduped entry, so nothing joins that rotation.
1120
+ */
1121
+ const forget = (baseUrl) => {
1122
+ generations.set(baseUrl, generationOf(baseUrl) + 1);
1123
+ rotationMap.delete(baseUrl);
1124
+ };
1125
+ /**
1126
+ * The rotation, and the one place a credential is declared dead.
1127
+ *
1128
+ * - A refused refresh token or session is unambiguous.
1129
+ * - The triggering 401 is not (an unreachable project answers the same), so never sign out on a replay.
1130
+ */
1131
+ const rotateOnce = async (baseUrl) => {
1132
+ const credential = state.auth.requireCredentialOf(baseUrl, mode);
1133
+ if (!credential.success) return credential;
1134
+ const refreshed = await refresh(baseUrl, renewalGrant(credential.data));
1135
+ if (!refreshed.success) {
1136
+ if (isUnauthorized(refreshed.error)) expire(baseUrl);
1137
+ return refreshed;
1138
+ }
1139
+ return Result.map(state.auth.applyRefresh(baseUrl, refreshed.data), () => refreshed.data.accessToken);
1140
+ };
1141
+ const rotate = (baseUrl) => ensure(rotationMap, baseUrl, () => dedupe(() => rotateOnce(baseUrl)))();
1142
+ const restoreStack = async (baseUrl, grant) => {
1143
+ if (!state.auth.startRestore(baseUrl).success) return "unreachable";
1144
+ const refreshed = await refresh(baseUrl, grant);
1145
+ if (!refreshed.success) {
1146
+ state.auth.cancelRestore(baseUrl);
1147
+ return isUnauthorized(refreshed.error) ? "refused" : "unreachable";
1148
+ }
1149
+ state.auth.authenticate(baseUrl, refreshed.data);
1150
+ return "restored";
1151
+ };
1152
+ const restoreProjects = (baseUrl, projects) => {
1153
+ for (const { projectId } of projects) state.projects.open(baseUrl, projectId);
1154
+ };
1155
+ /**
1156
+ * Every persisted stack back into the table, with whatever credential it can hand back.
1157
+ *
1158
+ * - Never writes the scope. `lastActive` is what was scoped when the session was stored, for the
1159
+ * caller to select.
1160
+ * - `status` reports what became of `lastActive`'s credential; the client reads it to decide
1161
+ * when persistence may start.
1162
+ */
1163
+ const restore = async () => {
1164
+ const hydrated = persistor.hydrate();
1165
+ const stacks = hydrated.stacks.map((stack) => stack.credential && stack.credential.type !== "static" && stack.credential.type !== mode ? {
1166
+ ...stack,
1167
+ credential: null
1168
+ } : stack);
1169
+ const { current } = hydrated;
1170
+ const scoped = stacks.find(({ baseUrl }) => baseUrl === current?.baseUrl);
1171
+ const restored = stacks.map(async ({ baseUrl, credential, projects }) => {
1172
+ state.stacks.ensure(baseUrl);
1173
+ if (!credential) return "unreachable";
1174
+ if (Result.unwrapOr(state.auth.getEpoch(baseUrl), 0) > 0) return "skipped";
1175
+ const outcome = credential.type === "static" ? state.auth.authenticate(baseUrl, credential).success ? "restored" : "refused" : await restoreStack(baseUrl, credential);
1176
+ if (outcome === "restored") restoreProjects(baseUrl, projects);
1177
+ return outcome;
1178
+ });
1179
+ const results = await Promise.all(restored);
1180
+ const outcome = scoped?.credential ? results[stacks.indexOf(scoped)] : void 0;
1181
+ return {
1182
+ lastActive: current,
1183
+ status: outcome === void 0 || outcome === "skipped" ? "empty" : outcome === "restored" ? "restored" : outcome === "unreachable" ? "unreachable" : "expired"
1184
+ };
1185
+ };
1186
+ const isStale = (baseUrl) => {
1187
+ const ageing = Result.map(state.auth.requireCredentialOf(baseUrl, mode), ({ issuedAt, expiresIn }) => Date.now() >= issuedAt + expiresIn * 1e3 * refreshThreshold);
1188
+ return Result.unwrapOr(ageing, false);
1189
+ };
1190
+ const signOut = (baseUrl) => {
1191
+ rotationMap.delete(baseUrl);
1192
+ const signedOut = state.auth.signOut(baseUrl);
1193
+ onSignedOut?.(baseUrl);
1194
+ return signedOut;
1195
+ };
1196
+ const expire = (baseUrl) => {
1197
+ if (state.auth.notifyExpired(baseUrl)) signOut(baseUrl);
1198
+ };
1199
+ const canRefresh = (baseUrl) => state.auth.requireCredentialOf(baseUrl, mode).success;
1200
+ const middleware = (baseUrl) => createBearerAuthMiddleware({ getAccessToken: async ({ forceRefresh = false } = {}) => {
1201
+ if (forceRefresh) return canRefresh(baseUrl) ? Result.unwrap(await rotate(baseUrl)) : null;
1202
+ if (!isStale(baseUrl)) return state.auth.getAccessToken(baseUrl);
1203
+ return Result.unwrapOr(await rotate(baseUrl), state.auth.getAccessToken(baseUrl));
1204
+ } });
1205
+ return {
1206
+ middleware,
1207
+ rotate,
1208
+ restore,
1209
+ signOut,
1210
+ forget
1211
+ };
1212
+ };
1213
+ //#endregion
1214
+ //#region src/keboola/bearer/state/factories.ts
1215
+ /**
1216
+ * Everything the table constructs: the entries themselves, and the failures reading them produces.
1217
+ *
1218
+ * Nothing here touches the store — a factory takes what it is told and returns a value, so the
1219
+ * namespaces the tables build on can be read without following a dependency.
1220
+ */
1221
+ const projectEntryId = (baseUrl, projectId) => `${baseUrl}#${projectId}`;
1222
+ /** What every project entry of one stack shares — the one thing a per-stack teardown matches on. */
1223
+ const projectEntryPrefix = (baseUrl) => `${baseUrl}#`;
1224
+ const isUnderStack = (baseUrl) => (id) => id.startsWith(projectEntryPrefix(baseUrl));
1225
+ const anonymousAuth = () => ({ status: "anonymous" });
1226
+ const restoringAuth = () => ({ status: "restoring" });
1227
+ const authenticatedAuth = (credential) => ({
1228
+ status: "authenticated",
1229
+ credential
1230
+ });
1231
+ const bearerCredential = (input) => input.type === "static" ? input : {
1232
+ ...input,
1233
+ issuedAt: Date.now()
1234
+ };
1235
+ const expiredCredential = (credential) => ({
1236
+ ...credential,
1237
+ issuedAt: Date.now() - credential.expiresIn * 1e3
1238
+ });
1239
+ const stack = (baseUrl) => ({
1240
+ baseUrl,
1241
+ context: "idle",
1242
+ epoch: 0,
1243
+ auth: anonymousAuth()
1244
+ });
1245
+ const project = (baseUrl, projectId) => ({
1246
+ id: projectEntryId(baseUrl, projectId),
1247
+ baseUrl,
1248
+ projectId,
1249
+ context: "idle"
1250
+ });
1251
+ const stackAddress = (baseUrl) => ({
1252
+ baseUrl,
1253
+ projectId: null
1254
+ });
1255
+ const projectAddress = (baseUrl, projectId) => ({
1256
+ baseUrl,
1257
+ projectId
1258
+ });
1259
+ const table = (defaultBaseUrl) => ({
1260
+ active: stackAddress(defaultBaseUrl),
1261
+ stacks: { [defaultBaseUrl]: stack(defaultBaseUrl) },
1262
+ projects: {}
1263
+ });
1264
+ const Entry = {
1265
+ projectEntryId,
1266
+ isUnderStack,
1267
+ stack,
1268
+ project,
1269
+ stackAddress,
1270
+ projectAddress,
1271
+ table,
1272
+ anonymousAuth,
1273
+ restoringAuth,
1274
+ authenticatedAuth,
1275
+ bearerCredential,
1276
+ expiredCredential
1277
+ };
1278
+ /**
1279
+ * Every failure the table can produce.
1280
+ *
1281
+ * - The typed ones carry a `KeboolaErrorType` a consumer branches on; the rest are plain `Error`s
1282
+ * whose message names the entry, because nothing branches on them.
1283
+ */
1284
+ const Errors = {
1285
+ notAuthenticated: () => new KeboolaError(KeboolaErrorType.NotAuthenticated),
1286
+ stackActive: () => new KeboolaError(KeboolaErrorType.StackActive),
1287
+ /** A stack that was never opened — nothing has been configured for it. */
1288
+ unconfigured: () => new KeboolaError(KeboolaErrorType.Unconfigured),
1289
+ alreadyAuthenticated: () => new KeboolaError(KeboolaErrorType.AlreadyAuthenticated),
1290
+ notReady: () => new KeboolaError(KeboolaErrorType.NotReady),
1291
+ alreadyRestoring: (baseUrl) => /* @__PURE__ */ new Error(`Stack "${baseUrl}" is already being restored`),
1292
+ notRestoring: (baseUrl) => /* @__PURE__ */ new Error(`Stack "${baseUrl}" is not being restored`),
1293
+ unexpectedCredentialKind: (baseUrl, kind) => /* @__PURE__ */ new Error(`Stack "${baseUrl}" holds a ${kind} credential`),
1294
+ notRotatingCredential: (baseUrl) => /* @__PURE__ */ new Error(`Stack "${baseUrl}" holds a static credential`),
1295
+ credentialKindChanged: (from, to) => /* @__PURE__ */ new Error(`A ${from} credential cannot become ${to}`),
1296
+ missingProject: (id) => /* @__PURE__ */ new Error(`No project "${id}"`)
1297
+ };
1298
+ const authenticated = (auth) => auth.status === "authenticated" ? Result.success(auth.credential) : Result.failure(Errors.notAuthenticated());
1299
+ //#endregion
1300
+ //#region src/keboola/bearer/state/auth.ts
1301
+ /**
1302
+ * Fire-once per sign-in: the first report of a dead credential returns `true`, the rest `false`,
1303
+ * and `authenticate` re-arms it. Held beside the table because it is not state anyone restores.
1304
+ */
1305
+ const createExpiryLatch = () => {
1306
+ const notified = /* @__PURE__ */ new Map();
1307
+ return {
1308
+ arm: (baseUrl) => notified.set(baseUrl, false),
1309
+ forget: (baseUrl) => notified.delete(baseUrl),
1310
+ report: (baseUrl) => {
1311
+ if (notified.get(baseUrl)) return false;
1312
+ notified.set(baseUrl, true);
1313
+ return true;
1314
+ }
1315
+ };
1316
+ };
1317
+ /**
1318
+ * The stack's credential and its sign-in pin.
1319
+ *
1320
+ * - `epoch` moves on `authenticate` and `signOut` and never on a rotation, so it is exactly "which
1321
+ * sign-in is this" — what an in-flight exchange compares itself against.
1322
+ */
1323
+ const createAuth = ({ stacks, projects, expiry }) => {
1324
+ const requireUnauthenticated = (baseUrl) => Result.andThen(stacks.get(baseUrl), (stack) => stack.auth.status === "authenticated" ? Result.failure(Errors.alreadyAuthenticated()) : Result.success(stack));
1325
+ const requireAnonymous = (baseUrl) => Result.andThen(requireUnauthenticated(baseUrl), (stack) => stack.auth.status === "restoring" ? Result.failure(Errors.alreadyRestoring(baseUrl)) : Result.success(stack));
1326
+ const requireRestoring = (baseUrl) => Result.andThen(stacks.get(baseUrl), (stack) => stack.auth.status === "restoring" ? Result.success(stack) : Result.failure(Errors.notRestoring(baseUrl)));
1327
+ const requireRotatingCredential = (baseUrl) => Result.andThen(stacks.requireCredential(baseUrl), (credential) => credential.type === "static" ? Result.failure(Errors.notRotatingCredential(baseUrl)) : Result.success(credential));
1328
+ const requireCredentialOf = (baseUrl, mode) => Result.andThen(requireRotatingCredential(baseUrl), (credential) => credential.type === mode ? Result.success(credential) : Result.failure(Errors.unexpectedCredentialKind(baseUrl, credential.type)));
1329
+ const startRestore = (baseUrl) => Result.map(requireAnonymous(baseUrl), (stack) => stacks.set({
1330
+ ...stack,
1331
+ auth: Entry.restoringAuth()
1332
+ }));
1333
+ const cancelRestore = (baseUrl) => Result.map(requireRestoring(baseUrl), (stack) => stacks.set({
1334
+ ...stack,
1335
+ auth: Entry.anonymousAuth()
1336
+ }));
1337
+ const authenticate = (baseUrl, input) => Result.map(requireUnauthenticated(baseUrl), (stack) => {
1338
+ expiry.arm(baseUrl);
1339
+ return stacks.set({
1340
+ ...stack,
1341
+ epoch: stack.epoch + 1,
1342
+ auth: Entry.authenticatedAuth(Entry.bearerCredential(input))
1343
+ });
1344
+ });
1345
+ const applyRefresh = (baseUrl, input) => Result.andThen(requireRotatingCredential(baseUrl), (credential) => credential.type !== input.type ? Result.failure(Errors.credentialKindChanged(credential.type, input.type)) : Result.map(stacks.get(baseUrl), (stack) => stacks.set({
1346
+ ...stack,
1347
+ auth: Entry.authenticatedAuth(Entry.bearerCredential(input))
1348
+ })));
1349
+ const forceExpire = (baseUrl) => Result.andThen(requireRotatingCredential(baseUrl), (credential) => Result.map(stacks.get(baseUrl), (stack) => stacks.set({
1350
+ ...stack,
1351
+ auth: Entry.authenticatedAuth(Entry.expiredCredential(credential))
1352
+ })));
1353
+ const signOut = (baseUrl) => Result.map(stacks.get(baseUrl), (stack) => {
1354
+ projects.closeAll(baseUrl);
1355
+ return stacks.set({
1356
+ ...stack,
1357
+ epoch: stack.epoch + 1,
1358
+ auth: Entry.anonymousAuth()
1359
+ });
1360
+ });
1361
+ const getEpoch = (baseUrl) => Result.map(stacks.get(baseUrl), (stack) => stack.epoch);
1362
+ const getAccessToken = (baseUrl) => Result.unwrapOr(Result.map(stacks.requireCredential(baseUrl), ({ accessToken }) => accessToken), null);
1363
+ return {
1364
+ startRestore,
1365
+ cancelRestore,
1366
+ authenticate,
1367
+ applyRefresh,
1368
+ forceExpire,
1369
+ signOut,
1370
+ notifyExpired: expiry.report,
1371
+ requireCredential: stacks.requireCredential,
1372
+ requireRotatingCredential,
1373
+ requireCredentialOf,
1374
+ getEpoch,
1375
+ getAccessToken
1376
+ };
1377
+ };
1378
+ //#endregion
1379
+ //#region src/keboola/bearer/state/projects.ts
1380
+ /** The projects open under a stack, and what authorizes a request to one. */
1381
+ const createProjects = ({ store, stacks }) => {
1382
+ const has = (id) => id in store.get().projects;
1383
+ const get = (id) => {
1384
+ const project = store.get().projects[id];
1385
+ return project ? Result.success(project) : Result.failure(Errors.missingProject(id));
1386
+ };
1387
+ const list = (baseUrl) => Object.values(store.get().projects).filter((project) => project.baseUrl === baseUrl);
1388
+ /** Every open project with this id, whatever stack it sits on — a project number is not unique. */
1389
+ const findAll = (projectId) => Object.values(store.get().projects).filter((project) => project.projectId === projectId);
1390
+ const set = (project) => {
1391
+ const state = store.get();
1392
+ store.set({
1393
+ ...state,
1394
+ projects: {
1395
+ ...state.projects,
1396
+ [project.id]: project
1397
+ }
1398
+ });
1399
+ return project;
1400
+ };
1401
+ const update = (id, updater) => Result.map(get(id), (project) => set(updater(project)));
1402
+ const removeMany = (ids, nextActive) => {
1403
+ const state = store.get();
1404
+ const projects = { ...state.projects };
1405
+ for (const id of ids) delete projects[id];
1406
+ store.set({
1407
+ ...state,
1408
+ active: nextActive,
1409
+ projects
1410
+ });
1411
+ };
1412
+ const requireCredential = (id) => Result.andThen(get(id), (project) => stacks.requireCredential(project.baseUrl));
1413
+ const open = (baseUrl, projectId) => {
1414
+ const id = Entry.projectEntryId(baseUrl, projectId);
1415
+ if (has(id)) return get(id);
1416
+ return Result.map(stacks.requireCredential(baseUrl), () => set(Entry.project(baseUrl, projectId)));
1417
+ };
1418
+ const close = (id) => Result.tap(get(id), ({ baseUrl, projectId }) => {
1419
+ const { active } = store.get();
1420
+ const isScoped = active.baseUrl === baseUrl && active.projectId === projectId;
1421
+ removeMany([id], isScoped ? Entry.stackAddress(baseUrl) : active);
1422
+ });
1423
+ /** Every project under a stack, with the scope falling back to the stack itself. */
1424
+ const closeAll = (baseUrl) => {
1425
+ const ids = list(baseUrl).map((project) => project.id);
1426
+ const { active } = store.get();
1427
+ removeMany(ids, active.baseUrl === baseUrl ? Entry.stackAddress(baseUrl) : active);
1428
+ };
1429
+ const updateContext = (id, context) => update(id, (project) => ({
1430
+ ...project,
1431
+ context
1432
+ }));
1433
+ return {
1434
+ has,
1435
+ get,
1436
+ list,
1437
+ findAll,
1438
+ set,
1439
+ update,
1440
+ open,
1441
+ close,
1442
+ closeAll,
1443
+ updateContext,
1444
+ requireCredential
1445
+ };
1446
+ };
1447
+ //#endregion
1448
+ //#region src/keboola/bearer/state/scope.ts
1449
+ /**
1450
+ * What `api.*` addresses: the `active` slot, and the address in it resolved against the tables it
1451
+ * points into.
1452
+ *
1453
+ * The tables never write here — they read `active` through the pure helpers in `address.ts`, so
1454
+ * that this can depend on them rather than the other way round.
1455
+ */
1456
+ const createScope = ({ store, stacks, projects }) => {
1457
+ const get = () => store.get().active;
1458
+ const isSame = (a, b) => a === b || a.baseUrl === b.baseUrl && a.projectId === b.projectId;
1459
+ const set = (active) => {
1460
+ if (isSame(store.get().active, active)) return;
1461
+ store.set({
1462
+ ...store.get(),
1463
+ active
1464
+ });
1465
+ };
1466
+ const locate = (active) => {
1467
+ const stack = stacks.get(active.baseUrl);
1468
+ if (!stack.success) return null;
1469
+ if (active.projectId === null) return {
1470
+ stack: stack.data,
1471
+ project: null
1472
+ };
1473
+ const project = projects.get(Entry.projectEntryId(active.baseUrl, active.projectId));
1474
+ if (!project.success) return null;
1475
+ return {
1476
+ stack: stack.data,
1477
+ project: project.data
1478
+ };
1479
+ };
1480
+ const getActive = () => {
1481
+ const location = locate(get());
1482
+ if (!location) throw new Error(`The scope names no row: ${JSON.stringify(get())}`);
1483
+ return location;
1484
+ };
1485
+ const getActiveStack = () => getActive().stack;
1486
+ const activateStack = (baseUrl) => Result.map(stacks.get(baseUrl), (stack) => {
1487
+ const next = Entry.stackAddress(stack.baseUrl);
1488
+ set(next);
1489
+ return next;
1490
+ });
1491
+ const activateProject = (baseUrl, projectId) => Result.map(projects.requireCredential(Entry.projectEntryId(baseUrl, projectId)), () => {
1492
+ const next = Entry.projectAddress(baseUrl, projectId);
1493
+ set(next);
1494
+ return next;
1495
+ });
1496
+ const selectStack = (baseUrl) => {
1497
+ const stack = stacks.ensure(baseUrl);
1498
+ return Result.map(activateStack(stack.baseUrl), () => stack);
1499
+ };
1500
+ const selectProject = (projectId) => {
1501
+ const { baseUrl } = getActiveStack();
1502
+ const project = projects.open(baseUrl, projectId);
1503
+ if (!project.success) return project;
1504
+ return Result.map(activateProject(baseUrl, projectId), () => project.data);
1505
+ };
1506
+ const deactivate = () => {
1507
+ const active = get();
1508
+ if (active.projectId === null) return;
1509
+ set(Entry.stackAddress(active.baseUrl));
1510
+ };
1511
+ const requireActiveProject = () => {
1512
+ const { project } = getActive();
1513
+ return project ? Result.success(project) : Result.failure(Errors.notReady());
1514
+ };
1515
+ return {
1516
+ get,
1517
+ getActive,
1518
+ activateStack,
1519
+ activateProject,
1520
+ selectStack,
1521
+ selectProject,
1522
+ deactivate,
1523
+ getActiveStack,
1524
+ requireActiveProject
1525
+ };
1526
+ };
1527
+ //#endregion
1528
+ //#region src/keboola/bearer/state/stacks.ts
1529
+ /** One entry per stack: the entries, and the verbs that open and close them. */
1530
+ const createStacks = ({ store, forgetExpiry }) => {
1531
+ const has = (baseUrl) => baseUrl in store.get().stacks;
1532
+ const get = (baseUrl) => {
1533
+ const stack = store.get().stacks[baseUrl];
1534
+ return stack ? Result.success(stack) : Result.failure(Errors.unconfigured());
1535
+ };
1536
+ const list = () => Object.values(store.get().stacks);
1537
+ const set = (stack) => {
1538
+ const state = store.get();
1539
+ store.set({
1540
+ ...state,
1541
+ stacks: {
1542
+ ...state.stacks,
1543
+ [stack.baseUrl]: stack
1544
+ }
1545
+ });
1546
+ return stack;
1547
+ };
1548
+ const update = (baseUrl, updater) => Result.map(get(baseUrl), (stack) => set(updater(stack)));
1549
+ const requireCredential = (baseUrl) => Result.andThen(get(baseUrl), (stack) => authenticated(stack.auth));
1550
+ const ensure = (baseUrl) => {
1551
+ const existing = get(baseUrl);
1552
+ if (existing.success) return existing.data;
1553
+ return set(Entry.stack(baseUrl));
1554
+ };
1555
+ const close = (baseUrl) => {
1556
+ const stack = get(baseUrl);
1557
+ if (!stack.success) return stack;
1558
+ const state = store.get();
1559
+ if (state.active.baseUrl === baseUrl) return Result.failure(Errors.stackActive());
1560
+ const stacks = { ...state.stacks };
1561
+ delete stacks[baseUrl];
1562
+ const projects = Object.fromEntries(Object.entries(state.projects).filter(([, project]) => project.baseUrl !== baseUrl));
1563
+ store.set({
1564
+ active: state.active,
1565
+ stacks,
1566
+ projects
1567
+ });
1568
+ forgetExpiry(baseUrl);
1569
+ return stack;
1570
+ };
1571
+ const updateContext = (baseUrl, context) => update(baseUrl, (stack) => ({
1572
+ ...stack,
1573
+ context
1574
+ }));
1575
+ return {
1576
+ has,
1577
+ get,
1578
+ list,
1579
+ set,
1580
+ update,
1581
+ ensure,
1582
+ close,
1583
+ updateContext,
1584
+ requireCredential
1585
+ };
1586
+ };
1587
+ //#endregion
1588
+ //#region src/keboola/bearer/state/state.ts
1589
+ /**
1590
+ * The stack table and the rules over it, one namespace per concern.
1591
+ *
1592
+ * - Built in dependency order: a project reads its stack's credential, and the scope resolves
1593
+ * the active address against both tables.
1594
+ */
1595
+ const createState = (defaultBaseUrl) => {
1596
+ const store = createStore(Entry.table(defaultBaseUrl));
1597
+ const expiry = createExpiryLatch();
1598
+ const stacks = createStacks({
1599
+ store,
1600
+ forgetExpiry: expiry.forget
1601
+ });
1602
+ const projects = createProjects({
1603
+ store,
1604
+ stacks
1605
+ });
1606
+ const scope = createScope({
1607
+ store,
1608
+ stacks,
1609
+ projects
1610
+ });
1611
+ const auth = createAuth({
1612
+ stacks,
1613
+ projects,
1614
+ expiry
1615
+ });
1616
+ return {
1617
+ store: store.asReadable(),
1618
+ stacks,
1619
+ projects,
1620
+ auth,
1621
+ scope
1622
+ };
1623
+ };
1624
+ //#endregion
1625
+ //#region src/keboola/bearer/context/resource.ts
1626
+ /**
1627
+ * Owns fetching one async value per key — a caller names what it needs and never orchestrates the
1628
+ * request. Backs the stack and project contexts.
1629
+ *
1630
+ * - One fetch per key: concurrent askers share it, a landed value is never refetched.
1631
+ * - A failure is held, not thrown away — nothing here needs a rejection handler.
1632
+ * - Status lives here and nowhere else; a consumer that has to mirror it subscribes.
1633
+ */
1634
+ const createResource = ({ key, fetch }) => {
1635
+ const entries = /* @__PURE__ */ new Map();
1636
+ const changes = createEmitter();
1637
+ const set = (id, entry) => {
1638
+ entries.set(id, entry);
1639
+ changes.emit({
1640
+ key: id,
1641
+ status: entry.status
1642
+ });
1643
+ };
1644
+ const run = (id, input) => {
1645
+ const settle = (next) => {
1646
+ if (entries.get(id) === entry) set(id, {
1647
+ input,
1648
+ ...next
1649
+ });
1650
+ return next;
1651
+ };
1652
+ const attempt = async () => await fetch(input);
1653
+ const entry = {
1654
+ input,
1655
+ status: "pending",
1656
+ settled: attempt().then((value) => settle({
1657
+ status: "ready",
1658
+ value
1659
+ }), (error) => settle({
1660
+ status: "errored",
1661
+ error
1662
+ }))
1663
+ };
1664
+ set(id, entry);
1665
+ return entry;
1666
+ };
1667
+ const get = (id) => {
1668
+ const entry = entries.get(id);
1669
+ return entry?.status === "ready" ? entry.value : null;
1670
+ };
1671
+ const getAsync = async (input) => {
1672
+ const id = key(input);
1673
+ const cached = entries.get(id);
1674
+ const entry = cached === void 0 || cached.status === "errored" ? run(id, input) : cached;
1675
+ const settled = entry.status === "pending" ? await entry.settled : entry;
1676
+ if (settled.status === "errored") throw settled.error;
1677
+ return settled.value;
1678
+ };
1679
+ const forget = (matches) => {
1680
+ for (const id of entries.keys()) if (matches(id)) entries.delete(id);
1681
+ };
1682
+ const prefetch = (input) => {
1683
+ const id = key(input);
1684
+ if (!entries.has(id)) run(id, input);
1685
+ };
1686
+ const retry = (id) => {
1687
+ const entry = entries.get(id);
1688
+ if (entry !== void 0) run(id, entry.input);
1689
+ };
1690
+ return {
1691
+ get,
1692
+ getAsync,
1693
+ prefetch,
1694
+ retry,
1695
+ forget,
1696
+ subscribe: changes.subscribe
1697
+ };
1698
+ };
1699
+ //#endregion
1700
+ //#region src/keboola/bearer/context/project.ts
1701
+ const createProjectContext = ({ state, credentials, stackContext }) => {
1702
+ const resource = createResource({
1703
+ key: (project) => project.id,
1704
+ fetch: async ({ baseUrl, projectId }) => {
1705
+ const withProjectId = (next) => (request) => {
1706
+ request.request.headers.set(KeboolaHttpHeader.PROJECT_ID, String(projectId));
1707
+ return next(request);
1708
+ };
1709
+ const client = createStorageClient({
1710
+ baseUrl,
1711
+ auth: {
1712
+ type: "bearer",
1713
+ token: "",
1714
+ projectId
1715
+ },
1716
+ middlewares: [(next) => withProjectId(credentials.middleware(baseUrl)(next))]
1717
+ });
1718
+ const [token, devBranches] = await Promise.all([
1719
+ client.tokens.verify(),
1720
+ client.branches.getDevBranches(),
1721
+ stackContext.getAsync(baseUrl)
1722
+ ]);
1723
+ return {
1724
+ token,
1725
+ defaultBranch: createDefaultBranch({ devBranches })
1726
+ };
1727
+ }
1728
+ });
1729
+ resource.subscribe(({ key, status }) => {
1730
+ state.projects.updateContext(key, status);
1731
+ });
1732
+ const subscriber = ({ projects }) => {
1733
+ for (const project of Object.values(projects)) resource.prefetch(project);
1734
+ };
1735
+ /**
1736
+ * Dropped with the sign-in that fetched them: a verified token is what a credential answered
1737
+ * for, so it belongs to that credential and not to the project id it was keyed by.
1738
+ */
1739
+ const forgetUnder = (baseUrl) => resource.forget(Entry.isUnderStack(baseUrl));
1740
+ /** One project, closed on purpose. */
1741
+ const forget = (id) => resource.forget((key) => key === id);
1742
+ return {
1743
+ subscriber,
1744
+ get: resource.get,
1745
+ getAsync: resource.getAsync,
1746
+ retry: resource.retry,
1747
+ forget,
1748
+ forgetUnder
1749
+ };
1750
+ };
1751
+ //#endregion
1752
+ //#region src/keboola/bearer/context/stack.ts
1753
+ const createStackContext = (state) => {
1754
+ const resource = createResource({
1755
+ key: (baseUrl) => baseUrl,
1756
+ fetch: (baseUrl) => createStorageClient({
1757
+ baseUrl,
1758
+ auth: {
1759
+ type: "sapi-token",
1760
+ token: ""
1761
+ }
1762
+ }).getStackInfo({ exclude: "componentDetails" })
1763
+ });
1764
+ resource.subscribe(({ key, status }) => {
1765
+ state.stacks.updateContext(key, status);
1766
+ });
1767
+ const subscriber = ({ stacks }) => {
1768
+ for (const { baseUrl } of Object.values(stacks)) resource.prefetch(baseUrl);
1769
+ };
1770
+ /** Dropped with the stack itself — a stack that comes back re-reads its index. */
1771
+ const forget = (baseUrl) => resource.forget((key) => key === baseUrl);
1772
+ return {
1773
+ subscriber,
1774
+ get: resource.get,
1775
+ getAsync: resource.getAsync,
1776
+ retry: resource.retry,
1777
+ forget
1778
+ };
1779
+ };
1780
+ //#endregion
1781
+ //#region src/keboola/bearer/perProject.ts
1782
+ const once = (build) => {
1783
+ let value = null;
1784
+ return () => value ??= build();
1785
+ };
1786
+ /**
1787
+ * Everything one project derives, and the one call that drops it.
1788
+ *
1789
+ * Every field belongs to the credential that built it — a client set carries its middleware chain,
1790
+ * the storage client holds a `liveProject` seeded with its token, a fetched context *is* what it
1791
+ * answered for `tokens.verify` — so the record dies with the sign-in, and `forgetUnder` is the
1792
+ * only thing that ends one.
1793
+ */
1794
+ const createPerProject = ({ state, credentials, middlewareFor, stack, clientServiceUrls, buildApi }) => {
1795
+ const context = createProjectContext({
1796
+ state,
1797
+ credentials,
1798
+ stackContext: stack.context
1799
+ });
1800
+ const attachFor = ({ baseUrl, projectId }) => {
1801
+ const withProjectId = (next) => (request) => {
1802
+ request.request.headers.set(KeboolaHttpHeader.PROJECT_ID, String(projectId));
1803
+ return next(request);
1804
+ };
1805
+ return (next) => withProjectId(credentials.middleware(baseUrl)(next));
1806
+ };
1807
+ const buildClients = ({ baseUrl, projectId }, attach) => createServiceClients({
1808
+ baseUrl,
1809
+ auth: {
1810
+ type: "bearer",
1811
+ token: "",
1812
+ projectId
1813
+ },
1814
+ getServiceBaseUrl: (serviceId) => async () => {
1815
+ const stackInfo = await stack.context.getAsync(baseUrl);
1816
+ const serviceUrl = createStack({
1817
+ stackInfo,
1818
+ clientServiceUrls
1819
+ }).getServiceUrl(serviceId);
1820
+ assert$1(serviceUrl, KeboolaErrorType.NotReady);
1821
+ return serviceUrl;
1822
+ },
1823
+ middlewareFor,
1824
+ attachTokenMiddleware: attach
1825
+ });
1826
+ /**
1827
+ * `api.storage` and `api.context`, built together: both read one live token — the storage client
1828
+ * carries its re-verify middleware, the context reports the project it re-verifies.
1829
+ *
1830
+ * - Both fetches it reads are already running. `NotReady` covers the window before they land,
1831
+ * which the table reports as `project.context`.
1832
+ * - `storage` is gated on the stack index too, though it addresses the project's own `baseUrl`
1833
+ * and does not need it — that is the gate as it stands, not a requirement.
1834
+ */
1835
+ const buildLive = (project, attach) => {
1836
+ const stackInfo = stack.context.get(project.baseUrl);
1837
+ assert$1(stackInfo, KeboolaErrorType.NotReady);
1838
+ const fetched = context.get(project.id);
1839
+ assert$1(fetched, KeboolaErrorType.NotReady);
1840
+ const { baseUrl, projectId } = project;
1841
+ const auth = {
1842
+ type: "bearer",
1843
+ token: "",
1844
+ projectId
1845
+ };
1846
+ const reader = createStorageClient({
1847
+ baseUrl,
1848
+ auth,
1849
+ middlewares: [attach]
1850
+ });
1851
+ const liveProject = createLiveProject({
1852
+ initialToken: fetched.token,
1853
+ verify: () => reader.tokens.verify()
1854
+ });
1855
+ const storageTableStore = createDerivedStore({
1856
+ source: liveProject.store,
1857
+ build: createStorageTable,
1858
+ dependsOn: (live) => ({
1859
+ useLegacyBucketPrefix: !live.hasFeature(ProjectFeature.DisableLegacyBucketPrefix),
1860
+ hasProtectedDefaultBranch: live.hasFeature(ProjectFeature.SoxProtectedDefaultBranch),
1861
+ hasStorageBranches: live.hasFeature(ProjectFeature.StorageBranches)
1862
+ })
1863
+ });
1864
+ return {
1865
+ storage: createStorageClient({
1866
+ baseUrl,
1867
+ auth,
1868
+ middlewares: middlewareFor("storage", [attach, liveProject.middleware])
1869
+ }),
1870
+ context: {
1871
+ baseUrl,
1872
+ stack: createStack({
1873
+ stackInfo,
1874
+ clientServiceUrls
1875
+ }),
1876
+ defaultBranch: fetched.defaultBranch,
1877
+ get project() {
1878
+ return liveProject.getProject();
1879
+ },
1880
+ get st() {
1881
+ return storageTableStore.get();
1882
+ }
1883
+ }
1884
+ };
1885
+ };
1886
+ const build = (project) => {
1887
+ const attach = attachFor(project);
1888
+ const live = once(() => buildLive(project, attach));
1889
+ const clients = once(() => buildClients(project, attach));
1890
+ return {
1891
+ api: buildApi(project),
1892
+ get clients() {
1893
+ return clients();
1894
+ },
1895
+ get storage() {
1896
+ return live().storage;
1897
+ },
1898
+ get context() {
1899
+ return live().context;
1900
+ }
1901
+ };
1902
+ };
1903
+ const derived = /* @__PURE__ */ new Map();
1904
+ const get = (project) => ensure(derived, project.id, () => build(project));
1905
+ /** One project, closed on purpose — a handle for it stops answering from the next read. */
1906
+ const forget = (id) => {
1907
+ derived.delete(id);
1908
+ context.forget(id);
1909
+ };
1910
+ const forgetUnder = (baseUrl) => {
1911
+ const isUnder = Entry.isUnderStack(baseUrl);
1912
+ for (const id of derived.keys()) if (isUnder(id)) derived.delete(id);
1913
+ context.forgetUnder(baseUrl);
1914
+ };
1915
+ return {
1916
+ context,
1917
+ get,
1918
+ forget,
1919
+ forgetUnder
1920
+ };
1921
+ };
1922
+ //#endregion
1923
+ //#region src/keboola/bearer/persistor.ts
1924
+ /**
1925
+ * Where a bearer session is persisted, under whichever adapter the client was given.
1926
+ *
1927
+ * Exported because a consumer sometimes has to drop a session a client cannot reach: the adapter is
1928
+ * chosen at construction, so a client built without one holds no handle to the storage its own
1929
+ * session is sitting in. `AppAuthStrategy` in kbc-ui is that case.
1930
+ */
1931
+ const SESSION_STORAGE_KEY = "keboola:session";
1932
+ /**
1933
+ * What survives a reload, per credential kind.
1934
+ *
1935
+ * - `token`: the refresh token. It rotates, is single-use and is server-revocable, so a leaked
1936
+ * snapshot has limited and revocable value. The access token is never written.
1937
+ * - `static`: the token itself — a long-lived PAT the user pasted, which nothing can re-mint.
1938
+ * - `cookie`: the session id. The session cookie is the durable half and the browser keeps it;
1939
+ * the id alone renews nothing.
1940
+ */
1941
+ const persistedCredentialSchema = z$1.discriminatedUnion("type", [
1942
+ z$1.object({
1943
+ type: z$1.literal("token"),
1944
+ refreshToken: z$1.string()
1945
+ }),
1946
+ z$1.object({
1947
+ type: z$1.literal("cookie"),
1948
+ sessionId: z$1.string()
1949
+ }),
1950
+ z$1.object({
1951
+ type: z$1.literal("static"),
1952
+ accessToken: z$1.string()
1953
+ })
1954
+ ]);
1955
+ /** A record per project rather than a bare id, so a project can grow a field without a migration. */
1956
+ const persistedProjectSchema = z$1.object({ projectId: z$1.number() });
1957
+ const persistedSessionSchema = z$1.object({
1958
+ current: z$1.object({
1959
+ baseUrl: z$1.string(),
1960
+ projectId: z$1.number().nullable()
1961
+ }).nullable(),
1962
+ stacks: z$1.array(z$1.object({
1963
+ baseUrl: z$1.string(),
1964
+ credential: persistedCredentialSchema.nullable(),
1965
+ projects: z$1.array(persistedProjectSchema)
1966
+ }))
1967
+ });
1968
+ const EMPTY_PERSISTED_SESSION = {
1969
+ current: null,
1970
+ stacks: []
1971
+ };
1972
+ const durableCredential = (stack) => {
1973
+ if (stack.auth.status !== "authenticated") return null;
1974
+ const { credential } = stack.auth;
1975
+ if (credential.type === "token") return {
1976
+ type: "token",
1977
+ refreshToken: credential.refreshToken
1978
+ };
1979
+ if (credential.type === "cookie") return {
1980
+ type: "cookie",
1981
+ sessionId: credential.sessionId
1982
+ };
1983
+ return {
1984
+ type: "static",
1985
+ accessToken: credential.accessToken
1986
+ };
1987
+ };
1988
+ const createSessionPersistor = (storage) => {
1989
+ const persistor = createPersistor({
1990
+ storage,
1991
+ key: SESSION_STORAGE_KEY,
1992
+ schema: persistedSessionSchema,
1993
+ defaultValue: EMPTY_PERSISTED_SESSION
1994
+ });
1995
+ const persist = ({ active, stacks, projects }) => persistor.persist({
1996
+ current: {
1997
+ baseUrl: active.baseUrl,
1998
+ projectId: active.projectId
1999
+ },
2000
+ stacks: Object.values(stacks).map((stack) => ({
2001
+ baseUrl: stack.baseUrl,
2002
+ credential: durableCredential(stack),
2003
+ projects: Object.values(projects).filter((project) => project.baseUrl === stack.baseUrl).map(({ projectId }) => ({ projectId }))
2004
+ }))
2005
+ });
2006
+ return {
2007
+ ...persistor,
2008
+ persist
2009
+ };
2010
+ };
2011
+ //#endregion
2012
+ //#region src/keboola/bearer/perStack.ts
2013
+ /**
2014
+ * Everything one stack derives, and the one call that drops it.
2015
+ *
2016
+ * Outlives a sign-out, unlike anything in `perProject`: both clients read the credential live per
2017
+ * request, so neither belongs to one sign-in, and the stack index is public.
2018
+ */
2019
+ const createPerStack = ({ state, credentials, middlewareFor }) => {
2020
+ const context = createStackContext(state);
2021
+ const derived = /* @__PURE__ */ new Map();
2022
+ const get = (baseUrl) => ensure(derived, baseUrl, () => ({
2023
+ auth: createAuthClient({
2024
+ baseUrl,
2025
+ middlewares: middlewareFor("auth", [credentials.middleware(baseUrl)])
2026
+ }),
2027
+ management: createManagementClient({
2028
+ baseUrl,
2029
+ auth: {
2030
+ type: "bearer",
2031
+ token: ""
2032
+ },
2033
+ middlewares: middlewareFor("management", [credentials.middleware(baseUrl)])
2034
+ })
2035
+ }));
2036
+ const forget = (baseUrl) => {
2037
+ derived.delete(baseUrl);
2038
+ context.forget(baseUrl);
2039
+ };
2040
+ return {
2041
+ context,
2042
+ get,
2043
+ forget
2044
+ };
2045
+ };
2046
+ //#endregion
2047
+ //#region src/keboola/bearer/keboola.ts
2048
+ /**
2049
+ * The bearer client: the session table, its two scopes, and the surface they back.
2050
+ *
2051
+ * - Credential-derived state is owned by the scope whose end ends it (`perStack`, `perProject`).
2052
+ */
2053
+ const createKeboola = ({ defaultBaseUrl, storage, middlewares, clientServiceUrls, credentials: mode = "token" }) => {
2054
+ const state = createState(normalizeBaseUrl(defaultBaseUrl));
2055
+ const persistor = createSessionPersistor(storage);
2056
+ const middlewareFor = createMiddlewareFor(middlewares);
2057
+ const credentials = createCredentials({
2058
+ state,
2059
+ persistor,
2060
+ middlewares: middlewareFor("auth"),
2061
+ mode,
2062
+ onSignedOut: (baseUrl) => perProject.forgetUnder(baseUrl)
2063
+ });
2064
+ const perStack = createPerStack({
2065
+ state,
2066
+ credentials,
2067
+ middlewareFor
2068
+ });
2069
+ const perProject = createPerProject({
2070
+ state,
2071
+ credentials,
2072
+ middlewareFor,
2073
+ stack: perStack,
2074
+ clientServiceUrls,
2075
+ buildApi: (project) => createApiFor({
2076
+ stackUrl: () => project.baseUrl,
2077
+ project: () => Result.unwrap(state.projects.get(project.id)),
2078
+ pinned: true
2079
+ })
2080
+ });
2081
+ state.store.subscribe(perStack.context.subscriber);
2082
+ perStack.context.subscriber(state.store.get());
2083
+ state.store.subscribe(perProject.context.subscriber);
2084
+ const selectStack = (baseUrl) => Result.unwrap(state.scope.selectStack(normalizeBaseUrl(baseUrl)));
2085
+ const selectProject = (projectId) => Result.unwrap(state.scope.selectProject(projectId));
2086
+ /** The scoped stack, or a named one — normalised to key like `select`. */
2087
+ const requireStackUrl = (baseUrl) => baseUrl === void 0 ? state.scope.getActiveStack().baseUrl : normalizeBaseUrl(baseUrl);
2088
+ /** The scoped project, or the row a table id names — on whichever stack that is. */
2089
+ const requireProjectEntry = (id) => id === void 0 ? Result.unwrap(state.scope.requireActiveProject()) : Result.unwrap(state.projects.get(id));
2090
+ /**
2091
+ * The scoped project, or a named open one.
2092
+ *
2093
+ * - An id is ambiguous across stacks: the active stack decides, else the single one open elsewhere.
2094
+ */
2095
+ const requireProject = (projectId) => {
2096
+ if (projectId === void 0) return Result.unwrap(state.scope.requireActiveProject());
2097
+ const scoped = state.projects.get(Entry.projectEntryId(requireStackUrl(), projectId));
2098
+ if (scoped.success) return scoped.data;
2099
+ const [only, ...rest] = state.projects.findAll(projectId);
2100
+ return only !== void 0 && rest.length === 0 ? only : Result.unwrap(scoped);
2101
+ };
2102
+ /**
2103
+ * Auth headers for a non-fetch transport (the chat stream).
2104
+ *
2105
+ * - A read, not a rotation: no middleware recovers a 401 there; the fetch clients keep it fresh.
2106
+ */
2107
+ const getAuthHeaders = (projectId) => {
2108
+ const project = requireProject(projectId);
2109
+ const credential = Result.unwrap(state.auth.requireCredential(project.baseUrl));
2110
+ return {
2111
+ [HttpHeader.AUTHORIZATION]: `Bearer ${credential.accessToken}`,
2112
+ [KeboolaHttpHeader.PROJECT_ID]: String(project.projectId)
2113
+ };
2114
+ };
2115
+ const authenticate = (input) => {
2116
+ const stack = state.scope.getActiveStack();
2117
+ if (input.type !== "static" && input.type !== mode) throw new KeboolaError(KeboolaErrorType.CredentialKindMismatch);
2118
+ if (input.type !== "token") return Result.unwrap(state.auth.authenticate(stack.baseUrl, input));
2119
+ const { refreshToken } = input;
2120
+ if (!refreshToken) throw new KeboolaError(KeboolaErrorType.NotAuthenticated);
2121
+ return Result.unwrap(state.auth.authenticate(stack.baseUrl, {
2122
+ ...input,
2123
+ refreshToken
2124
+ }));
2125
+ };
2126
+ /**
2127
+ * The flat product surface: `auth` and `management` per stack, the rest per project.
2128
+ *
2129
+ * - Both resolvers run per property read: that re-points the active handle and makes a pinned
2130
+ * one throw once its project is gone.
2131
+ */
2132
+ const createApiFor = (resolve) => new Proxy({}, { get: (_target, property) => {
2133
+ if (isBuiltInProperty(property)) return void 0;
2134
+ if (property === "auth" || property === "management") {
2135
+ if (resolve.pinned) resolve.project();
2136
+ return perStack.get(resolve.stackUrl())[property];
2137
+ }
2138
+ const derived = perProject.get(resolve.project());
2139
+ if (property === "context") return derived.context;
2140
+ if (property === "storage") return derived.storage;
2141
+ const { client, meta } = derived.clients;
2142
+ if (property === "serviceMeta") return meta;
2143
+ return client[property];
2144
+ } });
2145
+ const activeApi = createApiFor({
2146
+ stackUrl: () => state.scope.getActiveStack().baseUrl,
2147
+ project: () => Result.unwrap(state.scope.requireActiveProject())
2148
+ });
2149
+ /** The scoped project's surface. Re-points when the scope moves. */
2150
+ const getActiveApi = () => activeApi;
2151
+ /**
2152
+ * One project's surface, on the active stack — one credential serves all of them.
2153
+ *
2154
+ * - Pinned: never re-points; stops once the project closes (`session.project.close`, sign-out).
2155
+ * - Memoised per project: a React `key` or a hook dep compares handles by identity.
2156
+ */
2157
+ const getApi = (projectId) => {
2158
+ const { baseUrl } = state.scope.getActiveStack();
2159
+ const project = Entry.project(baseUrl, projectId);
2160
+ Result.unwrapOr(state.projects.open(baseUrl, projectId), null);
2161
+ return perProject.get(project).api;
2162
+ };
2163
+ /** The scope's sign-in, or a named stack's — and everything that sign-in derived. */
2164
+ const signOut = (baseUrl) => {
2165
+ const target = requireStackUrl(baseUrl);
2166
+ return Result.unwrap(credentials.signOut(target));
2167
+ };
2168
+ /**
2169
+ * `input` replaces the active stack's sign-in, whatever it holds.
2170
+ *
2171
+ * - Signs out first, always: a sign-out moves the epoch even on an anonymous stack, so a stored
2172
+ * session still being restored cannot land on top of this one.
2173
+ */
2174
+ const replace = (input) => {
2175
+ signOut();
2176
+ return authenticate(input);
2177
+ };
2178
+ /**
2179
+ * A server-injected `token` credential, adopted whatever this client's mode.
2180
+ *
2181
+ * @deprecated Temporary, for the agent-project claim page only: Connection injects an API-mode
2182
+ * session through `UiConfig.programmaticAuth`. Remove together with that injection.
2183
+ *
2184
+ * - Replaces the active stack's sign-in, like `replace`.
2185
+ * - A cookie-mode client never rotates it, so it lasts as long as its access token.
2186
+ */
2187
+ const adoptInjected = (input) => {
2188
+ signOut();
2189
+ return Result.unwrap(state.auth.authenticate(getActiveStack().baseUrl, input));
2190
+ };
2191
+ /**
2192
+ * Leave one project: its row and everything built for it; its handles stop answering.
2193
+ *
2194
+ * - Counterpart of `getApi(projectId)`; without it the project is held and persisted until sign-out.
2195
+ */
2196
+ const closeProject = (projectId) => {
2197
+ const id = Entry.projectEntryId(requireStackUrl(), projectId);
2198
+ const closed = Result.unwrapOr(state.projects.close(id), null);
2199
+ if (closed === null) return null;
2200
+ perProject.forget(id);
2201
+ return closed;
2202
+ };
2203
+ const closeStack = (baseUrl) => {
2204
+ const target = normalizeBaseUrl(baseUrl);
2205
+ if (state.scope.get().baseUrl === target) throw new KeboolaError(KeboolaErrorType.StackActive);
2206
+ const closed = Result.unwrapOr(state.stacks.close(target), null);
2207
+ if (closed === null) return null;
2208
+ perProject.forgetUnder(target);
2209
+ perStack.forget(target);
2210
+ credentials.forget(target);
2211
+ return closed;
2212
+ };
2213
+ let persisting = false;
2214
+ /**
2215
+ * Persistence starts only once the restore has settled.
2216
+ *
2217
+ * - Mid-hydration an unexchanged stack is `anonymous`; `durableCredential` would erase the
2218
+ * refresh token the exchange is about to spend.
2219
+ * - Writes the settled table once: the subscription fires only on the next change.
2220
+ */
2221
+ const enablePersistence = () => {
2222
+ if (persisting) return;
2223
+ persisting = true;
2224
+ persistor.persist(state.store.get());
2225
+ state.store.subscribe(persistor.persist);
2226
+ };
2227
+ /**
2228
+ * The same, deferred until a sign-in.
2229
+ *
2230
+ * - After an unreachable restore the table is anonymous but the stored token is still good;
2231
+ * writing earlier would drop it.
2232
+ */
2233
+ const enablePersistenceOnSignIn = () => {
2234
+ const stop = state.store.subscribe((next) => {
2235
+ if (!Object.values(next.stacks).some(({ auth }) => auth.status === "authenticated")) return;
2236
+ stop();
2237
+ enablePersistence();
2238
+ });
2239
+ };
2240
+ const restore = lazy(() => credentials.restore().then((restored) => {
2241
+ if (restored.status === "unreachable") enablePersistenceOnSignIn();
2242
+ else enablePersistence();
2243
+ return restored;
2244
+ }, (error) => {
2245
+ enablePersistenceOnSignIn();
2246
+ throw error;
2247
+ }));
2248
+ const getActiveStack = state.scope.getActiveStack;
2249
+ const isAuthenticated = () => getActiveStack().auth.status === "authenticated";
2250
+ /**
2251
+ * Picks up where the stored session left off, once.
2252
+ *
2253
+ * 1. A stored stack becomes active again, with its project if its credential came back.
2254
+ * 2. Nothing stored, or the restore failed: `defaultBaseUrl` stays active; a failure rethrows.
2255
+ * 3. The caller got there first (a select, sign-in or sign-out): its scope and sign-ins stand.
2256
+ *
2257
+ * - Resolves with the stored credential's fate — only this tells `expired` from `empty`.
2258
+ * - Other stacks still come back, persistence still starts; repeat calls share one promise.
2259
+ */
2260
+ const resume = lazy(() => restore().then(({ lastActive, status }) => {
2261
+ if (!lastActive || callerScoped) return status;
2262
+ const stack = selectStack(lastActive.baseUrl);
2263
+ if (lastActive.projectId !== null && stack.auth.status === "authenticated") selectProject(lastActive.projectId);
2264
+ return status;
2265
+ }));
2266
+ let callerScoped = false;
2267
+ const byCaller = (verb) => (...args) => {
2268
+ callerScoped = true;
2269
+ return verb(...args);
2270
+ };
2271
+ return {
2272
+ getActiveApi,
2273
+ getApi,
2274
+ session: {
2275
+ getState: state.store.get,
2276
+ subscribe: state.store.subscribe,
2277
+ resume,
2278
+ stack: {
2279
+ getActive: getActiveStack,
2280
+ select: byCaller(selectStack),
2281
+ close: closeStack,
2282
+ retryContext: perStack.context.retry,
2283
+ getContext: (baseUrl) => perStack.context.get(requireStackUrl(baseUrl)),
2284
+ getContextAsync: (baseUrl) => perStack.context.getAsync(requireStackUrl(baseUrl))
2285
+ },
2286
+ project: {
2287
+ select: byCaller(selectProject),
2288
+ close: closeProject,
2289
+ deactivate: state.scope.deactivate,
2290
+ retryContext: perProject.context.retry,
2291
+ getContext: (id) => perProject.context.get(id ?? requireProjectEntry().id),
2292
+ getContextAsync: (id) => perProject.context.getAsync(requireProjectEntry(id))
2293
+ },
2294
+ auth: {
2295
+ authenticate: byCaller(authenticate),
2296
+ replace: byCaller(replace),
2297
+ adoptInjected: byCaller(adoptInjected),
2298
+ signOut: byCaller(signOut),
2299
+ /** Whether the active stack holds a credential — `restoring` is not one yet. */
2300
+ isAuthenticated,
2301
+ isAuthenticatedAsync: () => resume().then(isAuthenticated),
2302
+ rotate: (baseUrl) => credentials.rotate(baseUrl).then(Result.unwrap),
2303
+ getHeaders: getAuthHeaders
2304
+ }
2305
+ }
2306
+ };
2307
+ };
2308
+ //#endregion
2309
+ //#region src/middlewares/loggingMiddleware.ts
2310
+ const CORRELATION_ID_HEADER = "X-Correlation-ID";
2311
+ const ALWAYS_REDACTED_HEADERS = [
2312
+ KeboolaHttpHeader.MANAGEMENT_API_TOKEN,
2313
+ KeboolaHttpHeader.STORAGE_API_TOKEN,
2314
+ "authorization",
2315
+ "cookie",
2316
+ "set-cookie"
2317
+ ];
2318
+ const ALWAYS_REDACTED_QUERY_PARAMS = /* @__PURE__ */ new Set([
2319
+ "token",
2320
+ "apikey",
2321
+ "api_key",
2322
+ "access_token",
2323
+ "refresh_token",
2324
+ "code",
2325
+ "state",
2326
+ "signature",
2327
+ "sig",
2328
+ "x-amz-signature",
2329
+ "x-amz-credential",
2330
+ "x-amz-security-token",
2331
+ "password",
2332
+ "secret"
2333
+ ]);
2334
+ const REDACTED = "[REDACTED]";
2335
+ const getRedactedUrl = (rawUrl) => {
2336
+ const url = new URL(rawUrl);
2337
+ if (url.username) url.username = REDACTED;
2338
+ if (url.password) url.password = REDACTED;
2339
+ url.searchParams.forEach((_value, key) => {
2340
+ if (ALWAYS_REDACTED_QUERY_PARAMS.has(key.toLowerCase())) url.searchParams.set(key, REDACTED);
2341
+ });
2342
+ return url.toString();
2343
+ };
2344
+ const ensureCorrelationId = (request) => {
2345
+ const correlationId = request.headers.get(CORRELATION_ID_HEADER) ?? generateUUID();
2346
+ request.headers.set(CORRELATION_ID_HEADER, correlationId);
2347
+ return correlationId;
2348
+ };
2349
+ const getRedactedHeaders = (headers, redacted) => {
2350
+ const redactedSet = new Set([...ALWAYS_REDACTED_HEADERS, ...redacted].map((h) => h.toLowerCase()));
2351
+ const result = {};
2352
+ headers.forEach((value, name) => {
2353
+ result[name] = redactedSet.has(name.toLowerCase()) ? REDACTED : value;
2354
+ });
2355
+ return result;
2356
+ };
2357
+ const getRequestLog = (request, redactedHeaders) => ({
2358
+ url: getRedactedUrl(request.url),
2359
+ headers: getRedactedHeaders(request.headers, redactedHeaders)
2360
+ });
2361
+ const getResponseLog = (response, redactedHeaders) => ({
2362
+ status: response.status,
2363
+ statusText: response.statusText,
2364
+ headers: getRedactedHeaders(response.headers, redactedHeaders)
2365
+ });
2366
+ const redactApiError = (error, redactedHeaders) => new ApiError({
2367
+ request: new Request(getRedactedUrl(error.request.url), {
2368
+ method: error.request.method,
2369
+ headers: getRedactedHeaders(error.request.headers, redactedHeaders)
2370
+ }),
2371
+ response: new Response(null, {
2372
+ status: error.response.status,
2373
+ statusText: error.response.statusText,
2374
+ headers: getRedactedHeaders(error.response.headers, redactedHeaders)
2375
+ }),
2376
+ data: error.data
2377
+ });
2378
+ const formatLog = (level, log) => {
2379
+ const parts = [
2380
+ `[${level.toUpperCase()}]`,
2381
+ `${Math.round(log.durationMs)}ms`,
2382
+ log.method
2383
+ ];
2384
+ parts.push(log.request.url);
2385
+ if ("response" in log) parts.push(String(log.response.status));
2386
+ return parts.join(" ");
2387
+ };
2388
+ const createSafeLogger = (logger, level = "error-only") => {
2389
+ return {
2390
+ info: (log) => {
2391
+ if (level !== "all") return;
2392
+ try {
2393
+ if (logger?.info) {
2394
+ logger.info(log);
2395
+ return;
2396
+ }
2397
+ console.info(formatLog("info", log));
2398
+ } catch {}
2399
+ },
2400
+ error: (log) => {
2401
+ try {
2402
+ if (logger?.error) {
2403
+ logger.error(log);
2404
+ return;
2405
+ }
2406
+ console.error(formatLog("error", log));
2407
+ } catch {}
2408
+ }
2409
+ };
2410
+ };
2411
+ const createLoggingMiddleware = (options = {}) => {
2412
+ const safeLogger = createSafeLogger(options.logger, options.level);
2413
+ const redactHeaders = options.redactHeaders ?? [];
2414
+ return (next) => async (fetchRequest) => {
2415
+ const correlationId = ensureCorrelationId(fetchRequest.request);
2416
+ const start = performance.now();
2417
+ const method = fetchRequest.request.method.toLowerCase();
2418
+ const requestLog = getRequestLog(fetchRequest.request, redactHeaders);
2419
+ try {
2420
+ const result = await next(fetchRequest);
2421
+ safeLogger.info({
2422
+ correlationId,
2423
+ method,
2424
+ durationMs: performance.now() - start,
2425
+ request: requestLog,
2426
+ response: getResponseLog(result.response, redactHeaders)
2427
+ });
2428
+ return result;
2429
+ } catch (error) {
2430
+ if (error instanceof Error) safeLogger.error({
2431
+ correlationId,
2432
+ method,
2433
+ durationMs: performance.now() - start,
2434
+ request: requestLog,
2435
+ error: isApiError(error) ? redactApiError(error, redactHeaders) : error
2436
+ });
2437
+ throw error;
2438
+ }
2439
+ };
2440
+ };
2441
+ //#endregion
2442
+ //#region src/middlewares/retryMiddleware.ts
2443
+ const DEFAULT_MAX_RETRIES = 5;
2444
+ const DEFAULT_RETRYABLE_STATUSES = [
2445
+ HttpStatus.INTERNAL_SERVER_ERROR,
2446
+ HttpStatus.BAD_GATEWAY,
2447
+ HttpStatus.SERVICE_UNAVAILABLE,
2448
+ HttpStatus.GATEWAY_TIMEOUT
2449
+ ];
2450
+ const DEFAULT_BACKOFF_FACTOR = .3;
2451
+ const defaultShouldRetry = (error) => error instanceof ApiError && DEFAULT_RETRYABLE_STATUSES.includes(error.response.status);
2452
+ const createRetryMiddleware = (options) => {
2453
+ const { maxRetries = DEFAULT_MAX_RETRIES, backoffFactor = DEFAULT_BACKOFF_FACTOR, shouldRetry = defaultShouldRetry } = options ?? {};
2454
+ if (!Number.isInteger(maxRetries) || maxRetries < 0) throw new RangeError("maxRetries must be a non-negative integer");
2455
+ if (!Number.isFinite(backoffFactor) || backoffFactor < 0) throw new RangeError("backoffFactor must be a finite non-negative number");
2456
+ return (next) => async (request) => {
2457
+ for (let attempt = 0; attempt <= maxRetries; attempt++) try {
2458
+ return await next({
2459
+ ...request,
2460
+ request: request.request.clone()
2461
+ });
2462
+ } catch (error) {
2463
+ if (attempt === maxRetries || !shouldRetry(error, attempt)) throw error;
2464
+ const delayMs = backoffFactor * 1e3 * Math.pow(2, attempt);
2465
+ await delay(delayMs, request.request.signal ?? void 0);
2466
+ }
2467
+ throw new Error("unreachable");
2468
+ };
2469
+ };
2470
+ //#endregion
2471
+ export { ApiError, HtmlResponseError, HttpContentType, HttpHeader, KeboolaError, KeboolaErrorType, KeboolaHttpHeader, ManagementClientAuthError, QueryJobError, QueryJobTimeoutError, Result, SESSION_STORAGE_KEY, ServiceUnavailableError, SyncActionError, UserError, ValidationError, asError, assert, coalesce, collect, concurrent, createDerivedAsyncStore, createDerivedStore, createEmitter, createGenericFetchClient, createKeboola, createLegacyKeboola, createLocalStorage, createLoggingMiddleware, createMemoryStorage, createNullStorage, createPersistor, createPollRegistry, createQueryServiceSdk, createRetryMiddleware, createSessionStorage, createStorageSdk, createStore, dedupe, deepMerge, delay, emitter, ensure, failureOf, formatValidationIssues, generateUUID, isAbortError, isApiError, isEmptyDeep, isFetchClientError, isHtmlResponseError, isKeboolaError, isManagementClientAuthError, isPlainObject, isQueryJobError, isQueryJobTimeoutError, isStorageTokenMutatingRequest, isSyncActionError, isTimeoutError, isValidationError, jobStatus, keboolaUID, lazy, parseLogLines, parseOrThrow, poll, poller, readableReason, schemaGuidedMerge, series, shallowEqual };
1877
2472
 
1878
2473
  //# sourceMappingURL=index.js.map