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