@northern.tech/store 0.2.1 → 0.3.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 (391) hide show
  1. package/dist/actions.cjs +1812 -0
  2. package/dist/actions.cjs.map +1 -0
  3. package/dist/actions.js +18 -1860
  4. package/dist/actions.js.map +1 -1
  5. package/dist/api/general-api.cjs +336 -0
  6. package/dist/api/general-api.cjs.map +1 -0
  7. package/dist/api/general-api.js +15 -1051
  8. package/dist/api/general-api.js.map +1 -1
  9. package/dist/api/users-api.cjs +342 -0
  10. package/dist/api/users-api.cjs.map +1 -0
  11. package/dist/api/users-api.js +12 -1062
  12. package/dist/api/users-api.js.map +1 -1
  13. package/dist/appSlice/constants.cjs +207 -0
  14. package/dist/appSlice/constants.cjs.map +1 -0
  15. package/dist/appSlice/{constants.d.mts → constants.d.cts} +12 -1
  16. package/dist/appSlice/constants.d.ts +12 -1
  17. package/dist/appSlice/constants.js +39 -181
  18. package/dist/appSlice/constants.js.map +1 -1
  19. package/dist/appSlice/index.cjs +393 -0
  20. package/dist/appSlice/index.cjs.map +1 -0
  21. package/dist/appSlice/index.js +18 -1112
  22. package/dist/appSlice/index.js.map +1 -1
  23. package/dist/appSlice/selectors.cjs +58 -0
  24. package/dist/appSlice/selectors.cjs.map +1 -0
  25. package/dist/appSlice/selectors.js +17 -46
  26. package/dist/appSlice/selectors.js.map +1 -1
  27. package/dist/appSlice/thunks.cjs +4670 -0
  28. package/dist/appSlice/thunks.cjs.map +1 -0
  29. package/dist/appSlice/thunks.js +42 -5750
  30. package/dist/appSlice/thunks.js.map +1 -1
  31. package/dist/auth.cjs +320 -0
  32. package/dist/auth.cjs.map +1 -0
  33. package/dist/auth.js +20 -1031
  34. package/dist/auth.js.map +1 -1
  35. package/dist/{chunk-5VNQCCAQ.mjs → chunk-25AKG5HH.js} +5 -2
  36. package/dist/chunk-25AKG5HH.js.map +1 -0
  37. package/dist/{chunk-QQBUNZHA.mjs → chunk-4B3IMP4I.js} +17 -12
  38. package/dist/{chunk-QQBUNZHA.mjs.map → chunk-4B3IMP4I.js.map} +1 -1
  39. package/dist/{chunk-3ORTTLIB.mjs → chunk-7PVGDMNM.js} +2 -2
  40. package/dist/{chunk-IFWKT27G.mjs → chunk-A6CT6GTI.js} +3 -3
  41. package/dist/{chunk-ZK4W5T53.mjs → chunk-AMGWP7A4.js} +2 -2
  42. package/dist/{chunk-G4FGNSV3.mjs → chunk-CK6YE6AN.js} +1 -1
  43. package/dist/{chunk-4SDUITD4.mjs → chunk-CYV6632F.js} +2 -2
  44. package/dist/{chunk-KJAZNKV2.mjs → chunk-DGD6FVWF.js} +29 -29
  45. package/dist/{chunk-DIZJVB6M.mjs → chunk-DQ4ZLUIU.js} +75 -431
  46. package/dist/chunk-DQ4ZLUIU.js.map +1 -0
  47. package/dist/{chunk-JA27QXVB.mjs → chunk-E5LEU5PF.js} +3 -3
  48. package/dist/{chunk-B42NUKMZ.mjs → chunk-FGKMJS3B.js} +1 -1
  49. package/dist/{chunk-NJNSCJEY.mjs → chunk-GZ5VQMDM.js} +18 -21
  50. package/dist/chunk-GZ5VQMDM.js.map +1 -0
  51. package/dist/{chunk-O6TYYKSD.mjs → chunk-H6DUEJFF.js} +20 -70
  52. package/dist/chunk-H6DUEJFF.js.map +1 -0
  53. package/dist/{chunk-WYHJFSMQ.mjs → chunk-JAROCU6M.js} +3 -3
  54. package/dist/{chunk-QBKCUIWO.mjs → chunk-JIS4PA3R.js} +1 -1
  55. package/dist/{chunk-XD7INCM4.mjs → chunk-KAQJH2YL.js} +4 -4
  56. package/dist/{chunk-2Z3RFYW4.mjs → chunk-LIJIIRON.js} +1 -1
  57. package/dist/{chunk-IU4OXOPA.mjs → chunk-MRCFLG45.js} +1 -1
  58. package/dist/chunk-NMAXZ3ZY.js +1 -0
  59. package/dist/{chunk-K2NZL5V4.mjs → chunk-Q6M5TTDQ.js} +2 -2
  60. package/dist/{chunk-CHUCIHMY.mjs → chunk-RX55KAKX.js} +2 -2
  61. package/dist/{chunk-ZE7R2XXE.mjs → chunk-UEP36GCI.js} +3 -3
  62. package/dist/{chunk-WCUGLHYM.mjs → chunk-UVQX743T.js} +13 -13
  63. package/dist/{chunk-H5UCKQWK.mjs → chunk-V4DKKRWS.js} +14 -14
  64. package/dist/{chunk-XC5UXEIB.mjs → chunk-VOCOFE4I.js} +2 -2
  65. package/dist/{chunk-R7LXL3KJ.mjs → chunk-XTRPX7JZ.js} +3 -3
  66. package/dist/{chunk-6CSGHZ3E.mjs → chunk-XXHONFSQ.js} +3 -3
  67. package/dist/{chunk-KPPU6OWF.mjs → chunk-YETZPQFR.js} +4 -19
  68. package/dist/chunk-YETZPQFR.js.map +1 -0
  69. package/dist/{chunk-KZSTW27Q.mjs → chunk-YGBFDXXA.js} +2 -2
  70. package/dist/{chunk-H2PQQMRY.mjs → chunk-YO22XLHI.js} +1 -1
  71. package/dist/{chunk-65YIOCCD.mjs → chunk-YT73QWCN.js} +3 -3
  72. package/dist/{chunk-AZRVRNXT.mjs → chunk-YTQUNAZP.js} +3 -3
  73. package/dist/commonConstants.cjs +285 -0
  74. package/dist/commonConstants.cjs.map +1 -0
  75. package/dist/{commonConstants.d.mts → commonConstants.d.cts} +3 -3
  76. package/dist/commonConstants.d.ts +3 -3
  77. package/dist/commonConstants.js +37 -268
  78. package/dist/commonConstants.js.map +1 -1
  79. package/dist/commonSelectors.cjs +1487 -0
  80. package/dist/commonSelectors.cjs.map +1 -0
  81. package/dist/commonSelectors.js +53 -1500
  82. package/dist/commonSelectors.js.map +1 -1
  83. package/dist/constants.cjs +1297 -0
  84. package/dist/constants.cjs.map +1 -0
  85. package/dist/{constants.d.mts → constants.d.cts} +10 -10
  86. package/dist/constants.d.ts +1 -1
  87. package/dist/constants.js +220 -1189
  88. package/dist/constants.js.map +1 -1
  89. package/dist/deploymentdevicehook.cjs +4686 -0
  90. package/dist/deploymentdevicehook.cjs.map +1 -0
  91. package/dist/deploymentdevicehook.d.cts +3 -0
  92. package/dist/deploymentdevicehook.d.ts +3 -0
  93. package/dist/deploymentdevicehook.js +60 -0
  94. package/dist/deploymentdevicehook.js.map +1 -0
  95. package/dist/deploymentsSlice/constants.cjs +562 -0
  96. package/dist/deploymentsSlice/constants.cjs.map +1 -0
  97. package/dist/deploymentsSlice/constants.js +39 -1006
  98. package/dist/deploymentsSlice/constants.js.map +1 -1
  99. package/dist/deploymentsSlice/index.cjs +648 -0
  100. package/dist/deploymentsSlice/index.cjs.map +1 -0
  101. package/dist/deploymentsSlice/index.js +18 -1104
  102. package/dist/deploymentsSlice/index.js.map +1 -1
  103. package/dist/deploymentsSlice/selectors.cjs +561 -0
  104. package/dist/deploymentsSlice/selectors.cjs.map +1 -0
  105. package/dist/deploymentsSlice/selectors.js +22 -1014
  106. package/dist/deploymentsSlice/selectors.js.map +1 -1
  107. package/dist/deploymentsSlice/thunks.cjs +4686 -0
  108. package/dist/deploymentsSlice/thunks.cjs.map +1 -0
  109. package/dist/deploymentsSlice/thunks.js +60 -5757
  110. package/dist/deploymentsSlice/thunks.js.map +1 -1
  111. package/dist/devicesSlice/constants.cjs +435 -0
  112. package/dist/devicesSlice/constants.cjs.map +1 -0
  113. package/dist/devicesSlice/constants.js +37 -1007
  114. package/dist/devicesSlice/constants.js.map +1 -1
  115. package/dist/devicesSlice/index.cjs +586 -0
  116. package/dist/devicesSlice/index.cjs.map +1 -0
  117. package/dist/devicesSlice/index.js +18 -1161
  118. package/dist/devicesSlice/index.js.map +1 -1
  119. package/dist/devicesSlice/selectors.cjs +531 -0
  120. package/dist/devicesSlice/selectors.cjs.map +1 -0
  121. package/dist/devicesSlice/selectors.js +50 -1097
  122. package/dist/devicesSlice/selectors.js.map +1 -1
  123. package/dist/devicesSlice/thunks.cjs +4758 -0
  124. package/dist/devicesSlice/thunks.cjs.map +1 -0
  125. package/dist/devicesSlice/thunks.js +132 -5793
  126. package/dist/devicesSlice/thunks.js.map +1 -1
  127. package/dist/monitorSlice/constants.cjs +165 -0
  128. package/dist/monitorSlice/constants.cjs.map +1 -0
  129. package/dist/monitorSlice/constants.js +11 -970
  130. package/dist/monitorSlice/constants.js.map +1 -1
  131. package/dist/monitorSlice/index.cjs +435 -0
  132. package/dist/monitorSlice/index.cjs.map +1 -0
  133. package/dist/monitorSlice/index.js +18 -1022
  134. package/dist/monitorSlice/index.js.map +1 -1
  135. package/dist/monitorSlice/selectors.cjs +31 -0
  136. package/dist/monitorSlice/selectors.cjs.map +1 -0
  137. package/dist/monitorSlice/selectors.js +5 -25
  138. package/dist/monitorSlice/selectors.js.map +1 -1
  139. package/dist/monitorSlice/thunks.cjs +2623 -0
  140. package/dist/monitorSlice/thunks.cjs.map +1 -0
  141. package/dist/monitorSlice/thunks.js +41 -2624
  142. package/dist/monitorSlice/thunks.js.map +1 -1
  143. package/dist/onboardingSlice/constants.cjs +71 -0
  144. package/dist/onboardingSlice/constants.cjs.map +1 -0
  145. package/dist/onboardingSlice/constants.js +7 -64
  146. package/dist/onboardingSlice/constants.js.map +1 -1
  147. package/dist/onboardingSlice/index.cjs +80 -0
  148. package/dist/onboardingSlice/index.cjs.map +1 -0
  149. package/dist/onboardingSlice/index.js +13 -71
  150. package/dist/onboardingSlice/index.js.map +1 -1
  151. package/dist/onboardingSlice/selectors.cjs +31 -0
  152. package/dist/onboardingSlice/selectors.cjs.map +1 -0
  153. package/dist/onboardingSlice/selectors.js +5 -25
  154. package/dist/onboardingSlice/selectors.js.map +1 -1
  155. package/dist/onboardingSlice/thunks.cjs +4774 -0
  156. package/dist/onboardingSlice/thunks.cjs.map +1 -0
  157. package/dist/onboardingSlice/thunks.js +48 -5753
  158. package/dist/onboardingSlice/thunks.js.map +1 -1
  159. package/dist/organizationSlice/constants.cjs +830 -0
  160. package/dist/organizationSlice/constants.cjs.map +1 -0
  161. package/dist/organizationSlice/constants.js +33 -1014
  162. package/dist/organizationSlice/constants.js.map +1 -1
  163. package/dist/organizationSlice/index.cjs +505 -0
  164. package/dist/organizationSlice/index.cjs.map +1 -0
  165. package/dist/organizationSlice/index.js +18 -1067
  166. package/dist/organizationSlice/index.js.map +1 -1
  167. package/dist/organizationSlice/selectors.cjs +300 -0
  168. package/dist/organizationSlice/selectors.cjs.map +1 -0
  169. package/dist/organizationSlice/selectors.js +36 -1013
  170. package/dist/organizationSlice/selectors.js.map +1 -1
  171. package/dist/organizationSlice/thunks.cjs +5006 -0
  172. package/dist/organizationSlice/thunks.cjs.map +1 -0
  173. package/dist/organizationSlice/thunks.js +98 -5776
  174. package/dist/organizationSlice/thunks.js.map +1 -1
  175. package/dist/releasesSlice/constants.cjs +40 -0
  176. package/dist/releasesSlice/constants.cjs.map +1 -0
  177. package/dist/releasesSlice/constants.js +11 -31
  178. package/dist/releasesSlice/constants.js.map +1 -1
  179. package/dist/releasesSlice/index.cjs +355 -0
  180. package/dist/releasesSlice/index.cjs.map +1 -0
  181. package/dist/releasesSlice/index.js +18 -1070
  182. package/dist/releasesSlice/index.js.map +1 -1
  183. package/dist/releasesSlice/selectors.cjs +290 -0
  184. package/dist/releasesSlice/selectors.cjs.map +1 -0
  185. package/dist/releasesSlice/selectors.js +25 -1009
  186. package/dist/releasesSlice/selectors.js.map +1 -1
  187. package/dist/releasesSlice/thunks.cjs +2896 -0
  188. package/dist/releasesSlice/thunks.cjs.map +1 -0
  189. package/dist/releasesSlice/thunks.js +63 -2931
  190. package/dist/releasesSlice/thunks.js.map +1 -1
  191. package/dist/selectors.cjs +1641 -0
  192. package/dist/selectors.cjs.map +1 -0
  193. package/dist/{selectors.d.mts → selectors.d.cts} +9 -9
  194. package/dist/selectors.js +206 -1582
  195. package/dist/selectors.js.map +1 -1
  196. package/dist/store.cjs +1932 -0
  197. package/dist/store.cjs.map +1 -0
  198. package/dist/store.js +28 -1980
  199. package/dist/store.js.map +1 -1
  200. package/dist/storehooks.cjs +5565 -0
  201. package/dist/storehooks.cjs.map +1 -0
  202. package/dist/storehooks.js +122 -5802
  203. package/dist/storehooks.js.map +1 -1
  204. package/dist/thunks.cjs +5675 -0
  205. package/dist/thunks.cjs.map +1 -0
  206. package/dist/{thunks.d.mts → thunks.d.cts} +8 -8
  207. package/dist/thunks.js +360 -5910
  208. package/dist/thunks.js.map +1 -1
  209. package/dist/usersSlice/constants.cjs +798 -0
  210. package/dist/usersSlice/constants.cjs.map +1 -0
  211. package/dist/usersSlice/constants.js +42 -1001
  212. package/dist/usersSlice/constants.js.map +1 -1
  213. package/dist/usersSlice/index.cjs +890 -0
  214. package/dist/usersSlice/index.cjs.map +1 -0
  215. package/dist/usersSlice/index.js +18 -1107
  216. package/dist/usersSlice/index.js.map +1 -1
  217. package/dist/usersSlice/selectors.cjs +826 -0
  218. package/dist/usersSlice/selectors.cjs.map +1 -0
  219. package/dist/usersSlice/selectors.js +35 -1034
  220. package/dist/usersSlice/selectors.js.map +1 -1
  221. package/dist/usersSlice/thunks.cjs +4732 -0
  222. package/dist/usersSlice/thunks.cjs.map +1 -0
  223. package/dist/usersSlice/thunks.js +106 -5780
  224. package/dist/usersSlice/thunks.js.map +1 -1
  225. package/dist/utils.cjs +739 -0
  226. package/dist/utils.cjs.map +1 -0
  227. package/dist/{utils.d.mts → utils.d.cts} +1 -3
  228. package/dist/utils.d.ts +1 -3
  229. package/dist/utils.js +42 -1186
  230. package/dist/utils.js.map +1 -1
  231. package/package.json +71 -47
  232. package/dist/actions.mjs +0 -21
  233. package/dist/api/general-api.mjs +0 -18
  234. package/dist/api/general-api.mjs.map +0 -1
  235. package/dist/api/users-api.mjs +0 -15
  236. package/dist/api/users-api.mjs.map +0 -1
  237. package/dist/appSlice/constants.mjs +0 -42
  238. package/dist/appSlice/constants.mjs.map +0 -1
  239. package/dist/appSlice/index.mjs +0 -21
  240. package/dist/appSlice/index.mjs.map +0 -1
  241. package/dist/appSlice/selectors.mjs +0 -20
  242. package/dist/appSlice/selectors.mjs.map +0 -1
  243. package/dist/appSlice/thunks.mjs +0 -45
  244. package/dist/appSlice/thunks.mjs.map +0 -1
  245. package/dist/auth.mjs +0 -23
  246. package/dist/auth.mjs.map +0 -1
  247. package/dist/chunk-5VNQCCAQ.mjs.map +0 -1
  248. package/dist/chunk-DIZJVB6M.mjs.map +0 -1
  249. package/dist/chunk-KPPU6OWF.mjs.map +0 -1
  250. package/dist/chunk-LZOMFHX3.mjs +0 -38
  251. package/dist/chunk-LZOMFHX3.mjs.map +0 -1
  252. package/dist/chunk-NJNSCJEY.mjs.map +0 -1
  253. package/dist/chunk-O6TYYKSD.mjs.map +0 -1
  254. package/dist/chunk-V32GTKOS.mjs +0 -1
  255. package/dist/chunk-V32GTKOS.mjs.map +0 -1
  256. package/dist/commonConstants.mjs +0 -40
  257. package/dist/commonConstants.mjs.map +0 -1
  258. package/dist/commonSelectors.mjs +0 -56
  259. package/dist/commonSelectors.mjs.map +0 -1
  260. package/dist/constants.mjs +0 -223
  261. package/dist/constants.mjs.map +0 -1
  262. package/dist/deploymentsSlice/constants.mjs +0 -42
  263. package/dist/deploymentsSlice/constants.mjs.map +0 -1
  264. package/dist/deploymentsSlice/index.mjs +0 -21
  265. package/dist/deploymentsSlice/index.mjs.map +0 -1
  266. package/dist/deploymentsSlice/selectors.mjs +0 -25
  267. package/dist/deploymentsSlice/selectors.mjs.map +0 -1
  268. package/dist/deploymentsSlice/thunks.mjs +0 -63
  269. package/dist/deploymentsSlice/thunks.mjs.map +0 -1
  270. package/dist/devicesSlice/constants.mjs +0 -40
  271. package/dist/devicesSlice/constants.mjs.map +0 -1
  272. package/dist/devicesSlice/index.mjs +0 -21
  273. package/dist/devicesSlice/index.mjs.map +0 -1
  274. package/dist/devicesSlice/selectors.mjs +0 -53
  275. package/dist/devicesSlice/selectors.mjs.map +0 -1
  276. package/dist/devicesSlice/thunks.mjs +0 -135
  277. package/dist/devicesSlice/thunks.mjs.map +0 -1
  278. package/dist/monitorSlice/constants.mjs +0 -14
  279. package/dist/monitorSlice/constants.mjs.map +0 -1
  280. package/dist/monitorSlice/index.mjs +0 -21
  281. package/dist/monitorSlice/index.mjs.map +0 -1
  282. package/dist/monitorSlice/selectors.mjs +0 -8
  283. package/dist/monitorSlice/selectors.mjs.map +0 -1
  284. package/dist/monitorSlice/thunks.mjs +0 -44
  285. package/dist/monitorSlice/thunks.mjs.map +0 -1
  286. package/dist/onboardingSlice/constants.mjs +0 -10
  287. package/dist/onboardingSlice/constants.mjs.map +0 -1
  288. package/dist/onboardingSlice/index.mjs +0 -16
  289. package/dist/onboardingSlice/index.mjs.map +0 -1
  290. package/dist/onboardingSlice/selectors.mjs +0 -8
  291. package/dist/onboardingSlice/selectors.mjs.map +0 -1
  292. package/dist/onboardingSlice/thunks.mjs +0 -51
  293. package/dist/onboardingSlice/thunks.mjs.map +0 -1
  294. package/dist/organizationSlice/constants.mjs +0 -36
  295. package/dist/organizationSlice/constants.mjs.map +0 -1
  296. package/dist/organizationSlice/index.mjs +0 -21
  297. package/dist/organizationSlice/index.mjs.map +0 -1
  298. package/dist/organizationSlice/selectors.mjs +0 -39
  299. package/dist/organizationSlice/selectors.mjs.map +0 -1
  300. package/dist/organizationSlice/thunks.mjs +0 -101
  301. package/dist/organizationSlice/thunks.mjs.map +0 -1
  302. package/dist/releasesSlice/constants.mjs +0 -14
  303. package/dist/releasesSlice/constants.mjs.map +0 -1
  304. package/dist/releasesSlice/index.mjs +0 -21
  305. package/dist/releasesSlice/index.mjs.map +0 -1
  306. package/dist/releasesSlice/selectors.mjs +0 -28
  307. package/dist/releasesSlice/selectors.mjs.map +0 -1
  308. package/dist/releasesSlice/thunks.mjs +0 -66
  309. package/dist/releasesSlice/thunks.mjs.map +0 -1
  310. package/dist/selectors.mjs +0 -209
  311. package/dist/selectors.mjs.map +0 -1
  312. package/dist/store.mjs +0 -32
  313. package/dist/store.mjs.map +0 -1
  314. package/dist/storehooks.mjs +0 -282
  315. package/dist/storehooks.mjs.map +0 -1
  316. package/dist/thunks.mjs +0 -363
  317. package/dist/thunks.mjs.map +0 -1
  318. package/dist/usersSlice/constants.mjs +0 -45
  319. package/dist/usersSlice/constants.mjs.map +0 -1
  320. package/dist/usersSlice/index.mjs +0 -21
  321. package/dist/usersSlice/index.mjs.map +0 -1
  322. package/dist/usersSlice/selectors.mjs +0 -38
  323. package/dist/usersSlice/selectors.mjs.map +0 -1
  324. package/dist/usersSlice/thunks.mjs +0 -109
  325. package/dist/usersSlice/thunks.mjs.map +0 -1
  326. package/dist/utils.mjs +0 -49
  327. package/dist/utils.mjs.map +0 -1
  328. /package/dist/{actions.d.mts → actions.d.cts} +0 -0
  329. /package/dist/api/{general-api.d.mts → general-api.d.cts} +0 -0
  330. /package/dist/api/{users-api.d.mts → users-api.d.cts} +0 -0
  331. /package/dist/appSlice/{index.d.mts → index.d.cts} +0 -0
  332. /package/dist/appSlice/{selectors.d.mts → selectors.d.cts} +0 -0
  333. /package/dist/appSlice/{thunks.d.mts → thunks.d.cts} +0 -0
  334. /package/dist/{auth.d.mts → auth.d.cts} +0 -0
  335. /package/dist/{chunk-3ORTTLIB.mjs.map → chunk-7PVGDMNM.js.map} +0 -0
  336. /package/dist/{chunk-IFWKT27G.mjs.map → chunk-A6CT6GTI.js.map} +0 -0
  337. /package/dist/{chunk-ZK4W5T53.mjs.map → chunk-AMGWP7A4.js.map} +0 -0
  338. /package/dist/{chunk-G4FGNSV3.mjs.map → chunk-CK6YE6AN.js.map} +0 -0
  339. /package/dist/{chunk-4SDUITD4.mjs.map → chunk-CYV6632F.js.map} +0 -0
  340. /package/dist/{chunk-KJAZNKV2.mjs.map → chunk-DGD6FVWF.js.map} +0 -0
  341. /package/dist/{chunk-JA27QXVB.mjs.map → chunk-E5LEU5PF.js.map} +0 -0
  342. /package/dist/{chunk-B42NUKMZ.mjs.map → chunk-FGKMJS3B.js.map} +0 -0
  343. /package/dist/{chunk-WYHJFSMQ.mjs.map → chunk-JAROCU6M.js.map} +0 -0
  344. /package/dist/{chunk-QBKCUIWO.mjs.map → chunk-JIS4PA3R.js.map} +0 -0
  345. /package/dist/{chunk-XD7INCM4.mjs.map → chunk-KAQJH2YL.js.map} +0 -0
  346. /package/dist/{chunk-2Z3RFYW4.mjs.map → chunk-LIJIIRON.js.map} +0 -0
  347. /package/dist/{chunk-IU4OXOPA.mjs.map → chunk-MRCFLG45.js.map} +0 -0
  348. /package/dist/{actions.mjs.map → chunk-NMAXZ3ZY.js.map} +0 -0
  349. /package/dist/{chunk-K2NZL5V4.mjs.map → chunk-Q6M5TTDQ.js.map} +0 -0
  350. /package/dist/{chunk-CHUCIHMY.mjs.map → chunk-RX55KAKX.js.map} +0 -0
  351. /package/dist/{chunk-ZE7R2XXE.mjs.map → chunk-UEP36GCI.js.map} +0 -0
  352. /package/dist/{chunk-WCUGLHYM.mjs.map → chunk-UVQX743T.js.map} +0 -0
  353. /package/dist/{chunk-H5UCKQWK.mjs.map → chunk-V4DKKRWS.js.map} +0 -0
  354. /package/dist/{chunk-XC5UXEIB.mjs.map → chunk-VOCOFE4I.js.map} +0 -0
  355. /package/dist/{chunk-R7LXL3KJ.mjs.map → chunk-XTRPX7JZ.js.map} +0 -0
  356. /package/dist/{chunk-6CSGHZ3E.mjs.map → chunk-XXHONFSQ.js.map} +0 -0
  357. /package/dist/{chunk-KZSTW27Q.mjs.map → chunk-YGBFDXXA.js.map} +0 -0
  358. /package/dist/{chunk-H2PQQMRY.mjs.map → chunk-YO22XLHI.js.map} +0 -0
  359. /package/dist/{chunk-65YIOCCD.mjs.map → chunk-YT73QWCN.js.map} +0 -0
  360. /package/dist/{chunk-AZRVRNXT.mjs.map → chunk-YTQUNAZP.js.map} +0 -0
  361. /package/dist/{commonSelectors.d.mts → commonSelectors.d.cts} +0 -0
  362. /package/dist/deploymentsSlice/{constants.d.mts → constants.d.cts} +0 -0
  363. /package/dist/deploymentsSlice/{index.d.mts → index.d.cts} +0 -0
  364. /package/dist/deploymentsSlice/{selectors.d.mts → selectors.d.cts} +0 -0
  365. /package/dist/deploymentsSlice/{thunks.d.mts → thunks.d.cts} +0 -0
  366. /package/dist/devicesSlice/{constants.d.mts → constants.d.cts} +0 -0
  367. /package/dist/devicesSlice/{index.d.mts → index.d.cts} +0 -0
  368. /package/dist/devicesSlice/{selectors.d.mts → selectors.d.cts} +0 -0
  369. /package/dist/devicesSlice/{thunks.d.mts → thunks.d.cts} +0 -0
  370. /package/dist/monitorSlice/{constants.d.mts → constants.d.cts} +0 -0
  371. /package/dist/monitorSlice/{index.d.mts → index.d.cts} +0 -0
  372. /package/dist/monitorSlice/{selectors.d.mts → selectors.d.cts} +0 -0
  373. /package/dist/monitorSlice/{thunks.d.mts → thunks.d.cts} +0 -0
  374. /package/dist/onboardingSlice/{constants.d.mts → constants.d.cts} +0 -0
  375. /package/dist/onboardingSlice/{index.d.mts → index.d.cts} +0 -0
  376. /package/dist/onboardingSlice/{selectors.d.mts → selectors.d.cts} +0 -0
  377. /package/dist/onboardingSlice/{thunks.d.mts → thunks.d.cts} +0 -0
  378. /package/dist/organizationSlice/{constants.d.mts → constants.d.cts} +0 -0
  379. /package/dist/organizationSlice/{index.d.mts → index.d.cts} +0 -0
  380. /package/dist/organizationSlice/{selectors.d.mts → selectors.d.cts} +0 -0
  381. /package/dist/organizationSlice/{thunks.d.mts → thunks.d.cts} +0 -0
  382. /package/dist/releasesSlice/{constants.d.mts → constants.d.cts} +0 -0
  383. /package/dist/releasesSlice/{index.d.mts → index.d.cts} +0 -0
  384. /package/dist/releasesSlice/{selectors.d.mts → selectors.d.cts} +0 -0
  385. /package/dist/releasesSlice/{thunks.d.mts → thunks.d.cts} +0 -0
  386. /package/dist/{store.d.mts → store.d.cts} +0 -0
  387. /package/dist/{storehooks.d.mts → storehooks.d.cts} +0 -0
  388. /package/dist/usersSlice/{constants.d.mts → constants.d.cts} +0 -0
  389. /package/dist/usersSlice/{index.d.mts → index.d.cts} +0 -0
  390. /package/dist/usersSlice/{selectors.d.mts → selectors.d.cts} +0 -0
  391. /package/dist/usersSlice/{thunks.d.mts → thunks.d.cts} +0 -0
