@northern.tech/store 0.29.0 → 0.30.1

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