@@ -0,0 +1,4732 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/usersSlice/thunks.ts
31
+ var thunks_exports = {};
32
+ __export(thunks_exports, {
33
+ addUserToCurrentTenant: () => addUserToCurrentTenant,
34
+ createRole: () => createRole,
35
+ createUser: () => createUser,
36
+ disableUser2fa: () => disableUser2fa,
37
+ editRole: () => editRole,
38
+ editUser: () => editUser,
39
+ enableUser2fa: () => enableUser2fa,
40
+ generateToken: () => generateToken,
41
+ get2FAQRCode: () => get2FAQRCode,
42
+ getGlobalSettings: () => getGlobalSettings2,
43
+ getPermissionSets: () => getPermissionSets,
44
+ getRoles: () => getRoles,
45
+ getTokens: () => getTokens,
46
+ getUser: () => getUser,
47
+ getUserList: () => getUserList,
48
+ getUserSettings: () => getUserSettings2,
49
+ initializeSelf: () => initializeSelf,
50
+ loginUser: () => loginUser,
51
+ logoutUser: () => logoutUser,
52
+ normalizeRbacRoles: () => normalizeRbacRoles,
53
+ passwordResetComplete: () => passwordResetComplete,
54
+ passwordResetStart: () => passwordResetStart,
55
+ removeRole: () => removeRole,
56
+ removeUser: () => removeUser,
57
+ revokeToken: () => revokeToken,
58
+ saveGlobalSettings: () => saveGlobalSettings,
59
+ saveUserSettings: () => saveUserSettings,
60
+ setAllTooltipsReadState: () => setAllTooltipsReadState,
61
+ setHideAnnouncement: () => setHideAnnouncement,
62
+ setTooltipReadState: () => setTooltipReadState,
63
+ submitFeedback: () => submitFeedback,
64
+ switchUserOrganization: () => switchUserOrganization,
65
+ updateUserColumnSettings: () => updateUserColumnSettings,
66
+ verify2FA: () => verify2FA,
67
+ verifyEmailComplete: () => verifyEmailComplete,
68
+ verifyEmailStart: () => verifyEmailStart
69
+ });
70
+ module.exports = __toCommonJS(thunks_exports);
71
+
72
+ // src/appSlice/constants.ts
73
+ var import_icons_material = require("@mui/icons-material");
74
+ var startingDeviceCount = {
75
+ os: "for first 50 devices",
76
+ professional: "for first 250 devices"
77
+ };
78
+ var apiRoot = "/api/management";
79
+ var apiUrl = {
80
+ v1: `${apiRoot}/v1`,
81
+ v2: `${apiRoot}/v2`
82
+ };
83
+ var headerNames = {
84
+ link: "link",
85
+ location: "location",
86
+ total: "x-total-count"
87
+ };
88
+ var chartTypes = {
89
+ bar: { key: "bar", Icon: import_icons_material.BarChart },
90
+ pie: { key: "pie", Icon: import_icons_material.PieChartOutline }
91
+ };
92
+ var emptyChartSelection = { software: "", group: "", chartType: chartTypes.bar.key, attribute: "artifact_name" };
93
+ var defaultReportType = "distribution";
94
+ var defaultReports = [{ ...emptyChartSelection, group: null, attribute: "artifact_name", type: defaultReportType }];
95
+ var PLANS = {
96
+ os: {
97
+ id: "os",
98
+ name: "Basic",
99
+ offer: true,
100
+ price: "$32/month",
101
+ deviceCount: startingDeviceCount.os,
102
+ offerprice: "$23/month for first 50 devices",
103
+ price2: "for first 6 months;\n$29/month thereafter",
104
+ features: ["Basic OTA features"]
105
+ },
106
+ professional: {
107
+ id: "professional",
108
+ name: "Professional",
109
+ offer: true,
110
+ price: "$269/month",
111
+ deviceCount: startingDeviceCount.professional,
112
+ offerprice: "$200/month for first 50 devices",
113
+ price2: "for first 6 months;\n$249/month thereafter",
114
+ features: ["+ Advanced OTA features", "+ Standard support"]
115
+ },
116
+ enterprise: {
117
+ id: "enterprise",
118
+ name: "Enterprise",
119
+ price: "Custom pricing",
120
+ deviceCount: "unlimited devices",
121
+ features: ["+ Enterprise-grade OTA features", "+ Premium support"]
122
+ }
123
+ };
124
+ var ADDONS = {
125
+ configure: {
126
+ id: "configure",
127
+ title: "Configure",
128
+ description: "Expand your plan with device configuration features",
129
+ needs: ["hasDeviceConfig"],
130
+ os: {
131
+ price: "$11/month",
132
+ deviceCount: startingDeviceCount.os
133
+ },
134
+ professional: {
135
+ price: "$65/month",
136
+ deviceCount: startingDeviceCount.professional
137
+ },
138
+ eligible: ["os", "professional", "enterprise"]
139
+ },
140
+ troubleshoot: {
141
+ id: "troubleshoot",
142
+ title: "Troubleshoot",
143
+ description: "Expand your plan with device troubleshooting features",
144
+ needs: ["hasDeviceConnect"],
145
+ os: {
146
+ price: "$27/month",
147
+ deviceCount: startingDeviceCount.os
148
+ },
149
+ professional: {
150
+ price: "$72/month",
151
+ deviceCount: startingDeviceCount.professional
152
+ },
153
+ eligible: ["os", "professional", "enterprise"]
154
+ },
155
+ monitor: {
156
+ id: "monitor",
157
+ title: "Monitor",
158
+ description: "Expand your plan with device monitoring features",
159
+ needs: ["hasMonitor"],
160
+ os: {
161
+ price: "-",
162
+ deviceCount: "-"
163
+ },
164
+ professional: {
165
+ price: "$86/month",
166
+ deviceCount: startingDeviceCount.professional
167
+ },
168
+ eligible: ["professional", "enterprise"]
169
+ }
170
+ };
171
+ var BENEFITS = {
172
+ auditlog: { id: "auditlog", benefit: "trace change across your devices and access troubleshooting session replay", requiredPlan: PLANS.professional.id },
173
+ dashboard: { id: "dashboard", benefit: "actionable insights into the devices you are updating with Mender", requiredPlan: PLANS.enterprise.id },
174
+ deltaGeneration: {
175
+ id: "deltaGeneration",
176
+ benefit: "automatic delta artifacts generation to minimize data transfer and improve the update delivery",
177
+ requiredPlan: PLANS.enterprise.id
178
+ },
179
+ deviceConfiguration: { id: "deviceConfiguration", benefit: "device configuration features", requiredAddon: ADDONS.configure.id },
180
+ deviceMonitor: { id: "deviceMonitor", benefit: "device monitoring features", requiredAddon: ADDONS.monitor.id, requiredPlan: PLANS.professional.id },
181
+ deviceTroubleshoot: { id: "deviceTroubleshoot", benefit: "device troubleshooting features", requiredAddon: ADDONS.troubleshoot.id },
182
+ dynamicGroups: { id: "dynamicGroups", benefit: "create dynamic groups to ease device management", requiredPlan: PLANS.enterprise.id },
183
+ fullFiltering: { id: "fullFiltering", benefit: "filtering by multiple attributes to improve the device overview", requiredPlan: PLANS.professional.id },
184
+ gateway: { id: "gateway", benefit: "see devices connected to your gateway device for easy access", requiredPlans: PLANS.professional.id },
185
+ pausedDeployments: {
186
+ id: "pausedDeployments",
187
+ benefit: "granular control about update rollout to allow synchronization across your fleet",
188
+ requiredPlan: PLANS.enterprise.id
189
+ },
190
+ phasedDeployments: { id: "phasedDeployments", benefit: "choose to roll out deployments in multiple phases", requiredPlan: PLANS.enterprise.id },
191
+ rbac: { id: "rbac", benefit: "granular role based access control", requiredPlan: PLANS.enterprise.id },
192
+ retryDeployments: { id: "retryDeployments", benefit: "optional retries for failed rollout attempts", requiredPlan: PLANS.professional.id },
193
+ scheduledDeployments: {
194
+ id: "scheduledDeployments",
195
+ benefit: "scheduled deployments to steer the distribution of your updates.",
196
+ requiredPlan: PLANS.professional.id
197
+ },
198
+ webhookEvents: {
199
+ id: "webhookEvents",
200
+ benefit: "receive inventory events and select which type(s) of events the webhook will receive",
201
+ requiredPlan: PLANS.professional.id
202
+ },
203
+ default: { id: "default", benefit: "gain access to this feature", requiredPlan: PLANS.enterprise.id }
204
+ };
205
+ var DARK_MODE = "dark";
206
+ var APPLICATION_JSON_CONTENT_TYPE = "application/json";
207
+ var APPLICATION_JWT_CONTENT_TYPE = "application/jwt";
208
+
209
+ // src/commonConstants.tsx
210
+ var import_js = require("@mdi/js");
211
+ var import_jsx_runtime = require("react/jsx-runtime");
212
+ var DEVICE_LIST_DEFAULTS = {
213
+ page: 1,
214
+ perPage: 20
215
+ };
216
+ var timeUnits = {
217
+ days: "days",
218
+ minutes: "minutes",
219
+ hours: "hours"
220
+ };
221
+ var ALL_DEVICES = "All devices";
222
+ var UNGROUPED_GROUP = { id: "*|=ungrouped=|*", name: "Unassigned" };
223
+ var DEVICE_LIST_MAXIMUM_LENGTH = 50;
224
+ var DEVICE_FILTERING_OPTIONS = {
225
+ $eq: { key: "$eq", title: "equals", shortform: "=" },
226
+ $ne: { key: "$ne", title: "not equal", shortform: "!=" },
227
+ $gt: {
228
+ key: "$gt",
229
+ title: ">",
230
+ shortform: ">",
231
+ help: 'The "greater than" operator can work both on numbers and strings. In the latter case, the operator applies the lexicographical order to the value strings.'
232
+ },
233
+ $gte: {
234
+ title: ">=",
235
+ shortform: ">=",
236
+ help: 'The "greater than or equal" operator can work both on numbers and strings. In the latter case, the operator applies the lexicographical order to the value strings.'
237
+ },
238
+ $lt: {
239
+ key: "$lt",
240
+ title: "<",
241
+ shortform: "<",
242
+ help: 'The "lesser than" operator can work both on numbers and strings. In the latter case, the operator applies the lexicographical order to the value strings.'
243
+ },
244
+ $lte: {
245
+ title: "<=",
246
+ shortform: "<=",
247
+ help: 'The "lesser than or equal" operator can work both on numbers and strings. In the latter case, the operator applies the lexicographical order to the value strings.'
248
+ },
249
+ $ltne: {
250
+ key: "$ltne",
251
+ title: "$ltne",
252
+ shortform: "ltne",
253
+ help: 'The "lesser than or does not exist" operator can work both on numbers and strings. In the latter case, the operator applies the lexicographical order to the value strings.'
254
+ },
255
+ $in: {
256
+ key: "$in",
257
+ title: "in",
258
+ shortform: "in",
259
+ help: 'The "in" operator accepts a list of comma-separated values. It matches if the selected field is equal to one of the specified values.'
260
+ },
261
+ $nin: {
262
+ key: "$nin",
263
+ title: "not in",
264
+ shortform: "not in",
265
+ help: `The "not in" operator accepts a list of comma-separated values. It matches if the selected field's value is not equal to any of the specified options.`
266
+ },
267
+ $exists: {
268
+ key: "$exists",
269
+ title: "exists",
270
+ shortform: "exists",
271
+ value: true,
272
+ help: `The "exists" operator matches if the selected field's value has a value. No value needs to be provided for this operator.`
273
+ },
274
+ $nexists: {
275
+ key: "$nexists",
276
+ title: `doesn't exist`,
277
+ shortform: `doesn't exist`,
278
+ value: true,
279
+ help: `The "doesn't exist" operator matches if the selected field's value has no value. No value needs to be provided for this operator.`
280
+ },
281
+ $regex: {
282
+ key: "$regex",
283
+ title: `matches regular expression`,
284
+ shortform: `matches`,
285
+ help: `The "regular expression" operator matches the selected field's value with a Perl compatible regular expression (PCRE), automatically anchored by ^. If the regular expression is not valid, the filter will produce no results. If you need to specify options and flags, you can provide the full regex in the format of /regex/flags, for example.`
286
+ }
287
+ };
288
+ var DEVICE_ISSUE_OPTIONS = {
289
+ issues: {
290
+ isCategory: true,
291
+ key: "issues",
292
+ title: "Devices with issues",
293
+ filterRule: {}
294
+ },
295
+ offline: {
296
+ issueCategory: "issues",
297
+ key: "offline",
298
+ needsFullFiltering: true,
299
+ needsMonitor: false,
300
+ needsReporting: false,
301
+ filterRule: {
302
+ scope: "system",
303
+ key: "check_in_time",
304
+ operator: DEVICE_FILTERING_OPTIONS.$ltne.key,
305
+ value: ({ offlineThreshold }) => offlineThreshold
306
+ },
307
+ title: "Offline devices"
308
+ },
309
+ failedLastUpdate: {
310
+ issueCategory: "issues",
311
+ key: "failedLastUpdate",
312
+ needsFullFiltering: false,
313
+ needsMonitor: false,
314
+ needsReporting: true,
315
+ filterRule: { scope: "monitor", key: "failed_last_update", operator: DEVICE_FILTERING_OPTIONS.$eq.key, value: true },
316
+ title: "Deployment failed"
317
+ },
318
+ monitoring: {
319
+ issueCategory: "issues",
320
+ key: "monitoring",
321
+ needsFullFiltering: false,
322
+ needsMonitor: true,
323
+ needsReporting: false,
324
+ filterRule: { scope: "monitor", key: "alerts", operator: DEVICE_FILTERING_OPTIONS.$eq.key, value: true },
325
+ title: "Monitoring alert"
326
+ },
327
+ authRequests: {
328
+ key: "authRequests",
329
+ needsFullFiltering: false,
330
+ needsMonitor: false,
331
+ needsReporting: true,
332
+ filterRule: { scope: "monitor", key: "auth_requests", operator: DEVICE_FILTERING_OPTIONS.$gt.key, value: 1 },
333
+ title: "Devices with new authentication requests"
334
+ },
335
+ gatewayDevices: {
336
+ key: "gatewayDevices",
337
+ needsFullFiltering: false,
338
+ needsMonitor: false,
339
+ needsReporting: true,
340
+ filterRule: { scope: "inventory", key: "mender_is_gateway", operator: DEVICE_FILTERING_OPTIONS.$eq.key, value: "true" },
341
+ title: "Gateway devices"
342
+ }
343
+ };
344
+ var oneSecond = 1e3;
345
+ var TIMEOUTS = {
346
+ debounceDefault: 700,
347
+ debounceShort: 300,
348
+ halfASecond: 0.5 * oneSecond,
349
+ oneSecond,
350
+ twoSeconds: 2 * oneSecond,
351
+ threeSeconds: 3 * oneSecond,
352
+ fiveSeconds: 5 * oneSecond,
353
+ refreshDefault: 10 * oneSecond,
354
+ refreshLong: 60 * oneSecond
355
+ };
356
+ var SORTING_OPTIONS = {
357
+ asc: "asc",
358
+ desc: "desc"
359
+ };
360
+ var DEVICE_ONLINE_CUTOFF = { interval: 1, intervalName: timeUnits.days };
361
+ var ATTRIBUTE_SCOPES = {
362
+ inventory: "inventory",
363
+ identity: "identity",
364
+ monitor: "monitor",
365
+ system: "system",
366
+ tags: "tags"
367
+ };
368
+ var defaultIdAttribute = Object.freeze({ attribute: "id", scope: ATTRIBUTE_SCOPES.identity });
369
+ var credentialTypes = {
370
+ aws: "aws",
371
+ http: "http",
372
+ sas: "sas",
373
+ x509: "x509"
374
+ };
375
+ var EXTERNAL_PROVIDER = {
376
+ "iot-core": {
377
+ credentialsType: credentialTypes.aws,
378
+ icon: import_js.mdiAws,
379
+ title: "AWS IoT Core",
380
+ twinTitle: "Device Shadow",
381
+ provider: "iot-core",
382
+ enabled: true,
383
+ deviceTwin: true,
384
+ configHint: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children: "For help finding your AWS IoT Core connection string, check the AWS IoT documentation." })
385
+ },
386
+ "iot-hub": {
387
+ credentialsType: credentialTypes.sas,
388
+ icon: import_js.mdiMicrosoftAzure,
389
+ title: "Azure IoT Hub",
390
+ twinTitle: "Device Twin",
391
+ provider: "iot-hub",
392
+ enabled: true,
393
+ deviceTwin: true,
394
+ configHint: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { children: [
395
+ "For help finding your Azure IoT Hub connection string, look under 'Shared access policies' in the Microsoft Azure UI as described",
396
+ " ",
397
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
398
+ "a",
399
+ {
400
+ href: "https://devblogs.microsoft.com/iotdev/understand-different-connection-strings-in-azure-iot-hub/#iothubconn",
401
+ target: "_blank",
402
+ rel: "noopener noreferrer",
403
+ children: "here"
404
+ }
405
+ ),
406
+ "."
407
+ ] })
408
+ },
409
+ webhook: {
410
+ credentialsType: credentialTypes.http,
411
+ deviceTwin: false,
412
+ // disable the webhook provider here, since it is treated different than other integrations, with a custom configuration & management view, etc.
413
+ enabled: false,
414
+ provider: "webhook"
415
+ }
416
+ };
417
+ var MAX_PAGE_SIZE = 500;
418
+ var ALL_RELEASES = "All releases";
419
+ var emptyUiPermissions = Object.freeze({
420
+ auditlog: [],
421
+ deployments: [],
422
+ groups: Object.freeze({}),
423
+ releases: Object.freeze({}),
424
+ tenantManagement: [],
425
+ userManagement: []
426
+ });
427
+ var emptyRole = Object.freeze({
428
+ name: void 0,
429
+ description: "",
430
+ permissions: [],
431
+ uiPermissions: Object.freeze({ ...emptyUiPermissions })
432
+ });
433
+
434
+ // src/deploymentsSlice/constants.ts
435
+ var alreadyInstalled = "already-installed";
436
+ var deploymentsApiUrl = `${apiUrl.v1}/deployments`;
437
+ var deploymentsApiUrlV2 = `${apiUrl.v2}/deployments`;
438
+ var deploymentSubstates = {
439
+ aborted: "aborted",
440
+ alreadyInstalled,
441
+ decommissioned: "decommissioned",
442
+ downloading: "downloading",
443
+ failure: "failure",
444
+ installing: "installing",
445
+ noartifact: "noartifact",
446
+ pause_before_committing: "pause_before_committing",
447
+ pause_before_installing: "pause_before_installing",
448
+ pause_before_rebooting: "pause_before_rebooting",
449
+ pending: "pending",
450
+ rebooting: "rebooting",
451
+ success: "success"
452
+ };
453
+ var deploymentStatesToSubstates = {
454
+ failures: [deploymentSubstates.failure, deploymentSubstates.aborted, deploymentSubstates.decommissioned],
455
+ inprogress: [deploymentSubstates.downloading, deploymentSubstates.installing, deploymentSubstates.rebooting],
456
+ paused: [deploymentSubstates.pause_before_installing, deploymentSubstates.pause_before_rebooting, deploymentSubstates.pause_before_committing],
457
+ pending: [deploymentSubstates.pending],
458
+ successes: [deploymentSubstates.success, deploymentSubstates.alreadyInstalled, deploymentSubstates.noartifact]
459
+ };
460
+ var deploymentStatesToSubstatesWithSkipped = {
461
+ ...deploymentStatesToSubstates,
462
+ failures: [deploymentSubstates.failure],
463
+ skipped: [deploymentSubstates.aborted, deploymentSubstates.noartifact, deploymentSubstates.alreadyInstalled, deploymentSubstates.decommissioned],
464
+ successes: [deploymentSubstates.success]
465
+ };
466
+ var installationSubstatesMap = {
467
+ download: {
468
+ title: "download",
469
+ done: "downloaded",
470
+ successIndicators: [deploymentSubstates.installing, deploymentSubstates.rebooting, ...deploymentStatesToSubstates.paused, deploymentSubstates.success],
471
+ failureIndicators: deploymentStatesToSubstates.failures,
472
+ pauseConfigurationIndicator: "ArtifactInstall_Enter"
473
+ },
474
+ install: {
475
+ title: "install",
476
+ done: "installed",
477
+ successIndicators: [
478
+ deploymentSubstates.rebooting,
479
+ deploymentSubstates.pause_before_rebooting,
480
+ deploymentSubstates.pause_before_committing,
481
+ deploymentSubstates.success
482
+ ],
483
+ failureIndicators: deploymentStatesToSubstates.failures,
484
+ pauseConfigurationIndicator: "ArtifactReboot_Enter"
485
+ },
486
+ reboot: {
487
+ title: "reboot",
488
+ done: "rebooted",
489
+ successIndicators: [deploymentSubstates.pause_before_committing, deploymentSubstates.success],
490
+ failureIndicators: deploymentStatesToSubstates.failures,
491
+ pauseConfigurationIndicator: "ArtifactCommit_Enter"
492
+ },
493
+ commit: {
494
+ title: "commit",
495
+ done: "committed",
496
+ successIndicators: deploymentStatesToSubstates.successes,
497
+ failureIndicators: deploymentStatesToSubstates.failures,
498
+ pauseConfigurationIndicator: void 0
499
+ }
500
+ };
501
+ var DEPLOYMENT_STATES = {
502
+ finished: "finished",
503
+ inprogress: "inprogress",
504
+ pending: "pending",
505
+ scheduled: "scheduled"
506
+ };
507
+ var listDefaultsByState = {
508
+ [DEPLOYMENT_STATES.inprogress]: { page: 1, perPage: 10 },
509
+ [DEPLOYMENT_STATES.pending]: { page: 1, perPage: 10 },
510
+ [DEPLOYMENT_STATES.scheduled]: { ...DEVICE_LIST_DEFAULTS },
511
+ [DEPLOYMENT_STATES.finished]: { ...DEVICE_LIST_DEFAULTS },
512
+ sort: { direction: SORTING_OPTIONS.desc }
513
+ };
514
+ var DEFAULT_PENDING_INPROGRESS_COUNT = 10;
515
+ var DEPLOYMENT_ROUTES = {
516
+ active: {
517
+ key: "active",
518
+ route: "/deployments/active",
519
+ states: [DEPLOYMENT_STATES.pending, DEPLOYMENT_STATES.inprogress],
520
+ title: "Active"
521
+ },
522
+ finished: {
523
+ key: "finished",
524
+ route: "/deployments/finished",
525
+ states: [DEPLOYMENT_STATES.finished],
526
+ title: "Finished"
527
+ },
528
+ scheduled: {
529
+ key: "scheduled",
530
+ route: "/deployments/scheduled",
531
+ states: [DEPLOYMENT_STATES.scheduled],
532
+ title: "Scheduled"
533
+ }
534
+ };
535
+ var DEPLOYMENT_TYPES = {
536
+ software: "software",
537
+ configuration: "configuration"
538
+ };
539
+ var defaultStats = {
540
+ [deploymentSubstates.aborted]: 0,
541
+ [deploymentSubstates.alreadyInstalled]: 0,
542
+ [deploymentSubstates.decommissioned]: 0,
543
+ [deploymentSubstates.downloading]: 0,
544
+ [deploymentSubstates.failure]: 0,
545
+ [deploymentSubstates.installing]: 0,
546
+ [deploymentSubstates.noartifact]: 0,
547
+ [deploymentSubstates.pause_before_committing]: 0,
548
+ [deploymentSubstates.pause_before_installing]: 0,
549
+ [deploymentSubstates.pause_before_rebooting]: 0,
550
+ [deploymentSubstates.pending]: 0,
551
+ [deploymentSubstates.rebooting]: 0,
552
+ [deploymentSubstates.success]: 0
553
+ };
554
+ var deploymentPrototype = {
555
+ devices: {},
556
+ name: void 0,
557
+ statistics: { status: {} }
558
+ };
559
+ var pauseMap = {
560
+ [deploymentSubstates.pause_before_installing]: {
561
+ title: installationSubstatesMap.download.done,
562
+ followUp: installationSubstatesMap.download.pauseConfigurationIndicator
563
+ },
564
+ [deploymentSubstates.pause_before_rebooting]: {
565
+ title: installationSubstatesMap.install.done,
566
+ followUp: installationSubstatesMap.install.pauseConfigurationIndicator
567
+ },
568
+ [deploymentSubstates.pause_before_committing]: {
569
+ title: installationSubstatesMap.reboot.done,
570
+ followUp: installationSubstatesMap.reboot.pauseConfigurationIndicator
571
+ }
572
+ };
573
+ var limitDefault = { min: 5, max: 100, default: 10 };
574
+
575
+ // src/devicesSlice/constants.ts
576
+ var emptyFilter = { key: null, value: "", operator: DEVICE_FILTERING_OPTIONS.$eq.key, scope: "inventory" };
577
+ var deviceAuthV2 = `${apiUrl.v2}/devauth`;
578
+ var deviceConnect = `${apiUrl.v1}/deviceconnect`;
579
+ var inventoryApiUrl = `${apiUrl.v1}/inventory`;
580
+ var inventoryApiUrlV2 = `${apiUrl.v2}/inventory`;
581
+ var deviceConfig = `${apiUrl.v1}/deviceconfig/configurations/device`;
582
+ var reportingApiUrl = `${apiUrl.v1}/reporting`;
583
+ var iotManagerBaseURL = `${apiUrl.v1}/iot-manager`;
584
+ var ALL_DEVICE_STATES = "any";
585
+ var DEVICE_STATES = {
586
+ accepted: "accepted",
587
+ pending: "pending",
588
+ preauth: "preauthorized",
589
+ rejected: "rejected"
590
+ };
591
+ var geoAttributes = ["geo-lat", "geo-lon"].map((attribute) => ({ attribute, scope: "inventory" }));
592
+
593
+ // src/monitorSlice/constants.ts
594
+ var alertChannels = { email: "email" };
595
+ var monitorApiUrlv1 = `${apiUrl.v1}/devicemonitor`;
596
+
597
+ // src/onboardingSlice/constants.ts
598
+ var onboardingSteps = {
599
+ ONBOARDING_START: "onboarding-start",
600
+ DEVICES_PENDING_ONBOARDING_START: "devices-pending-onboarding-start",
601
+ DASHBOARD_ONBOARDING_START: "dashboard-onboarding-start",
602
+ DASHBOARD_ONBOARDING_PENDINGS: "dashboard-onboarding-pendings",
603
+ DEVICES_DELAYED_ONBOARDING: "devices-delayed-onboarding",
604
+ DEVICES_PENDING_ONBOARDING: "devices-pending-onboarding",
605
+ DEVICES_ACCEPTED_ONBOARDING: "devices-accepted-onboarding",
606
+ DEVICES_PENDING_ACCEPTING_ONBOARDING: "devices-pending-accepting-onboarding",
607
+ DEVICES_DEPLOY_RELEASE_ONBOARDING: "devices-deploy-release-onboarding",
608
+ SCHEDULING_ARTIFACT_SELECTION: "scheduling-artifact-selection",
609
+ SCHEDULING_ALL_DEVICES_SELECTION: "scheduling-all-devices-selection",
610
+ SCHEDULING_GROUP_SELECTION: "scheduling-group-selection",
611
+ SCHEDULING_RELEASE_TO_DEVICES: "scheduling-release-to-devices",
612
+ DEPLOYMENTS_INPROGRESS: "deployments-inprogress",
613
+ DEPLOYMENTS_PAST: "deployments-past",
614
+ DEPLOYMENTS_PAST_COMPLETED: "deployments-past-completed",
615
+ DEPLOYMENTS_PAST_COMPLETED_FAILURE: "deployments-past-completed-failure",
616
+ ONBOARDING_CANCELED: "onboarding-canceled"
617
+ };
618
+ var orderedOnboardingSteps = [
619
+ onboardingSteps.DASHBOARD_ONBOARDING_START,
620
+ onboardingSteps.DEVICES_PENDING_ONBOARDING_START,
621
+ onboardingSteps.DEVICES_DELAYED_ONBOARDING,
622
+ onboardingSteps.DEVICES_PENDING_ONBOARDING,
623
+ onboardingSteps.DEVICES_PENDING_ACCEPTING_ONBOARDING,
624
+ onboardingSteps.DASHBOARD_ONBOARDING_PENDINGS,
625
+ onboardingSteps.DEVICES_ACCEPTED_ONBOARDING,
626
+ onboardingSteps.DEVICES_DEPLOY_RELEASE_ONBOARDING,
627
+ onboardingSteps.SCHEDULING_ALL_DEVICES_SELECTION,
628
+ onboardingSteps.SCHEDULING_GROUP_SELECTION,
629
+ onboardingSteps.SCHEDULING_ARTIFACT_SELECTION,
630
+ onboardingSteps.SCHEDULING_RELEASE_TO_DEVICES,
631
+ onboardingSteps.DEPLOYMENTS_INPROGRESS,
632
+ onboardingSteps.DEPLOYMENTS_PAST,
633
+ onboardingSteps.DEPLOYMENTS_PAST_COMPLETED,
634
+ onboardingSteps.DEPLOYMENTS_PAST_COMPLETED_FAILURE,
635
+ onboardingSteps.ONBOARDING_CANCELED
636
+ ];
637
+
638
+ // src/organizationSlice/constants.ts
639
+ var auditLogsApiUrl = `${apiUrl.v1}/auditlogs`;
640
+ var tenantadmApiUrlv1 = `${apiUrl.v1}/tenantadm`;
641
+ var tenantadmApiUrlv2 = `${apiUrl.v2}/tenantadm`;
642
+ var ssoIdpApiUrlv1 = `${apiUrl.v1}/useradm/sso/idp/metadata`;
643
+ var XML_METADATA_FORMAT = "xml";
644
+ var JSON_METADATA_FORMAT = "json";
645
+ var getSamlStartUrl = (id) => `${window.location.origin}${useradmApiUrlv1}/auth/sso/${id}/login`;
646
+ var getOidcStartUrl = (id) => `${window.location.origin}${useradmApiUrlv1}/oidc/${id}/start`;
647
+ var SSO_TYPES = {
648
+ saml: {
649
+ id: "saml",
650
+ type: "saml",
651
+ title: "SAML",
652
+ metadataFormat: XML_METADATA_FORMAT,
653
+ editorLanguage: XML_METADATA_FORMAT,
654
+ contentType: "application/samlmetadata+xml",
655
+ getStartUrl: getSamlStartUrl,
656
+ configDetails: [
657
+ { key: "entityID", label: "Entity ID", getValue: (id) => `${window.location.origin}${useradmApiUrlv1}/sso/sp/metadata/${id}` },
658
+ { key: "acs", label: "ACS URL", getValue: (id) => `${window.location.origin}${useradmApiUrlv1}/auth/sso/${id}/acs` },
659
+ { key: "startURL", label: "Start URL", getValue: getSamlStartUrl }
660
+ ]
661
+ },
662
+ oidc: {
663
+ id: "oidc",
664
+ type: "oidc",
665
+ title: "OpenID Connect",
666
+ metadataFormat: JSON_METADATA_FORMAT,
667
+ editorLanguage: JSON_METADATA_FORMAT,
668
+ contentType: "application/json",
669
+ getStartUrl: getOidcStartUrl,
670
+ configDetails: [{ key: "startURL", label: "Start Url", getValue: getOidcStartUrl }]
671
+ }
672
+ };
673
+ var AUDIT_LOGS_TYPES = [
674
+ { title: "Artifact", queryParameter: "object_type", value: "artifact" },
675
+ { title: "Deployment", queryParameter: "object_deployment_name", value: "deployment" },
676
+ { title: "Device", queryParameter: "object_id", value: "device" },
677
+ { title: "User", queryParameter: "object_id", value: "user" }
678
+ ];
679
+ var SP_AUDIT_LOGS_TYPES = [AUDIT_LOGS_TYPES[3], { title: "Tenant", queryParameter: "object_id", value: "tenant" }];
680
+ var emptyWebhook = {
681
+ description: "",
682
+ enabled: true,
683
+ credentials: {
684
+ type: EXTERNAL_PROVIDER.webhook.credentialsType,
685
+ [EXTERNAL_PROVIDER.webhook.credentialsType]: {
686
+ secret: "",
687
+ url: ""
688
+ }
689
+ }
690
+ };
691
+ var TENANT_LIST_DEFAULT = {
692
+ page: 1,
693
+ perPage: 20
694
+ };
695
+
696
+ // src/releasesSlice/constants.ts
697
+ var rootfsImageVersion = "rootfs-image.version";
698
+ var softwareTitleMap = { [rootfsImageVersion]: { title: "Root filesystem", priority: 0, key: rootfsImageVersion } };
699
+
700
+ // src/usersSlice/constants.ts
701
+ var useradmApiUrlv1 = `${apiUrl.v1}/useradm`;
702
+ var useradmApiUrlv2 = `${apiUrl.v2}/useradm`;
703
+ var staticRolesByName = {
704
+ admin: "RBAC_ROLE_PERMIT_ALL",
705
+ readOnly: "RBAC_ROLE_OBSERVER",
706
+ ci: "RBAC_ROLE_CI",
707
+ deploymentsManager: "RBAC_ROLE_DEPLOYMENTS_MANAGER",
708
+ terminalAccess: "RBAC_ROLE_REMOTE_TERMINAL"
709
+ };
710
+ var PermissionTypes = {
711
+ Any: "any",
712
+ Get: "GET",
713
+ Post: "POST",
714
+ Put: "PUT",
715
+ Delete: "DELETE",
716
+ Patch: "PATCH",
717
+ DeviceGroup: "DEVICE_GROUP",
718
+ DeviceId: "DEVICE_ID"
719
+ };
720
+ var permissionSetIds = {
721
+ Basic: "Basic",
722
+ ConfigureDevices: "ConfigureDevices",
723
+ ConnectToDevices: "ConnectToDevices",
724
+ DeployToDevices: "DeployToDevices",
725
+ ManageDevices: "ManageDevices",
726
+ ManageReleases: "ManageReleases",
727
+ ManageTenants: "ManageTenants",
728
+ ManageUsers: "ManageUsers",
729
+ ReadAuditLogs: "ReadAuditLogs",
730
+ ReadDevices: "ReadDevices",
731
+ ReadReleases: "ReadReleases",
732
+ ReadTenants: "ReadTenants",
733
+ ReadUsers: "ReadUsers",
734
+ SuperUser: "SuperUser",
735
+ UploadArtifacts: "UploadArtifacts"
736
+ };
737
+ var uiPermissionsById = {
738
+ configure: {
739
+ explanations: { groups: `'Configure' allows the user to use mender-configure features and apply configurations.` },
740
+ permissionLevel: 2,
741
+ permissionSets: { groups: permissionSetIds.ConfigureDevices },
742
+ title: "Configure",
743
+ value: "configure",
744
+ verbs: [PermissionTypes.Get, PermissionTypes.Put, PermissionTypes.Post]
745
+ },
746
+ connect: {
747
+ explanations: { groups: `'Connect' allows the user to use mender-connect features and Troubleshoot add-ons.` },
748
+ permissionLevel: 2,
749
+ permissionSets: { groups: permissionSetIds.ConnectToDevices },
750
+ title: "Connect",
751
+ value: "connect",
752
+ verbs: [PermissionTypes.Get, PermissionTypes.Put]
753
+ },
754
+ deploy: {
755
+ explanations: { groups: `'Deploy' allows the user to deploy software or configuration updates to devices.` },
756
+ permissionLevel: 2,
757
+ permissionSets: { deployments: permissionSetIds.DeployToDevices, groups: permissionSetIds.DeployToDevices },
758
+ title: "Deploy",
759
+ value: "deploy",
760
+ verbs: [PermissionTypes.Post]
761
+ },
762
+ manage: {
763
+ explanations: {
764
+ groups: `'Manage' allows the user to edit device name, notes, and manage authentication status. For 'All devices' it also allows the user to edit and create device groups.`,
765
+ releases: `'Manage' allows the user to upload new artifacts, edit release descriptions and remove artifacts.`
766
+ },
767
+ permissionLevel: 2,
768
+ permissionSets: {
769
+ groups: permissionSetIds.ManageDevices,
770
+ releases: permissionSetIds.ManageReleases,
771
+ tenantManagement: permissionSetIds.ManageTenants,
772
+ userManagement: permissionSetIds.ManageUsers
773
+ },
774
+ title: "Manage",
775
+ value: "manage",
776
+ verbs: [PermissionTypes.Post, PermissionTypes.Put, PermissionTypes.Patch]
777
+ },
778
+ read: {
779
+ explanations: { groups: `'Read' allows the user to view devices.` },
780
+ permissionLevel: 1,
781
+ permissionSets: {
782
+ auditlog: permissionSetIds.ReadAuditLogs,
783
+ groups: permissionSetIds.ReadDevices,
784
+ releases: permissionSetIds.ReadReleases,
785
+ tenantManagement: permissionSetIds.ReadTenants,
786
+ userManagement: permissionSetIds.ReadUsers
787
+ },
788
+ title: "Read",
789
+ value: "read",
790
+ verbs: [PermissionTypes.Get, PermissionTypes.Post]
791
+ },
792
+ upload: {
793
+ explanations: { groups: `'Upload' allows the user to upload new Artifacts.` },
794
+ unscopedOnly: { releases: true },
795
+ permissionLevel: 1,
796
+ permissionSets: { releases: permissionSetIds.UploadArtifacts },
797
+ title: "Upload",
798
+ value: "upload",
799
+ verbs: [PermissionTypes.Post, PermissionTypes.Put, PermissionTypes.Patch]
800
+ }
801
+ };
802
+ var scopedPermissionAreas = {
803
+ groups: { key: "groups", excessiveAccessSelector: ALL_DEVICES, scopeType: "DeviceGroups" },
804
+ releases: { key: "releases", excessiveAccessSelector: ALL_RELEASES, scopeType: "Releases" }
805
+ };
806
+ var uiPermissionsByArea = {
807
+ auditlog: {
808
+ endpoints: [{ path: /\/(auditlog)/i, types: [PermissionTypes.Get], uiPermissions: [uiPermissionsById.read] }],
809
+ explanation: "Granting access to the audit log will allow tracing changes to devices, releases and user accounts, as well as providing information about deployments.",
810
+ key: "auditlog",
811
+ uiPermissions: [uiPermissionsById.read],
812
+ title: "System audit log"
813
+ },
814
+ deployments: {
815
+ endpoints: [
816
+ { path: /\/(deployments\/deployments)/i, types: [PermissionTypes.Post, PermissionTypes.Put], uiPermissions: [uiPermissionsById.deploy] },
817
+ { path: /\/(deployments\/deployments)/i, types: [PermissionTypes.Get], uiPermissions: [uiPermissionsById.read] },
818
+ { path: /\/(deployments\/config)/i, types: [PermissionTypes.Get, PermissionTypes.Put], uiPermissions: [uiPermissionsById.manage] }
819
+ ],
820
+ explanation: "Providing deploy permissions will allow deployments to be created using the releases and devices a user has access to.",
821
+ key: "deployments",
822
+ uiPermissions: [uiPermissionsById.read, uiPermissionsById.deploy],
823
+ title: "Deployments"
824
+ },
825
+ groups: {
826
+ endpoints: [
827
+ {
828
+ path: /\/(devauth|inventory|deviceconfig|devicemonitor|deviceconnect\/devices)/i,
829
+ types: [PermissionTypes.Get],
830
+ uiPermissions: [uiPermissionsById.read]
831
+ },
832
+ { path: /\/(devauth|inventory)/i, types: [PermissionTypes.Put, PermissionTypes.Post], uiPermissions: [uiPermissionsById.manage] },
833
+ { path: /\/(deviceconfig)/i, types: [PermissionTypes.Get, PermissionTypes.Put, PermissionTypes.Post], uiPermissions: [uiPermissionsById.configure] },
834
+ { path: /\/(deviceconnect\/devices)/i, types: [PermissionTypes.Get, PermissionTypes.Post], uiPermissions: [uiPermissionsById.connect] }
835
+ ],
836
+ explanation: "Device group management permissions control the degree to which devices in a group can be accessed and moved to other groups.",
837
+ key: "groups",
838
+ scope: scopedPermissionAreas.groups.scopeType,
839
+ uiPermissions: [uiPermissionsById.read, uiPermissionsById.manage, uiPermissionsById.deploy, uiPermissionsById.configure, uiPermissionsById.connect],
840
+ title: "Group Management"
841
+ },
842
+ releases: {
843
+ endpoints: [
844
+ { path: /\/(deployments\/artifacts|deployments\/deployments\/releases)/i, types: [PermissionTypes.Get], uiPermissions: [uiPermissionsById.read] },
845
+ {
846
+ path: /\/(deployments\/artifacts|deployments\/deployments\/releases)/i,
847
+ types: [PermissionTypes.Post, PermissionTypes.Put],
848
+ uiPermissions: [uiPermissionsById.read, uiPermissionsById.upload]
849
+ },
850
+ {
851
+ path: /\/(deployments\/artifacts|deployments\/deployments\/releases)/i,
852
+ types: [PermissionTypes.Delete],
853
+ uiPermissions: [uiPermissionsById.read, uiPermissionsById.manage]
854
+ }
855
+ ],
856
+ explanation: "Release permissions can be granted to allow artifact & release modifications, as well as the creation of new releases.",
857
+ key: "releases",
858
+ scope: "ReleaseTags",
859
+ uiPermissions: [uiPermissionsById.read, uiPermissionsById.manage, uiPermissionsById.upload],
860
+ title: "Release Management"
861
+ },
862
+ tenantManagement: {
863
+ endpoints: [
864
+ { path: /\/(tenantadm\/tenants)/i, types: [PermissionTypes.Get], uiPermissions: [uiPermissionsById.read] },
865
+ { path: /\/(tenantadm\/tenants)/i, types: [PermissionTypes.Post, PermissionTypes.Put], uiPermissions: [uiPermissionsById.manage] },
866
+ { path: /\/(users\/exists)/i, types: [PermissionTypes.Get], uiPermissions: [uiPermissionsById.manage] }
867
+ ],
868
+ explanation: "Tenant management permissions allow listing, creating and modifying child tenants",
869
+ key: "tenantManagement",
870
+ uiPermissions: [uiPermissionsById.read, uiPermissionsById.manage],
871
+ title: "Tenant Management"
872
+ },
873
+ userManagement: {
874
+ endpoints: [
875
+ { path: /\/(useradm)/i, types: [PermissionTypes.Get], uiPermissions: [uiPermissionsById.read] },
876
+ { path: /\/(useradm)/i, types: [PermissionTypes.Post], uiPermissions: [uiPermissionsById.manage] }
877
+ ],
878
+ explanation: "User management permissions should be granted carefully, as these allow privilege increases for any users managed by a user with user management permissions",
879
+ key: "userManagement",
880
+ uiPermissions: [uiPermissionsById.read, uiPermissionsById.manage],
881
+ title: "User Management"
882
+ }
883
+ };
884
+ var permissionMapper = (permission) => permission.value;
885
+ var itemUiPermissionsReducer = (accu, { item, uiPermissions }) => item ? { ...accu, [item]: uiPermissions } : accu;
886
+ var rolesById = Object.freeze({
887
+ [staticRolesByName.admin]: {
888
+ name: "Admin",
889
+ value: staticRolesByName.admin,
890
+ description: "Full access",
891
+ permissions: [],
892
+ // permissions refers to the values returned from the backend
893
+ uiPermissions: {
894
+ ...emptyUiPermissions,
895
+ auditlog: uiPermissionsByArea.auditlog.uiPermissions.map(permissionMapper),
896
+ deployments: uiPermissionsByArea.deployments.uiPermissions.map(permissionMapper),
897
+ groups: { [ALL_DEVICES]: uiPermissionsByArea.groups.uiPermissions.map(permissionMapper) },
898
+ releases: { [ALL_RELEASES]: uiPermissionsByArea.releases.uiPermissions.map(permissionMapper) },
899
+ userManagement: uiPermissionsByArea.userManagement.uiPermissions.map(permissionMapper)
900
+ }
901
+ },
902
+ [staticRolesByName.readOnly]: {
903
+ name: "Read Access",
904
+ value: staticRolesByName.readOnly,
905
+ description: "",
906
+ permissions: [],
907
+ uiPermissions: {
908
+ ...emptyUiPermissions,
909
+ deployments: [uiPermissionsById.read.value],
910
+ groups: { [ALL_DEVICES]: [uiPermissionsById.read.value] },
911
+ releases: { [ALL_RELEASES]: [uiPermissionsById.read.value] },
912
+ userManagement: [uiPermissionsById.read.value]
913
+ }
914
+ },
915
+ [staticRolesByName.ci]: {
916
+ name: "Releases Manager",
917
+ value: staticRolesByName.ci,
918
+ description: "",
919
+ permissions: [],
920
+ uiPermissions: {
921
+ ...emptyUiPermissions,
922
+ releases: { [ALL_RELEASES]: uiPermissionsByArea.releases.uiPermissions.map(permissionMapper) }
923
+ }
924
+ },
925
+ [staticRolesByName.deploymentsManager]: {
926
+ name: "Deployments Manager",
927
+ value: staticRolesByName.deploymentsManager,
928
+ description: "",
929
+ permissions: [],
930
+ uiPermissions: {
931
+ ...emptyUiPermissions,
932
+ deployments: uiPermissionsByArea.deployments.uiPermissions.map(permissionMapper),
933
+ groups: { [ALL_DEVICES]: [uiPermissionsById.deploy.value, uiPermissionsById.read.value] },
934
+ releases: { [ALL_RELEASES]: [uiPermissionsById.read.value] }
935
+ }
936
+ },
937
+ [staticRolesByName.terminalAccess]: {
938
+ name: "Troubleshooting",
939
+ value: staticRolesByName.terminalAccess,
940
+ description: "Access to the troubleshooting features: Remote Terminal, File Transfer, Port Forwarding",
941
+ permissions: [],
942
+ uiPermissions: {
943
+ ...emptyUiPermissions,
944
+ groups: { [ALL_DEVICES]: [uiPermissionsById.connect.value] }
945
+ }
946
+ }
947
+ });
948
+ var serviceProviderRolesById = {
949
+ admin: {
950
+ name: "Admin",
951
+ value: staticRolesByName.admin,
952
+ description: "Full access",
953
+ permissions: [],
954
+ uiPermissions: {
955
+ ...emptyUiPermissions,
956
+ auditlog: uiPermissionsByArea.auditlog.uiPermissions.map(permissionMapper),
957
+ userManagement: uiPermissionsByArea.userManagement.uiPermissions.map(permissionMapper),
958
+ tenantManagement: uiPermissionsByArea.tenantManagement.uiPermissions.map(permissionMapper)
959
+ }
960
+ },
961
+ readOnly: {
962
+ name: "Read access",
963
+ value: staticRolesByName.admin,
964
+ description: "This role can see all linked organizations but cannot make any changes",
965
+ permissions: [],
966
+ uiPermissions: {
967
+ ...emptyUiPermissions,
968
+ auditlog: [uiPermissionsById.read.value],
969
+ userManagement: [uiPermissionsById.read.value],
970
+ tenantManagement: [uiPermissionsById.read.value]
971
+ }
972
+ }
973
+ };
974
+ var defaultPermissionSets = {
975
+ [permissionSetIds.Basic]: {
976
+ name: permissionSetIds.Basic,
977
+ result: {
978
+ // this is needed to prevent the detailed permissions of the basic permission set from being interpreted as allowing read & management access to user endpoints
979
+ userManagement: [uiPermissionsById.read.value]
980
+ }
981
+ },
982
+ [permissionSetIds.SuperUser]: {
983
+ name: permissionSetIds.SuperUser,
984
+ result: {
985
+ ...rolesById[staticRolesByName.admin].uiPermissions
986
+ }
987
+ },
988
+ [permissionSetIds.ManageUsers]: {
989
+ name: permissionSetIds.ManageUsers,
990
+ result: {
991
+ userManagement: [uiPermissionsById.manage.value]
992
+ }
993
+ },
994
+ [permissionSetIds.ReadAuditLogs]: {
995
+ name: permissionSetIds.ReadAuditLogs,
996
+ result: {
997
+ auditlog: [uiPermissionsById.read.value]
998
+ }
999
+ },
1000
+ [permissionSetIds.ReadReleases]: {
1001
+ name: permissionSetIds.ReadReleases,
1002
+ result: {
1003
+ releases: { [ALL_RELEASES]: [uiPermissionsById.read.value] }
1004
+ }
1005
+ },
1006
+ [permissionSetIds.ReadTenants]: {
1007
+ name: permissionSetIds.ReadTenants,
1008
+ result: {
1009
+ tenantManagement: [uiPermissionsById.read.value]
1010
+ }
1011
+ },
1012
+ [permissionSetIds.ManageTenants]: {
1013
+ name: permissionSetIds.ManageTenants,
1014
+ result: {
1015
+ tenantManagement: [uiPermissionsById.manage.value]
1016
+ }
1017
+ },
1018
+ [permissionSetIds.ReadUsers]: {
1019
+ name: permissionSetIds.ReadUsers,
1020
+ result: {
1021
+ userManagement: [uiPermissionsById.read.value]
1022
+ }
1023
+ },
1024
+ [permissionSetIds.UploadArtifacts]: {
1025
+ name: permissionSetIds.UploadArtifacts,
1026
+ result: {
1027
+ releases: { [ALL_RELEASES]: [uiPermissionsById.upload.value] }
1028
+ }
1029
+ },
1030
+ [permissionSetIds.ManageReleases]: {
1031
+ name: permissionSetIds.ManageReleases,
1032
+ result: {
1033
+ releases: { [ALL_RELEASES]: [uiPermissionsById.manage.value] }
1034
+ }
1035
+ },
1036
+ [permissionSetIds.ConfigureDevices]: {
1037
+ name: permissionSetIds.ConfigureDevices,
1038
+ result: {
1039
+ deployments: [uiPermissionsById.read.value, uiPermissionsById.deploy.value],
1040
+ groups: { [ALL_DEVICES]: [uiPermissionsById.read.value, uiPermissionsById.configure.value] }
1041
+ }
1042
+ },
1043
+ [permissionSetIds.ConnectToDevices]: {
1044
+ name: permissionSetIds.ConnectToDevices,
1045
+ result: {
1046
+ groups: { [ALL_DEVICES]: [uiPermissionsById.read.value, uiPermissionsById.connect.value] }
1047
+ }
1048
+ },
1049
+ [permissionSetIds.DeployToDevices]: {
1050
+ name: permissionSetIds.DeployToDevices,
1051
+ result: {
1052
+ deployments: [uiPermissionsById.deploy.value, uiPermissionsById.manage.value, uiPermissionsById.read.value],
1053
+ groups: { [ALL_DEVICES]: [uiPermissionsById.read.value, uiPermissionsById.deploy.value] }
1054
+ }
1055
+ },
1056
+ [permissionSetIds.ManageDevices]: {
1057
+ name: permissionSetIds.ManageDevices,
1058
+ result: {
1059
+ groups: { [ALL_DEVICES]: [uiPermissionsById.read.value, uiPermissionsById.manage.value] }
1060
+ }
1061
+ },
1062
+ [permissionSetIds.ReadDevices]: {
1063
+ name: permissionSetIds.ReadDevices,
1064
+ result: {
1065
+ groups: { [ALL_DEVICES]: [uiPermissionsById.read.value] }
1066
+ }
1067
+ }
1068
+ };
1069
+ var USER_LOGOUT = "USER_LOGOUT";
1070
+ var OWN_USER_ID = "me";
1071
+ var rolesByName = {
1072
+ ...staticRolesByName,
1073
+ deploymentCreation: { action: "CREATE_DEPLOYMENT", object: { type: "DEVICE_GROUP", value: void 0 } },
1074
+ groupAccess: { action: "VIEW_DEVICE", object: { type: "DEVICE_GROUP", value: void 0 } },
1075
+ userManagement: { action: "http", object: { type: "any", value: `${useradmApiUrlv1}/.*` } }
1076
+ };
1077
+ var twoFAStates = {
1078
+ enabled: "enabled",
1079
+ disabled: "disabled",
1080
+ unverified: "unverified"
1081
+ };
1082
+ var settingsKeys = { initialized: "settings-initialized" };
1083
+ var READ_STATES = {
1084
+ read: "read",
1085
+ seen: "seen",
1086
+ unread: "unread"
1087
+ };
1088
+
1089
+ // src/appSlice/index.ts
1090
+ var import_toolkit = require("@reduxjs/toolkit");
1091
+ var sliceName = "app";
1092
+ var getYesterday = () => {
1093
+ const today = /* @__PURE__ */ new Date();
1094
+ today.setDate(today.getDate() - 1);
1095
+ return today.toISOString();
1096
+ };
1097
+ var initialState = {
1098
+ cancelSource: void 0,
1099
+ demoArtifactLink: "https://dgsbl4vditpls.cloudfront.net/mender-demo-artifact.mender",
1100
+ hostAddress: null,
1101
+ snackbar: {
1102
+ open: false,
1103
+ message: "",
1104
+ maxWidth: 900,
1105
+ autoHideDuration: void 0,
1106
+ action: void 0,
1107
+ children: void 0,
1108
+ onClick: void 0,
1109
+ onClose: void 0
1110
+ },
1111
+ // return boolean rather than organization details
1112
+ features: {
1113
+ hasAuditlogs: false,
1114
+ hasDeltaProgress: false,
1115
+ hasMultitenancy: false,
1116
+ hasDeviceConfig: false,
1117
+ hasDeviceConnect: false,
1118
+ hasFeedbackEnabled: false,
1119
+ hasMonitor: false,
1120
+ hasReporting: false,
1121
+ isDemoMode: false,
1122
+ isHosted: false,
1123
+ isEnterprise: false
1124
+ },
1125
+ feedbackProbability: 0.3,
1126
+ firstLoginAfterSignup: false,
1127
+ hostedAnnouncement: "",
1128
+ docsVersion: "",
1129
+ recaptchaSiteKey: "",
1130
+ searchState: {
1131
+ deviceIds: [],
1132
+ searchTerm: "",
1133
+ searchTotal: 0,
1134
+ sort: {
1135
+ direction: SORTING_OPTIONS.desc
1136
+ // key: null,
1137
+ // scope: null
1138
+ }
1139
+ },
1140
+ stripeAPIKey: "",
1141
+ trackerCode: "",
1142
+ uploadsById: {
1143
+ // id: { uploading: false, uploadProgress: 0, cancelSource: undefined }
1144
+ },
1145
+ newThreshold: getYesterday(),
1146
+ offlineThreshold: getYesterday(),
1147
+ versionInformation: {
1148
+ Integration: "",
1149
+ "Mender-Client": "",
1150
+ "Mender-Artifact": "",
1151
+ "Meta-Mender": "",
1152
+ Deployments: "",
1153
+ Deviceauth: "",
1154
+ Inventory: "",
1155
+ GUI: "latest"
1156
+ },
1157
+ yesterday: void 0
1158
+ };
1159
+ var appSlice = (0, import_toolkit.createSlice)({
1160
+ name: sliceName,
1161
+ initialState,
1162
+ reducers: {
1163
+ setFeatures: (state, action) => {
1164
+ state.features = {
1165
+ ...state.features,
1166
+ ...action.payload
1167
+ };
1168
+ },
1169
+ setSnackbar: (state, { payload }) => {
1170
+ let { message, autoHideDuration, action, children, onClick, onClose } = payload;
1171
+ if (typeof payload === "string" || payload instanceof String) {
1172
+ message = payload;
1173
+ }
1174
+ state.snackbar = {
1175
+ open: message ? true : false,
1176
+ message,
1177
+ maxWidth: 900,
1178
+ autoHideDuration,
1179
+ action,
1180
+ children,
1181
+ onClick,
1182
+ onClose
1183
+ };
1184
+ },
1185
+ setFirstLoginAfterSignup: (state, action) => {
1186
+ state.firstLoginAfterSignup = action.payload;
1187
+ },
1188
+ setAnnouncement: (state, action) => {
1189
+ state.hostedAnnouncement = action.payload;
1190
+ },
1191
+ setSearchState: (state, action) => {
1192
+ state.searchState = {
1193
+ ...state.searchState,
1194
+ ...action.payload
1195
+ };
1196
+ },
1197
+ setOfflineThreshold: (state, action) => {
1198
+ state.offlineThreshold = action.payload;
1199
+ },
1200
+ initUpload: (state, action) => {
1201
+ const { id, upload } = action.payload;
1202
+ state.uploadsById[id] = upload;
1203
+ },
1204
+ uploadProgress: (state, action) => {
1205
+ const { id, progress: progress2 } = action.payload;
1206
+ state.uploadsById[id] = {
1207
+ ...state.uploadsById[id],
1208
+ progress: progress2
1209
+ };
1210
+ },
1211
+ cleanUpUpload: (state, action) => {
1212
+ const { [action.payload]: current, ...remainder } = state.uploadsById;
1213
+ state.uploadsById = remainder;
1214
+ },
1215
+ setVersionInformation: (state, action) => {
1216
+ state.versionInformation = {
1217
+ ...state.versionInformation,
1218
+ ...action.payload
1219
+ };
1220
+ },
1221
+ setEnvironmentData: (state, action) => {
1222
+ return { ...state, ...action.payload };
1223
+ }
1224
+ }
1225
+ });
1226
+ var actions = appSlice.actions;
1227
+ var appSlice_default = appSlice.reducer;
1228
+
1229
+ // src/deploymentsSlice/index.ts
1230
+ var import_toolkit2 = require("@reduxjs/toolkit");
1231
+ var sliceName2 = "deployments";
1232
+ var initialState2 = {
1233
+ byId: {
1234
+ // [id]: { statistics: { status: {}, total_size }, devices: { [deploymentId]: { id, log } }, totalDeviceCount }
1235
+ },
1236
+ byStatus: {
1237
+ finished: { deploymentIds: [], total: 0 },
1238
+ inprogress: { deploymentIds: [], total: 0 },
1239
+ pending: { deploymentIds: [], total: 0 },
1240
+ scheduled: { deploymentIds: [], total: 0 }
1241
+ },
1242
+ config: {
1243
+ binaryDelta: {
1244
+ timeout: -1,
1245
+ duplicatesWindow: -1,
1246
+ compressionLevel: -1,
1247
+ disableChecksum: false,
1248
+ disableDecompression: false,
1249
+ inputWindow: -1,
1250
+ instructionBuffer: -1,
1251
+ sourceWindow: -1
1252
+ },
1253
+ binaryDeltaLimits: {
1254
+ timeout: { ...limitDefault, default: 60, max: 3600, min: 60 },
1255
+ sourceWindow: limitDefault,
1256
+ inputWindow: limitDefault,
1257
+ duplicatesWindow: limitDefault,
1258
+ instructionBuffer: limitDefault
1259
+ }
1260
+ },
1261
+ deploymentDeviceLimit: 5e3,
1262
+ selectedDeviceIds: [],
1263
+ selectionState: {
1264
+ finished: { ...DEVICE_LIST_DEFAULTS, endDate: void 0, search: "", selection: [], startDate: void 0, total: 0, type: "" },
1265
+ inprogress: { ...DEVICE_LIST_DEFAULTS, perPage: DEFAULT_PENDING_INPROGRESS_COUNT, selection: [] },
1266
+ pending: { ...DEVICE_LIST_DEFAULTS, perPage: DEFAULT_PENDING_INPROGRESS_COUNT, selection: [] },
1267
+ scheduled: { ...DEVICE_LIST_DEFAULTS, selection: [] },
1268
+ general: {
1269
+ state: DEPLOYMENT_ROUTES.active.key,
1270
+ showCreationDialog: false,
1271
+ showReportDialog: false,
1272
+ reportType: null
1273
+ // DeploymentConstants.DEPLOYMENT_TYPES.configuration|DeploymentConstants.DEPLOYMENT_TYPES.software
1274
+ },
1275
+ selectedId: void 0
1276
+ }
1277
+ };
1278
+ var deploymentsSlice = (0, import_toolkit2.createSlice)({
1279
+ name: sliceName2,
1280
+ initialState: initialState2,
1281
+ reducers: {
1282
+ createdDeployment: (state, action) => {
1283
+ state.byId[action.payload.id] = {
1284
+ ...deploymentPrototype,
1285
+ ...action.payload
1286
+ };
1287
+ state.byStatus[DEPLOYMENT_STATES.pending].total = state.byStatus[DEPLOYMENT_STATES.pending].total + 1;
1288
+ state.byStatus[DEPLOYMENT_STATES.pending].deploymentIds = [...state.byStatus.pending.deploymentIds, action.payload.id];
1289
+ state.selectionState[DEPLOYMENT_STATES.pending].selection = [action.payload.id, ...state.selectionState[DEPLOYMENT_STATES.pending].selection], state.selectionState[DEPLOYMENT_STATES.pending].total = state.selectionState[DEPLOYMENT_STATES.pending].total + 1;
1290
+ },
1291
+ removedDeployment: (state, action) => {
1292
+ const { [action.payload]: removedDeployment, ...remainder } = state.byId;
1293
+ state.byId = remainder;
1294
+ },
1295
+ receivedDeployment: (state, action) => {
1296
+ state.byId[action.payload.id] = {
1297
+ ...state.byId[action.payload.id] || {},
1298
+ ...action.payload
1299
+ };
1300
+ },
1301
+ receivedDeploymentDeviceLog: (state, action) => {
1302
+ const { id, deviceId, log } = action.payload;
1303
+ const deployment = {
1304
+ ...deploymentPrototype,
1305
+ ...state.byId[id]
1306
+ };
1307
+ state.byId[id] = {
1308
+ ...deployment,
1309
+ devices: {
1310
+ ...deployment.devices,
1311
+ [deviceId]: {
1312
+ ...deployment.devices[deviceId],
1313
+ log
1314
+ }
1315
+ }
1316
+ };
1317
+ },
1318
+ receivedDeploymentDevices: (state, action) => {
1319
+ const { id, devices, selectedDeviceIds, totalDeviceCount } = action.payload;
1320
+ state.byId[id] = {
1321
+ ...state.byId[id],
1322
+ devices,
1323
+ totalDeviceCount
1324
+ };
1325
+ state.selectedDeviceIds = selectedDeviceIds;
1326
+ },
1327
+ receivedDeployments: (state, action) => {
1328
+ state.byId = {
1329
+ ...state.byId,
1330
+ ...action.payload
1331
+ };
1332
+ },
1333
+ receivedDeploymentsForStatus: (state, action) => {
1334
+ const { status, deploymentIds, total } = action.payload;
1335
+ state.byStatus[status].deploymentIds = deploymentIds;
1336
+ state.byStatus[status].total = total;
1337
+ },
1338
+ selectDeploymentsForStatus: (state, action) => {
1339
+ const { status, deploymentIds, total } = action.payload;
1340
+ state.selectionState[status].selection = deploymentIds;
1341
+ state.selectionState[status].total = total;
1342
+ },
1343
+ setDeploymentsState: (state, action) => {
1344
+ state.selectionState = action.payload;
1345
+ },
1346
+ setDeploymentsConfig: (state, action) => {
1347
+ state.config = action.payload;
1348
+ }
1349
+ }
1350
+ });
1351
+ var actions2 = deploymentsSlice.actions;
1352
+ var deploymentsSlice_default = deploymentsSlice.reducer;
1353
+
1354
+ // src/devicesSlice/index.ts
1355
+ var import_helpers = require("@northern.tech/utils/helpers");
1356
+ var import_toolkit3 = require("@reduxjs/toolkit");
1357
+ var sliceName3 = "devices";
1358
+ var initialState3 = {
1359
+ byId: {
1360
+ // [deviceId]: {
1361
+ // ...,
1362
+ // twinsByIntegration: { [external.provider.id]: twinData }
1363
+ // }
1364
+ },
1365
+ byStatus: {
1366
+ [DEVICE_STATES.accepted]: { deviceIds: [], total: 0 },
1367
+ active: { deviceIds: [], total: 0 },
1368
+ inactive: { deviceIds: [], total: 0 },
1369
+ [DEVICE_STATES.pending]: { deviceIds: [], total: 0 },
1370
+ [DEVICE_STATES.preauth]: { deviceIds: [], total: 0 },
1371
+ [DEVICE_STATES.rejected]: { deviceIds: [], total: 0 }
1372
+ },
1373
+ deviceList: {
1374
+ deviceIds: [],
1375
+ ...DEVICE_LIST_DEFAULTS,
1376
+ selectedAttributes: [],
1377
+ selectedIssues: [],
1378
+ selection: [],
1379
+ sort: {
1380
+ direction: SORTING_OPTIONS.desc
1381
+ // key: null,
1382
+ // scope: null
1383
+ },
1384
+ state: DEVICE_STATES.accepted,
1385
+ total: 0
1386
+ },
1387
+ filters: [
1388
+ // { key: 'device_type', value: 'raspberry', operator: '$eq', scope: 'inventory' }
1389
+ ],
1390
+ filteringAttributes: { identityAttributes: [], inventoryAttributes: [], systemAttributes: [], tagAttributes: [] },
1391
+ filteringAttributesLimit: 10,
1392
+ filteringAttributesConfig: {
1393
+ attributes: {
1394
+ // inventory: ['some_attribute']
1395
+ },
1396
+ count: 0,
1397
+ limit: 100
1398
+ },
1399
+ reports: [
1400
+ // { items: [{ key: "someKey", count: 42 }], otherCount: 123, total: <otherCount + itemsCount> }
1401
+ ],
1402
+ total: 0,
1403
+ limit: 0,
1404
+ groups: {
1405
+ byId: {
1406
+ // groupName: { deviceIds: [], total: 0, filters: [] },
1407
+ // dynamo: { deviceIds: [], total: 3, filters: [{ a: 1 }] }
1408
+ },
1409
+ selectedGroup: void 0
1410
+ }
1411
+ };
1412
+ var devicesSlice = (0, import_toolkit3.createSlice)({
1413
+ name: sliceName3,
1414
+ initialState: initialState3,
1415
+ reducers: {
1416
+ receivedGroups: (state, action) => {
1417
+ state.groups.byId = action.payload;
1418
+ },
1419
+ addToGroup: (state, action) => {
1420
+ const { group, deviceIds } = action.payload;
1421
+ const maybeExistingGroup = {
1422
+ filters: [],
1423
+ deviceIds: [],
1424
+ ...state.groups.byId[group]
1425
+ };
1426
+ state.groups.byId[group] = {
1427
+ ...maybeExistingGroup,
1428
+ deviceIds: [...maybeExistingGroup.deviceIds, ...deviceIds].filter(import_helpers.duplicateFilter),
1429
+ total: (maybeExistingGroup.total || 0) + 1
1430
+ };
1431
+ },
1432
+ removeFromGroup: (state, action) => {
1433
+ const { group, deviceIds: removedIds } = action.payload;
1434
+ const { deviceIds = [], total = 0, ...maybeExistingGroup } = state.groups.byId[group] || {};
1435
+ const changedGroup = {
1436
+ ...maybeExistingGroup,
1437
+ deviceIds: deviceIds.filter((id) => !removedIds.includes(id)),
1438
+ total: Math.max(total - removedIds.length, 0)
1439
+ };
1440
+ if (changedGroup.total || changedGroup.deviceIds.length) {
1441
+ state.groups.byId[group] = changedGroup;
1442
+ return;
1443
+ } else if (state.groups.selectedGroup === group) {
1444
+ state.groups.selectedGroup = void 0;
1445
+ }
1446
+ const { [group]: removal, ...remainingById } = state.groups.byId;
1447
+ state.groups.byId = remainingById;
1448
+ },
1449
+ addGroup: (state, action) => {
1450
+ const { groupName, group } = action.payload;
1451
+ state.groups.byId[groupName] = {
1452
+ ...state.groups.byId[groupName],
1453
+ ...group
1454
+ };
1455
+ },
1456
+ selectGroup: (state, { payload: group }) => {
1457
+ state.deviceList.deviceIds = state.groups.byId[group] && state.groups.byId[group].deviceIds.length > 0 ? state.groups.byId[group].deviceIds : [];
1458
+ state.groups.selectedGroup = group;
1459
+ },
1460
+ removeGroup: (state, action) => {
1461
+ const { [action.payload]: removal, ...remainingById } = state.groups.byId;
1462
+ state.groups.byId = remainingById;
1463
+ state.groups.selectedGroup = state.groups.selectedGroup === action.payload ? void 0 : state.groups.selectedGroup;
1464
+ },
1465
+ setDeviceListState: (state, action) => {
1466
+ state.deviceList = {
1467
+ ...state.deviceList,
1468
+ ...action.payload,
1469
+ sort: {
1470
+ ...state.deviceList.sort,
1471
+ ...action.payload.sort
1472
+ }
1473
+ };
1474
+ },
1475
+ setFilterAttributes: (state, action) => {
1476
+ state.filteringAttributes = action.payload;
1477
+ },
1478
+ setFilterablesConfig: (state, action) => {
1479
+ state.filteringAttributesConfig = action.payload;
1480
+ },
1481
+ receivedDevices: (state, action) => {
1482
+ state.byId = {
1483
+ ...state.byId,
1484
+ ...action.payload
1485
+ };
1486
+ },
1487
+ setDeviceFilters: (state, action) => {
1488
+ if ((0, import_helpers.deepCompare)(action.payload, state.filters)) {
1489
+ return;
1490
+ }
1491
+ state.filters = action.payload.filter((filter) => filter.key && filter.operator && filter.scope && typeof filter.value !== "undefined");
1492
+ },
1493
+ setInactiveDevices: (state, action) => {
1494
+ const { activeDeviceTotal, inactiveDeviceTotal } = action.payload;
1495
+ state.byStatus.active.total = activeDeviceTotal;
1496
+ state.byStatus.inactive.total = inactiveDeviceTotal;
1497
+ },
1498
+ setDeviceReports: (state, action) => {
1499
+ state.reports = action.payload;
1500
+ },
1501
+ setDevicesByStatus: (state, action) => {
1502
+ const { forceUpdate, status, total, deviceIds } = action.payload;
1503
+ state.byStatus[status] = total || forceUpdate ? { deviceIds, total } : state.byStatus[status];
1504
+ },
1505
+ setDevicesCountByStatus: (state, action) => {
1506
+ const { count, status } = action.payload;
1507
+ state.byStatus[status].total = count;
1508
+ },
1509
+ setTotalDevices: (state, action) => {
1510
+ state.total = action.payload;
1511
+ },
1512
+ setDeviceLimit: (state, action) => {
1513
+ state.limit = action.payload;
1514
+ },
1515
+ receivedDevice: (state, action) => {
1516
+ state.byId[action.payload.id] = {
1517
+ ...state.byId[action.payload.id],
1518
+ ...action.payload
1519
+ };
1520
+ },
1521
+ maybeUpdateDevicesByStatus: (state, action) => {
1522
+ const { deviceId, authId } = action.payload;
1523
+ const device = state.byId[deviceId];
1524
+ const hasMultipleAuthSets = authId ? device.auth_sets.filter((authset) => authset.id !== authId).length > 0 : false;
1525
+ if (!hasMultipleAuthSets && Object.values(DEVICE_STATES).includes(device.status)) {
1526
+ const deviceIds = state.byStatus[device.status].deviceIds.filter((id) => id !== deviceId);
1527
+ state.byStatus[device.status] = { deviceIds, total: Math.max(0, state.byStatus[device.status].total - 1) };
1528
+ }
1529
+ }
1530
+ }
1531
+ });
1532
+ var actions3 = devicesSlice.actions;
1533
+ var devicesSlice_default = devicesSlice.reducer;
1534
+
1535
+ // src/monitorSlice/index.ts
1536
+ var import_toolkit4 = require("@reduxjs/toolkit");
1537
+ var sliceName4 = "monitor";
1538
+ var initialState4 = {
1539
+ alerts: {
1540
+ alertList: { ...DEVICE_LIST_DEFAULTS, total: 0 },
1541
+ byDeviceId: {}
1542
+ },
1543
+ issueCounts: {
1544
+ byType: Object.values(DEVICE_ISSUE_OPTIONS).reduce((accu, { key }) => ({ ...accu, [key]: { filtered: 0, total: 0 } }), {})
1545
+ },
1546
+ settings: {
1547
+ global: {
1548
+ channels: {
1549
+ ...Object.keys(alertChannels).reduce((accu, item) => ({ ...accu, [item]: { enabled: true } }), {})
1550
+ }
1551
+ }
1552
+ }
1553
+ };
1554
+ var monitorSlice = (0, import_toolkit4.createSlice)({
1555
+ name: sliceName4,
1556
+ initialState: initialState4,
1557
+ reducers: {
1558
+ changeAlertChannel: (state, action) => {
1559
+ const { channel, enabled } = action.payload;
1560
+ state.settings.global.channels[channel] = { enabled };
1561
+ },
1562
+ receiveDeviceAlerts: (state, action) => {
1563
+ const { deviceId, alerts } = action.payload;
1564
+ state.alerts.byDeviceId[deviceId] = { alerts };
1565
+ },
1566
+ receiveLatestDeviceAlerts: (state, action) => {
1567
+ const { deviceId, alerts } = action.payload;
1568
+ state.alerts.byDeviceId[deviceId] = { ...state.alerts.byDeviceId[deviceId], latest: alerts };
1569
+ },
1570
+ receiveDeviceIssueCounts: (state, action) => {
1571
+ const { issueType, counts } = action.payload;
1572
+ state.issueCounts.byType[issueType] = counts;
1573
+ },
1574
+ setAlertListState: (state, action) => {
1575
+ state.alerts.alertList = { ...state.alerts.alertList, ...action.payload };
1576
+ }
1577
+ }
1578
+ });
1579
+ var actions4 = monitorSlice.actions;
1580
+ var monitorSlice_default = monitorSlice.reducer;
1581
+
1582
+ // src/onboardingSlice/index.ts
1583
+ var import_toolkit5 = require("@reduxjs/toolkit");
1584
+ var sliceName5 = "onboarding";
1585
+ var initialState5 = {
1586
+ approach: null,
1587
+ complete: false,
1588
+ deviceType: null,
1589
+ demoArtifactPort: 85,
1590
+ progress: null,
1591
+ showTips: null,
1592
+ showTipsDialog: false
1593
+ };
1594
+ var onboardingSlice = (0, import_toolkit5.createSlice)({
1595
+ name: sliceName5,
1596
+ initialState: initialState5,
1597
+ reducers: {
1598
+ setOnboardingState: (state, action) => {
1599
+ return { ...state, ...action.payload };
1600
+ },
1601
+ setDemoArtifactPort: (state, action) => {
1602
+ state.demoArtifactPort = action.payload;
1603
+ },
1604
+ setShowOnboardingHelp: (state, action) => {
1605
+ state.showTips = action.payload;
1606
+ },
1607
+ setShowDismissOnboardingTipsDialog: (state, action) => {
1608
+ state.showTipsDialog = action.payload;
1609
+ },
1610
+ setOnboardingComplete: (state, action) => {
1611
+ state.complete = action.payload;
1612
+ },
1613
+ setOnboardingProgress: (state, action) => {
1614
+ state.progress = action.payload;
1615
+ },
1616
+ setOnboardingDeviceType: (state, action) => {
1617
+ state.deviceType = action.payload;
1618
+ },
1619
+ setOnboardingApproach: (state, action) => {
1620
+ state.approach = action.payload;
1621
+ }
1622
+ }
1623
+ });
1624
+ var actions5 = onboardingSlice.actions;
1625
+ var onboardingSlice_default = onboardingSlice.reducer;
1626
+
1627
+ // src/organizationSlice/index.ts
1628
+ var import_toolkit6 = require("@reduxjs/toolkit");
1629
+ var sliceName6 = "organization";
1630
+ var initialState6 = {
1631
+ card: {
1632
+ last4: "",
1633
+ expiration: { month: 1, year: 2020 },
1634
+ brand: ""
1635
+ },
1636
+ intentId: null,
1637
+ tenantList: {
1638
+ ...TENANT_LIST_DEFAULT,
1639
+ total: 0,
1640
+ tenants: [],
1641
+ selectedTenant: null,
1642
+ sort: {
1643
+ direction: SORTING_OPTIONS.desc,
1644
+ key: "name"
1645
+ }
1646
+ },
1647
+ organization: {
1648
+ // id, name, status, tenant_token, plan
1649
+ },
1650
+ auditlog: {
1651
+ events: [],
1652
+ selectionState: {
1653
+ ...DEVICE_LIST_DEFAULTS,
1654
+ detail: void 0,
1655
+ endDate: void 0,
1656
+ selectedIssue: void 0,
1657
+ sort: { direction: SORTING_OPTIONS.desc },
1658
+ startDate: void 0,
1659
+ total: 0,
1660
+ type: void 0,
1661
+ user: void 0
1662
+ }
1663
+ },
1664
+ externalDeviceIntegrations: [
1665
+ // { <connection_string|x509|...>, id, provider }
1666
+ ],
1667
+ ssoConfigs: [],
1668
+ webhooks: {
1669
+ // [id]: { events: [] }
1670
+ // for now:
1671
+ events: [],
1672
+ eventsTotal: 0
1673
+ }
1674
+ };
1675
+ var organizationSlice = (0, import_toolkit6.createSlice)({
1676
+ name: sliceName6,
1677
+ initialState: initialState6,
1678
+ reducers: {
1679
+ receiveAuditLogs: (state, action) => {
1680
+ const { events, total } = action.payload;
1681
+ state.auditlog.events = events;
1682
+ state.auditlog.selectionState.total = total;
1683
+ },
1684
+ setAuditLogState: (state, action) => {
1685
+ state.auditlog.selectionState = {
1686
+ ...state.auditlog.selectionState,
1687
+ ...action.payload
1688
+ };
1689
+ },
1690
+ receiveCurrentCard: (state, action) => {
1691
+ state.card = action.payload;
1692
+ },
1693
+ receiveSetupIntent: (state, action) => {
1694
+ state.intentId = action.payload;
1695
+ },
1696
+ setOrganization: (state, action) => {
1697
+ state.organization = { ...state.organization, ...action.payload };
1698
+ },
1699
+ setTenantListState: (state, action) => {
1700
+ state.tenantList = action.payload;
1701
+ },
1702
+ receiveExternalDeviceIntegrations: (state, action) => {
1703
+ state.externalDeviceIntegrations = action.payload;
1704
+ },
1705
+ receiveSsoConfigs: (state, action) => {
1706
+ state.ssoConfigs = action.payload;
1707
+ },
1708
+ receiveWebhookEvents: (state, action) => {
1709
+ const { value, total } = action.payload;
1710
+ state.webhooks.events = value;
1711
+ state.webhooks.eventsTotal = total;
1712
+ }
1713
+ }
1714
+ });
1715
+ var actions6 = organizationSlice.actions;
1716
+ var organizationSlice_default = organizationSlice.reducer;
1717
+
1718
+ // src/releasesSlice/index.ts
1719
+ var import_toolkit7 = require("@reduxjs/toolkit");
1720
+ var sliceName7 = "releases";
1721
+ var initialState7 = {
1722
+ /*
1723
+ * Return list of saved artifacts objects
1724
+ */
1725
+ /*
1726
+ * return list of artifacts where duplicate names are collated with device compatibility lists combined
1727
+ */
1728
+ // artifacts: AppStore.getCollatedArtifacts(AppStore.getArtifactsRepo()),
1729
+ artifacts: [],
1730
+ /*
1731
+ * Return list of saved release objects
1732
+ */
1733
+ byId: {
1734
+ /*
1735
+ [releaseName]: {
1736
+ artifacts: [
1737
+ {
1738
+ id: '',
1739
+ name: '',
1740
+ description: '',
1741
+ device_types_compatible: [],
1742
+ ...
1743
+ updates: [{
1744
+ files: [
1745
+ { size: 123, name: '' }
1746
+ ],
1747
+ type_info: { type: '' }
1748
+ }],
1749
+ url: '' // optional
1750
+ }
1751
+ ],
1752
+ modified: ''
1753
+ device_types_compatible,
1754
+ name: '',
1755
+ tags: ['something'],
1756
+ notes: ''
1757
+ }
1758
+ */
1759
+ },
1760
+ releasesList: {
1761
+ ...DEVICE_LIST_DEFAULTS,
1762
+ searchedIds: [],
1763
+ releaseIds: [],
1764
+ selection: [],
1765
+ sort: {
1766
+ direction: SORTING_OPTIONS.desc,
1767
+ key: "modified"
1768
+ },
1769
+ isLoading: void 0,
1770
+ searchTerm: "",
1771
+ searchTotal: 0,
1772
+ selectedTags: [],
1773
+ total: 0,
1774
+ type: ""
1775
+ },
1776
+ tags: [],
1777
+ updateTypes: [],
1778
+ /*
1779
+ * Return single release with corresponding Artifacts
1780
+ */
1781
+ selectedRelease: null
1782
+ };
1783
+ var releaseSlice = (0, import_toolkit7.createSlice)({
1784
+ name: sliceName7,
1785
+ initialState: initialState7,
1786
+ reducers: {
1787
+ receiveRelease: (state, action) => {
1788
+ const { name } = action.payload;
1789
+ state.byId[name] = action.payload;
1790
+ },
1791
+ receiveReleases: (state, action) => {
1792
+ state.byId = action.payload;
1793
+ },
1794
+ receiveReleaseTags: (state, action) => {
1795
+ state.tags = action.payload;
1796
+ },
1797
+ receiveReleaseTypes: (state, action) => {
1798
+ state.updateTypes = action.payload;
1799
+ },
1800
+ removeRelease: (state, action) => {
1801
+ const { [action.payload]: toBeRemoved, ...byId } = state.byId;
1802
+ state.byId = byId;
1803
+ state.selectedRelease = action.payload === state.selectedRelease ? null : state.selectedRelease;
1804
+ },
1805
+ selectedRelease: (state, action) => {
1806
+ state.selectedRelease = action.payload;
1807
+ },
1808
+ setReleaseListState: (state, action) => {
1809
+ state.releasesList = action.payload;
1810
+ }
1811
+ }
1812
+ });
1813
+ var actions7 = releaseSlice.actions;
1814
+ var releasesSlice_default = releaseSlice.reducer;
1815
+
1816
+ // src/usersSlice/index.ts
1817
+ var import_toolkit8 = require("@reduxjs/toolkit");
1818
+ var sliceName8 = "users";
1819
+ var initialState8 = {
1820
+ activationCode: void 0,
1821
+ byId: {},
1822
+ currentUser: null,
1823
+ currentSession: {
1824
+ // { token: window.localStorage.getItem('JWT'), expiresAt: '2023-01-01T00:15:00.000Z' | undefined }, // expiresAt depending on the stay logged in setting
1825
+ },
1826
+ customColumns: [],
1827
+ qrCode: null,
1828
+ globalSettings: {
1829
+ id_attribute: void 0,
1830
+ previousFilters: [],
1831
+ previousPhases: [],
1832
+ retries: 0
1833
+ },
1834
+ permissionSetsById: {
1835
+ ...defaultPermissionSets
1836
+ },
1837
+ rolesById: {
1838
+ ...rolesById
1839
+ },
1840
+ settingsInitialized: false,
1841
+ showConnectDeviceDialog: false,
1842
+ showFeedbackDialog: false,
1843
+ showStartupNotification: false,
1844
+ tooltips: {
1845
+ byId: {
1846
+ // <id>: { readState: <read|unread> } // this object is getting enhanced by the tooltip texts in the app constants
1847
+ }
1848
+ },
1849
+ userSettings: {
1850
+ columnSelection: [],
1851
+ onboarding: {}
1852
+ },
1853
+ userSettingsInitialized: false
1854
+ };
1855
+ var usersSlice = (0, import_toolkit8.createSlice)({
1856
+ name: sliceName8,
1857
+ initialState: initialState8,
1858
+ reducers: {
1859
+ receivedQrCode: (state, action) => {
1860
+ state.qrCode = action.payload;
1861
+ },
1862
+ successfullyLoggedIn: (state, action) => {
1863
+ state.currentSession = action.payload;
1864
+ },
1865
+ receivedUserList: (state, action) => {
1866
+ state.byId = action.payload;
1867
+ },
1868
+ receivedActivationCode: (state, action) => {
1869
+ state.activationCode = action.payload;
1870
+ },
1871
+ receivedUser: (state, action) => {
1872
+ state.byId[action.payload.id] = action.payload;
1873
+ state.currentUser = action.payload.id;
1874
+ },
1875
+ createdUser: (state, action) => {
1876
+ state.byId[0] = action.payload;
1877
+ },
1878
+ removedUser: (state, action) => {
1879
+ const { [action.payload]: removedUser, ...byId } = state.byId;
1880
+ state.byId = byId;
1881
+ state.currentUser = state.currentUser === action.payload ? null : state.currentUser;
1882
+ },
1883
+ updatedUser: (state, action) => {
1884
+ state.byId[action.payload.id] = {
1885
+ ...state.byId[action.payload.id],
1886
+ ...action.payload
1887
+ };
1888
+ },
1889
+ receivedPermissionSets: (state, action) => {
1890
+ state.permissionSetsById = action.payload;
1891
+ },
1892
+ receivedRoles: (state, action) => {
1893
+ state.rolesById = action.payload;
1894
+ },
1895
+ createdRole: (state, action) => {
1896
+ state.rolesById[action.payload.name] = {
1897
+ ...state.rolesById[action.payload.name],
1898
+ ...action.payload
1899
+ };
1900
+ },
1901
+ removedRole: (state, action) => {
1902
+ const { [action.payload]: toBeRemoved, ...rolesById2 } = state.rolesById;
1903
+ state.rolesById = rolesById2;
1904
+ },
1905
+ setCustomColumns: (state, action) => {
1906
+ state.customColumns = action.payload;
1907
+ },
1908
+ setGlobalSettings: (state, action) => {
1909
+ state.settingsInitialized = true;
1910
+ state.globalSettings = {
1911
+ ...state.globalSettings,
1912
+ ...action.payload
1913
+ };
1914
+ },
1915
+ setUserSettings: (state, action) => {
1916
+ state.userSettingsInitialized = true;
1917
+ state.userSettings = {
1918
+ ...state.userSettings,
1919
+ ...action.payload
1920
+ };
1921
+ },
1922
+ setTooltipState: (state, action) => {
1923
+ const { id, readState = READ_STATES.read } = action.payload;
1924
+ state.tooltips.byId[id].readState = readState;
1925
+ },
1926
+ setTooltipsState: (state, action) => {
1927
+ state.tooltips.byId = {
1928
+ ...state.tooltips.byId,
1929
+ ...action.payload
1930
+ };
1931
+ },
1932
+ setShowFeedbackDialog: (state, action) => {
1933
+ state.showFeedbackDialog = action.payload;
1934
+ },
1935
+ setShowConnectingDialog: (state, action) => {
1936
+ state.showConnectDeviceDialog = action.payload;
1937
+ },
1938
+ setShowStartupNotification: (state, action) => {
1939
+ state.showStartupNotification = action.payload;
1940
+ }
1941
+ }
1942
+ });
1943
+ var actions8 = usersSlice.actions;
1944
+ var usersSlice_default = usersSlice.reducer;
1945
+
1946
+ // src/actions.ts
1947
+ var actions_default = {
1948
+ ...actions,
1949
+ ...actions2,
1950
+ ...actions3,
1951
+ ...actions4,
1952
+ ...actions5,
1953
+ ...actions6,
1954
+ ...actions7,
1955
+ ...actions8
1956
+ };
1957
+
1958
+ // src/api/general-api.ts
1959
+ var import_axios = __toESM(require("axios"), 1);
1960
+
1961
+ // src/auth.ts
1962
+ var import_universal_cookie = __toESM(require("universal-cookie"), 1);
1963
+ var cookies = new import_universal_cookie.default();
1964
+ var emptySession = Object.freeze({ token: "", exiresAt: void 0 });
1965
+ var tokenCache = "";
1966
+ var getSessionInfo = () => {
1967
+ let sessionInfo = { ...emptySession };
1968
+ try {
1969
+ sessionInfo = JSON.parse(window.localStorage.getItem("JWT") ?? "");
1970
+ } catch {
1971
+ }
1972
+ if (sessionInfo.expiresAt && new Date(sessionInfo.expiresAt) < /* @__PURE__ */ new Date()) {
1973
+ cleanUp();
1974
+ return { ...emptySession };
1975
+ }
1976
+ if (!sessionInfo.token) {
1977
+ let jwtTokenFromCookie = cookies.get("JWT", { doNotParse: true }) ?? "";
1978
+ if (jwtTokenFromCookie) {
1979
+ setSessionInfo({ token: jwtTokenFromCookie, undefined: void 0 });
1980
+ sessionInfo.token = jwtTokenFromCookie;
1981
+ cookies.remove("JWT");
1982
+ cookies.remove("JWT", { path: "/" });
1983
+ }
1984
+ }
1985
+ sessionInfo.token = sessionInfo.token || void 0;
1986
+ tokenCache = sessionInfo.token;
1987
+ return sessionInfo;
1988
+ };
1989
+ var getToken = () => tokenCache ? tokenCache : getSessionInfo().token;
1990
+ var setSessionInfo = ({ token, expiresAt }) => {
1991
+ tokenCache = token;
1992
+ window.localStorage.setItem("JWT", JSON.stringify({ token, expiresAt }));
1993
+ };
1994
+ var cleanUp = () => {
1995
+ tokenCache = "";
1996
+ cookies.remove("JWT");
1997
+ cookies.remove("JWT", { path: "/" });
1998
+ window.localStorage.removeItem("JWT");
1999
+ window.localStorage.removeItem("oauth");
2000
+ };
2001
+ var maxSessionAge = 900;
2002
+
2003
+ // src/api/general-api.ts
2004
+ var unauthorizedRedirect = (error) => {
2005
+ if (!(0, import_axios.isCancel)(error) && error.response?.status === 401 && getToken()) {
2006
+ cleanUp();
2007
+ window.location.replace("/ui/");
2008
+ }
2009
+ return Promise.reject(error);
2010
+ };
2011
+ var commonRequestConfig = { timeout: TIMEOUTS.refreshDefault, headers: { "Content-Type": "application/json" } };
2012
+ var authenticatedRequest = import_axios.default.create(commonRequestConfig);
2013
+ authenticatedRequest.interceptors.response.use((res) => res, unauthorizedRedirect);
2014
+ authenticatedRequest.interceptors.request.use(
2015
+ (config) => ({ ...config, headers: { ...config.headers, Authorization: `Bearer ${getToken()}` } }),
2016
+ (error) => Promise.reject(error)
2017
+ );
2018
+ var Api = {
2019
+ get: authenticatedRequest.get,
2020
+ delete: (url, data) => authenticatedRequest.request({ method: "delete", url, data }),
2021
+ patch: authenticatedRequest.patch,
2022
+ post: authenticatedRequest.post,
2023
+ postUnauthorized: (url, data, config = {}) => import_axios.default.post(url, data, { ...commonRequestConfig, ...config }),
2024
+ put: authenticatedRequest.put,
2025
+ upload: (url, formData, progress2, cancelSignal) => authenticatedRequest.post(url, formData, {
2026
+ headers: { "Content-Type": "multipart/form-data" },
2027
+ onUploadProgress: progress2,
2028
+ timeout: 0,
2029
+ signal: cancelSignal
2030
+ }),
2031
+ uploadPut: (url, formData, progress2, cancelSignal) => authenticatedRequest.put(url, formData, {
2032
+ headers: { "Content-Type": "multipart/form-data" },
2033
+ onUploadProgress: progress2,
2034
+ timeout: 0,
2035
+ signal: cancelSignal
2036
+ })
2037
+ };
2038
+ var general_api_default = Api;
2039
+
2040
+ // src/api/users-api.ts
2041
+ var import_axios2 = __toESM(require("axios"), 1);
2042
+ var Api2 = {
2043
+ postLogin: (url, { email: username, password, ...body }) => import_axios2.default.post(url, body, { ...commonRequestConfig, auth: { username, password } }).then((res) => ({ text: res.data, code: res.status, contentType: res.headers?.["content-type"] })),
2044
+ putVerifyTFA: (url, userData) => {
2045
+ let body = {};
2046
+ if (userData.hasOwnProperty("token2fa")) {
2047
+ body = { token2fa: userData.token2fa };
2048
+ }
2049
+ return import_axios2.default.put(url, body, { ...commonRequestConfig, headers: { ...commonRequestConfig.headers, Authorization: `Bearer ${getToken()}` } });
2050
+ }
2051
+ };
2052
+ var users_api_default = Api2;
2053
+
2054
+ // src/appSlice/selectors.ts
2055
+ var import_helpers2 = require("@northern.tech/utils/helpers");
2056
+ var import_toolkit9 = require("@reduxjs/toolkit");
2057
+ var getAppDocsVersion = (state) => state.app.docsVersion;
2058
+ var getFeatures = (state) => state.app.features;
2059
+ var getFullVersionInformation = (state) => state.app.versionInformation;
2060
+ var getDocsVersion = (0, import_toolkit9.createSelector)([getAppDocsVersion, getFeatures], (appDocsVersion, { isHosted }) => {
2061
+ const docsVersion = appDocsVersion ? `${appDocsVersion}/` : "development/";
2062
+ return isHosted ? "" : docsVersion;
2063
+ });
2064
+ var getSearchState = (state) => state.app.searchState;
2065
+ var getSearchedDevices = (0, import_toolkit9.createSelector)([getSearchState], ({ deviceIds }) => deviceIds);
2066
+ var getVersionInformation = (0, import_toolkit9.createSelector)(
2067
+ [getFullVersionInformation, getFeatures],
2068
+ ({ Integration, ...remainder }, { isHosted }) => isHosted && Integration !== "next" ? remainder : { ...remainder, Integration }
2069
+ );
2070
+ var getIsPreview = (0, import_toolkit9.createSelector)([getFullVersionInformation], ({ Integration }) => (0, import_helpers2.versionCompare)(Integration, "next") > -1);
2071
+
2072
+ // src/commonSelectors.ts
2073
+ var import_helpers5 = require("@northern.tech/utils/helpers");
2074
+ var import_toolkit15 = require("@reduxjs/toolkit");
2075
+
2076
+ // src/deploymentsSlice/selectors.ts
2077
+ var import_toolkit10 = require("@reduxjs/toolkit");
2078
+ var getDeploymentsById = (state) => state.deployments.byId;
2079
+ var getDeploymentsByStatus = (state) => state.deployments.byStatus;
2080
+ var getSelectedDeploymentDeviceIds = (state) => state.deployments.selectedDeviceIds;
2081
+ var getDeploymentsSelectionState = (state) => state.deployments.selectionState;
2082
+ var getMappedDeploymentSelection = (0, import_toolkit10.createSelector)(
2083
+ [getDeploymentsSelectionState, (_, deploymentsState) => deploymentsState, getDeploymentsById],
2084
+ (selectionState, deploymentsState, deploymentsById) => {
2085
+ const { selection = [] } = selectionState[deploymentsState] ?? {};
2086
+ return selection.reduce((accu, id) => {
2087
+ if (deploymentsById[id]) {
2088
+ accu.push(deploymentsById[id]);
2089
+ }
2090
+ return accu;
2091
+ }, []);
2092
+ }
2093
+ );
2094
+ var relevantDeploymentStates = [DEPLOYMENT_STATES.pending, DEPLOYMENT_STATES.inprogress, DEPLOYMENT_STATES.finished];
2095
+ var DEPLOYMENT_CUTOFF = 3;
2096
+ var getRecentDeployments = (0, import_toolkit10.createSelector)(
2097
+ [getDeploymentsById, getDeploymentsByStatus],
2098
+ (deploymentsById, deploymentsByStatus) => Object.entries(deploymentsByStatus).reduce(
2099
+ (accu, [state, byStatus]) => {
2100
+ if (!relevantDeploymentStates.includes(state) || !byStatus.deploymentIds.length) {
2101
+ return accu;
2102
+ }
2103
+ accu[state] = byStatus.deploymentIds.reduce((accu2, id) => {
2104
+ if (deploymentsById[id]) {
2105
+ accu2.push(deploymentsById[id]);
2106
+ }
2107
+ return accu2;
2108
+ }, []).slice(0, DEPLOYMENT_CUTOFF);
2109
+ accu.total += byStatus.total;
2110
+ return accu;
2111
+ },
2112
+ { total: 0 }
2113
+ )
2114
+ );
2115
+
2116
+ // src/devicesSlice/selectors.ts
2117
+ var import_helpers3 = require("@northern.tech/utils/helpers");
2118
+ var import_toolkit11 = require("@reduxjs/toolkit");
2119
+ var getAcceptedDevices = (state) => state.devices.byStatus.accepted;
2120
+ var getDevicesByStatus = (state) => state.devices.byStatus;
2121
+ var getDevicesById = (state) => state.devices.byId;
2122
+ var getGroupsById = (state) => state.devices.groups.byId;
2123
+ var getSelectedGroup = (state) => state.devices.groups.selectedGroup;
2124
+ var getDeviceListState = (state) => state.devices.deviceList;
2125
+ var getListedDevices = (state) => state.devices.deviceList.deviceIds;
2126
+ var getFilteringAttributes = (state) => state.devices.filteringAttributes;
2127
+ var getDeviceFilters = (state) => state.devices.filters || [];
2128
+ var getFilteringAttributesFromConfig = (state) => state.devices.filteringAttributesConfig.attributes;
2129
+ var getSortedFilteringAttributes = (0, import_toolkit11.createSelector)([getFilteringAttributes], (filteringAttributes) => ({
2130
+ ...filteringAttributes,
2131
+ identityAttributes: [...filteringAttributes.identityAttributes, "id"]
2132
+ }));
2133
+ var getDeviceLimit = (state) => state.devices.limit;
2134
+ var getFilteringAttributesLimit = (state) => state.devices.filteringAttributesLimit;
2135
+ var getDeviceIdentityAttributes = (0, import_toolkit11.createSelector)(
2136
+ [getFilteringAttributes, getFilteringAttributesLimit],
2137
+ ({ identityAttributes }, filteringAttributesLimit) => {
2138
+ const attributes = identityAttributes.slice(0, filteringAttributesLimit);
2139
+ return attributes.reduce(
2140
+ (accu, value) => {
2141
+ accu.push({ value, label: value, scope: "identity" });
2142
+ return accu;
2143
+ },
2144
+ [
2145
+ { value: "name", label: "Name", scope: "tags" },
2146
+ { value: "id", label: "Device ID", scope: "identity" }
2147
+ ]
2148
+ );
2149
+ }
2150
+ );
2151
+ var getDeviceCountsByStatus = (0, import_toolkit11.createSelector)(
2152
+ [getDevicesByStatus],
2153
+ (byStatus) => Object.values(DEVICE_STATES).reduce((accu, state) => {
2154
+ accu[state] = byStatus[state].total || 0;
2155
+ return accu;
2156
+ }, {})
2157
+ );
2158
+ var getDeviceById = (0, import_toolkit11.createSelector)([getDevicesById, (_, deviceId) => deviceId], (devicesById, deviceId = "") => devicesById[deviceId] ?? {});
2159
+ var getSelectedGroupInfo = (0, import_toolkit11.createSelector)(
2160
+ [getAcceptedDevices, getGroupsById, getSelectedGroup],
2161
+ ({ total: acceptedDeviceTotal }, groupsById, selectedGroup) => {
2162
+ let groupCount = acceptedDeviceTotal;
2163
+ let groupFilters = [];
2164
+ if (selectedGroup && groupsById[selectedGroup]) {
2165
+ groupCount = groupsById[selectedGroup].total;
2166
+ groupFilters = groupsById[selectedGroup].filters || [];
2167
+ }
2168
+ return { groupCount, selectedGroup, groupFilters };
2169
+ }
2170
+ );
2171
+ var getLimitMaxed = (0, import_toolkit11.createSelector)(
2172
+ [getAcceptedDevices, getDeviceLimit],
2173
+ ({ total: acceptedDevices = 0 }, deviceLimit) => Boolean(deviceLimit && deviceLimit <= acceptedDevices)
2174
+ );
2175
+ var getGroupsByIdWithoutUngrouped = (0, import_toolkit11.createSelector)([getGroupsById], ({ [UNGROUPED_GROUP.id]: ungrouped, ...groups }) => groups);
2176
+ var getGroups = (0, import_toolkit11.createSelector)([getGroupsById], (groupsById) => {
2177
+ const groupNames = Object.keys(groupsById).sort();
2178
+ const groupedGroups = Object.entries(groupsById).sort((a, b) => a[0].localeCompare(b[0])).reduce(
2179
+ (accu, [groupname, group]) => {
2180
+ const name = groupname === UNGROUPED_GROUP.id ? UNGROUPED_GROUP.name : groupname;
2181
+ const groupItem = { ...group, groupId: name, name: groupname };
2182
+ if (group.filters.length > 0) {
2183
+ if (groupname !== UNGROUPED_GROUP.id) {
2184
+ accu.dynamic.push(groupItem);
2185
+ } else {
2186
+ accu.ungrouped.push(groupItem);
2187
+ }
2188
+ } else {
2189
+ accu.static.push(groupItem);
2190
+ }
2191
+ return accu;
2192
+ },
2193
+ { dynamic: [], static: [], ungrouped: [] }
2194
+ );
2195
+ return { groupNames, ...groupedGroups };
2196
+ });
2197
+ var getAttributesList = (0, import_toolkit11.createSelector)(
2198
+ [getFilteringAttributes, getFilteringAttributesFromConfig],
2199
+ ({ identityAttributes = [], inventoryAttributes = [] }, { identity = [], inventory = [] }) => [...identityAttributes, ...inventoryAttributes, ...identity, ...inventory].filter(import_helpers3.duplicateFilter)
2200
+ );
2201
+ var getDeviceTypes = (0, import_toolkit11.createSelector)(
2202
+ [getAcceptedDevices, getDevicesById],
2203
+ ({ deviceIds = [] }, devicesById) => Object.keys(
2204
+ deviceIds.slice(0, 200).reduce((accu, item) => {
2205
+ const { device_type: deviceTypes = [] } = devicesById[item] ? devicesById[item].attributes : {};
2206
+ accu = deviceTypes.reduce((deviceTypeAccu, deviceType) => {
2207
+ if (deviceType.length > 1) {
2208
+ deviceTypeAccu[deviceType] = deviceTypeAccu[deviceType] ? deviceTypeAccu[deviceType] + 1 : 1;
2209
+ }
2210
+ return deviceTypeAccu;
2211
+ }, accu);
2212
+ return accu;
2213
+ }, {})
2214
+ )
2215
+ );
2216
+
2217
+ // src/monitorSlice/selectors.ts
2218
+ var getIssueCountsByType = (state) => state.monitor.issueCounts.byType;
2219
+
2220
+ // src/onboardingSlice/selectors.ts
2221
+ var getOnboarding = (state) => state.onboarding;
2222
+
2223
+ // src/organizationSlice/selectors.ts
2224
+ var import_toolkit12 = require("@reduxjs/toolkit");
2225
+ var getOrganization = (state) => state.organization.organization;
2226
+ var getExternalIntegrations = (state) => state.organization.externalDeviceIntegrations;
2227
+ var getAuditLog = (state) => state.organization.auditlog.events;
2228
+ var getAuditLogSelectionState = (state) => state.organization.auditlog.selectionState;
2229
+ var getWebhookEvents = (state) => state.organization.webhooks.events;
2230
+ var getWebhookEventTotal = (state) => state.organization.webhooks.eventTotal;
2231
+ var getDeviceTwinIntegrations = (0, import_toolkit12.createSelector)(
2232
+ [getExternalIntegrations],
2233
+ (integrations) => integrations.filter((integration) => integration.id && EXTERNAL_PROVIDER[integration.provider]?.deviceTwin)
2234
+ );
2235
+ var getIsServiceProvider = (state) => state.organization.organization.service_provider;
2236
+ var getWebhooks = (0, import_toolkit12.createSelector)(
2237
+ [getExternalIntegrations],
2238
+ (integrations) => integrations.filter((integration) => integration.id && integration.provider === EXTERNAL_PROVIDER.webhook.provider)
2239
+ );
2240
+ var getWebhookEventInfo = (0, import_toolkit12.createSelector)(
2241
+ [getWebhooks, getWebhookEvents, getWebhookEventTotal],
2242
+ (webhooks, events, eventTotal) => webhooks.length ? { events, eventTotal } : { events: [], eventTotal: 0 }
2243
+ );
2244
+ var getAuditLogEntry = (0, import_toolkit12.createSelector)([getAuditLog, getAuditLogSelectionState], (events, { selectedId }) => {
2245
+ if (!selectedId) {
2246
+ return;
2247
+ }
2248
+ const [eventAction, eventTime] = atob(selectedId).split("|");
2249
+ return events.find((item) => item.action === eventAction && item.time === eventTime);
2250
+ });
2251
+
2252
+ // src/utils.ts
2253
+ var import_helpers4 = require("@northern.tech/utils/helpers");
2254
+ var filterProcessors = {
2255
+ $gt: (val) => Number(val) || val,
2256
+ $gte: (val) => Number(val) || val,
2257
+ $lt: (val) => Number(val) || val,
2258
+ $lte: (val) => Number(val) || val,
2259
+ $in: (val) => ("" + val).split(",").map((i) => i.trim()),
2260
+ $nin: (val) => ("" + val).split(",").map((i) => i.trim()),
2261
+ $exists: import_helpers4.yes,
2262
+ $nexists: () => false
2263
+ };
2264
+ var filterAliases = {
2265
+ $nexists: { alias: DEVICE_FILTERING_OPTIONS.$exists.key, value: false }
2266
+ };
2267
+ var mapFiltersToTerms = (filters) => filters.map((filter) => ({
2268
+ scope: filter.scope,
2269
+ attribute: filter.key,
2270
+ type: filterAliases[filter.operator]?.alias || filter.operator,
2271
+ value: filterProcessors.hasOwnProperty(filter.operator) ? filterProcessors[filter.operator](filter.value) : filter.value
2272
+ }));
2273
+ var mapTermsToFilters = (terms) => terms.map((term) => {
2274
+ const aliasedFilter = Object.entries(filterAliases).find(
2275
+ (aliasDefinition) => aliasDefinition[1].alias === term.type && aliasDefinition[1].value === term.value
2276
+ );
2277
+ const operator = aliasedFilter ? aliasedFilter[0] : term.type;
2278
+ return { scope: term.scope, key: term.attribute, operator, value: term.value };
2279
+ });
2280
+ var convertIssueOptionsToFilters = (issuesSelection, filtersState = {}) => issuesSelection.map((item) => {
2281
+ if (typeof DEVICE_ISSUE_OPTIONS[item].filterRule.value === "function") {
2282
+ return { ...DEVICE_ISSUE_OPTIONS[item].filterRule, value: DEVICE_ISSUE_OPTIONS[item].filterRule.value(filtersState) };
2283
+ }
2284
+ return DEVICE_ISSUE_OPTIONS[item].filterRule;
2285
+ });
2286
+ var convertDeviceListStateToFilters = ({ filters = [], group, groups = { byId: {} }, offlineThreshold, selectedIssues = [], status }) => {
2287
+ let applicableFilters = [...filters];
2288
+ if (typeof group === "string" && !(groups.byId[group]?.filters || applicableFilters).length) {
2289
+ applicableFilters.push({ key: "group", value: group, operator: DEVICE_FILTERING_OPTIONS.$eq.key, scope: "system" });
2290
+ }
2291
+ const nonMonitorFilters = applicableFilters.filter(
2292
+ (filter) => !Object.values(DEVICE_ISSUE_OPTIONS).some(
2293
+ ({ filterRule }) => filter.scope !== "inventory" && filterRule.scope === filter.scope && filterRule.key === filter.key
2294
+ )
2295
+ );
2296
+ const deviceIssueFilters = convertIssueOptionsToFilters(selectedIssues, { offlineThreshold });
2297
+ applicableFilters = [...nonMonitorFilters, ...deviceIssueFilters];
2298
+ const effectiveFilters = status ? [...applicableFilters, { key: "status", value: status, operator: DEVICE_FILTERING_OPTIONS.$eq.key, scope: "identity" }] : applicableFilters;
2299
+ return { applicableFilters: nonMonitorFilters, filterTerms: mapFiltersToTerms(effectiveFilters) };
2300
+ };
2301
+ var filterCompare = (filter, item) => Object.keys(emptyFilter).every((key) => item[key].toString() === filter[key].toString());
2302
+ var filtersFilter = (item, index, array) => {
2303
+ const firstIndex = array.findIndex((filter) => filterCompare(filter, item));
2304
+ return firstIndex === index;
2305
+ };
2306
+ var listItemMapper = (byId, ids, { defaultObject = {}, cutOffSize = DEVICE_LIST_MAXIMUM_LENGTH }) => {
2307
+ return ids.slice(0, cutOffSize).reduce((accu, id) => {
2308
+ if (id && byId[id]) {
2309
+ accu.push({ ...defaultObject, ...byId[id] });
2310
+ }
2311
+ return accu;
2312
+ }, []);
2313
+ };
2314
+ var mergePermissions = (existingPermissions = { ...emptyUiPermissions }, addedPermissions) => Object.entries(existingPermissions).reduce(
2315
+ (accu, [key, value]) => {
2316
+ let values;
2317
+ if (!accu[key]) {
2318
+ accu[key] = value;
2319
+ return accu;
2320
+ }
2321
+ if (Array.isArray(value)) {
2322
+ values = [...value, ...accu[key]].filter(import_helpers4.duplicateFilter);
2323
+ } else {
2324
+ values = mergePermissions(accu[key], { ...value });
2325
+ }
2326
+ accu[key] = values;
2327
+ return accu;
2328
+ },
2329
+ { ...addedPermissions }
2330
+ );
2331
+ var mapUserRolesToUiPermissions = (userRoles, roles) => userRoles.reduce(
2332
+ (accu, roleId) => {
2333
+ if (!(roleId && roles[roleId])) {
2334
+ return accu;
2335
+ }
2336
+ return mergePermissions(accu, roles[roleId].uiPermissions);
2337
+ },
2338
+ { ...emptyUiPermissions }
2339
+ );
2340
+ var progress = ({ loaded, total }) => {
2341
+ let uploadProgress3 = loaded / total * 100;
2342
+ return uploadProgress3 = uploadProgress3 < 50 ? Math.ceil(uploadProgress3) : Math.round(uploadProgress3);
2343
+ };
2344
+ var getComparisonCompatibleVersion = (version) => isNaN(version.charAt(0)) && version !== "next" ? "master" : version;
2345
+ var mapDeviceAttributes = (attributes = []) => attributes.reduce(
2346
+ (accu, attribute) => {
2347
+ if (!(attribute.value && attribute.name) && attribute.scope === ATTRIBUTE_SCOPES.inventory) {
2348
+ return accu;
2349
+ }
2350
+ accu[attribute.scope || ATTRIBUTE_SCOPES.inventory] = {
2351
+ ...accu[attribute.scope || ATTRIBUTE_SCOPES.inventory],
2352
+ [attribute.name]: attribute.value
2353
+ };
2354
+ if (attribute.name === "device_type" && attribute.scope === ATTRIBUTE_SCOPES.inventory) {
2355
+ accu.inventory.device_type = [].concat(attribute.value);
2356
+ }
2357
+ return accu;
2358
+ },
2359
+ { inventory: { device_type: [], artifact_name: "" }, identity: {}, monitor: {}, system: {}, tags: {} }
2360
+ );
2361
+ var isDarkMode = (mode) => mode === DARK_MODE;
2362
+
2363
+ // src/releasesSlice/selectors.ts
2364
+ var import_toolkit13 = require("@reduxjs/toolkit");
2365
+ var getSelectedReleaseId = (state) => state.releases.selectedRelease;
2366
+ var getReleasesById = (state) => state.releases.byId;
2367
+ var getReleaseTags = (state) => state.releases.tags;
2368
+ var getReleaseListState = (state) => state.releases.releasesList;
2369
+ var getListedReleases = (state) => state.releases.releasesList.releaseIds;
2370
+ var getReleaseMappingDefaults = () => ({});
2371
+ var getReleasesList = (0, import_toolkit13.createSelector)([getReleasesById, getListedReleases, getReleaseMappingDefaults], listItemMapper);
2372
+ var getReleaseTagsById = (0, import_toolkit13.createSelector)([getReleaseTags], (releaseTags) => releaseTags.reduce((accu, key) => ({ ...accu, [key]: key }), {}));
2373
+ var getHasReleases = (0, import_toolkit13.createSelector)(
2374
+ [getReleaseListState, getReleasesById],
2375
+ ({ searchTotal, total }, byId) => !!(Object.keys(byId).length || total || searchTotal)
2376
+ );
2377
+ var getSelectedRelease = (0, import_toolkit13.createSelector)([getReleasesById, getSelectedReleaseId], (byId, id) => byId[id] ?? {});
2378
+
2379
+ // src/usersSlice/selectors.ts
2380
+ var import_toolkit14 = require("@reduxjs/toolkit");
2381
+ var getRolesById = (state) => state.users.rolesById;
2382
+ var getTooltipsById = (state) => state.users.tooltips.byId;
2383
+ var getGlobalSettings = (state) => state.users.globalSettings;
2384
+ var getCurrentUserId = (state) => state.users.currentUser;
2385
+ var getUsersById = (state) => state.users.byId;
2386
+ var getCurrentUser = (0, import_toolkit14.createSelector)([getUsersById, getCurrentUserId], (usersById, userId) => usersById[userId] ?? {});
2387
+ var getUserSettings = (state) => state.users.userSettings;
2388
+ var getIsDarkMode = (0, import_toolkit14.createSelector)([getUserSettings], ({ mode }) => isDarkMode(mode));
2389
+ var getShowHelptips = (0, import_toolkit14.createSelector)(
2390
+ [getTooltipsById],
2391
+ (tooltips) => Object.values(tooltips).reduce((accu, { readState }) => accu || readState === READ_STATES.unread, false)
2392
+ );
2393
+ var getTooltipsState = (0, import_toolkit14.createSelector)(
2394
+ [getTooltipsById, getUserSettings],
2395
+ (byId, { tooltips = {} }) => Object.entries(byId).reduce(
2396
+ (accu, [id, value]) => {
2397
+ accu[id] = { ...accu[id], ...value };
2398
+ return accu;
2399
+ },
2400
+ { ...tooltips }
2401
+ )
2402
+ );
2403
+ var getHas2FA = (0, import_toolkit14.createSelector)(
2404
+ [getCurrentUser],
2405
+ (currentUser) => currentUser.hasOwnProperty("tfa_status") && currentUser.tfa_status === twoFAStates.enabled
2406
+ );
2407
+ var getIdAttribute = (0, import_toolkit14.createSelector)([getGlobalSettings], ({ id_attribute = { ...defaultIdAttribute } }) => id_attribute);
2408
+ var getOfflineThresholdSettings = (0, import_toolkit14.createSelector)([getGlobalSettings], ({ offlineThreshold }) => ({
2409
+ interval: offlineThreshold?.interval || DEVICE_ONLINE_CUTOFF.interval,
2410
+ intervalUnit: offlineThreshold?.intervalUnit || DEVICE_ONLINE_CUTOFF.intervalName
2411
+ }));
2412
+ var getRolesList = (0, import_toolkit14.createSelector)([getRolesById], (rolesById2) => Object.entries(rolesById2).map(([id, role]) => ({ id, ...role })));
2413
+
2414
+ // src/commonSelectors.ts
2415
+ var getIsEnterprise = (0, import_toolkit15.createSelector)(
2416
+ [getOrganization, getFeatures],
2417
+ ({ plan = PLANS.os.id }, { isEnterprise, isHosted }) => isEnterprise || isHosted && plan === PLANS.enterprise.id
2418
+ );
2419
+ var getAttrsEndpoint = (0, import_toolkit15.createSelector)(
2420
+ [getFeatures],
2421
+ ({ hasReporting }) => hasReporting ? `${reportingApiUrl}/devices/search/attributes` : `${inventoryApiUrlV2}/filters/attributes`
2422
+ );
2423
+ var getSearchEndpoint = (0, import_toolkit15.createSelector)(
2424
+ [getFeatures],
2425
+ ({ hasReporting }) => hasReporting ? `${reportingApiUrl}/devices/search` : `${inventoryApiUrlV2}/filters/search`
2426
+ );
2427
+ var getUserRoles = (0, import_toolkit15.createSelector)(
2428
+ [getCurrentUser, getRolesById, getIsEnterprise, getFeatures, getOrganization],
2429
+ (currentUser, rolesById2, isEnterprise, { isHosted, hasMultitenancy }, { plan = PLANS.os.id }) => {
2430
+ const isAdmin = currentUser.roles?.length ? currentUser.roles.some((role) => role === rolesByName.admin) : !(hasMultitenancy || isEnterprise || isHosted && plan !== PLANS.os.id);
2431
+ const uiPermissions = isAdmin ? mapUserRolesToUiPermissions([rolesByName.admin], rolesById2) : mapUserRolesToUiPermissions(currentUser.roles || [], rolesById2);
2432
+ return { isAdmin, uiPermissions };
2433
+ }
2434
+ );
2435
+ var hasPermission = (thing, permission) => Object.values(thing).some((permissions) => permissions.includes(permission));
2436
+ var getUserCapabilities = (0, import_toolkit15.createSelector)([getUserRoles, getIsServiceProvider], ({ uiPermissions }, isServiceProvider) => {
2437
+ const canManageReleases = hasPermission(uiPermissions.releases, uiPermissionsById.manage.value);
2438
+ const canReadReleases = canManageReleases || hasPermission(uiPermissions.releases, uiPermissionsById.read.value);
2439
+ const canUploadReleases = canManageReleases || hasPermission(uiPermissions.releases, uiPermissionsById.upload.value);
2440
+ const canAuditlog = uiPermissions.auditlog.includes(uiPermissionsById.read.value);
2441
+ const canReadUsers = uiPermissions.userManagement.includes(uiPermissionsById.read.value);
2442
+ const canManageUsers = uiPermissions.userManagement.includes(uiPermissionsById.manage.value);
2443
+ const canReadDevices = hasPermission(uiPermissions.groups, uiPermissionsById.read.value);
2444
+ const canWriteDevices = Object.values(uiPermissions.groups).some(
2445
+ (groupPermissions) => groupPermissions.includes(uiPermissionsById.read.value) && groupPermissions.length > 1
2446
+ );
2447
+ const canTroubleshoot = hasPermission(uiPermissions.groups, uiPermissionsById.connect.value);
2448
+ const canManageDevices = hasPermission(uiPermissions.groups, uiPermissionsById.manage.value);
2449
+ const canConfigure = hasPermission(uiPermissions.groups, uiPermissionsById.configure.value);
2450
+ const canDeploy = uiPermissions.deployments.includes(uiPermissionsById.deploy.value) || hasPermission(uiPermissions.groups, uiPermissionsById.deploy.value);
2451
+ const canReadDeployments = uiPermissions.deployments.includes(uiPermissionsById.read.value);
2452
+ return {
2453
+ canAuditlog,
2454
+ canConfigure,
2455
+ canDeploy,
2456
+ canManageDevices,
2457
+ canManageReleases,
2458
+ canManageUsers,
2459
+ canReadDeployments,
2460
+ canReadDevices,
2461
+ canReadReleases,
2462
+ canReadUsers,
2463
+ canTroubleshoot,
2464
+ canUploadReleases,
2465
+ canWriteDevices,
2466
+ groupsPermissions: uiPermissions.groups,
2467
+ releasesPermissions: uiPermissions.releases,
2468
+ SPTenant: isServiceProvider
2469
+ };
2470
+ });
2471
+ var getTenantCapabilities = (0, import_toolkit15.createSelector)(
2472
+ [getFeatures, getOrganization, getIsEnterprise],
2473
+ ({ hasAuditlogs: isAuditlogEnabled, hasDeviceConfig: isDeviceConfigEnabled, hasDeviceConnect: isDeviceConnectEnabled, hasMonitor: isMonitorEnabled }, { addons = [], plan = PLANS.os.id }, isEnterprise) => {
2474
+ const canDelta = isEnterprise || plan === PLANS.professional.id;
2475
+ const hasAuditlogs = isAuditlogEnabled && isEnterprise;
2476
+ const hasDeviceConfig = isDeviceConfigEnabled && addons.some((addon) => addon.name === "configure" && Boolean(addon.enabled));
2477
+ const hasDeviceConnect = isDeviceConnectEnabled && (!isEnterprise || addons.some((addon) => addon.name === "troubleshoot" && Boolean(addon.enabled)));
2478
+ const hasMonitor = isMonitorEnabled && addons.some((addon) => addon.name === "monitor" && Boolean(addon.enabled));
2479
+ return {
2480
+ canDelta,
2481
+ canRetry: canDelta,
2482
+ canSchedule: canDelta,
2483
+ hasAuditlogs,
2484
+ hasDeviceConfig,
2485
+ hasDeviceConnect,
2486
+ hasFullFiltering: canDelta,
2487
+ hasMonitor,
2488
+ isEnterprise,
2489
+ plan
2490
+ };
2491
+ }
2492
+ );
2493
+ var getFilterAttributes = (0, import_toolkit15.createSelector)(
2494
+ [getGlobalSettings, getFilteringAttributes],
2495
+ ({ previousFilters }, { identityAttributes, inventoryAttributes, systemAttributes, tagAttributes }) => {
2496
+ const deviceNameAttribute = { key: "name", value: "Name", scope: ATTRIBUTE_SCOPES.tags, category: ATTRIBUTE_SCOPES.tags, priority: 1 };
2497
+ const deviceIdAttribute = { key: "id", value: "Device ID", scope: ATTRIBUTE_SCOPES.identity, category: ATTRIBUTE_SCOPES.identity, priority: 1 };
2498
+ const checkInAttribute = { key: "check_in_time", value: "Latest activity", scope: ATTRIBUTE_SCOPES.system, category: ATTRIBUTE_SCOPES.system, priority: 4 };
2499
+ const updateAttribute = { ...checkInAttribute, key: "updated_ts", value: "Last inventory update" };
2500
+ const firstRequestAttribute = { key: "created_ts", value: "First request", scope: ATTRIBUTE_SCOPES.system, category: ATTRIBUTE_SCOPES.system, priority: 4 };
2501
+ const attributes = [
2502
+ ...previousFilters.map((item) => ({
2503
+ ...item,
2504
+ value: deviceIdAttribute.key === item.key ? deviceIdAttribute.value : item.key,
2505
+ category: "recently used",
2506
+ priority: 0
2507
+ })),
2508
+ deviceNameAttribute,
2509
+ deviceIdAttribute,
2510
+ ...identityAttributes.map((item) => ({ key: item, value: item, scope: ATTRIBUTE_SCOPES.identity, category: ATTRIBUTE_SCOPES.identity, priority: 1 })),
2511
+ ...inventoryAttributes.map((item) => ({ key: item, value: item, scope: ATTRIBUTE_SCOPES.inventory, category: ATTRIBUTE_SCOPES.inventory, priority: 2 })),
2512
+ ...tagAttributes.map((item) => ({ key: item, value: item, scope: ATTRIBUTE_SCOPES.tags, category: ATTRIBUTE_SCOPES.tags, priority: 3 })),
2513
+ checkInAttribute,
2514
+ updateAttribute,
2515
+ firstRequestAttribute,
2516
+ ...systemAttributes.map((item) => ({ key: item, value: item, scope: ATTRIBUTE_SCOPES.system, category: ATTRIBUTE_SCOPES.system, priority: 4 }))
2517
+ ];
2518
+ return (0, import_helpers5.attributeDuplicateFilter)(attributes, "key");
2519
+ }
2520
+ );
2521
+ var getOnboardingState = (0, import_toolkit15.createSelector)([getOnboarding, getUserSettings], ({ complete, progress: progress2, showTips, ...remainder }, { onboarding = {} }) => ({
2522
+ ...remainder,
2523
+ ...onboarding,
2524
+ complete: onboarding.complete || complete,
2525
+ progress: Object.keys(onboardingSteps).findIndex((step) => step === progress2) > Object.keys(onboardingSteps).findIndex((step) => step === onboarding.progress) ? progress2 : onboarding.progress,
2526
+ showTips: !onboarding.showTips ? onboarding.showTips : showTips
2527
+ }));
2528
+ var getDemoDeviceAddress = (0, import_toolkit15.createSelector)([getDevicesById, getOnboarding], (devicesById, { approach, demoArtifactPort }) => {
2529
+ const demoDeviceAddress = `http://${(0, import_helpers5.getDemoDeviceAddress)(Object.values(devicesById), approach)}`;
2530
+ return demoArtifactPort ? `${demoDeviceAddress}:${demoArtifactPort}` : demoDeviceAddress;
2531
+ });
2532
+ var getDeviceConfigDeployment = (0, import_toolkit15.createSelector)([getDeviceById, getDeploymentsById], (device, deploymentsById) => {
2533
+ const { config = {} } = device;
2534
+ const { deployment_id: configDeploymentId } = config;
2535
+ const deviceConfigDeployment = deploymentsById[configDeploymentId] || {};
2536
+ return { device, deviceConfigDeployment };
2537
+ });
2538
+ var getDeploymentRelease = (0, import_toolkit15.createSelector)(
2539
+ [getDeploymentsById, getDeploymentsSelectionState, getReleasesById],
2540
+ (deploymentsById, { selectedId }, releasesById) => {
2541
+ const deployment = deploymentsById[selectedId] || {};
2542
+ return deployment.artifact_name && releasesById[deployment.artifact_name] ? releasesById[deployment.artifact_name] : { device_types_compatible: [] };
2543
+ }
2544
+ );
2545
+ var getSelectedDeploymentData = (0, import_toolkit15.createSelector)(
2546
+ [getDeploymentsById, getDeploymentsSelectionState, getDevicesById, getSelectedDeploymentDeviceIds],
2547
+ (deploymentsById, { selectedId }, devicesById, selectedDeviceIds) => {
2548
+ const deployment = deploymentsById[selectedId] ?? {};
2549
+ const { devices = {} } = deployment;
2550
+ return {
2551
+ deployment,
2552
+ selectedDevices: selectedDeviceIds.map((deviceId) => ({ ...devicesById[deviceId], ...devices[deviceId] }))
2553
+ };
2554
+ }
2555
+ );
2556
+ var getAvailableIssueOptionsByType = (0, import_toolkit15.createSelector)(
2557
+ [getFeatures, getTenantCapabilities, getIssueCountsByType],
2558
+ ({ hasReporting }, { hasFullFiltering, hasMonitor }, issueCounts) => Object.values(DEVICE_ISSUE_OPTIONS).reduce((accu, { isCategory, key, needsFullFiltering, needsMonitor, needsReporting, title }) => {
2559
+ if (isCategory || needsReporting && !hasReporting || needsFullFiltering && !hasFullFiltering || needsMonitor && !hasMonitor) {
2560
+ return accu;
2561
+ }
2562
+ accu[key] = { count: issueCounts[key].filtered, key, title };
2563
+ return accu;
2564
+ }, {})
2565
+ );
2566
+ var getGroupNames = (0, import_toolkit15.createSelector)([getGroupsById, getUserRoles, (_, options = {}) => options], (groupsById, { uiPermissions }, { staticOnly }) => {
2567
+ const { [UNGROUPED_GROUP.id]: ungrouped, ...groups } = groupsById;
2568
+ if (staticOnly) {
2569
+ return Object.keys(uiPermissions.groups).sort();
2570
+ }
2571
+ return Object.keys(
2572
+ Object.entries(groups).reduce((accu, [groupName, group]) => {
2573
+ if (group.filterId || uiPermissions.groups[ALL_DEVICES]) {
2574
+ accu[groupName] = group;
2575
+ }
2576
+ return accu;
2577
+ }, uiPermissions.groups)
2578
+ ).sort();
2579
+ });
2580
+ var getDeviceReportsForUser = (0, import_toolkit15.createSelector)(
2581
+ [getUserSettings, getCurrentUser, getGlobalSettings, getDevicesById],
2582
+ ({ reports }, { id: currentUserId }, globalSettings, devicesById) => {
2583
+ return reports || globalSettings[`${currentUserId}-reports`] || (Object.keys(devicesById).length ? defaultReports : []);
2584
+ }
2585
+ );
2586
+ var listTypeDeviceIdMap = {
2587
+ deviceList: getListedDevices,
2588
+ search: getSearchedDevices
2589
+ };
2590
+ var deviceMapDefault = { defaultObject: { auth_sets: [] }, cutOffSize: DEVICE_LIST_MAXIMUM_LENGTH };
2591
+ var getDeviceMappingDefaults = () => deviceMapDefault;
2592
+ var getMappedDevicesList = (0, import_toolkit15.createSelector)(
2593
+ [getDevicesById, (state, listType) => listTypeDeviceIdMap[listType](state), getDeviceMappingDefaults],
2594
+ listItemMapper
2595
+ );
2596
+ var getAuditlogDevice = (0, import_toolkit15.createSelector)([getAuditLogEntry, getDevicesById], (auditlogEvent, devicesById) => {
2597
+ let auditlogDevice = {};
2598
+ if (auditlogEvent) {
2599
+ const { object = {} } = auditlogEvent;
2600
+ const { device = {}, id, type } = object;
2601
+ auditlogDevice = type === "device" ? { id, ...device } : auditlogDevice;
2602
+ }
2603
+ return { ...auditlogDevice, ...devicesById[auditlogDevice.id] };
2604
+ });
2605
+ var getRelevantRoles = (0, import_toolkit15.createSelector)([getOrganization, getRolesList], ({ service_provider }, roles) => {
2606
+ if (service_provider) {
2607
+ return roles.reduce((accu, role) => {
2608
+ if (rolesById[role.id]) {
2609
+ return accu;
2610
+ }
2611
+ accu.push(role);
2612
+ return accu;
2613
+ }, Object.values(serviceProviderRolesById));
2614
+ }
2615
+ return Object.keys(rolesById).reverse().reduce((accu, key) => {
2616
+ const index = accu.findIndex(({ id }) => id === key);
2617
+ accu = [accu[index], ...accu.filter((item, itemIndex) => index !== itemIndex)];
2618
+ return accu;
2619
+ }, roles);
2620
+ });
2621
+
2622
+ // src/store.ts
2623
+ var import_helpers6 = require("@northern.tech/utils/helpers");
2624
+ var import_toolkit16 = require("@reduxjs/toolkit");
2625
+ var { setSnackbar, uploadProgress } = actions_default;
2626
+ var keys = ["sessionDeploymentChecker", settingsKeys.initialized];
2627
+ var resetEnvironment = () => {
2628
+ keys.map((key) => window.sessionStorage.removeItem(key));
2629
+ };
2630
+ resetEnvironment();
2631
+ var commonErrorFallback = "Please check your connection.";
2632
+ var commonErrorHandler = (err, errorContext, dispatch, fallback, mightBeAuthRelated = false) => {
2633
+ const errMsg = (0, import_helpers6.extractErrorMessage)(err, fallback);
2634
+ if (mightBeAuthRelated || getToken()) {
2635
+ dispatch(setSnackbar({ message: (0, import_helpers6.preformatWithRequestID)(err.response, `${errorContext} ${errMsg}`), action: "Copy to clipboard" }));
2636
+ }
2637
+ return Promise.reject(err);
2638
+ };
2639
+ var rootReducer = (0, import_toolkit16.combineReducers)({
2640
+ app: appSlice_default,
2641
+ devices: devicesSlice_default,
2642
+ deployments: deploymentsSlice_default,
2643
+ monitor: monitorSlice_default,
2644
+ onboarding: onboardingSlice_default,
2645
+ organization: organizationSlice_default,
2646
+ releases: releasesSlice_default,
2647
+ users: usersSlice_default
2648
+ });
2649
+ var sessionReducer = (state, action) => {
2650
+ if (action.type === USER_LOGOUT) {
2651
+ state = void 0;
2652
+ }
2653
+ return rootReducer(state, action);
2654
+ };
2655
+ var getConfiguredStore = (options = {}) => {
2656
+ const { preloadedState = {}, ...config } = options;
2657
+ return (0, import_toolkit16.configureStore)({
2658
+ ...config,
2659
+ preloadedState,
2660
+ reducer: sessionReducer,
2661
+ middleware: (getDefaultMiddleware) => getDefaultMiddleware({
2662
+ immutableCheck: {
2663
+ ignoredPaths: ["app.uploadsById"]
2664
+ },
2665
+ serializableCheck: {
2666
+ ignoredActions: [actions6.receiveExternalDeviceIntegrations.name, setSnackbar.name, uploadProgress.name],
2667
+ ignoredActionPaths: ["uploads", "snackbar", /payload\..*$/],
2668
+ ignoredPaths: ["app.uploadsById", "app.snackbar", "organization.externalDeviceIntegrations"]
2669
+ }
2670
+ })
2671
+ });
2672
+ };
2673
+ var store = getConfiguredStore({
2674
+ preloadedState: {}
2675
+ });
2676
+
2677
+ // src/appSlice/thunks.ts
2678
+ var import_helpers7 = require("@northern.tech/utils/helpers");
2679
+ var import_toolkit17 = require("@reduxjs/toolkit");
2680
+ var import_universal_cookie2 = __toESM(require("universal-cookie"), 1);
2681
+ var cookies2 = new import_universal_cookie2.default();
2682
+ var setFirstLoginAfterSignup = (0, import_toolkit17.createAsyncThunk)(`${sliceName}/setFirstLoginAfterSignup`, (firstLoginAfterSignup, { dispatch }) => {
2683
+ cookies2.set("firstLoginAfterSignup", !!firstLoginAfterSignup, { maxAge: 60, path: "/", domain: ".mender.io", sameSite: false });
2684
+ dispatch(actions.setFirstLoginAfterSignup(!!firstLoginAfterSignup));
2685
+ });
2686
+ var dateFunctionMap = {
2687
+ getDays: "getDate",
2688
+ setDays: "setDate"
2689
+ };
2690
+ var setOfflineThreshold = (0, import_toolkit17.createAsyncThunk)(`${sliceName}/setOfflineThreshold`, (_, { dispatch, getState }) => {
2691
+ const { interval, intervalUnit } = getOfflineThresholdSettings(getState());
2692
+ const today = /* @__PURE__ */ new Date();
2693
+ const intervalName = `${intervalUnit.charAt(0).toUpperCase()}${intervalUnit.substring(1)}`;
2694
+ const setter = dateFunctionMap[`set${intervalName}`] ?? `set${intervalName}`;
2695
+ const getter = dateFunctionMap[`get${intervalName}`] ?? `get${intervalName}`;
2696
+ today[setter](today[getter]() - interval);
2697
+ let value;
2698
+ try {
2699
+ value = today.toISOString();
2700
+ } catch {
2701
+ return Promise.resolve(dispatch(actions.setSnackbar("There was an error saving the offline threshold, please check your settings.")));
2702
+ }
2703
+ return Promise.resolve(dispatch(actions.setOfflineThreshold(value)));
2704
+ });
2705
+ var versionRegex = new RegExp(/\d+\.\d+/);
2706
+ var getLatestRelease = (thing) => {
2707
+ const latestKey = Object.keys(thing).filter((key) => versionRegex.test(key)).sort().reverse()[0];
2708
+ return thing[latestKey];
2709
+ };
2710
+ var repoKeyMap = {
2711
+ integration: "Integration",
2712
+ mender: "Mender-Client",
2713
+ "mender-artifact": "Mender-Artifact"
2714
+ };
2715
+ var deductSaasState = (latestRelease, guiTags, saasReleases) => {
2716
+ const latestGuiTag = guiTags.length ? guiTags[0].name : "";
2717
+ const latestSaasRelease = latestGuiTag.startsWith("saas-v") ? { date: latestGuiTag.split("-v")[1].replaceAll(".", "-"), tag: latestGuiTag } : saasReleases[0];
2718
+ return latestSaasRelease.date > latestRelease.release_date ? latestSaasRelease.tag : latestRelease.release;
2719
+ };
2720
+ var getLatestReleaseInfo = (0, import_toolkit17.createAsyncThunk)(`${sliceName}/getLatestReleaseInfo`, (_, { dispatch, getState }) => {
2721
+ if (!getFeatures(getState()).isHosted) {
2722
+ return Promise.resolve();
2723
+ }
2724
+ return Promise.all([general_api_default.get("/versions.json"), general_api_default.get("/tags.json")]).catch((err) => {
2725
+ console.log("init error:", (0, import_helpers7.extractErrorMessage)(err));
2726
+ return Promise.resolve([{ data: {} }, { data: [] }]);
2727
+ }).then(([{ data }, { data: guiTags }]) => {
2728
+ if (!guiTags.length) {
2729
+ return Promise.resolve();
2730
+ }
2731
+ const { releases, saas } = data;
2732
+ const latestRelease = getLatestRelease(getLatestRelease(releases));
2733
+ const { latestRepos, latestVersions } = latestRelease.repos.reduce(
2734
+ (accu, item) => {
2735
+ if (repoKeyMap[item.name]) {
2736
+ accu.latestVersions[repoKeyMap[item.name]] = getComparisonCompatibleVersion(item.version);
2737
+ }
2738
+ accu.latestRepos[item.name] = getComparisonCompatibleVersion(item.version);
2739
+ return accu;
2740
+ },
2741
+ { latestVersions: { ...getState().app.versionInformation }, latestRepos: {} }
2742
+ );
2743
+ const info = deductSaasState(latestRelease, guiTags, saas);
2744
+ return Promise.resolve(
2745
+ dispatch(
2746
+ actions.setVersionInformation({
2747
+ ...latestVersions,
2748
+ backend: info,
2749
+ GUI: info,
2750
+ latestRelease: {
2751
+ releaseDate: latestRelease.release_date,
2752
+ repos: latestRepos
2753
+ }
2754
+ })
2755
+ )
2756
+ );
2757
+ });
2758
+ });
2759
+ var setSearchState = (0, import_toolkit17.createAsyncThunk)(`${sliceName}/setSearchState`, (searchState, { dispatch, getState }) => {
2760
+ const currentState = getSearchState(getState());
2761
+ let nextState = {
2762
+ ...currentState,
2763
+ ...searchState,
2764
+ sort: {
2765
+ ...currentState.sort,
2766
+ ...searchState.sort
2767
+ }
2768
+ };
2769
+ let tasks = [];
2770
+ const { isSearching: currentSearching, deviceIds: currentDevices, searchTotal: currentTotal, ...currentRequestState } = currentState;
2771
+ const { isSearching: nextSearching, deviceIds: nextDevices, searchTotal: nextTotal, ...nextRequestState } = nextState;
2772
+ if (nextRequestState.searchTerm && !(0, import_helpers7.deepCompare)(currentRequestState, nextRequestState)) {
2773
+ nextState.isSearching = true;
2774
+ tasks.push(
2775
+ dispatch(searchDevices(nextState)).unwrap().then((results) => {
2776
+ const searchResult = results[results.length - 1];
2777
+ return dispatch(actions.setSearchState({ ...searchResult, isSearching: false }));
2778
+ }).catch(() => dispatch(actions.setSearchState({ isSearching: false, searchTotal: 0 })))
2779
+ );
2780
+ }
2781
+ tasks.push(dispatch(actions.setSearchState(nextState)));
2782
+ return Promise.all(tasks);
2783
+ });
2784
+
2785
+ // src/deploymentsSlice/thunks.ts
2786
+ var import_helpers8 = require("@northern.tech/utils/helpers");
2787
+ var import_toolkit18 = require("@reduxjs/toolkit");
2788
+ var import_validator = require("validator");
2789
+ var { receivedDevice, setSnackbar: setSnackbar2 } = actions_default;
2790
+ var { page: defaultPage, perPage: defaultPerPage } = DEVICE_LIST_DEFAULTS;
2791
+ var deriveDeploymentGroup = ({ filter = {}, group, groups = [], name }) => group || groups.length === 1 && !(0, import_validator.isUUID)(name) ? groups[0] : filter.name;
2792
+ var transformDeployments = (deployments, deploymentsById) => deployments.sort(import_helpers8.startTimeSort).reduce(
2793
+ (accu, item) => {
2794
+ const filter = item.filter ?? {};
2795
+ let deployment = {
2796
+ ...deploymentPrototype,
2797
+ ...deploymentsById[item.id],
2798
+ ...item,
2799
+ filter: item.filter ? { ...filter, name: filter.name ?? filter.id, filters: mapTermsToFilters(filter.terms) } : void 0,
2800
+ name: decodeURIComponent(item.name)
2801
+ };
2802
+ deployment = { ...deployment, group: deriveDeploymentGroup(deployment) };
2803
+ accu.deployments[item.id] = deployment;
2804
+ accu.deploymentIds.push(item.id);
2805
+ return accu;
2806
+ },
2807
+ { deployments: {}, deploymentIds: [] }
2808
+ );
2809
+ var getDeploymentsByStatus2 = (0, import_toolkit18.createAsyncThunk)(`${sliceName2}/getDeploymentsByStatus`, (options = {}, { dispatch, getState }) => {
2810
+ const { status, page = defaultPage, per_page = defaultPerPage, startDate, endDate, group, type, shouldSelect = true, sort = SORTING_OPTIONS.desc } = options;
2811
+ const created_after = startDate ? `&created_after=${startDate}` : "";
2812
+ const created_before = endDate ? `&created_before=${endDate}` : "";
2813
+ const search = group ? `&search=${group}` : "";
2814
+ const typeFilter = type ? `&type=${type}` : "";
2815
+ return general_api_default.get(
2816
+ `${deploymentsApiUrl}/deployments?status=${status}&per_page=${per_page}&page=${page}${created_after}${created_before}${search}${typeFilter}&sort=${sort}`
2817
+ ).then((res) => {
2818
+ const { deployments, deploymentIds } = transformDeployments(res.data, getState().deployments.byId);
2819
+ const total = Number(res.headers[headerNames.total]);
2820
+ let tasks = [
2821
+ dispatch(actions2.receivedDeployments(deployments)),
2822
+ dispatch(
2823
+ actions2.receivedDeploymentsForStatus({
2824
+ deploymentIds,
2825
+ status,
2826
+ total: !(startDate || endDate || group || type) ? total : getState().deployments.byStatus[status].total
2827
+ })
2828
+ )
2829
+ ];
2830
+ tasks = deploymentIds.reduce((accu, deploymentId) => {
2831
+ if (deployments[deploymentId].type === DEPLOYMENT_TYPES.configuration) {
2832
+ accu.push(dispatch(getSingleDeployment(deploymentId)));
2833
+ }
2834
+ return accu;
2835
+ }, tasks);
2836
+ if (shouldSelect) {
2837
+ tasks.push(dispatch(actions2.selectDeploymentsForStatus({ deploymentIds, status, total })));
2838
+ }
2839
+ tasks.push({ deploymentIds, total });
2840
+ return Promise.all(tasks);
2841
+ });
2842
+ });
2843
+ var MAX_PREVIOUS_PHASES_COUNT = 5;
2844
+ var createDeployment = (0, import_toolkit18.createAsyncThunk)(`${sliceName2}/createDeployment`, ({ newDeployment, hasNewRetryDefault = false }, { dispatch, getState }) => {
2845
+ let request;
2846
+ if (newDeployment.filter_id) {
2847
+ request = general_api_default.post(`${deploymentsApiUrlV2}/deployments`, newDeployment);
2848
+ } else if (newDeployment.group) {
2849
+ request = general_api_default.post(`${deploymentsApiUrl}/deployments/group/${newDeployment.group}`, newDeployment);
2850
+ } else {
2851
+ request = general_api_default.post(`${deploymentsApiUrl}/deployments`, newDeployment);
2852
+ }
2853
+ return request.catch((err) => commonErrorHandler(err, "Error creating deployment.", dispatch)).then((data) => {
2854
+ const lastslashindex = data.headers.location.lastIndexOf("/");
2855
+ const deploymentId = data.headers.location.substring(lastslashindex + 1);
2856
+ const deployment = {
2857
+ ...newDeployment,
2858
+ id: deploymentId,
2859
+ devices: newDeployment.devices ? newDeployment.devices.map((id) => ({ id, status: "pending" })) : [],
2860
+ statistics: { status: {} }
2861
+ };
2862
+ let tasks = [
2863
+ dispatch(actions2.createdDeployment(deployment)),
2864
+ dispatch(getSingleDeployment(deploymentId)),
2865
+ dispatch(setSnackbar2("Deployment created successfully", TIMEOUTS.fiveSeconds))
2866
+ ];
2867
+ const { canManageUsers } = getUserCapabilities(getState());
2868
+ if (canManageUsers) {
2869
+ const { phases, retries } = newDeployment;
2870
+ const { previousPhases = [], retries: previousRetries = 0 } = getGlobalSettings(getState());
2871
+ let newSettings = { retries: hasNewRetryDefault ? retries : previousRetries, hasDeployments: true };
2872
+ if (phases) {
2873
+ const standardPhases = (0, import_helpers8.standardizePhases)(phases);
2874
+ let prevPhases = previousPhases.map(import_helpers8.standardizePhases);
2875
+ if (!prevPhases.find((previousPhaseList) => previousPhaseList.every((oldPhase) => standardPhases.find((phase) => (0, import_helpers8.deepCompare)(phase, oldPhase))))) {
2876
+ prevPhases.push(standardPhases);
2877
+ }
2878
+ newSettings.previousPhases = prevPhases.slice(-1 * MAX_PREVIOUS_PHASES_COUNT);
2879
+ }
2880
+ tasks.push(dispatch(saveGlobalSettings(newSettings)));
2881
+ }
2882
+ return Promise.all(tasks);
2883
+ });
2884
+ });
2885
+ var getDeploymentDevices = (0, import_toolkit18.createAsyncThunk)(`${sliceName2}/getDeploymentDevices`, (options, { dispatch, getState }) => {
2886
+ const { id, page = defaultPage, perPage = defaultPerPage } = options;
2887
+ return general_api_default.get(`${deploymentsApiUrl}/deployments/${id}/devices/list?&page=${page}&per_page=${perPage}`).then((response) => {
2888
+ const { devices: deploymentDevices = {} } = getState().deployments.byId[id] || {};
2889
+ const devices = response.data.reduce((accu, item) => {
2890
+ accu[item.id] = item;
2891
+ const log = (deploymentDevices[item.id] || {}).log;
2892
+ if (log) {
2893
+ accu[item.id].log = log;
2894
+ }
2895
+ return accu;
2896
+ }, {});
2897
+ const selectedDeviceIds = Object.keys(devices);
2898
+ let tasks = [
2899
+ dispatch(
2900
+ actions2.receivedDeploymentDevices({
2901
+ id,
2902
+ devices,
2903
+ selectedDeviceIds,
2904
+ totalDeviceCount: Number(response.headers[headerNames.total])
2905
+ })
2906
+ )
2907
+ ];
2908
+ const devicesById = getDevicesById(getState());
2909
+ const lackingData = selectedDeviceIds.reduce((accu, deviceId) => {
2910
+ const device = devicesById[deviceId];
2911
+ if (!device || !device.identity_data || !device.attributes || Object.keys(device.attributes).length === 0) {
2912
+ accu.push(deviceId);
2913
+ }
2914
+ return accu;
2915
+ }, []);
2916
+ tasks = lackingData.reduce((accu, deviceId) => [...accu, dispatch(getDeviceById2(deviceId)), dispatch(getDeviceAuth(deviceId))], tasks);
2917
+ return Promise.all(tasks);
2918
+ });
2919
+ });
2920
+ var parseDeviceDeployment = ({
2921
+ deployment: { id, artifact_name: release, status: deploymentStatus },
2922
+ device: { created, deleted, id: deviceId, finished, status, log }
2923
+ }) => ({
2924
+ id,
2925
+ release,
2926
+ created,
2927
+ deleted,
2928
+ deviceId,
2929
+ finished,
2930
+ status,
2931
+ log,
2932
+ route: Object.values(DEPLOYMENT_ROUTES).reduce((accu, { key, states }) => {
2933
+ if (!accu) {
2934
+ return states.includes(deploymentStatus) ? key : accu;
2935
+ }
2936
+ return accu;
2937
+ }, "")
2938
+ });
2939
+ var getDeviceDeployments = (0, import_toolkit18.createAsyncThunk)(`${sliceName2}/getDeviceDeployments`, (options, { dispatch }) => {
2940
+ const { deviceId, filterSelection = [], page = defaultPage, perPage = defaultPerPage } = options;
2941
+ const filters = filterSelection.map((item) => `&status=${item}`).join("");
2942
+ return general_api_default.get(`${deploymentsApiUrl}/deployments/devices/${deviceId}?page=${page}&per_page=${perPage}${filters}`).then(
2943
+ ({ data, headers }) => Promise.resolve(
2944
+ dispatch(
2945
+ receivedDevice({
2946
+ id: deviceId,
2947
+ deviceDeployments: data.map(parseDeviceDeployment),
2948
+ deploymentsCount: Number(headers[headerNames.total])
2949
+ })
2950
+ )
2951
+ )
2952
+ ).catch((err) => commonErrorHandler(err, "There was an error retrieving the device deployment history:", dispatch));
2953
+ });
2954
+ var resetDeviceDeployments = (0, import_toolkit18.createAsyncThunk)(
2955
+ `${sliceName2}/resetDeviceDeployments`,
2956
+ (deviceId, { dispatch }) => general_api_default.delete(`${deploymentsApiUrl}/deployments/devices/${deviceId}/history`).then(() => Promise.resolve(dispatch(getDeviceDeployments({ deviceId })))).catch((err) => commonErrorHandler(err, "There was an error resetting the device deployment history:", dispatch))
2957
+ );
2958
+ var getSingleDeployment = (0, import_toolkit18.createAsyncThunk)(
2959
+ `${sliceName2}/getSingleDeployment`,
2960
+ (id, { dispatch, getState }) => general_api_default.get(`${deploymentsApiUrl}/deployments/${id}`).then(({ data }) => {
2961
+ const { deployments } = transformDeployments([data], getState().deployments.byId);
2962
+ return Promise.resolve(dispatch(actions2.receivedDeployment(deployments[id])));
2963
+ })
2964
+ );
2965
+ var getDeviceLog = (0, import_toolkit18.createAsyncThunk)(
2966
+ `${sliceName2}/getDeviceLog`,
2967
+ ({ deploymentId, deviceId }, { dispatch }) => general_api_default.get(`${deploymentsApiUrl}/deployments/${deploymentId}/devices/${deviceId}/log`).catch((e) => {
2968
+ console.log("no log here", e);
2969
+ return Promise.reject();
2970
+ }).then(
2971
+ ({ data: log }) => Promise.all([Promise.resolve(dispatch(actions2.receivedDeploymentDeviceLog({ id: deploymentId, deviceId, log }))), Promise.resolve(log)])
2972
+ )
2973
+ );
2974
+ var abortDeployment = (0, import_toolkit18.createAsyncThunk)(
2975
+ `${sliceName2}/abortDeployment`,
2976
+ (deploymentId, { dispatch, getState }) => general_api_default.put(`${deploymentsApiUrl}/deployments/${deploymentId}/status`, { status: "aborted" }).then(() => {
2977
+ const deploymentsByStatus = getDeploymentsByStatus(getState());
2978
+ let status = DEPLOYMENT_STATES.pending;
2979
+ let index = deploymentsByStatus.pending.deploymentIds.findIndex((id) => id === deploymentId);
2980
+ if (index < 0) {
2981
+ status = DEPLOYMENT_STATES.inprogress;
2982
+ index = deploymentsByStatus.inprogress.deploymentIds.findIndex((id) => id === deploymentId);
2983
+ }
2984
+ const deploymentIds = [...deploymentsByStatus[status].deploymentIds.slice(0, index), ...deploymentsByStatus[status].deploymentIds.slice(index + 1)];
2985
+ const deploymentsById = getDeploymentsById(getState());
2986
+ const deployments = deploymentIds.reduce((accu, id) => {
2987
+ accu[id] = deploymentsById[id];
2988
+ return accu;
2989
+ }, {});
2990
+ const total = Math.max(deploymentsByStatus[status].total - 1, 0);
2991
+ return Promise.all([
2992
+ dispatch(actions2.receivedDeployments(deployments)),
2993
+ dispatch(actions2.receivedDeploymentsForStatus({ deploymentIds, status, total })),
2994
+ dispatch(actions2.removedDeployment(deploymentId)),
2995
+ dispatch(setSnackbar2("The deployment was successfully aborted"))
2996
+ ]);
2997
+ }).catch((err) => commonErrorHandler(err, "There was an error while aborting the deployment:", dispatch))
2998
+ );
2999
+ var updateDeploymentControlMap = (0, import_toolkit18.createAsyncThunk)(
3000
+ `${sliceName2}/updateDeploymentControlMap`,
3001
+ ({ deploymentId, updateControlMap }, { dispatch }) => general_api_default.patch(`${deploymentsApiUrl}/deployments/${deploymentId}`, { update_control_map: updateControlMap }).catch((err) => commonErrorHandler(err, "There was an error while updating the deployment status:", dispatch)).then(() => Promise.resolve(dispatch(getSingleDeployment(deploymentId))))
3002
+ );
3003
+ var setDeploymentsState = (0, import_toolkit18.createAsyncThunk)(`${sliceName2}/setDeploymentsState`, (selection, { dispatch, getState }) => {
3004
+ const { page, perPage, ...selectionState } = selection;
3005
+ const currentState = getState().deployments.selectionState;
3006
+ let nextState = {
3007
+ ...currentState,
3008
+ ...selectionState,
3009
+ ...Object.keys(DEPLOYMENT_STATES).reduce((accu, item) => {
3010
+ accu[item] = {
3011
+ ...currentState[item],
3012
+ ...selectionState[item]
3013
+ };
3014
+ return accu;
3015
+ }, {}),
3016
+ general: {
3017
+ ...currentState.general,
3018
+ ...selectionState.general
3019
+ }
3020
+ };
3021
+ let tasks = [dispatch(actions2.setDeploymentsState(nextState))];
3022
+ if (nextState.selectedId && currentState.selectedId !== nextState.selectedId) {
3023
+ tasks.push(dispatch(getSingleDeployment(nextState.selectedId)));
3024
+ }
3025
+ return Promise.all(tasks);
3026
+ });
3027
+ var deltaAttributeMappings = [
3028
+ { here: "compressionLevel", there: "compression_level" },
3029
+ { here: "disableChecksum", there: "disable_checksum" },
3030
+ { here: "disableDecompression", there: "disable_external_decompression" },
3031
+ { here: "sourceWindow", there: "source_window_size" },
3032
+ { here: "inputWindow", there: "input_window_size" },
3033
+ { here: "duplicatesWindow", there: "compression_duplicates_window" },
3034
+ { here: "instructionBuffer", there: "instruction_buffer_size" }
3035
+ ];
3036
+ var mapExternalDeltaConfig = (config = {}) => deltaAttributeMappings.reduce((accu, { here, there }) => {
3037
+ if (config[there] !== void 0) {
3038
+ accu[here] = config[there];
3039
+ }
3040
+ return accu;
3041
+ }, {});
3042
+ var getDeploymentsConfig = (0, import_toolkit18.createAsyncThunk)(
3043
+ `${sliceName2}/getDeploymentsConfig`,
3044
+ (_, { dispatch, getState }) => general_api_default.get(`${deploymentsApiUrl}/config`).then(({ data }) => {
3045
+ const oldConfig = getState().deployments.config;
3046
+ const { delta = {} } = data;
3047
+ const { binary_delta = {}, binary_delta_limits = {} } = delta;
3048
+ const { xdelta_args = {}, timeout: timeoutConfig = oldConfig.binaryDelta.timeout } = binary_delta;
3049
+ const { xdelta_args_limits = {}, timeout: timeoutLimit = oldConfig.binaryDeltaLimits.timeout } = binary_delta_limits;
3050
+ const config = {
3051
+ ...oldConfig,
3052
+ hasDelta: Boolean(delta.enabled),
3053
+ binaryDelta: {
3054
+ ...oldConfig.binaryDelta,
3055
+ timeout: timeoutConfig,
3056
+ ...mapExternalDeltaConfig(xdelta_args)
3057
+ },
3058
+ binaryDeltaLimits: {
3059
+ ...oldConfig.binaryDeltaLimits,
3060
+ timeout: timeoutLimit,
3061
+ ...mapExternalDeltaConfig(xdelta_args_limits)
3062
+ }
3063
+ };
3064
+ return Promise.resolve(dispatch(actions2.setDeploymentsConfig(config)));
3065
+ })
3066
+ );
3067
+ var deepClean = (source) => Object.entries(source).reduce((accu, [key, value]) => {
3068
+ if (value !== void 0) {
3069
+ let cleanedValue = typeof value === "object" ? deepClean(value) : value;
3070
+ if (cleanedValue === void 0 || typeof cleanedValue === "object" && (0, import_helpers8.isEmpty)(cleanedValue)) {
3071
+ return accu;
3072
+ }
3073
+ accu = { ...accu ?? {}, [key]: cleanedValue };
3074
+ }
3075
+ return accu;
3076
+ }, void 0);
3077
+ var saveDeltaDeploymentsConfig = (0, import_toolkit18.createAsyncThunk)(`${sliceName2}/saveDeltaDeploymentsConfig`, (config, { dispatch, getState }) => {
3078
+ const configChange = {
3079
+ timeout: config.timeout,
3080
+ xdelta_args: deltaAttributeMappings.reduce((accu, { here, there }) => {
3081
+ if (config[here] !== void 0) {
3082
+ accu[there] = config[here];
3083
+ }
3084
+ return accu;
3085
+ }, {})
3086
+ };
3087
+ const result = deepClean(configChange);
3088
+ if (!result) {
3089
+ return Promise.resolve();
3090
+ }
3091
+ return general_api_default.put(`${deploymentsApiUrl}/config/binary_delta`, result).catch((err) => commonErrorHandler(err, "There was a problem storing your delta artifact generation configuration.", dispatch)).then(() => {
3092
+ const oldConfig = getState().deployments.config;
3093
+ const newConfig = {
3094
+ ...oldConfig,
3095
+ binaryDelta: {
3096
+ ...oldConfig.binaryDelta,
3097
+ ...config
3098
+ }
3099
+ };
3100
+ return Promise.all([dispatch(actions2.setDeploymentsConfig(newConfig)), dispatch(setSnackbar2("Settings saved successfully"))]);
3101
+ });
3102
+ });
3103
+
3104
+ // src/devicesSlice/thunks.tsx
3105
+ var import_react_router_dom = require("react-router-dom");
3106
+ var import_helpers9 = require("@northern.tech/utils/helpers");
3107
+ var import_toolkit19 = require("@reduxjs/toolkit");
3108
+ var import_axios3 = require("axios");
3109
+ var import_pluralize = __toESM(require("pluralize"), 1);
3110
+ var import_uuid = require("uuid");
3111
+ var import_jsx_runtime2 = require("react/jsx-runtime");
3112
+ var { cleanUpUpload, initUpload, setSnackbar: setSnackbar3, uploadProgress: uploadProgress2 } = actions_default;
3113
+ var { page: defaultPage2, perPage: defaultPerPage2 } = DEVICE_LIST_DEFAULTS;
3114
+ var defaultAttributes = [
3115
+ { scope: "identity", attribute: "status" },
3116
+ { scope: "inventory", attribute: "artifact_name" },
3117
+ { scope: "inventory", attribute: "device_type" },
3118
+ { scope: "inventory", attribute: "mender_is_gateway" },
3119
+ { scope: "inventory", attribute: "mender_gateway_system_id" },
3120
+ { scope: "inventory", attribute: rootfsImageVersion },
3121
+ { scope: "monitor", attribute: "alerts" },
3122
+ { scope: "system", attribute: "created_ts" },
3123
+ { scope: "system", attribute: "updated_ts" },
3124
+ { scope: "system", attribute: "check_in_time" },
3125
+ { scope: "system", attribute: "group" },
3126
+ { scope: "tags", attribute: "name" }
3127
+ ];
3128
+ var getGroups2 = (0, import_toolkit19.createAsyncThunk)(
3129
+ `${sliceName3}/getGroups`,
3130
+ (_, { dispatch, getState }) => general_api_default.get(`${inventoryApiUrl}/groups`).then((res) => {
3131
+ const state = getGroupsById(getState());
3132
+ const dynamicGroups = Object.entries(state).reduce((accu, [id, group]) => {
3133
+ if (group.id || group.filters?.length && id !== UNGROUPED_GROUP.id) {
3134
+ accu[id] = group;
3135
+ }
3136
+ return accu;
3137
+ }, {});
3138
+ const groups = res.data.reduce((accu, group) => {
3139
+ accu[group] = { deviceIds: [], filters: [], total: 0, ...state[group] };
3140
+ return accu;
3141
+ }, dynamicGroups);
3142
+ const filters = [{ key: "group", value: res.data, operator: DEVICE_FILTERING_OPTIONS.$nin.key, scope: "system" }];
3143
+ return Promise.all([
3144
+ dispatch(actions3.receivedGroups(groups)),
3145
+ dispatch(getDevicesByStatus2({ filterSelection: filters, group: 0, page: 1, perPage: 1, status: void 0 }))
3146
+ ]).then((promises) => {
3147
+ const devicesRetrieval = promises[promises.length - 1] || [];
3148
+ const { payload } = devicesRetrieval || {};
3149
+ const result = payload[payload.length - 1] || {};
3150
+ if (!result.total) {
3151
+ return Promise.resolve();
3152
+ }
3153
+ return Promise.resolve(
3154
+ dispatch(
3155
+ actions3.addGroup({
3156
+ groupName: UNGROUPED_GROUP.id,
3157
+ group: { filters: [{ key: "group", value: res.data, operator: DEVICE_FILTERING_OPTIONS.$nin.key, scope: "system" }] }
3158
+ })
3159
+ )
3160
+ );
3161
+ });
3162
+ })
3163
+ );
3164
+ var addDevicesToGroup = (0, import_toolkit19.createAsyncThunk)(
3165
+ `${sliceName3}/addDevicesToGroup`,
3166
+ ({ group, deviceIds, isCreation }, { dispatch }) => general_api_default.patch(`${inventoryApiUrl}/groups/${group}/devices`, deviceIds).then(() => dispatch(actions3.addToGroup({ group, deviceIds }))).finally(() => isCreation ? Promise.resolve(dispatch(getGroups2())) : {})
3167
+ );
3168
+ var removeDevicesFromGroup = (0, import_toolkit19.createAsyncThunk)(
3169
+ `${sliceName3}/removeDevicesFromGroup`,
3170
+ ({ group, deviceIds }, { dispatch }) => general_api_default.delete(`${inventoryApiUrl}/groups/${group}/devices`, deviceIds).then(
3171
+ () => Promise.all([
3172
+ dispatch(actions3.removeFromGroup({ group, deviceIds })),
3173
+ dispatch(setSnackbar3(`The ${(0, import_pluralize.default)("devices", deviceIds.length)} ${(0, import_pluralize.default)("were", deviceIds.length)} removed from the group`, TIMEOUTS.fiveSeconds))
3174
+ ])
3175
+ )
3176
+ );
3177
+ var getGroupNotification = (newGroup, selectedGroup) => {
3178
+ const successMessage = "The group was updated successfully";
3179
+ if (newGroup === selectedGroup) {
3180
+ return [successMessage, TIMEOUTS.fiveSeconds];
3181
+ }
3182
+ return [
3183
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
3184
+ successMessage,
3185
+ " - ",
3186
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_react_router_dom.Link, { to: `/devices?inventory=group:eq:${newGroup}`, children: "click here" }),
3187
+ " to see it."
3188
+ ] }),
3189
+ 5e3,
3190
+ void 0,
3191
+ void 0,
3192
+ () => {
3193
+ }
3194
+ ];
3195
+ };
3196
+ var addStaticGroup = (0, import_toolkit19.createAsyncThunk)(
3197
+ `${sliceName3}/addStaticGroup`,
3198
+ ({ group, devices }, { dispatch, getState }) => Promise.resolve(dispatch(addDevicesToGroup({ group, deviceIds: devices.map(({ id }) => id), isCreation: true }))).then(
3199
+ () => Promise.resolve(
3200
+ dispatch(
3201
+ actions3.addGroup({
3202
+ group: { deviceIds: [], total: 0, filters: [], ...getState().devices.groups.byId[group] },
3203
+ groupName: group
3204
+ })
3205
+ )
3206
+ ).then(
3207
+ () => Promise.all([
3208
+ dispatch(setDeviceListState({ setOnly: true })),
3209
+ dispatch(getGroups2()),
3210
+ dispatch(setSnackbar3(...getGroupNotification(group, getState().devices.groups.selectedGroup)))
3211
+ ])
3212
+ )
3213
+ ).catch((err) => commonErrorHandler(err, `Group could not be updated:`, dispatch))
3214
+ );
3215
+ var removeStaticGroup = (0, import_toolkit19.createAsyncThunk)(
3216
+ `${sliceName3}/removeStaticGroup`,
3217
+ (groupName, { dispatch }) => general_api_default.delete(`${inventoryApiUrl}/groups/${groupName}`).then(
3218
+ () => Promise.all([
3219
+ dispatch(actions3.removeGroup(groupName)),
3220
+ dispatch(getGroups2()),
3221
+ dispatch(setSnackbar3("Group was removed successfully", TIMEOUTS.fiveSeconds))
3222
+ ])
3223
+ )
3224
+ );
3225
+ var getDynamicGroups = (0, import_toolkit19.createAsyncThunk)(
3226
+ `${sliceName3}/getDynamicGroups`,
3227
+ (_, { dispatch, getState }) => general_api_default.get(`${inventoryApiUrlV2}/filters?per_page=${MAX_PAGE_SIZE}`).then(({ data: filters }) => {
3228
+ const state = getGroupsById(getState());
3229
+ const staticGroups = Object.entries(state).reduce((accu, [id, group]) => {
3230
+ if (!(group.id || group.filters?.length)) {
3231
+ accu[id] = group;
3232
+ }
3233
+ return accu;
3234
+ }, {});
3235
+ const groups = (filters || []).reduce((accu, filter) => {
3236
+ accu[filter.name] = {
3237
+ deviceIds: [],
3238
+ total: 0,
3239
+ ...state[filter.name],
3240
+ id: filter.id,
3241
+ filters: mapTermsToFilters(filter.terms)
3242
+ };
3243
+ return accu;
3244
+ }, staticGroups);
3245
+ return Promise.resolve(dispatch(actions3.receivedGroups(groups)));
3246
+ }).catch(() => console.log("Dynamic group retrieval failed - likely accessing a non-enterprise backend"))
3247
+ );
3248
+ var addDynamicGroup = (0, import_toolkit19.createAsyncThunk)(
3249
+ `${sliceName3}/addDynamicGroup`,
3250
+ ({ groupName, filterPredicates }, { dispatch, getState }) => general_api_default.post(`${inventoryApiUrlV2}/filters`, { name: groupName, terms: mapFiltersToTerms(filterPredicates) }).then(
3251
+ (res) => Promise.resolve(
3252
+ dispatch(
3253
+ actions3.addGroup({
3254
+ groupName,
3255
+ group: {
3256
+ id: res.headers[headerNames.location].substring(res.headers[headerNames.location].lastIndexOf("/") + 1),
3257
+ filters: filterPredicates
3258
+ }
3259
+ })
3260
+ )
3261
+ ).then(() => {
3262
+ const { cleanedFilters } = getGroupFilters(groupName, getState().devices.groups);
3263
+ return Promise.all([
3264
+ dispatch(actions3.setDeviceFilters(cleanedFilters)),
3265
+ dispatch(setSnackbar3(...getGroupNotification(groupName, getState().devices.groups.selectedGroup))),
3266
+ dispatch(getDynamicGroups())
3267
+ ]);
3268
+ })
3269
+ ).catch((err) => commonErrorHandler(err, `Group could not be updated:`, dispatch))
3270
+ );
3271
+ var updateDynamicGroup = (0, import_toolkit19.createAsyncThunk)(`${sliceName3}/updateDynamicGroup`, ({ groupName, filterPredicates }, { dispatch, getState }) => {
3272
+ const filterId = getState().devices.groups.byId[groupName].id;
3273
+ return general_api_default.delete(`${inventoryApiUrlV2}/filters/${filterId}`).then(() => Promise.resolve(dispatch(addDynamicGroup({ groupName, filterPredicates }))));
3274
+ });
3275
+ var removeDynamicGroup = (0, import_toolkit19.createAsyncThunk)(`${sliceName3}/removeDynamicGroup`, (groupName, { dispatch, getState }) => {
3276
+ const filterId = getState().devices.groups.byId[groupName].id;
3277
+ return general_api_default.delete(`${inventoryApiUrlV2}/filters/${filterId}`).then(
3278
+ () => Promise.all([dispatch(actions3.removeGroup(groupName)), dispatch(setSnackbar3("Group was removed successfully", TIMEOUTS.fiveSeconds))])
3279
+ );
3280
+ });
3281
+ var getGroupFilters = (group, groupsState, filters = []) => {
3282
+ const groupName = group === UNGROUPED_GROUP.id || group === UNGROUPED_GROUP.name ? UNGROUPED_GROUP.id : group;
3283
+ const selectedGroup = groupsState.byId[groupName];
3284
+ const groupFilterLength = selectedGroup?.filters?.length || 0;
3285
+ const cleanedFilters = groupFilterLength ? [...filters, ...selectedGroup.filters].filter(filtersFilter) : filters;
3286
+ return { cleanedFilters, groupName, selectedGroup, groupFilterLength };
3287
+ };
3288
+ var selectGroup = (0, import_toolkit19.createAsyncThunk)(`${sliceName3}/selectGroup`, ({ group, filters = [] }, { dispatch, getState }) => {
3289
+ const { cleanedFilters, groupName, selectedGroup, groupFilterLength } = getGroupFilters(group, getState().devices.groups, filters);
3290
+ if (getSelectedGroup(getState()) === groupName && (filters.length === 0 && !groupFilterLength || filters.length === cleanedFilters.length)) {
3291
+ return Promise.resolve();
3292
+ }
3293
+ let tasks = [];
3294
+ if (groupFilterLength) {
3295
+ tasks.push(dispatch(actions3.setDeviceFilters(cleanedFilters)));
3296
+ } else {
3297
+ tasks.push(dispatch(actions3.setDeviceFilters(filters)));
3298
+ tasks.push(dispatch(getGroupDevices({ group: groupName, perPage: 1, shouldIncludeAllStates: true })));
3299
+ }
3300
+ const selectedGroupName = selectedGroup || !Object.keys(getGroupsById(getState())).length ? groupName : void 0;
3301
+ tasks.push(dispatch(actions3.selectGroup(selectedGroupName)));
3302
+ return Promise.all(tasks);
3303
+ });
3304
+ var getEarliestTs = (dateA = "", dateB = "") => !dateA || !dateB ? dateA || dateB : dateA < dateB ? dateA : dateB;
3305
+ var reduceReceivedDevices = (devices, ids, state, status) => devices.reduce(
3306
+ (accu, device) => {
3307
+ const stateDevice = getDeviceById(state, device.id);
3308
+ const {
3309
+ attributes: storedAttributes = {},
3310
+ identity_data: storedIdentity = {},
3311
+ monitor: storedMonitor = {},
3312
+ tags: storedTags = {},
3313
+ group: storedGroup
3314
+ } = stateDevice;
3315
+ const { identity, inventory, monitor, system = {}, tags } = mapDeviceAttributes(device.attributes);
3316
+ device.tags = { ...storedTags, ...tags };
3317
+ device.group = system.group ?? storedGroup;
3318
+ device.monitor = { ...storedMonitor, ...monitor };
3319
+ device.identity_data = { ...storedIdentity, ...identity, ...device.identity_data ? device.identity_data : {} };
3320
+ device.status = status ? status : device.status || identity.status;
3321
+ device.check_in_time_rounded = system.check_in_time ?? stateDevice.check_in_time_rounded;
3322
+ device.check_in_time_exact = device.check_in_time ?? stateDevice.check_in_time_exact;
3323
+ device.created_ts = getEarliestTs(getEarliestTs(system.created_ts, device.created_ts), stateDevice.created_ts);
3324
+ device.updated_ts = device.attributes ? device.updated_ts : stateDevice.updated_ts;
3325
+ device.isNew = new Date(device.created_ts) > new Date(state.app.newThreshold);
3326
+ device.isOffline = new Date(device.check_in_time_rounded) < new Date(state.app.offlineThreshold) || device.check_in_time_rounded === void 0;
3327
+ device.attributes = device.attributes ? { ...storedAttributes, ...inventory } : storedAttributes;
3328
+ accu.devicesById[device.id] = { ...stateDevice, ...device };
3329
+ accu.ids.push(device.id);
3330
+ return accu;
3331
+ },
3332
+ { ids, devicesById: {} }
3333
+ );
3334
+ var getGroupDevices = (0, import_toolkit19.createAsyncThunk)(`${sliceName3}/getGroupDevices`, (options, { dispatch, getState }) => {
3335
+ const { group, shouldIncludeAllStates, ...remainder } = options;
3336
+ const { cleanedFilters: filterSelection } = getGroupFilters(group, getState().devices.groups);
3337
+ return Promise.resolve(
3338
+ dispatch(getDevicesByStatus2({ ...remainder, filterSelection, group, status: shouldIncludeAllStates ? void 0 : DEVICE_STATES.accepted }))
3339
+ ).unwrap().then((results) => {
3340
+ if (!group) {
3341
+ return Promise.resolve();
3342
+ }
3343
+ const { deviceAccu, total } = results[results.length - 1];
3344
+ const stateGroup = getState().devices.groups.byId[group];
3345
+ if (!stateGroup && !total && !deviceAccu.ids.length) {
3346
+ return Promise.resolve();
3347
+ }
3348
+ return Promise.resolve(
3349
+ dispatch(
3350
+ actions3.addGroup({
3351
+ group: {
3352
+ deviceIds: deviceAccu.ids.length === total || deviceAccu.ids.length > stateGroup?.deviceIds ? deviceAccu.ids : stateGroup.deviceIds,
3353
+ total
3354
+ },
3355
+ groupName: group
3356
+ })
3357
+ )
3358
+ );
3359
+ });
3360
+ });
3361
+ var getAllGroupDevices = (0, import_toolkit19.createAsyncThunk)(`${sliceName3}/getAllGroupDevices`, (group, { dispatch, getState }) => {
3362
+ if (!group || !!group && (!getGroupsById(getState())[group] || getGroupsById(getState())[group].filters.length)) {
3363
+ return Promise.resolve();
3364
+ }
3365
+ const { attributes, filterTerms } = prepareSearchArguments({
3366
+ filters: [],
3367
+ group,
3368
+ state: getState(),
3369
+ status: DEVICE_STATES.accepted
3370
+ });
3371
+ const getAllDevices = (perPage = MAX_PAGE_SIZE, page = defaultPage2, devices = []) => general_api_default.post(getSearchEndpoint(getState()), {
3372
+ page,
3373
+ per_page: perPage,
3374
+ filters: filterTerms,
3375
+ attributes
3376
+ }).then((res) => {
3377
+ const state = getState();
3378
+ const deviceAccu = reduceReceivedDevices(res.data, devices, state);
3379
+ dispatch(actions3.receivedDevices(deviceAccu.devicesById));
3380
+ const total = Number(res.headers[headerNames.total]);
3381
+ if (total > perPage * page) {
3382
+ return getAllDevices(perPage, page + 1, deviceAccu.ids);
3383
+ }
3384
+ return Promise.resolve(dispatch(actions3.addGroup({ group: { deviceIds: deviceAccu.ids, total: deviceAccu.ids.length }, groupName: group })));
3385
+ });
3386
+ return getAllDevices();
3387
+ });
3388
+ var getAllDynamicGroupDevices = (0, import_toolkit19.createAsyncThunk)(`${sliceName3}/getAllDynamicGroupDevices`, (group, { dispatch, getState }) => {
3389
+ if (!!group && (!getGroupsById(getState())[group] || !getGroupsById(getState())[group].filters.length)) {
3390
+ return Promise.resolve();
3391
+ }
3392
+ const { attributes, filterTerms: filters } = prepareSearchArguments({
3393
+ filters: getState().devices.groups.byId[group].filters,
3394
+ state: getState(),
3395
+ status: DEVICE_STATES.accepted
3396
+ });
3397
+ const getAllDevices = (perPage = MAX_PAGE_SIZE, page = defaultPage2, devices = []) => general_api_default.post(getSearchEndpoint(getState()), { page, per_page: perPage, filters, attributes }).then((res) => {
3398
+ const state = getState();
3399
+ const deviceAccu = reduceReceivedDevices(res.data, devices, state);
3400
+ dispatch(actions3.receivedDevices(deviceAccu.devicesById));
3401
+ const total = Number(res.headers[headerNames.total]);
3402
+ if (total > deviceAccu.ids.length) {
3403
+ return getAllDevices(perPage, page + 1, deviceAccu.ids);
3404
+ }
3405
+ return Promise.resolve(dispatch(actions3.addGroup({ group: { deviceIds: deviceAccu.ids, total }, groupName: group })));
3406
+ });
3407
+ return getAllDevices();
3408
+ });
3409
+ var getDeviceById2 = (0, import_toolkit19.createAsyncThunk)(
3410
+ `${sliceName3}/getDeviceById`,
3411
+ (id, { dispatch, getState }) => general_api_default.get(`${inventoryApiUrl}/devices/${id}`).then((res) => {
3412
+ const device = reduceReceivedDevices([res.data], [], getState()).devicesById[id];
3413
+ device.etag = res.headers.etag;
3414
+ dispatch(actions3.receivedDevice(device));
3415
+ return Promise.resolve(device);
3416
+ }).catch((err) => {
3417
+ const errMsg = (0, import_helpers9.extractErrorMessage)(err);
3418
+ if (errMsg.includes("Not Found")) {
3419
+ console.log(`${id} does not have any inventory information`);
3420
+ const device = reduceReceivedDevices(
3421
+ [
3422
+ {
3423
+ id,
3424
+ attributes: [
3425
+ { name: "status", value: "decomissioned", scope: "identity" },
3426
+ { name: "decomissioned", value: "true", scope: "inventory" }
3427
+ ]
3428
+ }
3429
+ ],
3430
+ [],
3431
+ getState()
3432
+ ).devicesById[id];
3433
+ dispatch(actions3.receivedDevice(device));
3434
+ }
3435
+ })
3436
+ );
3437
+ var getDeviceInfo = (0, import_toolkit19.createAsyncThunk)(`${sliceName3}/getDeviceInfo`, (deviceId, { dispatch, getState }) => {
3438
+ const device = getDeviceById(getState(), deviceId);
3439
+ const { hasDeviceConfig, hasDeviceConnect, hasMonitor } = getTenantCapabilities(getState());
3440
+ const { canConfigure } = getUserCapabilities(getState());
3441
+ const integrations = getDeviceTwinIntegrations(getState());
3442
+ let tasks = [dispatch(getDeviceAuth(deviceId)), ...integrations.map((integration) => dispatch(getDeviceTwin({ deviceId, integration })))];
3443
+ if (hasDeviceConfig && canConfigure && [DEVICE_STATES.accepted, DEVICE_STATES.preauth].includes(device.status)) {
3444
+ tasks.push(dispatch(getDeviceConfig(deviceId)));
3445
+ }
3446
+ if (device.status === DEVICE_STATES.accepted) {
3447
+ tasks.push(dispatch(getDeviceById2(deviceId)));
3448
+ if (hasDeviceConnect) {
3449
+ tasks.push(dispatch(getDeviceConnect(deviceId)));
3450
+ }
3451
+ if (hasMonitor) {
3452
+ tasks.push(dispatch(getLatestDeviceAlerts({ id: deviceId })));
3453
+ tasks.push(dispatch(getDeviceMonitorConfig(deviceId)));
3454
+ }
3455
+ }
3456
+ return Promise.all(tasks);
3457
+ });
3458
+ var deriveInactiveDevices = (0, import_toolkit19.createAsyncThunk)(`${sliceName3}/deriveInactiveDevices`, (deviceIds, { dispatch, getState }) => {
3459
+ const yesterday = /* @__PURE__ */ new Date();
3460
+ yesterday.setDate(yesterday.getDate() - 1);
3461
+ const yesterdaysIsoString = yesterday.toISOString();
3462
+ const devices = deviceIds.reduce(
3463
+ (accu, id) => {
3464
+ const device = getDeviceById(getState(), id);
3465
+ if (device && device.updated_ts > yesterdaysIsoString) {
3466
+ accu.active.push(id);
3467
+ } else {
3468
+ accu.inactive.push(id);
3469
+ }
3470
+ return accu;
3471
+ },
3472
+ { active: [], inactive: [] }
3473
+ );
3474
+ return dispatch(actions3.setInactiveDevices({ activeDeviceTotal: devices.active.length, inactiveDeviceTotal: devices.inactive.length }));
3475
+ });
3476
+ var getDeviceCount = (0, import_toolkit19.createAsyncThunk)(
3477
+ `${sliceName3}/getDeviceCount`,
3478
+ (status, { dispatch, getState }) => general_api_default.post(getSearchEndpoint(getState()), {
3479
+ page: 1,
3480
+ per_page: 1,
3481
+ filters: mapFiltersToTerms([{ key: "status", value: status, operator: DEVICE_FILTERING_OPTIONS.$eq.key, scope: "identity" }]),
3482
+ attributes: defaultAttributes
3483
+ }).then((response) => {
3484
+ const count = Number(response.headers[headerNames.total]);
3485
+ if (status) {
3486
+ return dispatch(actions3.setDevicesCountByStatus({ count, status }));
3487
+ }
3488
+ return dispatch(actions3.setTotalDevices(count));
3489
+ })
3490
+ );
3491
+ var getAllDeviceCounts = (0, import_toolkit19.createAsyncThunk)(
3492
+ `${sliceName3}/getAllDeviceCounts`,
3493
+ (_, { dispatch }) => Promise.all([DEVICE_STATES.accepted, DEVICE_STATES.pending].map((status) => dispatch(getDeviceCount(status))))
3494
+ );
3495
+ var getDeviceLimit2 = (0, import_toolkit19.createAsyncThunk)(
3496
+ `${sliceName3}/getDeviceLimit`,
3497
+ (_, { dispatch }) => general_api_default.get(`${deviceAuthV2}/limits/max_devices`).then((res) => dispatch(actions3.setDeviceLimit(res.data.limit)))
3498
+ );
3499
+ var setDeviceListState = (0, import_toolkit19.createAsyncThunk)(
3500
+ `${sliceName3}/setDeviceListState`,
3501
+ ({ shouldSelectDevices = true, forceRefresh, fetchAuth = true, ...selectionState }, { dispatch, getState }) => {
3502
+ const currentState = getDeviceListState(getState());
3503
+ const refreshTrigger = forceRefresh ? !currentState.refreshTrigger : selectionState.refreshTrigger;
3504
+ let nextState = {
3505
+ ...currentState,
3506
+ setOnly: false,
3507
+ refreshTrigger,
3508
+ ...selectionState,
3509
+ sort: { ...currentState.sort, ...selectionState.sort }
3510
+ };
3511
+ let tasks = [];
3512
+ const { isLoading: currentLoading, deviceIds: currentDevices, selection: currentSelection, ...currentRequestState } = currentState;
3513
+ const { isLoading: nextLoading, deviceIds: nextDevices, selection: nextSelection, ...nextRequestState } = nextState;
3514
+ if (!nextState.setOnly && !(0, import_helpers9.deepCompare)(currentRequestState, nextRequestState)) {
3515
+ const { direction: sortDown = SORTING_OPTIONS.desc, key: sortCol, scope: sortScope } = nextState.sort ?? {};
3516
+ const sortBy = sortCol ? [{ attribute: sortCol, order: sortDown, scope: sortScope }] : void 0;
3517
+ const applicableSelectedState = nextState.state === ALL_DEVICE_STATES ? void 0 : nextState.state;
3518
+ nextState.isLoading = true;
3519
+ tasks.push(
3520
+ dispatch(getDevicesByStatus2({ ...nextState, status: applicableSelectedState, sortOptions: sortBy, fetchAuth })).unwrap().then((results) => {
3521
+ const { deviceAccu, total } = results[results.length - 1];
3522
+ const devicesState = shouldSelectDevices ? { deviceIds: deviceAccu.ids, total, isLoading: false } : { isLoading: false };
3523
+ return Promise.resolve(dispatch(actions3.setDeviceListState(devicesState)));
3524
+ }).catch(() => Promise.resolve({ isLoading: false }))
3525
+ );
3526
+ }
3527
+ tasks.push(dispatch(actions3.setDeviceListState(nextState)));
3528
+ return Promise.all(tasks);
3529
+ }
3530
+ );
3531
+ var getDevicesByStatus2 = (0, import_toolkit19.createAsyncThunk)(`${sliceName3}/getDevicesByStatus`, (options, { dispatch, getState }) => {
3532
+ const {
3533
+ status,
3534
+ fetchAuth = true,
3535
+ filterSelection,
3536
+ group,
3537
+ selectedIssues = [],
3538
+ page = defaultPage2,
3539
+ perPage = defaultPerPage2,
3540
+ sortOptions = [],
3541
+ selectedAttributes = []
3542
+ } = options;
3543
+ const state = getState();
3544
+ const { applicableFilters, filterTerms } = convertDeviceListStateToFilters({
3545
+ filters: filterSelection ?? getDeviceFilters(state),
3546
+ group: group ?? getSelectedGroup(state),
3547
+ groups: state.devices.groups,
3548
+ offlineThreshold: state.app.offlineThreshold,
3549
+ selectedIssues,
3550
+ status
3551
+ });
3552
+ const attributes = [...defaultAttributes, getIdAttribute(getState()), ...selectedAttributes];
3553
+ return general_api_default.post(getSearchEndpoint(getState()), {
3554
+ page,
3555
+ per_page: perPage,
3556
+ filters: filterTerms,
3557
+ sort: sortOptions,
3558
+ attributes
3559
+ }).then((response) => {
3560
+ const state2 = getState();
3561
+ const deviceAccu = reduceReceivedDevices(response.data, [], state2, status);
3562
+ let total = !applicableFilters.length ? Number(response.headers[headerNames.total]) : null;
3563
+ if (status && state2.devices.byStatus[status].total === deviceAccu.ids.length) {
3564
+ total = deviceAccu.ids.length;
3565
+ }
3566
+ let tasks = [dispatch(actions3.receivedDevices(deviceAccu.devicesById))];
3567
+ if (status) {
3568
+ tasks.push(dispatch(actions3.setDevicesByStatus({ deviceIds: deviceAccu.ids, status, total })));
3569
+ }
3570
+ const receivedDevices = Object.values(deviceAccu.devicesById);
3571
+ if (receivedDevices.length && fetchAuth) {
3572
+ tasks.push(dispatch(getDevicesWithAuth(receivedDevices)));
3573
+ }
3574
+ tasks.push(Promise.resolve({ deviceAccu, total: Number(response.headers[headerNames.total]) }));
3575
+ return Promise.all(tasks);
3576
+ }).catch((err) => commonErrorHandler(err, `${status} devices couldn't be loaded.`, dispatch, commonErrorFallback));
3577
+ });
3578
+ var getAllDevicesByStatus = (0, import_toolkit19.createAsyncThunk)(`${sliceName3}/getAllDevicesByStatus`, (status, { dispatch, getState }) => {
3579
+ const attributes = [...defaultAttributes, getIdAttribute(getState())];
3580
+ const getAllDevices = (perPage = MAX_PAGE_SIZE, page = 1, devices = []) => general_api_default.post(getSearchEndpoint(getState()), {
3581
+ page,
3582
+ per_page: perPage,
3583
+ filters: mapFiltersToTerms([{ key: "status", value: status, operator: DEVICE_FILTERING_OPTIONS.$eq.key, scope: "identity" }]),
3584
+ attributes
3585
+ }).then((res) => {
3586
+ const state = getState();
3587
+ const deviceAccu = reduceReceivedDevices(res.data, devices, state, status);
3588
+ dispatch(actions3.receivedDevices(deviceAccu.devicesById));
3589
+ const total = Number(res.headers[headerNames.total]);
3590
+ if (total > state.deployments.deploymentDeviceLimit) {
3591
+ return Promise.resolve();
3592
+ }
3593
+ if (total > perPage * page) {
3594
+ return getAllDevices(perPage, page + 1, deviceAccu.ids);
3595
+ }
3596
+ let tasks = [dispatch(actions3.setDevicesByStatus({ deviceIds: deviceAccu.ids, forceUpdate: true, status, total: deviceAccu.ids.length }))];
3597
+ if (status === DEVICE_STATES.accepted && deviceAccu.ids.length === total) {
3598
+ tasks.push(dispatch(deriveInactiveDevices(deviceAccu.ids)));
3599
+ tasks.push(dispatch(deriveReportsData()));
3600
+ }
3601
+ return Promise.all(tasks);
3602
+ });
3603
+ return getAllDevices();
3604
+ });
3605
+ var searchDevices = (0, import_toolkit19.createAsyncThunk)(`${sliceName3}/searchDevices`, (passedOptions = {}, { dispatch, getState }) => {
3606
+ const state = getState();
3607
+ let options = { ...state.app.searchState, ...passedOptions };
3608
+ const { page = defaultPage2, searchTerm, sortOptions = [] } = options;
3609
+ const { columnSelection = [] } = getUserSettings(state);
3610
+ const selectedAttributes = columnSelection.map((column) => ({ attribute: column.key, scope: column.scope }));
3611
+ const attributes = (0, import_helpers9.attributeDuplicateFilter)([...defaultAttributes, getIdAttribute(state), ...selectedAttributes], "attribute");
3612
+ return general_api_default.post(getSearchEndpoint(getState()), {
3613
+ page,
3614
+ per_page: 10,
3615
+ filters: [],
3616
+ sort: sortOptions,
3617
+ text: searchTerm,
3618
+ attributes
3619
+ }).then((response) => {
3620
+ const deviceAccu = reduceReceivedDevices(response.data, [], getState());
3621
+ return Promise.all([
3622
+ dispatch(actions3.receivedDevices(deviceAccu.devicesById)),
3623
+ Promise.resolve({ deviceIds: deviceAccu.ids, searchTotal: Number(response.headers[headerNames.total]) })
3624
+ ]);
3625
+ }).catch((err) => commonErrorHandler(err, `devices couldn't be searched.`, dispatch, commonErrorFallback));
3626
+ });
3627
+ var ATTRIBUTE_LIST_CUTOFF = 100;
3628
+ var attributeReducer = (attributes = []) => attributes.slice(0, ATTRIBUTE_LIST_CUTOFF).reduce(
3629
+ (accu, { name, scope }) => {
3630
+ if (!accu[scope]) {
3631
+ accu[scope] = [];
3632
+ }
3633
+ accu[scope].push(name);
3634
+ return accu;
3635
+ },
3636
+ { identity: [], inventory: [], system: [], tags: [] }
3637
+ );
3638
+ var getDeviceAttributes = (0, import_toolkit19.createAsyncThunk)(
3639
+ `${sliceName3}/getDeviceAttributes`,
3640
+ (_, { dispatch, getState }) => general_api_default.get(getAttrsEndpoint(getState())).then(({ data }) => {
3641
+ const { identity: identityAttributes, inventory: inventoryAttributes, system: systemAttributes, tags: tagAttributes } = attributeReducer(data || []);
3642
+ return dispatch(actions3.setFilterAttributes({ identityAttributes, inventoryAttributes, systemAttributes, tagAttributes }));
3643
+ })
3644
+ );
3645
+ var getReportingLimits = (0, import_toolkit19.createAsyncThunk)(
3646
+ `${sliceName3}/getReportingLimits`,
3647
+ (_, { dispatch }) => general_api_default.get(`${reportingApiUrl}/devices/attributes`).catch((err) => commonErrorHandler(err, `filterable attributes limit & usage could not be retrieved.`, dispatch, commonErrorFallback)).then(({ data }) => {
3648
+ const { attributes, count, limit } = data;
3649
+ const groupedAttributes = attributeReducer(attributes);
3650
+ return Promise.resolve(dispatch(actions3.setFilterablesConfig({ count, limit, attributes: groupedAttributes })));
3651
+ })
3652
+ );
3653
+ var ensureVersionString = (software, fallback) => software.length && software !== "artifact_name" ? software.endsWith(".version") ? software : `${software}.version` : fallback;
3654
+ var REPORT_CHART_SIZE_LIMIT = 6;
3655
+ var getSingleReportData = (reportConfig, groups) => {
3656
+ const { attribute, group, software = "" } = reportConfig;
3657
+ const filters = [{ key: "status", scope: "identity", operator: DEVICE_FILTERING_OPTIONS.$eq.key, value: "accepted" }];
3658
+ if (group) {
3659
+ const staticGroupFilter = { key: "group", scope: "system", operator: DEVICE_FILTERING_OPTIONS.$eq.key, value: group };
3660
+ const { cleanedFilters: groupFilters } = getGroupFilters(group, groups);
3661
+ filters.push(...groupFilters.length ? groupFilters : [staticGroupFilter]);
3662
+ }
3663
+ const aggregationAttribute = ensureVersionString(software, attribute);
3664
+ return general_api_default.post(`${reportingApiUrl}/devices/aggregate`, {
3665
+ aggregations: [{ attribute: aggregationAttribute, name: "*", scope: "inventory", size: REPORT_CHART_SIZE_LIMIT }],
3666
+ filters: mapFiltersToTerms(filters)
3667
+ }).then(({ data }) => ({ data, reportConfig }));
3668
+ };
3669
+ var getReportsData = (0, import_toolkit19.createAsyncThunk)(`${sliceName3}/getReportsData`, (_, { dispatch, getState }) => {
3670
+ const state = getState();
3671
+ const currentUserId = getCurrentUser(state).id;
3672
+ const reports = getUserSettings(state).reports || getGlobalSettings(state)[`${currentUserId}-reports`] || (Object.keys(getDevicesById(state)).length ? defaultReports : []);
3673
+ return Promise.all(reports.map((report) => getSingleReportData(report, getState().devices.groups))).then((results) => {
3674
+ const devicesState = getState().devices;
3675
+ const totalDeviceCount = devicesState.byStatus.accepted.total;
3676
+ const newReports = results.map(({ data, reportConfig }) => {
3677
+ let { items, other_count } = data[0];
3678
+ const { attribute, group, software = "" } = reportConfig;
3679
+ const dataCount = items.reduce((accu, item) => accu + item.count, 0);
3680
+ const otherCount = !group && (software === rootfsImageVersion || attribute === "artifact_name") ? totalDeviceCount - dataCount : other_count;
3681
+ return { items, otherCount, total: otherCount + dataCount };
3682
+ });
3683
+ return Promise.resolve(dispatch(actions3.setDeviceReports(newReports)));
3684
+ });
3685
+ });
3686
+ var initializeDistributionData = (report, groups, devices, totalDeviceCount) => {
3687
+ const { attribute, group = "", software = "" } = report;
3688
+ const effectiveAttribute = software ? software : attribute;
3689
+ const { deviceIds, total = 0 } = groups[group] || {};
3690
+ const relevantDevices = groups[group] ? deviceIds.map((id) => devices[id]) : Object.values(devices);
3691
+ const distributionByAttribute = relevantDevices.reduce((accu, item) => {
3692
+ if (!item.attributes || item.status !== DEVICE_STATES.accepted) return accu;
3693
+ if (!accu[item.attributes[effectiveAttribute]]) {
3694
+ accu[item.attributes[effectiveAttribute]] = 0;
3695
+ }
3696
+ accu[item.attributes[effectiveAttribute]] = accu[item.attributes[effectiveAttribute]] + 1;
3697
+ return accu;
3698
+ }, {});
3699
+ const distributionByAttributeSorted = Object.entries(distributionByAttribute).sort((pairA, pairB) => pairB[1] - pairA[1]);
3700
+ const items = distributionByAttributeSorted.map(([key, count]) => ({ key, count }));
3701
+ const dataCount = items.reduce((accu, item) => accu + item.count, 0);
3702
+ const otherCount = (groups[group] ? total : totalDeviceCount) - dataCount;
3703
+ return { items, otherCount, total: otherCount + dataCount };
3704
+ };
3705
+ var deriveReportsData = (0, import_toolkit19.createAsyncThunk)(`${sliceName3}/deriveReportsData`, (_, { dispatch, getState }) => {
3706
+ const state = getState();
3707
+ const {
3708
+ groups: { byId: groupsById },
3709
+ byId,
3710
+ byStatus: {
3711
+ accepted: { total }
3712
+ }
3713
+ } = state.devices;
3714
+ const reports = getUserSettings(state).reports || state.users.globalSettings[`${state.users.currentUser}-reports`] || (Object.keys(byId).length ? defaultReports : []);
3715
+ const newReports = reports.map((report) => initializeDistributionData(report, groupsById, byId, total));
3716
+ return Promise.resolve(dispatch(actions3.setDeviceReports(newReports)));
3717
+ });
3718
+ var getReportsDataWithoutBackendSupport = (0, import_toolkit19.createAsyncThunk)(
3719
+ `${sliceName3}/getReportsDataWithoutBackendSupport`,
3720
+ (_, { dispatch, getState }) => Promise.all([dispatch(getAllDevicesByStatus(DEVICE_STATES.accepted)), dispatch(getGroups2()), dispatch(getDynamicGroups())]).then(() => {
3721
+ const { dynamic: dynamicGroups, static: staticGroups } = getGroups(getState());
3722
+ return Promise.all([
3723
+ ...staticGroups.map(({ groupId }) => dispatch(getAllGroupDevices(groupId))),
3724
+ ...dynamicGroups.map(({ groupId }) => dispatch(getAllDynamicGroupDevices(groupId)))
3725
+ ]).then(() => dispatch(deriveReportsData()));
3726
+ })
3727
+ );
3728
+ var getDeviceConnect = (0, import_toolkit19.createAsyncThunk)(
3729
+ `${sliceName3}/getDeviceConnect`,
3730
+ (id, { dispatch }) => general_api_default.get(`${deviceConnect}/devices/${id}`).then(
3731
+ ({ data }) => Promise.all([dispatch(actions3.receivedDevice({ connect_status: data.status, connect_updated_ts: data.updated_ts, id })), Promise.resolve(data)])
3732
+ )
3733
+ );
3734
+ var getSessionDetails = (0, import_toolkit19.createAsyncThunk)(`${sliceName3}/getSessionDetails`, ({ sessionId, deviceId, userId, startDate, endDate }) => {
3735
+ const createdAfter = startDate ? `&created_after=${Math.round(Date.parse(startDate) / 1e3)}` : "";
3736
+ const createdBefore = endDate ? `&created_before=${Math.round(Date.parse(endDate) / 1e3)}` : "";
3737
+ const objectSearch = `&object_id=${deviceId}`;
3738
+ return general_api_default.get(`${auditLogsApiUrl}/logs?per_page=500${createdAfter}${createdBefore}&actor_id=${userId}${objectSearch}`).then(
3739
+ ({ data: auditLogEntries }) => {
3740
+ const { start, end } = auditLogEntries.reduce(
3741
+ (accu, item) => {
3742
+ if (item.meta?.session_id?.includes(sessionId)) {
3743
+ accu.start = new Date(item.action.startsWith("open") ? item.time : accu.start);
3744
+ accu.end = new Date(item.action.startsWith("close") ? item.time : accu.end);
3745
+ }
3746
+ return accu;
3747
+ },
3748
+ { start: startDate || endDate, end: endDate || startDate }
3749
+ );
3750
+ return Promise.resolve({ start, end });
3751
+ }
3752
+ );
3753
+ });
3754
+ var getDeviceFileDownloadLink = (0, import_toolkit19.createAsyncThunk)(
3755
+ `${sliceName3}/getDeviceFileDownloadLink`,
3756
+ ({ deviceId, path }) => Promise.resolve(`${window.location.origin}${deviceConnect}/devices/${deviceId}/download?path=${encodeURIComponent(path)}`)
3757
+ );
3758
+ var deviceFileUpload = (0, import_toolkit19.createAsyncThunk)(`${sliceName3}/deviceFileUpload`, ({ deviceId, path, file }, { dispatch }) => {
3759
+ let formData = new FormData();
3760
+ formData.append("path", path);
3761
+ formData.append("file", file);
3762
+ const uploadId = (0, import_uuid.v4)();
3763
+ const cancelSource = new AbortController();
3764
+ return Promise.all([
3765
+ dispatch(setSnackbar3("Uploading file")),
3766
+ dispatch(initUpload({ id: uploadId, upload: { inprogress: true, uploadProgress: 0, cancelSource } })),
3767
+ general_api_default.uploadPut(
3768
+ `${deviceConnect}/devices/${deviceId}/upload`,
3769
+ formData,
3770
+ (e) => dispatch(uploadProgress2({ id: uploadId, progress: progress(e) })),
3771
+ cancelSource.signal
3772
+ )
3773
+ ]).then(() => Promise.resolve(dispatch(setSnackbar3("Upload successful", TIMEOUTS.fiveSeconds)))).catch((err) => {
3774
+ if ((0, import_axios3.isCancel)(err)) {
3775
+ return dispatch(setSnackbar3("The upload has been cancelled", TIMEOUTS.fiveSeconds));
3776
+ }
3777
+ return commonErrorHandler(err, `Error uploading file to device.`, dispatch);
3778
+ }).finally(() => dispatch(cleanUpUpload(uploadId)));
3779
+ });
3780
+ var getDeviceAuth = (0, import_toolkit19.createAsyncThunk)(
3781
+ `${sliceName3}/getDeviceAuth`,
3782
+ (id, { dispatch }) => dispatch(getDevicesWithAuth([{ id }])).unwrap().then((results) => {
3783
+ if (results[results.length - 1]) {
3784
+ return Promise.resolve(results[results.length - 1][0]);
3785
+ }
3786
+ return Promise.resolve();
3787
+ })
3788
+ );
3789
+ var getDevicesWithAuth = (0, import_toolkit19.createAsyncThunk)(
3790
+ `${sliceName3}/getDevicesWithAuth`,
3791
+ (devices, { dispatch, getState }) => devices.length ? general_api_default.get(`${deviceAuthV2}/devices?id=${devices.map((device) => device.id).join("&id=")}`).then(({ data: receivedDevices }) => {
3792
+ const { devicesById } = reduceReceivedDevices(receivedDevices, [], getState());
3793
+ return Promise.all([dispatch(actions3.receivedDevices(devicesById)), Promise.resolve(receivedDevices)]);
3794
+ }).catch((err) => commonErrorHandler(err, `Error: ${err}`, dispatch)) : Promise.resolve([[], []])
3795
+ );
3796
+ var updateDeviceAuth = (0, import_toolkit19.createAsyncThunk)(
3797
+ `${sliceName3}/updateDeviceAuth`,
3798
+ ({ deviceId, authId, status }, { dispatch, getState }) => general_api_default.put(`${deviceAuthV2}/devices/${deviceId}/auth/${authId}/status`, { status }).then(() => Promise.all([dispatch(getDeviceAuth(deviceId)), dispatch(setSnackbar3("Device authorization status was updated successfully"))])).catch((err) => commonErrorHandler(err, "There was a problem updating the device authorization status:", dispatch)).then(() => Promise.resolve(dispatch(actions3.maybeUpdateDevicesByStatus({ deviceId, authId })))).finally(() => dispatch(setDeviceListState({ refreshTrigger: !getDeviceListState(getState()).refreshTrigger })))
3799
+ );
3800
+ var updateDevicesAuth = (0, import_toolkit19.createAsyncThunk)(`${sliceName3}/updateDevicesAuth`, ({ deviceIds, status }, { dispatch, getState }) => {
3801
+ let devices = getDevicesById(getState());
3802
+ const deviceIdsWithoutAuth = deviceIds.reduce((accu, id) => devices[id].auth_sets ? accu : [...accu, { id }], []);
3803
+ return dispatch(getDevicesWithAuth(deviceIdsWithoutAuth)).then(() => {
3804
+ devices = getDevicesById(getState());
3805
+ const deviceAuthUpdates = deviceIds.map((id) => {
3806
+ const device = devices[id];
3807
+ if (device.auth_sets.length !== 1) {
3808
+ return Promise.reject();
3809
+ }
3810
+ return dispatch(updateDeviceAuth({ authId: device.auth_sets[0].id, deviceId: device.id, status })).unwrap().catch((err) => commonErrorHandler(err, "The action was stopped as there was a problem updating a device authorization status: ", dispatch, "", false));
3811
+ });
3812
+ return Promise.allSettled(deviceAuthUpdates).then((results) => {
3813
+ const { skipped, count } = results.reduce(
3814
+ (accu, item) => {
3815
+ if (item.status === "rejected") {
3816
+ accu.skipped = accu.skipped + 1;
3817
+ } else {
3818
+ accu.count = accu.count + 1;
3819
+ }
3820
+ return accu;
3821
+ },
3822
+ { skipped: 0, count: 0 }
3823
+ );
3824
+ const message = (0, import_helpers9.getSnackbarMessage)(skipped, count);
3825
+ return dispatch(setSnackbar3(message));
3826
+ });
3827
+ });
3828
+ });
3829
+ var deleteAuthset = (0, import_toolkit19.createAsyncThunk)(
3830
+ `${sliceName3}/deleteAuthset`,
3831
+ ({ deviceId, authId }, { dispatch, getState }) => general_api_default.delete(`${deviceAuthV2}/devices/${deviceId}/auth/${authId}`).then(() => Promise.all([dispatch(setSnackbar3("Device authorization status was updated successfully"))])).catch((err) => commonErrorHandler(err, "There was a problem updating the device authorization status:", dispatch)).then(() => Promise.resolve(dispatch(actions3.maybeUpdateDevicesByStatus({ deviceId, authId })))).finally(() => dispatch(setDeviceListState({ refreshTrigger: !getState().devices.deviceList.refreshTrigger })))
3832
+ );
3833
+ var preauthDevice = (0, import_toolkit19.createAsyncThunk)(
3834
+ `${sliceName3}/preauthDevice`,
3835
+ (authset, { dispatch }) => general_api_default.post(`${deviceAuthV2}/devices`, authset).catch((err) => {
3836
+ if (err.response.status === 409) {
3837
+ return Promise.reject("A device with a matching identity data set already exists");
3838
+ }
3839
+ return commonErrorHandler(err, "The device could not be added:", dispatch);
3840
+ }).then(() => Promise.resolve(dispatch(setSnackbar3("Device was successfully added to the preauthorization list", TIMEOUTS.fiveSeconds))))
3841
+ );
3842
+ var decommissionDevice = (0, import_toolkit19.createAsyncThunk)(
3843
+ `${sliceName3}/decommissionDevice`,
3844
+ ({ deviceId, authId }, { dispatch, getState }) => general_api_default.delete(`${deviceAuthV2}/devices/${deviceId}`).then(() => Promise.resolve(dispatch(setSnackbar3("Device was decommissioned successfully")))).catch((err) => commonErrorHandler(err, "There was a problem decommissioning the device:", dispatch)).then(() => Promise.resolve(dispatch(actions3.maybeUpdateDevicesByStatus({ deviceId, authId })))).finally(() => dispatch(setDeviceListState({ refreshTrigger: !getState().devices.deviceList.refreshTrigger })))
3845
+ );
3846
+ var getDeviceConfig = (0, import_toolkit19.createAsyncThunk)(
3847
+ `${sliceName3}/getDeviceConfig`,
3848
+ (deviceId, { dispatch }) => general_api_default.get(`${deviceConfig}/${deviceId}`).then(({ data }) => Promise.all([dispatch(actions3.receivedDevice({ id: deviceId, config: data })), Promise.resolve(data)])).catch((err) => {
3849
+ if (err.response?.data?.error.status_code !== 404) {
3850
+ return commonErrorHandler(err, `There was an error retrieving the configuration for device ${deviceId}.`, dispatch, commonErrorFallback);
3851
+ }
3852
+ })
3853
+ );
3854
+ var setDeviceConfig = (0, import_toolkit19.createAsyncThunk)(
3855
+ `${sliceName3}/setDeviceConfig`,
3856
+ ({ deviceId, config }, { dispatch }) => general_api_default.put(`${deviceConfig}/${deviceId}`, config).catch((err) => commonErrorHandler(err, `There was an error setting the configuration for device ${deviceId}.`, dispatch, commonErrorFallback)).then(() => Promise.resolve(dispatch(getDeviceConfig(deviceId))))
3857
+ );
3858
+ var applyDeviceConfig = (0, import_toolkit19.createAsyncThunk)(
3859
+ `${sliceName3}/applyDeviceConfig`,
3860
+ ({ deviceId, configDeploymentConfiguration, isDefault, config }, { dispatch, getState }) => general_api_default.post(`${deviceConfig}/${deviceId}/deploy`, configDeploymentConfiguration).catch((err) => commonErrorHandler(err, `There was an error deploying the configuration to device ${deviceId}.`, dispatch, commonErrorFallback)).then(({ data }) => {
3861
+ const device = getDeviceById(getState(), deviceId);
3862
+ const { canManageUsers } = getUserCapabilities(getState());
3863
+ let tasks = [
3864
+ dispatch(actions3.receivedDevice({ ...device, config: { ...device.config, deployment_id: data.deployment_id } })),
3865
+ new Promise((resolve) => setTimeout(() => resolve(dispatch(getSingleDeployment(data.deployment_id))), TIMEOUTS.oneSecond))
3866
+ ];
3867
+ if (isDefault && canManageUsers) {
3868
+ const { previous } = getGlobalSettings(getState()).defaultDeviceConfig ?? {};
3869
+ tasks.push(dispatch(saveGlobalSettings({ defaultDeviceConfig: { current: config, previous } })));
3870
+ }
3871
+ return Promise.all(tasks);
3872
+ })
3873
+ );
3874
+ var setDeviceTags = (0, import_toolkit19.createAsyncThunk)(
3875
+ `${sliceName3}/setDeviceTags`,
3876
+ ({ deviceId, tags }, { dispatch }) => (
3877
+ // to prevent tag set failures, retrieve the device & use the freshest etag we can get
3878
+ Promise.resolve(dispatch(getDeviceById2(deviceId))).then((device) => {
3879
+ const headers = device.etag ? { "If-Match": device.etag } : {};
3880
+ return general_api_default.put(
3881
+ `${inventoryApiUrl}/devices/${deviceId}/tags`,
3882
+ Object.entries(tags).map(([name, value]) => ({ name, value })),
3883
+ { headers }
3884
+ ).catch((err) => commonErrorHandler(err, `There was an error setting tags for device ${deviceId}.`, dispatch, "Please check your connection.")).then(() => Promise.all([dispatch(actions3.receivedDevice({ ...device, id: deviceId, tags })), dispatch(setSnackbar3("Device name changed"))]));
3885
+ })
3886
+ )
3887
+ );
3888
+ var getDeviceTwin = (0, import_toolkit19.createAsyncThunk)(`${sliceName3}/getDeviceTwin`, ({ deviceId, integration }, { dispatch, getState }) => {
3889
+ let providerResult = {};
3890
+ return general_api_default.get(`${iotManagerBaseURL}/devices/${deviceId}/state`).then(({ data }) => {
3891
+ providerResult = { ...data, twinError: "" };
3892
+ }).catch((err) => {
3893
+ providerResult = {
3894
+ twinError: `There was an error getting the ${EXTERNAL_PROVIDER[integration.provider].twinTitle.toLowerCase()} for device ${deviceId}. ${err}`
3895
+ };
3896
+ }).finally(() => {
3897
+ const device = getDeviceById(getState(), deviceId);
3898
+ Promise.resolve(dispatch(actions3.receivedDevice({ ...device, twinsByIntegration: { ...device.twinsByIntegration, ...providerResult } })));
3899
+ });
3900
+ });
3901
+ var setDeviceTwin = (0, import_toolkit19.createAsyncThunk)(
3902
+ `${sliceName3}/setDeviceTwin`,
3903
+ ({ deviceId, integration, settings }, { dispatch, getState }) => general_api_default.put(`${iotManagerBaseURL}/devices/${deviceId}/state/${integration.id}`, { desired: settings }).catch(
3904
+ (err) => commonErrorHandler(
3905
+ err,
3906
+ `There was an error updating the ${EXTERNAL_PROVIDER[integration.provider].twinTitle.toLowerCase()} for device ${deviceId}.`,
3907
+ dispatch
3908
+ )
3909
+ ).then(() => {
3910
+ const device = getDeviceById(getState(), deviceId);
3911
+ const { twinsByIntegration = {} } = device;
3912
+ const { [integration.id]: currentState = {} } = twinsByIntegration;
3913
+ return Promise.resolve(
3914
+ dispatch(actions3.receivedDevice({ ...device, twinsByIntegration: { ...twinsByIntegration, [integration.id]: { ...currentState, desired: settings } } }))
3915
+ );
3916
+ })
3917
+ );
3918
+ var prepareSearchArguments = ({ filters, group, state, status }) => {
3919
+ const { filterTerms } = convertDeviceListStateToFilters({ filters, group, offlineThreshold: state.app.offlineThreshold, selectedIssues: [], status });
3920
+ const { columnSelection = [] } = getUserSettings(state);
3921
+ const selectedAttributes = columnSelection.map((column) => ({ attribute: column.key, scope: column.scope }));
3922
+ const attributes = [...defaultAttributes, getIdAttribute(state), ...selectedAttributes];
3923
+ return { attributes, filterTerms };
3924
+ };
3925
+ var getSystemDevices = (0, import_toolkit19.createAsyncThunk)(`${sliceName3}/getSystemDevices`, (options, { dispatch, getState }) => {
3926
+ const { id, page = defaultPage2, perPage = defaultPerPage2, sortOptions = [] } = options;
3927
+ const state = getState();
3928
+ const { hasFullFiltering } = getTenantCapabilities(state);
3929
+ if (!hasFullFiltering) {
3930
+ return Promise.resolve();
3931
+ }
3932
+ const { attributes: deviceAttributes = {} } = getDeviceById(state, id);
3933
+ const { mender_gateway_system_id = "" } = deviceAttributes;
3934
+ const filters = [
3935
+ { ...emptyFilter, key: "mender_is_gateway", operator: DEVICE_FILTERING_OPTIONS.$ne.key, value: "true", scope: "inventory" },
3936
+ { ...emptyFilter, key: "mender_gateway_system_id", value: mender_gateway_system_id, scope: "inventory" }
3937
+ ];
3938
+ const { attributes, filterTerms } = prepareSearchArguments({ filters, state });
3939
+ return general_api_default.post(getSearchEndpoint(getState()), {
3940
+ page,
3941
+ per_page: perPage,
3942
+ filters: filterTerms,
3943
+ sort: sortOptions,
3944
+ attributes
3945
+ }).catch((err) => commonErrorHandler(err, `There was an error getting system devices device ${id}.`, dispatch, "Please check your connection.")).then(({ data, headers }) => {
3946
+ const state2 = getState();
3947
+ const { devicesById, ids } = reduceReceivedDevices(data, [], state2);
3948
+ const device = {
3949
+ ...getDeviceById(state2, id),
3950
+ systemDeviceIds: ids,
3951
+ systemDeviceTotal: Number(headers[headerNames.total])
3952
+ };
3953
+ return Promise.resolve(dispatch(actions3.receivedDevices({ ...devicesById, [id]: device })));
3954
+ });
3955
+ });
3956
+ var getGatewayDevices = (0, import_toolkit19.createAsyncThunk)(`${sliceName3}/getGatewayDevices`, (deviceId, { dispatch, getState }) => {
3957
+ const state = getState();
3958
+ const { attributes = {} } = getDeviceById(state, deviceId);
3959
+ const { mender_gateway_system_id = "" } = attributes;
3960
+ const filters = [
3961
+ { ...emptyFilter, key: "id", operator: DEVICE_FILTERING_OPTIONS.$ne.key, value: deviceId, scope: "identity" },
3962
+ { ...emptyFilter, key: "mender_is_gateway", value: "true", scope: "inventory" },
3963
+ { ...emptyFilter, key: "mender_gateway_system_id", value: mender_gateway_system_id, scope: "inventory" }
3964
+ ];
3965
+ const { attributes: attributeSelection, filterTerms } = prepareSearchArguments({ filters, state });
3966
+ return general_api_default.post(getSearchEndpoint(getState()), {
3967
+ page: 1,
3968
+ per_page: MAX_PAGE_SIZE,
3969
+ filters: filterTerms,
3970
+ attributes: attributeSelection
3971
+ }).then(({ data }) => {
3972
+ const { ids } = reduceReceivedDevices(data, [], getState());
3973
+ let tasks = ids.map((deviceId2) => dispatch(getDeviceInfo(deviceId2)));
3974
+ tasks.push(dispatch(actions3.receivedDevice({ id: deviceId, gatewayIds: ids })));
3975
+ return Promise.all(tasks);
3976
+ });
3977
+ });
3978
+ var getDevicesInBounds = (0, import_toolkit19.createAsyncThunk)(`${sliceName3}/getDevicesInBounds`, ({ bounds, group }, { dispatch, getState }) => {
3979
+ const state = getState();
3980
+ const { filterTerms } = convertDeviceListStateToFilters({
3981
+ group: group === ALL_DEVICES ? void 0 : group,
3982
+ groups: state.devices.groups,
3983
+ status: DEVICE_STATES.accepted
3984
+ });
3985
+ return general_api_default.post(getSearchEndpoint(getState()), {
3986
+ page: 1,
3987
+ per_page: MAX_PAGE_SIZE,
3988
+ filters: filterTerms,
3989
+ attributes: geoAttributes,
3990
+ geo_bounding_box_filter: {
3991
+ geo_bounding_box: {
3992
+ location: {
3993
+ top_left: { lat: bounds._northEast.lat, lon: bounds._southWest.lng },
3994
+ bottom_right: { lat: bounds._southWest.lat, lon: bounds._northEast.lng }
3995
+ }
3996
+ }
3997
+ }
3998
+ }).then(({ data }) => {
3999
+ const { devicesById } = reduceReceivedDevices(data, [], getState());
4000
+ return Promise.resolve(dispatch(actions3.receivedDevices(devicesById)));
4001
+ });
4002
+ });
4003
+
4004
+ // src/monitorSlice/thunks.ts
4005
+ var import_toolkit20 = require("@reduxjs/toolkit");
4006
+ var { page: defaultPage3, perPage: defaultPerPage3 } = DEVICE_LIST_DEFAULTS;
4007
+ var cutoffLength = 75;
4008
+ var ellipsis = "...";
4009
+ var longTextTrimmer = (text) => text.length >= cutoffLength + ellipsis.length ? `${text.substring(0, cutoffLength + ellipsis.length)}${ellipsis}` : text;
4010
+ var sanitizeDeviceAlerts = (alerts) => alerts.map((alert) => ({ ...alert, fullName: alert.name, name: longTextTrimmer(alert.name) }));
4011
+ var getDeviceAlerts = (0, import_toolkit20.createAsyncThunk)(`${sliceName4}/getDeviceAlerts`, ({ id, config = {} }, { dispatch }) => {
4012
+ const { page = defaultPage3, perPage = defaultPerPage3, issuedBefore, issuedAfter, sortAscending = false } = config;
4013
+ const issued_after = issuedAfter ? `&issued_after=${issuedAfter}` : "";
4014
+ const issued_before = issuedBefore ? `&issued_before=${issuedBefore}` : "";
4015
+ return general_api_default.get(`${monitorApiUrlv1}/devices/${id}/alerts?page=${page}&per_page=${perPage}${issued_after}${issued_before}&sort_ascending=${sortAscending}`).catch((err) => commonErrorHandler(err, `Retrieving device alerts for device ${id} failed:`, dispatch)).then(
4016
+ (res) => Promise.all([
4017
+ dispatch(actions4.receiveDeviceAlerts({ deviceId: id, alerts: sanitizeDeviceAlerts(res.data) })),
4018
+ dispatch(actions4.setAlertListState({ total: Number(res.headers[headerNames.total]) }))
4019
+ ])
4020
+ );
4021
+ });
4022
+ var getLatestDeviceAlerts = (0, import_toolkit20.createAsyncThunk)(`${sliceName4}/getLatestDeviceAlerts`, ({ id, config = {} }, { dispatch }) => {
4023
+ const { page = defaultPage3, perPage = 10 } = config;
4024
+ return general_api_default.get(`${monitorApiUrlv1}/devices/${id}/alerts/latest?page=${page}&per_page=${perPage}`).catch((err) => commonErrorHandler(err, `Retrieving device alerts for device ${id} failed:`, dispatch)).then((res) => Promise.resolve(dispatch(actions4.receiveLatestDeviceAlerts({ deviceId: id, alerts: sanitizeDeviceAlerts(res.data) }))));
4025
+ });
4026
+ var getIssueCountsByType2 = (0, import_toolkit20.createAsyncThunk)(`${sliceName4}/getIssueCountsByType`, ({ type, options = {} }, { dispatch, getState }) => {
4027
+ const state = getState();
4028
+ const { filters = getDeviceFilters(state), group, status, ...remainder } = options;
4029
+ const { applicableFilters: nonMonitorFilters, filterTerms } = convertDeviceListStateToFilters({
4030
+ ...remainder,
4031
+ filters,
4032
+ group,
4033
+ offlineThreshold: state.app.offlineThreshold,
4034
+ selectedIssues: [type],
4035
+ status
4036
+ });
4037
+ return general_api_default.post(getSearchEndpoint(getState()), {
4038
+ page: 1,
4039
+ per_page: 1,
4040
+ filters: filterTerms,
4041
+ attributes: [{ scope: "identity", attribute: "status" }]
4042
+ }).catch((err) => commonErrorHandler(err, `Retrieving issue counts failed:`, dispatch, commonErrorFallback)).then((res) => {
4043
+ const total = nonMonitorFilters.length ? state.monitor.issueCounts.byType[type].total : Number(res.headers[headerNames.total]);
4044
+ const filtered = nonMonitorFilters.length ? Number(res.headers[headerNames.total]) : total;
4045
+ if (total === state.monitor.issueCounts.byType[type].total && filtered === state.monitor.issueCounts.byType[type].filtered) {
4046
+ return Promise.resolve();
4047
+ }
4048
+ return Promise.resolve(dispatch(actions4.receiveDeviceIssueCounts({ counts: { filtered, total }, issueType: type })));
4049
+ });
4050
+ });
4051
+ var getDeviceMonitorConfig = (0, import_toolkit20.createAsyncThunk)(
4052
+ `${sliceName4}/getDeviceMonitorConfig`,
4053
+ (id, { dispatch }) => general_api_default.get(`${monitorApiUrlv1}/devices/${id}/config`).catch((err) => commonErrorHandler(err, `Retrieving device monitor config for device ${id} failed:`, dispatch)).then(({ data }) => Promise.all([dispatch(actions_default.receivedDevice({ id, monitors: data }), Promise.resolve(data))]))
4054
+ );
4055
+ var changeNotificationSetting = (0, import_toolkit20.createAsyncThunk)(
4056
+ `${sliceName4}/changeNotificationSetting`,
4057
+ ({ enabled, channel = alertChannels.email }, { dispatch }) => {
4058
+ return general_api_default.put(`${monitorApiUrlv1}/settings/global/channel/alerts/${channel}/status`, { enabled }).catch((err) => commonErrorHandler(err, `${enabled ? "En" : "Dis"}abling ${channel} alerts failed:`, dispatch)).then(
4059
+ () => Promise.all([
4060
+ dispatch(actions4.changeAlertChannel({ channel, enabled })),
4061
+ dispatch(actions_default.setSnackbar(`Successfully ${enabled ? "en" : "dis"}abled ${channel} alerts`, TIMEOUTS.fiveSeconds))
4062
+ ])
4063
+ );
4064
+ }
4065
+ );
4066
+
4067
+ // src/usersSlice/thunks.ts
4068
+ var import_helpers10 = require("@northern.tech/utils/helpers");
4069
+ var import_retrytimer = require("@northern.tech/utils/retrytimer");
4070
+ var import_toolkit21 = require("@reduxjs/toolkit");
4071
+ var import_md5 = __toESM(require("md5"), 1);
4072
+ var import_universal_cookie3 = __toESM(require("universal-cookie"), 1);
4073
+ var cookies3 = new import_universal_cookie3.default();
4074
+ var { setAnnouncement, setSnackbar: setSnackbar4 } = actions_default;
4075
+ var handleLoginError = (err, { token2fa: has2FA, password }, rejectWithValue) => (dispatch) => {
4076
+ const errorText = (0, import_helpers10.extractErrorMessage)(err);
4077
+ const is2FABackend = errorText.includes("2fa");
4078
+ if (is2FABackend && !has2FA) {
4079
+ return rejectWithValue({ error: "2fa code missing" });
4080
+ }
4081
+ if (password === void 0) {
4082
+ return Promise.reject();
4083
+ }
4084
+ const twoFAError = is2FABackend ? " and verification code" : "";
4085
+ const errorMessage = `There was a problem logging in. Please check your email${twoFAError ? "," : " and"} password${twoFAError}. If you still have problems, contact an administrator.`;
4086
+ return Promise.reject(dispatch(setSnackbar4((0, import_helpers10.preformatWithRequestID)(err.response, errorMessage), null, "Copy to clipboard")));
4087
+ };
4088
+ var loginUser = (0, import_toolkit21.createAsyncThunk)(
4089
+ `${sliceName8}/loginUser`,
4090
+ ({ stayLoggedIn, ...userData }, { dispatch, rejectWithValue }) => users_api_default.postLogin(`${useradmApiUrlv1}/auth/login`, { ...userData, no_expiry: stayLoggedIn }).catch((err) => {
4091
+ cleanUp();
4092
+ return Promise.reject(dispatch(handleLoginError(err, userData, rejectWithValue)));
4093
+ }).then(({ text: response, contentType }) => {
4094
+ if (contentType.includes(APPLICATION_JSON_CONTENT_TYPE)) {
4095
+ const { id, kind } = response;
4096
+ const type = kind.split("/")[1];
4097
+ const ssoLoginUrl = SSO_TYPES[type].getStartUrl(id);
4098
+ window.location.replace(ssoLoginUrl);
4099
+ return;
4100
+ }
4101
+ const token = response;
4102
+ if (contentType !== APPLICATION_JWT_CONTENT_TYPE || !token) {
4103
+ return;
4104
+ }
4105
+ let now = /* @__PURE__ */ new Date();
4106
+ now.setSeconds(now.getSeconds() + maxSessionAge);
4107
+ const expiresAt = stayLoggedIn ? void 0 : now.toISOString();
4108
+ setSessionInfo({ token, expiresAt });
4109
+ cookies3.remove("JWT", { path: "/" });
4110
+ return (
4111
+ // @ts-ignore
4112
+ Promise.resolve(dispatch(getUser(OWN_USER_ID))).unwrap().catch((e) => {
4113
+ cleanUp();
4114
+ return Promise.reject(dispatch(setSnackbar4((0, import_helpers10.extractErrorMessage)(e))));
4115
+ }).then(() => {
4116
+ window.sessionStorage.removeItem("pendings-redirect");
4117
+ if (window.location.pathname !== "/ui/") {
4118
+ window.location.replace("/ui/");
4119
+ }
4120
+ return Promise.resolve(dispatch(actions8.successfullyLoggedIn({ expiresAt, token })));
4121
+ })
4122
+ );
4123
+ })
4124
+ );
4125
+ var logoutUser = (0, import_toolkit21.createAsyncThunk)(`${sliceName8}/logoutUser`, (_, { dispatch, getState }) => {
4126
+ if (Object.keys(getState().app.uploadsById).length) {
4127
+ return Promise.reject();
4128
+ }
4129
+ return general_api_default.post(`${useradmApiUrlv1}/auth/logout`).finally(() => {
4130
+ cleanUp();
4131
+ (0, import_retrytimer.clearAllRetryTimers)(setSnackbar4);
4132
+ return Promise.resolve(dispatch({ type: USER_LOGOUT }));
4133
+ });
4134
+ });
4135
+ var switchUserOrganization = (0, import_toolkit21.createAsyncThunk)(`${sliceName8}/switchUserOrganization`, (tenantId, { getState }) => {
4136
+ if (Object.keys(getState().app.uploadsById).length) {
4137
+ return Promise.reject();
4138
+ }
4139
+ return general_api_default.get(`${useradmApiUrlv1}/users/tenants/${tenantId}/token`).then(({ data: token }) => {
4140
+ setSessionInfo({ ...getSessionInfo(), token });
4141
+ window.location.reload();
4142
+ });
4143
+ });
4144
+ var passwordResetStart = (0, import_toolkit21.createAsyncThunk)(
4145
+ `${sliceName8}/passwordResetStart`,
4146
+ (email, { dispatch }) => general_api_default.post(`${useradmApiUrlv1}/auth/password-reset/start`, { email }).catch(
4147
+ (err) => commonErrorHandler(err, `The password reset request cannot be processed:`, dispatch, void 0, true)
4148
+ )
4149
+ );
4150
+ var passwordResetComplete = (0, import_toolkit21.createAsyncThunk)(
4151
+ `${sliceName8}/passwordResetComplete`,
4152
+ ({ secretHash, newPassword }, { dispatch }) => general_api_default.post(`${useradmApiUrlv1}/auth/password-reset/complete`, { secret_hash: secretHash, password: newPassword }).catch((err = {}) => {
4153
+ const { error, response = {} } = err;
4154
+ let errorMsg = "";
4155
+ if (response.status == 400) {
4156
+ errorMsg = "the link you are using expired or the request is not valid, please try again.";
4157
+ } else {
4158
+ errorMsg = error;
4159
+ }
4160
+ dispatch(setSnackbar4("The password reset request cannot be processed: " + errorMsg));
4161
+ return Promise.reject(err);
4162
+ })
4163
+ );
4164
+ var verifyEmailStart = (0, import_toolkit21.createAsyncThunk)(
4165
+ `${sliceName8}/verifyEmailStart`,
4166
+ (_, { dispatch, getState }) => general_api_default.post(`${useradmApiUrlv1}/auth/verify-email/start`, { email: getCurrentUser(getState()).email }).catch((err) => commonErrorHandler(err, "An error occured starting the email verification process:", dispatch)).finally(() => Promise.resolve(dispatch(getUser(OWN_USER_ID))))
4167
+ );
4168
+ var verifyEmailComplete = (0, import_toolkit21.createAsyncThunk)(
4169
+ `${sliceName8}/verifyEmailComplete`,
4170
+ (secret_hash, { dispatch }) => general_api_default.post(`${useradmApiUrlv1}/auth/verify-email/complete`, { secret_hash }).catch((err) => commonErrorHandler(err, "An error occured completing the email verification process:", dispatch)).finally(() => Promise.resolve(dispatch(getUser(OWN_USER_ID))))
4171
+ );
4172
+ var verify2FA = (0, import_toolkit21.createAsyncThunk)(
4173
+ `${sliceName8}/verify2FA`,
4174
+ (tfaData, { dispatch }) => users_api_default.putVerifyTFA(`${useradmApiUrlv1}/2faverify`, tfaData).then(() => Promise.resolve(dispatch(getUser(OWN_USER_ID)))).catch(
4175
+ (err) => commonErrorHandler(err, "An error occured validating the verification code: failed to verify token, please try again.", dispatch, void 0, true)
4176
+ )
4177
+ );
4178
+ var getUserList = (0, import_toolkit21.createAsyncThunk)(
4179
+ `${sliceName8}/getUserList`,
4180
+ (_, { dispatch }) => general_api_default.get(`${useradmApiUrlv1}/users`).then((res) => {
4181
+ const users = res.data.reduce((accu, item) => {
4182
+ accu[item.id] = item;
4183
+ return accu;
4184
+ }, {});
4185
+ return dispatch(actions8.receivedUserList(users));
4186
+ }).catch((err) => commonErrorHandler(err, `Users couldn't be loaded.`, dispatch, commonErrorFallback))
4187
+ );
4188
+ var getUser = (0, import_toolkit21.createAsyncThunk)(
4189
+ `${sliceName8}/getUser`,
4190
+ (id, { dispatch, rejectWithValue }) => general_api_default.get(`${useradmApiUrlv1}/users/${id}`).then(
4191
+ ({ data: user }) => Promise.all([
4192
+ dispatch(actions8.receivedUser(user)),
4193
+ // @ts-ignore
4194
+ dispatch(setHideAnnouncement({ shouldHide: false, userId: user.id })),
4195
+ // @ts-ignore
4196
+ dispatch(updateUserColumnSettings({ currentUserId: user.id })),
4197
+ user
4198
+ ])
4199
+ ).catch((e) => rejectWithValue(e))
4200
+ );
4201
+ var initializeSelf = (0, import_toolkit21.createAsyncThunk)(`${sliceName8}/initializeSelf`, (_, { dispatch }) => dispatch(getUser(OWN_USER_ID)));
4202
+ var updateUserColumnSettings = (0, import_toolkit21.createAsyncThunk)(`${sliceName8}/updateUserColumnSettings`, ({ columns, currentUserId }, { dispatch, getState }) => {
4203
+ const userId = currentUserId ?? getCurrentUser(getState()).id;
4204
+ const storageKey = `${userId}-column-widths`;
4205
+ let customColumns = [];
4206
+ if (!columns) {
4207
+ try {
4208
+ customColumns = JSON.parse(window.localStorage.getItem(storageKey)) || customColumns;
4209
+ } catch {
4210
+ }
4211
+ } else {
4212
+ customColumns = columns;
4213
+ }
4214
+ window.localStorage.setItem(storageKey, JSON.stringify(customColumns));
4215
+ return Promise.resolve(dispatch(actions8.setCustomColumns(customColumns)));
4216
+ });
4217
+ var userActions = {
4218
+ add: {
4219
+ successMessage: "The user was added successfully.",
4220
+ errorMessage: "adding"
4221
+ },
4222
+ create: {
4223
+ successMessage: "The user was created successfully.",
4224
+ errorMessage: "creating"
4225
+ },
4226
+ edit: {
4227
+ successMessage: "The user has been updated.",
4228
+ errorMessage: "editing"
4229
+ },
4230
+ remove: {
4231
+ successMessage: "The user was removed from the system.",
4232
+ errorMessage: "removing"
4233
+ }
4234
+ };
4235
+ var userActionErrorHandler = (err, type, dispatch) => commonErrorHandler(err, `There was an error ${userActions[type].errorMessage} the user.`, dispatch);
4236
+ var createUser = (0, import_toolkit21.createAsyncThunk)(
4237
+ `${sliceName8}/createUser`,
4238
+ ({ shouldResetPassword, ...userData }, { dispatch }) => general_api_default.post(`${useradmApiUrlv1}/users`, { ...userData, send_reset_password: shouldResetPassword }).then(() => Promise.all([dispatch(actions8.createdUser(userData)), dispatch(getUserList()), dispatch(setSnackbar4(userActions.create.successMessage))])).catch((err) => userActionErrorHandler(err, "create", dispatch))
4239
+ );
4240
+ var removeUser = (0, import_toolkit21.createAsyncThunk)(
4241
+ `${sliceName8}/removeUser`,
4242
+ (userId, { dispatch }) => (
4243
+ // @ts-ignore
4244
+ general_api_default.delete(`${useradmApiUrlv1}/users/${userId}`).then(() => Promise.all([dispatch(actions8.removedUser(userId)), dispatch(getUserList()), dispatch(setSnackbar4(userActions.remove.successMessage))])).catch((err) => userActionErrorHandler(err, "remove", dispatch))
4245
+ )
4246
+ );
4247
+ var editUser = (0, import_toolkit21.createAsyncThunk)(
4248
+ `${sliceName8}/editUser`,
4249
+ ({ id, ...userData }, { dispatch, getState }) => general_api_default.put(`${useradmApiUrlv1}/users/${id}`, userData).then(
4250
+ () => Promise.all([
4251
+ dispatch(actions8.updatedUser({ ...userData, id: id === OWN_USER_ID ? getCurrentUser(getState()).id : id })),
4252
+ dispatch(setSnackbar4(userActions.edit.successMessage))
4253
+ ])
4254
+ )
4255
+ );
4256
+ var addUserToCurrentTenant = (0, import_toolkit21.createAsyncThunk)(`${sliceName8}/addUserToTenant`, (userId, { dispatch, getState }) => {
4257
+ const { id } = getOrganization(getState());
4258
+ return general_api_default.post(`${useradmApiUrlv1}/users/${userId}/assign`, { tenant_ids: [id] }).catch((err) => commonErrorHandler(err, `There was an error adding the user to your organization:`, dispatch)).then(() => Promise.all([dispatch(setSnackbar4(userActions.add.successMessage)), dispatch(getUserList())]));
4259
+ });
4260
+ var enableUser2fa = (0, import_toolkit21.createAsyncThunk)(
4261
+ `${sliceName8}/enableUser2fa`,
4262
+ (userId = OWN_USER_ID, { dispatch }) => general_api_default.post(`${useradmApiUrlv1}/users/${userId}/2fa/enable`).catch((err) => commonErrorHandler(err, `There was an error enabling Two Factor authentication for the user.`, dispatch)).then(() => Promise.resolve(dispatch(getUser(userId))))
4263
+ );
4264
+ var disableUser2fa = (0, import_toolkit21.createAsyncThunk)(
4265
+ `${sliceName8}/disableUser2fa`,
4266
+ (userId = OWN_USER_ID, { dispatch }) => general_api_default.post(`${useradmApiUrlv1}/users/${userId}/2fa/disable`).catch((err) => commonErrorHandler(err, `There was an error disabling Two Factor authentication for the user.`, dispatch)).then(() => Promise.resolve(dispatch(getUser(userId))))
4267
+ );
4268
+ var mapHttpPermission = (permission) => Object.entries(uiPermissionsByArea).reduce(
4269
+ (accu, [area, definition]) => {
4270
+ const endpointMatches = definition.endpoints.filter(
4271
+ (endpoint) => endpoint.path.test(permission.value) && (endpoint.types.includes(permission.type) || permission.type === PermissionTypes.Any)
4272
+ );
4273
+ if (permission.value === PermissionTypes.Any || permission.value.includes(apiRoot) && endpointMatches.length) {
4274
+ const endpointUiPermission = endpointMatches.reduce((endpointAccu, endpoint) => [...endpointAccu, ...endpoint.uiPermissions], []);
4275
+ const collector = (endpointUiPermission || definition.uiPermissions).reduce((permissionsAccu, uiPermission) => {
4276
+ if (permission.type === PermissionTypes.Any || !endpointMatches.length && uiPermission.verbs.some((verb) => verb === permission.type)) {
4277
+ permissionsAccu.push(uiPermission.value);
4278
+ }
4279
+ return permissionsAccu;
4280
+ }, []).filter(import_helpers10.duplicateFilter);
4281
+ if (Array.isArray(accu[area])) {
4282
+ accu[area] = [...accu[area], ...collector].filter(import_helpers10.duplicateFilter);
4283
+ } else {
4284
+ accu[area] = mergePermissions(accu[area], { [scopedPermissionAreas[area].excessiveAccessSelector]: collector });
4285
+ }
4286
+ }
4287
+ return accu;
4288
+ },
4289
+ { ...emptyUiPermissions }
4290
+ );
4291
+ var permissionActionTypes = {
4292
+ any: mapHttpPermission,
4293
+ CREATE_DEPLOYMENT: (permission) => permission.type === PermissionTypes.DeviceGroup ? {
4294
+ deployments: [uiPermissionsById.deploy.value],
4295
+ groups: { [permission.value]: [uiPermissionsById.deploy.value] }
4296
+ } : {},
4297
+ http: mapHttpPermission,
4298
+ REMOTE_TERMINAL: (permission) => permission.type === PermissionTypes.DeviceGroup ? {
4299
+ groups: { [permission.value]: [uiPermissionsById.connect.value] }
4300
+ } : {},
4301
+ VIEW_DEVICE: (permission) => permission.type === PermissionTypes.DeviceGroup ? {
4302
+ groups: { [permission.value]: [uiPermissionsById.read.value] }
4303
+ } : {}
4304
+ };
4305
+ var combinePermissions = (existingPermissions, additionalPermissions = {}) => Object.entries(additionalPermissions).reduce((accu, [name, permissions]) => {
4306
+ let maybeExistingPermissions = accu[name] || [];
4307
+ accu[name] = [...permissions, ...maybeExistingPermissions].filter(import_helpers10.duplicateFilter);
4308
+ return accu;
4309
+ }, existingPermissions);
4310
+ var tryParseCustomPermission = (permission) => {
4311
+ const uiPermissions = permissionActionTypes[permission.action](permission.object);
4312
+ const result = mergePermissions({ ...emptyUiPermissions }, uiPermissions);
4313
+ return { isCustom: true, permission, result };
4314
+ };
4315
+ var customPermissionHandler = (accu, permission) => {
4316
+ let processor = tryParseCustomPermission(permission);
4317
+ return {
4318
+ ...accu,
4319
+ isCustom: accu.isCustom || processor.isCustom,
4320
+ uiPermissions: mergePermissions(accu.uiPermissions, processor.result)
4321
+ };
4322
+ };
4323
+ var mapPermissionSet = (permissionSetName, names, scope, existingGroupsPermissions = {}) => {
4324
+ const permission = Object.values(uiPermissionsById).find((permission2) => permission2.permissionSets[scope] === permissionSetName).value;
4325
+ const scopedPermissions = names.reduce((accu, name) => combinePermissions(accu, { [name]: [permission] }), existingGroupsPermissions);
4326
+ return Object.entries(scopedPermissions).reduce((accu, [key, permissions]) => ({ ...accu, [key]: deriveImpliedAreaPermissions(scope, permissions) }), {});
4327
+ };
4328
+ var isEmptyPermissionSet = (permissionSet) => !Object.values(permissionSet).reduce((accu, permissions) => {
4329
+ if (Array.isArray(permissions)) {
4330
+ return accu || !!permissions.length;
4331
+ }
4332
+ return accu || !(0, import_helpers10.isEmpty)(permissions);
4333
+ }, false);
4334
+ var parseRolePermissions = ({ permission_sets_with_scope = [], permissions = [] }, permissionSets) => {
4335
+ const preliminaryResult = permission_sets_with_scope.reduce(
4336
+ (accu, permissionSet) => {
4337
+ let processor = permissionSets[permissionSet.name];
4338
+ if (!processor) {
4339
+ return accu;
4340
+ }
4341
+ const scope = Object.keys(scopedPermissionAreas).find((scope2) => uiPermissionsByArea[scope2].scope === permissionSet.scope?.type);
4342
+ if (scope) {
4343
+ const result = mapPermissionSet(permissionSet.name, permissionSet.scope.value, scope, accu.uiPermissions[scope]);
4344
+ return { ...accu, uiPermissions: { ...accu.uiPermissions, [scope]: result } };
4345
+ } else if (isEmptyPermissionSet(processor.result)) {
4346
+ return processor.permissions.reduce(customPermissionHandler, accu);
4347
+ }
4348
+ return {
4349
+ ...accu,
4350
+ isCustom: accu.isCustom || processor.isCustom,
4351
+ uiPermissions: mergePermissions(accu.uiPermissions, processor.result)
4352
+ };
4353
+ },
4354
+ { isCustom: false, uiPermissions: { ...emptyUiPermissions, groups: {}, releases: {} } }
4355
+ );
4356
+ return permissions.reduce(customPermissionHandler, preliminaryResult);
4357
+ };
4358
+ var normalizeRbacRoles = (roles, rolesById2, permissionSets) => roles.reduce(
4359
+ (accu, role) => {
4360
+ let normalizedPermissions;
4361
+ let isCustom = false;
4362
+ if (rolesById2[role.name]) {
4363
+ normalizedPermissions = {
4364
+ ...rolesById2[role.name].uiPermissions,
4365
+ groups: { ...rolesById2[role.name].uiPermissions.groups },
4366
+ releases: { ...rolesById2[role.name].uiPermissions.releases }
4367
+ };
4368
+ } else {
4369
+ const result = parseRolePermissions(role, permissionSets);
4370
+ normalizedPermissions = result.uiPermissions;
4371
+ isCustom = result.isCustom;
4372
+ }
4373
+ const roleState = accu[role.name] ?? { ...emptyRole };
4374
+ accu[role.name] = {
4375
+ ...roleState,
4376
+ ...role,
4377
+ description: roleState.description ? roleState.description : role.description,
4378
+ editable: !rolesById[role.name] && !isCustom && (typeof roleState.editable !== "undefined" ? roleState.editable : true),
4379
+ isCustom,
4380
+ name: roleState.name ? roleState.name : role.name,
4381
+ uiPermissions: normalizedPermissions
4382
+ };
4383
+ return accu;
4384
+ },
4385
+ { ...rolesById2 }
4386
+ );
4387
+ var getPermissionSets = (0, import_toolkit21.createAsyncThunk)(
4388
+ `${sliceName8}/getPermissionSets`,
4389
+ (_, { dispatch, getState }) => general_api_default.get(`${useradmApiUrlv2}/permission_sets?per_page=500`).then(({ data }) => {
4390
+ const permissionSets = data.reduce(
4391
+ (accu, permissionSet) => {
4392
+ const permissionSetState = accu[permissionSet.name] ?? {};
4393
+ let permissionSetObject = { ...permissionSetState, ...permissionSet };
4394
+ permissionSetObject.result = Object.values(uiPermissionsById).reduce(
4395
+ (accu2, item) => Object.entries(item.permissionSets).reduce((collector, [area, permissionSet2]) => {
4396
+ if (scopedPermissionAreas[area]) {
4397
+ return collector;
4398
+ }
4399
+ if (permissionSet2 === permissionSetObject.name) {
4400
+ collector[area] = [...collector[area], item.value].filter(import_helpers10.duplicateFilter);
4401
+ }
4402
+ return collector;
4403
+ }, accu2),
4404
+ { ...emptyUiPermissions, ...permissionSetObject.result ?? {} }
4405
+ );
4406
+ const scopes = Object.values(scopedPermissionAreas).reduce((accu2, { key, scopeType }) => {
4407
+ if (permissionSetObject.supported_scope_types?.includes(key) || permissionSetObject.supported_scope_types?.includes(scopeType)) {
4408
+ accu2.push(key);
4409
+ }
4410
+ return accu2;
4411
+ }, []);
4412
+ permissionSetObject = scopes.reduce((accu2, scope) => {
4413
+ accu2.result[scope] = mapPermissionSet(permissionSetObject.name, [scopedPermissionAreas[scope].excessiveAccessSelector], scope);
4414
+ return accu2;
4415
+ }, permissionSetObject);
4416
+ accu[permissionSet.name] = permissionSetObject;
4417
+ return accu;
4418
+ },
4419
+ // @ts-ignore
4420
+ { ...getState().users.permissionSetsById }
4421
+ );
4422
+ return Promise.all([dispatch(actions8.receivedPermissionSets(permissionSets)), permissionSets]);
4423
+ }).catch(() => console.log("Permission set retrieval failed - likely accessing a non-RBAC backend"))
4424
+ );
4425
+ var getRoles = (0, import_toolkit21.createAsyncThunk)(
4426
+ `${sliceName8}/getRoles`,
4427
+ (_, { dispatch, getState }) => Promise.all([general_api_default.get(`${useradmApiUrlv2}/roles?per_page=500`), dispatch(getPermissionSets())]).then((results) => {
4428
+ if (!results) {
4429
+ return Promise.resolve();
4430
+ }
4431
+ const [{ data: roles }, { payload: permissionSetTasks }] = results;
4432
+ const rolesById2 = normalizeRbacRoles(roles, getRolesById(getState()), permissionSetTasks[permissionSetTasks.length - 1]);
4433
+ return Promise.resolve(dispatch(actions8.receivedRoles(rolesById2)));
4434
+ }).catch(() => console.log("Role retrieval failed - likely accessing a non-RBAC backend"))
4435
+ );
4436
+ var deriveImpliedAreaPermissions = (area, areaPermissions, skipPermissions = []) => {
4437
+ const highestAreaPermissionLevelSelected = areaPermissions.reduce(
4438
+ (highest, current) => uiPermissionsById[current].permissionLevel > highest ? uiPermissionsById[current].permissionLevel : highest,
4439
+ 1
4440
+ );
4441
+ return uiPermissionsByArea[area].uiPermissions.reduce((permissions, current) => {
4442
+ if ((current.permissionLevel < highestAreaPermissionLevelSelected || areaPermissions.includes(current.value)) && !skipPermissions.includes(current.value)) {
4443
+ permissions.push(current.value);
4444
+ }
4445
+ return permissions;
4446
+ }, []);
4447
+ };
4448
+ var transformAreaRoleDataToScopedPermissionsSets = (area, areaPermissions, excessiveAccessSelector) => {
4449
+ const permissionSetObject = areaPermissions.reduce((accu, { item, uiPermissions }) => {
4450
+ const skipPermissions = scopedPermissionAreas.releases.key === area && item !== ALL_RELEASES ? [uiPermissionsById.upload.value] : [];
4451
+ const impliedPermissions = deriveImpliedAreaPermissions(area, uiPermissions, skipPermissions);
4452
+ accu = impliedPermissions.reduce((itemPermissionAccu, impliedPermission) => {
4453
+ const permissionSetState = itemPermissionAccu[uiPermissionsById[impliedPermission].permissionSets[area]] ?? {
4454
+ type: uiPermissionsByArea[area].scope,
4455
+ value: []
4456
+ };
4457
+ itemPermissionAccu[uiPermissionsById[impliedPermission].permissionSets[area]] = {
4458
+ ...permissionSetState,
4459
+ value: [...permissionSetState.value, item]
4460
+ };
4461
+ return itemPermissionAccu;
4462
+ }, accu);
4463
+ return accu;
4464
+ }, {});
4465
+ return Object.entries(permissionSetObject).map(([name, { value, ...scope }]) => {
4466
+ if (value.includes(excessiveAccessSelector)) {
4467
+ return { name };
4468
+ }
4469
+ return { name, scope: { ...scope, value: value.filter(import_helpers10.duplicateFilter) } };
4470
+ });
4471
+ };
4472
+ var transformRoleDataToRole = (roleData, roleState = {}) => {
4473
+ const role = { ...roleState, ...roleData };
4474
+ const { description = "", name, uiPermissions = emptyUiPermissions } = role;
4475
+ const { maybeUiPermissions, remainderKeys } = Object.entries(emptyUiPermissions).reduce(
4476
+ (accu, [key, emptyPermissions]) => {
4477
+ if (!scopedPermissionAreas[key]) {
4478
+ accu.remainderKeys.push(key);
4479
+ } else if (uiPermissions[key]) {
4480
+ accu.maybeUiPermissions[key] = uiPermissions[key].reduce(itemUiPermissionsReducer, emptyPermissions);
4481
+ }
4482
+ return accu;
4483
+ },
4484
+ { maybeUiPermissions: {}, remainderKeys: [] }
4485
+ );
4486
+ const { permissionSetsWithScope, roleUiPermissions } = remainderKeys.reduce(
4487
+ (accu, area) => {
4488
+ const areaPermissions = role.uiPermissions[area];
4489
+ if (!Array.isArray(areaPermissions)) {
4490
+ return accu;
4491
+ }
4492
+ const impliedPermissions = deriveImpliedAreaPermissions(area, areaPermissions);
4493
+ accu.roleUiPermissions[area] = impliedPermissions;
4494
+ const mappedPermissions = impliedPermissions.map((uiPermission) => ({ name: uiPermissionsById[uiPermission].permissionSets[area] }));
4495
+ accu.permissionSetsWithScope.push(...mappedPermissions);
4496
+ return accu;
4497
+ },
4498
+ { permissionSetsWithScope: [{ name: defaultPermissionSets.Basic.name }], roleUiPermissions: {} }
4499
+ );
4500
+ const scopedPermissionSets = Object.values(scopedPermissionAreas).reduce((accu, { key, excessiveAccessSelector }) => {
4501
+ if (!uiPermissions[key]) {
4502
+ return accu;
4503
+ }
4504
+ accu.push(...transformAreaRoleDataToScopedPermissionsSets(key, uiPermissions[key], excessiveAccessSelector));
4505
+ return accu;
4506
+ }, []);
4507
+ return {
4508
+ permissionSetsWithScope: [...permissionSetsWithScope, ...scopedPermissionSets],
4509
+ role: {
4510
+ ...emptyRole,
4511
+ name,
4512
+ // @ts-ignore
4513
+ description: description ? description : roleState.description,
4514
+ uiPermissions: {
4515
+ ...emptyUiPermissions,
4516
+ ...roleUiPermissions,
4517
+ ...maybeUiPermissions
4518
+ }
4519
+ }
4520
+ };
4521
+ };
4522
+ var roleActions = {
4523
+ create: {
4524
+ successMessage: "The role was created successfully.",
4525
+ errorMessage: "creating"
4526
+ },
4527
+ edit: {
4528
+ successMessage: "The role has been updated.",
4529
+ errorMessage: "editing"
4530
+ },
4531
+ remove: {
4532
+ successMessage: "The role was deleted successfully.",
4533
+ errorMessage: "removing"
4534
+ }
4535
+ };
4536
+ var roleActionErrorHandler = (err, type, dispatch) => commonErrorHandler(err, `There was an error ${roleActions[type].errorMessage} the role.`, dispatch);
4537
+ var createRole = (0, import_toolkit21.createAsyncThunk)(`${sliceName8}/createRole`, (roleData, { dispatch }) => {
4538
+ const { permissionSetsWithScope, role } = transformRoleDataToRole(roleData);
4539
+ return general_api_default.post(`${useradmApiUrlv2}/roles`, {
4540
+ name: role.name,
4541
+ description: role.description,
4542
+ permission_sets_with_scope: permissionSetsWithScope
4543
+ }).then(() => Promise.all([dispatch(actions8.createdRole(role)), dispatch(getRoles()), dispatch(setSnackbar4(roleActions.create.successMessage))])).catch((err) => roleActionErrorHandler(err, "create", dispatch));
4544
+ });
4545
+ var editRole = (0, import_toolkit21.createAsyncThunk)(`${sliceName8}/editRole`, (roleData, { dispatch, getState }) => {
4546
+ const { permissionSetsWithScope, role } = transformRoleDataToRole(roleData, getRolesById(getState())[roleData.name]);
4547
+ return general_api_default.put(`${useradmApiUrlv2}/roles/${role.name}`, {
4548
+ description: role.description,
4549
+ name: role.name,
4550
+ permission_sets_with_scope: permissionSetsWithScope
4551
+ }).then(() => Promise.all([dispatch(actions8.createdRole(role)), dispatch(getRoles()), dispatch(setSnackbar4(roleActions.edit.successMessage))])).catch((err) => roleActionErrorHandler(err, "edit", dispatch));
4552
+ });
4553
+ var removeRole = (0, import_toolkit21.createAsyncThunk)(
4554
+ `${sliceName8}/removeRole`,
4555
+ (roleId, { dispatch }) => (
4556
+ // @ts-ignore
4557
+ general_api_default.delete(`${useradmApiUrlv2}/roles/${roleId}`).then(() => Promise.all([dispatch(actions8.removedRole(roleId)), dispatch(getRoles()), dispatch(setSnackbar4(roleActions.remove.successMessage))])).catch((err) => roleActionErrorHandler(err, "remove", dispatch))
4558
+ )
4559
+ );
4560
+ var getGlobalSettings2 = (0, import_toolkit21.createAsyncThunk)(
4561
+ `${sliceName8}/getGlobalSettings`,
4562
+ (_, { dispatch }) => general_api_default.get(`${useradmApiUrlv1}/settings`).then(({ data: settings, headers: { etag } }) => {
4563
+ window.sessionStorage.setItem(settingsKeys.initialized, true);
4564
+ return Promise.all([dispatch(actions8.setGlobalSettings(settings)), dispatch(setOfflineThreshold()), etag]);
4565
+ })
4566
+ );
4567
+ var saveGlobalSettings = (0, import_toolkit21.createAsyncThunk)(
4568
+ `${sliceName8}/saveGlobalSettings`,
4569
+ // @ts-ignore
4570
+ ({ beOptimistic = false, notify = false, ...settings }, { dispatch, getState }) => {
4571
+ if (!window.sessionStorage.getItem(settingsKeys.initialized) && !beOptimistic) {
4572
+ return;
4573
+ }
4574
+ return dispatch(getGlobalSettings2()).unwrap().then((result) => {
4575
+ let updatedSettings = { ...getState().users.globalSettings, ...settings };
4576
+ if (getCurrentUser(getState()).verified) {
4577
+ updatedSettings["2fa"] = twoFAStates.enabled;
4578
+ } else {
4579
+ delete updatedSettings["2fa"];
4580
+ }
4581
+ let tasks = [dispatch(actions8.setGlobalSettings(updatedSettings))];
4582
+ const headers = result[result.length - 1] ? { "If-Match": result[result.length - 1] } : {};
4583
+ return general_api_default.post(`${useradmApiUrlv1}/settings`, updatedSettings, { headers }).then(() => {
4584
+ if (notify) {
4585
+ tasks.push(dispatch(setSnackbar4("Settings saved successfully")));
4586
+ }
4587
+ return Promise.all(tasks);
4588
+ }).catch((err) => {
4589
+ if (beOptimistic) {
4590
+ return Promise.all([tasks]);
4591
+ }
4592
+ console.log(err);
4593
+ return commonErrorHandler(err, `The settings couldn't be saved.`, dispatch);
4594
+ });
4595
+ });
4596
+ }
4597
+ );
4598
+ var getUserSettings2 = (0, import_toolkit21.createAsyncThunk)(
4599
+ `${sliceName8}/getUserSettings`,
4600
+ (_, { dispatch }) => general_api_default.get(`${useradmApiUrlv1}/settings/me`).then(({ data: settings, headers: { etag } }) => {
4601
+ window.sessionStorage.setItem(settingsKeys.initialized, true);
4602
+ return Promise.all([dispatch(actions8.setUserSettings(settings)), etag]);
4603
+ })
4604
+ );
4605
+ var saveUserSettings = (0, import_toolkit21.createAsyncThunk)(`${sliceName8}/saveUserSettings`, (settings = { onboarding: {} }, { dispatch, getState }) => {
4606
+ if (!getCurrentUser(getState()).id) {
4607
+ return Promise.resolve();
4608
+ }
4609
+ return dispatch(getUserSettings2()).unwrap().then((result) => {
4610
+ const userSettings = getUserSettings(getState());
4611
+ const onboardingState = getOnboardingState(getState());
4612
+ const tooltipState = getTooltipsState(getState());
4613
+ const updatedSettings = {
4614
+ ...userSettings,
4615
+ // @ts-ignore
4616
+ ...settings,
4617
+ onboarding: {
4618
+ ...onboardingState,
4619
+ // @ts-ignore
4620
+ ...settings.onboarding
4621
+ },
4622
+ tooltips: tooltipState
4623
+ };
4624
+ const headers = result[result.length - 1] ? { "If-Match": result[result.length - 1] } : {};
4625
+ return Promise.all([
4626
+ Promise.resolve(dispatch(actions8.setUserSettings(updatedSettings))),
4627
+ general_api_default.post(`${useradmApiUrlv1}/settings/me`, updatedSettings, { headers })
4628
+ ]).catch(() => dispatch(actions8.setUserSettings(userSettings)));
4629
+ });
4630
+ });
4631
+ var get2FAQRCode = (0, import_toolkit21.createAsyncThunk)(
4632
+ `${sliceName8}/get2FAQRCode`,
4633
+ (_, { dispatch }) => general_api_default.get(`${useradmApiUrlv1}/2faqr`).then((res) => dispatch(actions8.receivedQrCode(res.data.qr)))
4634
+ );
4635
+ var setHideAnnouncement = (0, import_toolkit21.createAsyncThunk)(`${sliceName8}/setHideAnnouncement`, ({ shouldHide, userId }, { dispatch, getState }) => {
4636
+ const currentUserId = userId || getCurrentUser(getState()).id;
4637
+ const hash = getState().app.hostedAnnouncement ? (0, import_md5.default)(getState().app.hostedAnnouncement) : "";
4638
+ const announceCookie = cookies3.get(`${currentUserId}${hash}`);
4639
+ if (shouldHide || hash.length && typeof announceCookie !== "undefined") {
4640
+ cookies3.set(`${currentUserId}${hash}`, true, { maxAge: 604800 });
4641
+ return Promise.resolve(dispatch(setAnnouncement()));
4642
+ }
4643
+ return Promise.resolve();
4644
+ });
4645
+ var getTokens = (0, import_toolkit21.createAsyncThunk)(
4646
+ `${sliceName8}/getTokens`,
4647
+ (_, { dispatch, getState }) => general_api_default.get(`${useradmApiUrlv1}/settings/tokens`).then(({ data: tokens }) => {
4648
+ const user = getCurrentUser(getState());
4649
+ const updatedUser = {
4650
+ ...user,
4651
+ tokens
4652
+ };
4653
+ return Promise.resolve(dispatch(actions8.updatedUser(updatedUser)));
4654
+ })
4655
+ );
4656
+ var ONE_YEAR = 31536e3;
4657
+ var generateToken = (0, import_toolkit21.createAsyncThunk)(
4658
+ `${sliceName8}/generateToken`,
4659
+ ({ expiresIn = ONE_YEAR, name }, { dispatch }) => general_api_default.post(`${useradmApiUrlv1}/settings/tokens`, { name, expires_in: expiresIn }).then(({ data: token }) => Promise.all([dispatch(getTokens()), token])).catch((err) => commonErrorHandler(err, "There was an error creating the token:", dispatch))
4660
+ );
4661
+ var revokeToken = (0, import_toolkit21.createAsyncThunk)(
4662
+ `${sliceName8}/revokeToken`,
4663
+ (token, { dispatch }) => (
4664
+ // @ts-ignore
4665
+ general_api_default.delete(`${useradmApiUrlv1}/settings/tokens/${token.id}`).then(() => Promise.resolve(dispatch(getTokens())))
4666
+ )
4667
+ );
4668
+ var setTooltipReadState = (0, import_toolkit21.createAsyncThunk)(`${sliceName8}/setTooltipReadState`, ({ persist, ...remainder }, { dispatch }) => {
4669
+ let tasks = [dispatch(actions8.setTooltipState(remainder))];
4670
+ if (persist) {
4671
+ tasks.push(dispatch(saveUserSettings()));
4672
+ }
4673
+ return Promise.all(tasks);
4674
+ });
4675
+ var setAllTooltipsReadState = (0, import_toolkit21.createAsyncThunk)(`${sliceName8}/toggleHelptips`, ({ readState = READ_STATES.read, tooltips }, { dispatch }) => {
4676
+ const updatedTips = tooltips.reduce((accu, id) => ({ ...accu, [id]: { readState } }), {});
4677
+ return Promise.resolve(dispatch(actions8.setTooltipsState(updatedTips))).then(() => dispatch(saveUserSettings()));
4678
+ });
4679
+ var submitFeedback = (0, import_toolkit21.createAsyncThunk)(
4680
+ `${sliceName8}/submitFeedback`,
4681
+ // @ts-ignore
4682
+ ({ satisfaction, feedback, ...meta }, { dispatch }) => {
4683
+ return general_api_default.post(`${tenantadmApiUrlv2}/contact/support`, {
4684
+ subject: "feedback submission",
4685
+ body: JSON.stringify({ feedback, satisfaction, meta })
4686
+ }).then(() => {
4687
+ const today = /* @__PURE__ */ new Date();
4688
+ dispatch(saveUserSettings({ feedbackCollectedAt: today.toISOString().split("T")[0] }));
4689
+ setTimeout(() => dispatch(actions8.setShowFeedbackDialog(false)), TIMEOUTS.threeSeconds);
4690
+ });
4691
+ }
4692
+ );
4693
+ // Annotate the CommonJS export names for ESM import in node:
4694
+ 0 && (module.exports = {
4695
+ addUserToCurrentTenant,
4696
+ createRole,
4697
+ createUser,
4698
+ disableUser2fa,
4699
+ editRole,
4700
+ editUser,
4701
+ enableUser2fa,
4702
+ generateToken,
4703
+ get2FAQRCode,
4704
+ getGlobalSettings,
4705
+ getPermissionSets,
4706
+ getRoles,
4707
+ getTokens,
4708
+ getUser,
4709
+ getUserList,
4710
+ getUserSettings,
4711
+ initializeSelf,
4712
+ loginUser,
4713
+ logoutUser,
4714
+ normalizeRbacRoles,
4715
+ passwordResetComplete,
4716
+ passwordResetStart,
4717
+ removeRole,
4718
+ removeUser,
4719
+ revokeToken,
4720
+ saveGlobalSettings,
4721
+ saveUserSettings,
4722
+ setAllTooltipsReadState,
4723
+ setHideAnnouncement,
4724
+ setTooltipReadState,
4725
+ submitFeedback,
4726
+ switchUserOrganization,
4727
+ updateUserColumnSettings,
4728
+ verify2FA,
4729
+ verifyEmailComplete,
4730
+ verifyEmailStart
4731
+ });
4732
+ //# sourceMappingURL=thunks.cjs.map