@camstack/addon-admin-ui 1.2.427 → 1.2.429

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 (167) hide show
  1. package/dist/assets/{AddonAssetIcon-BgXfFdy2.js → AddonAssetIcon-DR35yt0E.js} +1 -1
  2. package/dist/assets/Addons-gkGgGpTC.js +4 -0
  3. package/dist/assets/{AdminPage-C0Zxs_ot.js → AdminPage-DAO24U0w.js} +1 -1
  4. package/dist/assets/AdminSectionedPage-B-qoE6ra.js +1 -0
  5. package/dist/assets/AiProfiles-BXcreqZP.js +3 -0
  6. package/dist/assets/BrokerForm-B3xs9aBj.js +1 -0
  7. package/dist/assets/Build-DeMAJfjN.js +40 -0
  8. package/dist/assets/Calendars-VPH-vy-o.js +1 -0
  9. package/dist/assets/Cluster-B-k0M79z.js +1 -0
  10. package/dist/assets/ClusterStepModel-DaAc_6nI.js +1 -0
  11. package/dist/assets/CompositionEditor-BrtLjoSu.js +1 -0
  12. package/dist/assets/{CompositionEditorPage-CDyW_Buu.js → CompositionEditorPage-D51jS9td.js} +1 -1
  13. package/dist/assets/Data-IfJuKcwc.js +2 -0
  14. package/dist/assets/DeviceDetail-D1qU_p1k.js +2 -0
  15. package/dist/assets/DeviceDoActionFields-B62Nv4K7.js +1 -0
  16. package/dist/assets/Devices-Cf5Exjsk.js +1 -0
  17. package/dist/assets/EmbedPlayerPage-CnEcSJ8D.js +1 -0
  18. package/dist/assets/Identity-DNE80jdX.js +1 -0
  19. package/dist/assets/IntegrationDetail-LKbiJFU3.js +1 -0
  20. package/dist/assets/IntegrationHub-DdjWEObX.js +1 -0
  21. package/dist/assets/Integrations-CU7Ll9U_.js +1 -0
  22. package/dist/assets/Integrations-uZB2ozhn.js +1 -0
  23. package/dist/assets/Library-DSuCaXt6.js +1 -0
  24. package/dist/assets/Locations-BeaznsZS.js +3 -0
  25. package/dist/assets/Logs-cm-1R2Z4.js +1 -0
  26. package/dist/assets/MaskShapeCanvas-CM9D4FOf.js +1 -0
  27. package/dist/assets/MotionZonesSettings-DqS8ndiK.js +1 -0
  28. package/dist/assets/MyAccess-Dxb11B6h.js +2 -0
  29. package/dist/assets/Network-BCDUHSB0.js +1 -0
  30. package/dist/assets/NodeAddonsSettingsPanel-BMat4ckt.js +1 -0
  31. package/dist/assets/Notifications-EPQiEZ1t.js +1 -0
  32. package/dist/assets/PrivacyMaskSettings-Bis0PO01.js +1 -0
  33. package/dist/assets/Recordings-BCeoXxL4.js +1 -0
  34. package/dist/assets/ScanNetworkModal-dHWFmbFe.js +1 -0
  35. package/dist/assets/SceneMonitorEditor-SFMMIopn.js +1 -0
  36. package/dist/assets/SessionsList-BRTwG3uv.js +2 -0
  37. package/dist/assets/{Showroom-Cw-6ZdvC.js → Showroom-Er-hes9K.js} +1 -1
  38. package/dist/assets/System-BDXxfgsq.js +1 -0
  39. package/dist/assets/{Terminal-D-YHBrHK.js → Terminal-B70jnm8e.js} +5 -5
  40. package/dist/assets/{Viewer-BmXiweP2.js → Viewer-BsGL5Dfa.js} +1 -1
  41. package/dist/assets/_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-C7iEnSHU.js +1 -0
  42. package/dist/assets/_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEHpkaJP.js +1 -0
  43. package/dist/assets/_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_trpc_mf_1_react_mf_2_query__loadShare__.js-DdJYWyu3.js +1 -0
  44. package/dist/assets/{_virtual_mf___mfe_internal__admin_ui_host__loadShare__react_mf_2_dom__loadShare__.js-BsvPG3BX.js → _virtual_mf___mfe_internal__admin_ui_host__loadShare__react_mf_2_dom__loadShare__.js-DPkvGqVU.js} +1 -1
  45. package/dist/assets/{_virtual_mf___mfe_internal__admin_ui_host__loadShare__react_mf_2_dom_mf_1_client__loadShare__.js-DtoGixA1.js → _virtual_mf___mfe_internal__admin_ui_host__loadShare__react_mf_2_dom_mf_1_client__loadShare__.js-Cb2QlpvS.js} +1 -1
  46. package/dist/assets/{_virtual_mf___mfe_internal__admin_ui_host__loadShare__react_mf_2_konva__loadShare__.js-PmiLsYEK.js → _virtual_mf___mfe_internal__admin_ui_host__loadShare__react_mf_2_konva__loadShare__.js-Cyj0Xie_.js} +4 -4
  47. package/dist/assets/{addon-icons-context-CvwUgMRr.js → addon-icons-context--6Hi3qRW.js} +1 -1
  48. package/dist/assets/{archive-Bwv0mNo-.js → archive-DtcjevJM.js} +1 -1
  49. package/dist/assets/{authed-media-0TPg9TTZ.js → authed-media-LCmlAEZ5.js} +1 -1
  50. package/dist/assets/{bell-off-D2KzCQW2.js → bell-off-eQBpwamg.js} +1 -1
  51. package/dist/assets/board-model-wzCmdEKJ.js +1 -0
  52. package/dist/assets/{boxes-BXQUMgws.js → boxes-DikDfAoo.js} +1 -1
  53. package/dist/assets/circle-slash-YVgGJTpJ.js +1 -0
  54. package/dist/assets/client-DYbvGOid.js +358 -0
  55. package/dist/assets/{cloud-upload-BsULjxPu.js → cloud-upload-DI9XunFf.js} +1 -1
  56. package/dist/assets/crop-CxZbpOyK.js +1 -0
  57. package/dist/assets/{device-integration-icon-CCoHGEQZ.js → device-integration-icon-D2lWVDM2.js} +1 -1
  58. package/dist/assets/device-picker-model-C4w1vbly.js +1 -0
  59. package/dist/assets/dist-CPO0KWoy.js +358 -0
  60. package/dist/assets/dist-ChQzskeX.js +1 -0
  61. package/dist/assets/{eraser-DB7_WMyf.js → eraser-Dl5ROV0l.js} +1 -1
  62. package/dist/assets/{file-up-DuqaeMYR.js → file-up-WS3s_T9x.js} +1 -1
  63. package/dist/assets/{hard-drive-download-CKj8xKOz.js → hard-drive-download-B1ard6ym.js} +1 -1
  64. package/dist/assets/{history-V8RQKQAb.js → history-BMhP0SFG.js} +1 -1
  65. package/dist/assets/{hostInit-CdxLRG1l.js → hostInit-FCvre9AW.js} +1 -1
  66. package/dist/assets/i18n-Vb3uBp7P.js +1 -0
  67. package/dist/assets/{icons-CEMmjIEL.js → icons-DocdgFuy.js} +1 -1
  68. package/dist/assets/index-DKqvG7BE.css +2 -0
  69. package/dist/assets/index-DvOECbab.js +4 -0
  70. package/dist/assets/{key-Bj5-ZBrb.js → key-B1M6i1mf.js} +1 -1
  71. package/dist/assets/{key-round-B2I1YisX.js → key-round-yCDTbIQb.js} +1 -1
  72. package/dist/assets/{layers-BARFkXZ5.js → layers-c960YTPf.js} +1 -1
  73. package/dist/assets/linked-devices-model-CB7qgVjI.js +1 -0
  74. package/dist/assets/{list-ordered-9lF0Gp3K.js → list-ordered-C7hEwAd1.js} +1 -1
  75. package/dist/assets/location-owned-usage-D28vwYJT.js +1 -0
  76. package/dist/assets/{log-in-CjtrIfG3.js → log-in-DFfxcqYz.js} +1 -1
  77. package/dist/assets/{memory-stick-B26_SbtH.js → memory-stick-BBfIGrWx.js} +1 -1
  78. package/dist/assets/{message-square-plus-COMrVZEZ.js → message-square-plus-D8ZUT6rz.js} +1 -1
  79. package/dist/assets/{mf-entry-bootstrap-0-ec37d41a.js → mf-entry-bootstrap-0-3035e647.js} +2 -2
  80. package/dist/assets/{mic-off-DBIqFVjg.js → mic-off-w2mFOBi3.js} +1 -1
  81. package/dist/assets/{monitor-off-CTQMySOs.js → monitor-off-DPi_gm_c.js} +1 -1
  82. package/dist/assets/{monitor-smartphone-iBd_3nPv.js → monitor-smartphone-9Ife1Trw.js} +1 -1
  83. package/dist/assets/mount-C4w1vbly.js +1 -0
  84. package/dist/assets/notification-schedule-field-BuLfSYLZ.js +1 -0
  85. package/dist/assets/{octagon-alert-DMjnTemh.js → octagon-alert-C-jH7VH_.js} +1 -1
  86. package/dist/assets/player-overlays-D0U2dNvn.js +1 -0
  87. package/dist/assets/{recycle-BCVF0r6Y.js → recycle-Bbki65G2.js} +1 -1
  88. package/dist/assets/remoteEntry-DYVoozgD.js +1 -0
  89. package/dist/assets/{scan-eye-DRXP3PgB.js → scan-eye-AfIM_Dlr.js} +1 -1
  90. package/dist/assets/{scissors-DUFtPb9T.js → scissors-CnL6g0BO.js} +1 -1
  91. package/dist/assets/{search-x-B3nve3vV.js → search-x-eqJd3G8u.js} +1 -1
  92. package/dist/assets/{send-P2KlabIu.js → send-B72RQ9UL.js} +1 -1
  93. package/dist/assets/{settings-2-reEhyiKz.js → settings-2-CXZ6DVRg.js} +1 -1
  94. package/dist/assets/{speaker-DSNMuvS8.js → speaker-CcCWWecW.js} +1 -1
  95. package/dist/assets/src-CGxdJN_f.js +67 -0
  96. package/dist/assets/{timer-reset-CsRTbSzh.js → timer-reset-B9Lihcw9.js} +1 -1
  97. package/dist/assets/{ungroup-BLeVa8__.js → ungroup-D753owNE.js} +1 -1
  98. package/dist/assets/{unlink-DeNvF8r-.js → unlink-DzoLNfsq.js} +1 -1
  99. package/dist/assets/{usb-CFseVsQJ.js → usb-CuSU-_EY.js} +1 -1
  100. package/dist/assets/{use-scenes-feed-C8frh3hQ.js → use-scenes-feed-CZjJNxfD.js} +1 -1
  101. package/dist/assets/{use-stationary-objects-DNayAuMq.js → use-stationary-objects-BoGqWyLV.js} +1 -1
  102. package/dist/assets/useEventInvalidation-C4w1vbly.js +1 -0
  103. package/dist/assets/useNodeUrlSelection-BA6CgjTU.js +1 -0
  104. package/dist/assets/useTranslation-D3Is_4B6.js +1 -0
  105. package/dist/assets/user-round-CMg3Ndlt.js +1 -0
  106. package/dist/assets/{user-x-CpaZ5HO0.js → user-x-PK8sSsso.js} +1 -1
  107. package/dist/assets/{video--MLJeLNU.js → video-BBtESt54.js} +1 -1
  108. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-1Do_dc2z.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-BKfTL-9e.js} +2 -2
  109. package/dist/index.html +12 -11
  110. package/dist/server/addon.js +199 -6
  111. package/package.json +1 -1
  112. package/dist/assets/Addons-BTWw53aT.js +0 -4
  113. package/dist/assets/AdminSectionedPage-D2kYQhvu.js +0 -1
  114. package/dist/assets/AiProfiles-Ca7zuVMp.js +0 -3
  115. package/dist/assets/BrokerForm-6-BwPs-g.js +0 -1
  116. package/dist/assets/Build-BsduavcU.js +0 -40
  117. package/dist/assets/Calendars-DVTk_2iT.js +0 -1
  118. package/dist/assets/Cluster-BPJ4maiI.js +0 -1
  119. package/dist/assets/ClusterStepModel-CjuZ-oml.js +0 -1
  120. package/dist/assets/CompositionEditor-DJcmWU2U.js +0 -1
  121. package/dist/assets/Data-CLLvqZwG.js +0 -1
  122. package/dist/assets/DeviceDetail-BKw1gufS.js +0 -2
  123. package/dist/assets/DeviceDoActionFields-R-ZYIdMv.js +0 -1
  124. package/dist/assets/Devices-CHeb_BTk.js +0 -1
  125. package/dist/assets/EmbedPlayerPage-B4y0Q0wO.js +0 -1
  126. package/dist/assets/Identity-NOlTR-3q.js +0 -1
  127. package/dist/assets/IntegrationDetail-CcZkPlbN.js +0 -1
  128. package/dist/assets/IntegrationHub-CuW7-WRy.js +0 -1
  129. package/dist/assets/Integrations-ACdx4iPR.js +0 -1
  130. package/dist/assets/Integrations-DjnhmLye.js +0 -1
  131. package/dist/assets/Library-B3iyoKdK.js +0 -1
  132. package/dist/assets/Locations-Cs1VwmXB.js +0 -3
  133. package/dist/assets/Logs-BMc6WXCH.js +0 -1
  134. package/dist/assets/MaskShapeCanvas-Dcpby34M.js +0 -1
  135. package/dist/assets/MotionZonesSettings-DjvGw8j4.js +0 -1
  136. package/dist/assets/MyAccess-BfUfTXrv.js +0 -2
  137. package/dist/assets/Network-F2lAIcbT.js +0 -1
  138. package/dist/assets/NodeAddonsSettingsPanel-D3ux_JIo.js +0 -1
  139. package/dist/assets/Notifications-Cp3qo_EC.js +0 -1
  140. package/dist/assets/PrivacyMaskSettings-IK6ytyM8.js +0 -1
  141. package/dist/assets/Recordings-D91q74Ga.js +0 -1
  142. package/dist/assets/ScanNetworkModal-DjU-xM4X.js +0 -1
  143. package/dist/assets/SceneMonitorEditor-V_pHxg3U.js +0 -1
  144. package/dist/assets/SessionsList-DQ7kj8fX.js +0 -2
  145. package/dist/assets/System-DLLa4weE.js +0 -1
  146. package/dist/assets/_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-wt87pCBz.js +0 -1
  147. package/dist/assets/_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js +0 -1
  148. package/dist/assets/_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_trpc_mf_1_react_mf_2_query__loadShare__.js-DX7sYWrs.js +0 -1
  149. package/dist/assets/board-model-Bmts6hrg.js +0 -1
  150. package/dist/assets/circle-slash-DpUtlEnB.js +0 -1
  151. package/dist/assets/client-CjyKfSu1.js +0 -358
  152. package/dist/assets/crop-BtQBZ9jm.js +0 -1
  153. package/dist/assets/device-picker-model-1Z6p3UkP.js +0 -1
  154. package/dist/assets/dist-DQtBl_2T.js +0 -1
  155. package/dist/assets/dist-DWoekMi0.js +0 -358
  156. package/dist/assets/index-D66JvELZ.js +0 -4
  157. package/dist/assets/index-dmZ34NAY.css +0 -2
  158. package/dist/assets/location-owned-usage-CNXQ-Obv.js +0 -1
  159. package/dist/assets/mount-1Z6p3UkP.js +0 -1
  160. package/dist/assets/notification-schedule-field-D8dd67dT.js +0 -1
  161. package/dist/assets/player-overlays-DWMIy1MJ.js +0 -1
  162. package/dist/assets/remoteEntry-RwWzzVu_.js +0 -1
  163. package/dist/assets/src-BLkInT8U.js +0 -67
  164. package/dist/assets/useEventInvalidation-1Z6p3UkP.js +0 -1
  165. package/dist/assets/useNodeUrlSelection-BsLRiUy8.js +0 -1
  166. package/dist/assets/useTranslation-Bc5yH9V9.js +0 -1
  167. package/dist/assets/user-round-BB0VDRnJ.js +0 -1
@@ -1,2 +0,0 @@
1
- import{I as e,K as t,Q as n,S as r,W as i,a,b as o,o as s,q as c,t as l,x as u,z as d}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{$t as f,D as p,Fi as m,G as h,Gn as g,It as _,J as v,Jr as y,K as b,Kr as x,Ln as S,Lr as C,O as w,Pi as T,Qi as E,Ri as D,Rn as O,Rr as k,St as A,T as j,Tn as M,V as N,W as P,Wn as F,Xt as I,Yn as L,Z as R,_n as z,_t as ee,ar as B,bi as V,bn as H,br as te,cr as ne,di as re,dt as ie,fn as ae,ht as U,m as oe,ot as W,qn as se,r as ce,si as G,sr as le,t as ue,un as de,vn as fe,wi as pe,yn as me,z as he}from"./player-overlays-DWMIy1MJ.js";import{t as ge}from"./archive-Bwv0mNo-.js";import{i as _e,n as ve,r as ye,t as be}from"./scan-eye-DRXP3PgB.js";import{t as xe}from"./bell-off-D2KzCQW2.js";import{t as K}from"./boxes-BXQUMgws.js";import{n as Se}from"./video--MLJeLNU.js";import{t as Ce}from"./circle-slash-DpUtlEnB.js";import{t as we}from"./layers-BARFkXZ5.js";import{Ar as q,Br as Te,Cr as Ee,Er as J,Mn as De,Nn as Oe,Pn as ke,Tr as Ae,Yn as je,_ as Me,b as Ne,cr as Pe,en as Fe,f as Ie,fn as Le,fr as Re,g as ze,gi as Be,gr as Ve,hi as He,in as Ue,jr as Y,kn as We,kr as Ge,ln as Ke,m as qe,nn as Je,p as Ye,rn as Xe,tn as Ze,u as Qe,un as $e,vr as et,zr as tt}from"./client-CjyKfSu1.js";import{$l as nt,$s as rt,A as it,Ai as at,An as ot,Bi as st,Bn as X,Ca as ct,Ct as lt,Dn as ut,Ds as dt,Ei as ft,En as pt,Fn as mt,Gl as ht,Ha as gt,Hi as _t,Ht as vt,Ia as yt,Ii as bt,In as xt,Is as St,Jr as Ct,K as wt,Kn as Tt,Kt as Et,Ln as Dt,M as Ot,Mn as kt,Mr as At,Ms as jt,Mt,Nn as Nt,Os as Pt,Qi as Ft,Qs as It,Qt as Lt,S as Rt,T as zt,Tc as Bt,Ti as Vt,Tn as Ht,Tt as Ut,Ui as Wt,Vn as Gt,Vs as Kt,Vt as qt,W as Jt,Wi as Yt,Xl as Xt,Yo as Zt,Zl as Qt,Zn as $t,Zs as en,Zt as tn,_t as nn,a as rn,an,ar as on,as as sn,at as cn,b as ln,ba as un,bt as dn,c as fn,cn as pn,co as mn,ct as hn,cu as gn,d as _n,da as vn,dn as yn,dt as bn,du as xn,ec as Sn,en as Cn,et as wn,eu as Tn,fo as En,ft as Dn,gt as On,gu as kn,ha as An,hn as jn,ht as Mn,i as Nn,in as Pn,it as Fn,j as In,ji as Ln,jn as Rn,js as zn,k as Bn,ka as Vn,kn as Hn,ks as Un,l as Wn,ln as Gn,lt as Kn,ma as qn,mo as Jn,mr as Yn,nc as Xn,nn as Zn,nt as Qn,o as $n,oa as er,or as tr,ot as nr,pa as rr,po as ir,q as ar,r as or,rn as sr,rs as cr,ru as lr,s as ur,sa as dr,sn as fr,sr as pr,ta as mr,tc as hr,tn as gr,tu as _r,ua as vr,uc as yr,un as br,uu as xr,w as Sr,wn as Cr,wt as wr,x as Tr,xt as Er,y as Dr,yt as Or,za as kr,zi as Ar,zt as jr}from"./src-BLkInT8U.js";import{t as Z}from"./useTranslation-Bc5yH9V9.js";import"./mount-1Z6p3UkP.js";import{A as Mr,B as Nr,D as Pr,E as Fr,G as Ir,H as Lr,K as Rr,L as zr,M as Br,O as Vr,R as Hr,U as Ur,W as Wr,X as Gr,Y as Kr,Z as qr,g as Jr,j as Yr,k as Xr,q as Zr,v as Qr,y as $r,z as ei}from"./index-D66JvELZ.js";import{C as ti,D as ni,E as ri,S as ii,_ as ai,a as oi,b as si,c as ci,d as li,f as ui,g as di,h as fi,i as pi,l as mi,m as hi,n as gi,o as _i,p as vi,r as yi,s as bi,t as xi,u as Si,v as Ci,x as wi,y as Ti}from"./CompositionEditor-DJcmWU2U.js";import{_ as Ei,a as Di,c as Oi,d as ki,f as Ai,g as ji,h as Mi,i as Ni,l as Pi,m as Fi,n as Ii,o as Li,p as Ri,s as zi,t as Bi,u as Vi,v as Hi,y as Ui}from"./ClusterStepModel-CjuZ-oml.js";import"./useEventInvalidation-1Z6p3UkP.js";import{t as Wi}from"./use-stationary-objects-DNayAuMq.js";import"./device-picker-model-1Z6p3UkP.js";import{t as Gi}from"./authed-media-0TPg9TTZ.js";n();function Ki(e){if(typeof e!=`object`||!e)return null;let t=e,n=t.id,r=t.label;if(typeof n!=`string`||typeof r!=`string`)return null;let i=t.available===!0,a=t.enabled,o=t.unavailableReason;return{id:n,label:r,costWhenOff:typeof t.costWhenOff==`string`?t.costWhenOff:``,on:i&&typeof a==`boolean`?a:null,available:i,unavailableReason:typeof o==`string`?o:null}}function qi(e){if(typeof e!=`object`||!e)return null;let t=e.switches;if(!Array.isArray(t))return null;let n=t.map(Ki).filter(e=>e!==null);return n.length===0?null:n}var Ji=[[/privacy|mask/i,`privacy`],[/microphone|mic\b/i,`microphone`],[/speaker|broker audio|stream audio/i,`speaker`],[/audio/i,`listening`],[/object|detect/i,`detection`],[/event/i,`archive`],[/record/i,`recording`],[/notif/i,`notifications`],[/stream|broker/i,`stream`]];function Yi(e){for(let[t,n]of Ji)if(t.test(e))return n;return`generic`}function Xi(e){let t=e.filter(e=>e.on===!1).map(e=>e.id),n=e.filter(e=>e.on===null).map(e=>e.id),r=t=>t.map(t=>e.find(e=>e.id===t)?.label??t).join(`, `),i=[];return t.length>0&&i.push(`Off: ${r(t)}`),n.length>0&&i.push(`Unknown: ${r(n)}`),{offIds:t,unknownIds:n,summary:i.length===0?`All camera functions on`:i.join(` · `)}}var Zi={stream:H,detection:be,privacy:C,microphone:L,speaker:A,listening:ve,archive:ge,recording:ye,notifications:T,generic:f};function Qi({deviceId:t}){let n=s(),i=Number.isFinite(t),[a,o]=c(null),[l,d]=c(!1),p=jt({deviceId:t},{enabled:i});or([`pipelineOrchestrator`,`getCameraSwitches`],[`capability.binding-changed`]);let m=qi(p.data),h=Xn({onError:(e,r)=>{console.error(`[CameraFunctionSwitches] switch write failed — reverting`,{tags:{deviceId:t},meta:{switchId:r.switchId,error:e instanceof Error?e.message:String(e)}}),n.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getCameraSwitches`]]}),o({id:r.switchId,message:e instanceof Error?e.message:String(e)})},onSuccess:()=>{o(null),n.invalidateQueries({queryKey:[[`pipelineOrchestrator`]]}),n.invalidateQueries({queryKey:[[`deviceManager`]]}),n.invalidateQueries({queryKey:[[`recording`]]})}}),g=e(e=>{!e.available||e.on===null||h.mutate({deviceId:t,switchId:e.id,enabled:!e.on})},[t,h]);if(m===null)return null;let _=Xi(m),v=e=>a?.id===e.id?a.message:null;return r(nt,{open:l,onOpenChange:d,children:[r(_r,{"aria-label":`Camera functions`,title:_.summary,className:`inline-flex items-center gap-1 rounded-lg border px-2 py-1.5 text-[11px] font-medium transition-colors ${a===null?_.offIds.length>0?`border-warning/40 text-warning hover:bg-warning/10`:`border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover`:`border-danger/50 text-danger bg-danger/5`}`,children:[u(f,{className:`h-3.5 w-3.5`}),u(`span`,{className:`hidden lg:inline`,children:`Functions`}),_.offIds.length>0&&r(`span`,{className:`rounded bg-warning/20 px-1 text-[9px] font-semibold uppercase tracking-wide`,children:[_.offIds.length,` off`]})]}),r(Tn,{align:`end`,className:`min-w-[240px] max-h-[60vh] overflow-y-auto p-1`,children:[u(`div`,{className:`px-2 py-1 text-[10px] uppercase tracking-wider text-foreground-subtle`,children:`Camera functions`}),u(`ul`,{className:`space-y-0.5`,children:m.map(e=>u(`li`,{children:u($i,{row:e,failure:v(e),onToggle:()=>g(e)})},e.id))})]})]})}function $i({row:e,failure:t,onToggle:n}){let i=Zi[Yi(e.label)],a=e.on===null,o=e.on===!1,s=t===null?a?e.unavailableReason??`The source that owns this did not answer.`:e.costWhenOff:`Write failed: ${t}`,c=t===null?a?e.unavailableReason??`unknown`:null:`write failed`;return r(`button`,{type:`button`,role:`switch`,"aria-label":e.label,"aria-checked":e.on===!0,disabled:!e.available,onClick:n,title:s,className:`flex w-full items-center gap-2 rounded-md px-2 py-1 text-left text-[12px] text-foreground transition-colors hover:bg-surface-hover disabled:opacity-40 disabled:cursor-not-allowed`,children:[u(i,{className:`h-3.5 w-3.5 shrink-0 ${t===null?a?`text-foreground-subtle/50`:o?`text-warning`:`text-success`:`text-danger`}`}),r(`span`,{className:`flex-1 min-w-0 truncate`,children:[e.label,c!==null&&r(`span`,{className:`ml-1 text-[10px] text-foreground-subtle`,children:[`· `,c]})]}),u(`span`,{className:`shrink-0 rounded px-1 py-0.5 text-[9px] font-semibold uppercase tracking-wide ${a?`bg-surface-hover text-foreground-subtle/60`:o?`bg-warning/20 text-warning`:`bg-success/20 text-success`}`,children:a?`—`:o?`off`:`on`})]})}function ea({deviceId:e}){let t=bn(W().trpcClient,e);return t===null?null:r(`a`,{href:t.url,target:`_blank`,rel:`noopener noreferrer`,title:`${t.label} — ${t.host}`,className:`inline-flex items-center gap-1.5 rounded-lg px-2 sm:px-2.5 py-1.5 text-[11px] font-medium border border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,children:[u(k,{className:`h-3.5 w-3.5`}),u(`span`,{className:`hidden sm:inline`,children:t.label})]})}function ta({parentDeviceId:e}){let{t}=Z(),n=Kr(),i=W(),{data:a,isLoading:o,isError:s}=Nr(e),{data:c}=vr({deviceId:e},{enabled:Number.isFinite(e)});if(o)return u(`div`,{className:`rounded-lg border border-border bg-surface p-3`,children:u(`p`,{className:`text-[10px] text-foreground-subtle`,children:t(`common.loading`,{defaultValue:`Loading…`})})});if(s)return u(`div`,{className:`rounded-lg border border-border bg-surface p-3`,children:u(`p`,{className:`text-[10px] text-warning`,children:t(`integrations.childrenLoadError`,{defaultValue:`Failed to load children`})})});let l=(a??[]).filter(e=>e.display?.hidden!==!0);if(l.length===0)return null;let d=nr(c?.stableId??``,l,c?.childLayout),f=d.ungrouped,p=e=>n(`/devices/${String(e)}`),m=c?.name??``,h=(e,t)=>u(Fn,{trpc:i.trpcClient,device:{...t,name:Dn(t,m)},variant:`minimal`,onNavigate:p},e),g=f.some(e=>!!e.role),_=f.some(e=>!e.role),v=g&&!_?t(`device.accessories`,{defaultValue:`Accessories`}):!g&&_?t(`device.adoptedDevices`,{defaultValue:`Adopted devices`}):t(`device.children`,{defaultValue:`Children`}),y=f.length>0?r(`div`,{className:`rounded-lg border border-border bg-surface p-3`,children:[u(`div`,{className:`text-[10px] font-semibold uppercase tracking-wide text-foreground-subtle mb-1.5`,children:v}),u(`div`,{className:`space-y-1`,children:f.map(e=>h(e.id,e))})]}):null,b=d.disabledSection===void 0?null:u(cn,{title:t(`device.disabledSection`,{defaultValue:`Disabled`}),count:d.disabledSection.children.length,defaultOpen:!1,children:u(`div`,{className:`opacity-60 space-y-1`,children:d.disabledSection.children.map(e=>h(e.id,e))})},d.disabledSection.title);if(d.sections.length===0)return b===null?y:r(`div`,{className:`space-y-2`,children:[y,b]});let x=_&&!g;return r(`div`,{className:`space-y-2`,children:[x?y:null,d.sections.map(e=>u(cn,{title:e.title,count:e.children.length,defaultOpen:e.defaultOpen,children:e.children.map(e=>h(e.id,e))},e.title)),x?null:y,b]})}function na({deviceId:e}){let t=W(),{data:n,isLoading:r}=ei(e),{data:i,isLoading:a}=Nr(e),o=r||a,s=(i??[]).map(e=>({id:e.id,stableId:e.stableId,type:e.type,name:e.name,features:e.features,...e.sourceInfo?{sourceInfo:{id:e.sourceInfo.id}}:{}})),c=typeof n?.linkDeviceId==`number`?n.linkDeviceId:null,l=typeof n?.primaryChildEntityId==`string`?n.primaryChildEntityId:null;return o?u(`div`,{className:`h-full min-h-32 w-full animate-pulse rounded-lg bg-surface`,"aria-hidden":`true`}):u(`div`,{className:`flex h-full w-full flex-col`,children:u(Mn,{trpc:t.trpcClient,children:s,linkDeviceId:c,primaryChildEntityId:l})})}n();function ra({dev:e,busy:t,setBusy:n}){let i=e?.motionTrigger,a=v(e?.state.motionTrigger),[o,s]=c(!1);if(!i)return null;let l=a?.enabled===!0,d=a!==void 0,f=async()=>{if(t||!d)return;let e=!l;n(!0),s(!0);try{await i.setMotionTrigger({enabled:e})}finally{n(!1),s(!1)}};return r(`button`,{type:`button`,onClick:()=>{f()},disabled:t||!d,title:d?l?`Disable trigger on motion`:`Enable trigger on motion`:`Awaiting state…`,"aria-pressed":l,className:`inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-[11px] font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${l?`border-primary/50 bg-primary/15 text-primary`:`border-border bg-surface text-foreground-subtle hover:text-foreground`}`,children:[u(E,{className:`h-3 w-3`}),u(`span`,{children:o?l?`Disabling…`:`Enabling…`:d?l?`On motion: on`:`On motion: off`:`On motion: …`})]})}n();function Q({deviceId:e,deviceType:t,features:n}){let i=W(),a=Or(t)?.HeroCard??dn,o=b(i.trpcClient,e),s=v(o?.state.deviceStatus),[l,d]=c(!1),f=s!==void 0&&s.online===!1,p=f?s.lastChangedAt:null;return r(`div`,{className:`flex h-full w-full flex-col items-stretch gap-3 p-3 sm:p-4`,children:[f?u(`div`,{className:`flex justify-center`,children:u(nn,{lastChangedAt:p})}):null,u(a,{trpc:i.trpcClient,deviceId:e,features:n}),u(`div`,{className:`flex justify-center`,children:u(ra,{dev:o,busy:l,setBusy:d})})]})}function ia({deviceId:e,features:t}){return u(`div`,{className:`flex h-full w-full flex-col items-stretch gap-3 p-3 sm:p-4`,children:u(Er,{trpc:W().trpcClient,deviceId:e,features:t})})}function aa({deviceId:e,features:t}){return u(`div`,{className:`flex h-full w-full flex-col items-stretch p-3 sm:p-4`,children:u(dn,{trpc:W().trpcClient,deviceId:e,features:t})})}function oa(e){if(!e)return null;let t=e.channel;return typeof t!=`number`||!Number.isInteger(t)||t<0?null:t}function sa(e){if(!e)return null;let t=oa(e.data);return t===null?e.eventType:`Button ${String(t)} · ${e.eventType}`}var ca=1e3,la=60*ca,ua=60*la,da=24*ua;function fa(e,t){if(e==null||e<=0)return`—`;let n=t-e;return n<ca?`just now`:n<la?`${String(Math.floor(n/ca))}s ago`:n<ua?`${String(Math.floor(n/la))}m ago`:n<da?`${String(Math.floor(n/ua))}h ago`:`${String(Math.floor(n/da))}d ago`}n();var pa=1500,ma=15e3,ha=1e3;function ga({deviceId:e}){let n=b(W().trpcClient,e)?.state.eventEmitter,i=v(n);d(()=>{if(!n)return;n.refresh();let e=setInterval(()=>{n.refresh()},ma);return()=>{clearInterval(e)}},[n]);let a=i?.lastEvent??null,o=a?.seq??null,s=t(null),[l,f]=c(!1);d(()=>{if(o===null)return;let e=s.current;if(s.current=o,e===null||e===o)return;f(!0);let t=setTimeout(()=>{f(!1)},pa);return()=>{clearTimeout(t)}},[o]);let[p,m]=c(()=>Date.now());d(()=>{let e=setInterval(()=>{m(Date.now())},ha);return()=>{clearInterval(e)}},[]);let h=sa(a),g=i?.eventTypes??[],_=i?.eventCountSinceStart??0,y=i!==void 0,x=oa(a?.data);return r(`div`,{className:`flex h-full w-full flex-col items-center justify-center gap-3 p-4`,children:[u(`div`,{"data-testid":`event-emitter-indicator`,"data-flashing":String(l),className:`flex h-24 w-24 items-center justify-center rounded-full border-2 transition-all ${l?`border-primary bg-primary/20 text-primary shadow-lg shadow-primary/30 scale-105`:`border-border bg-surface text-foreground-subtle`}`,"aria-live":`polite`,title:h??`No press recorded`,children:u(l?F:te,{className:`h-10 w-10`})}),r(`div`,{className:`text-center`,children:[x!==null&&u(`div`,{className:`text-xs font-semibold uppercase tracking-wide text-primary`,children:`Button ${String(x)}`}),u(`div`,{"data-testid":`event-emitter-headline`,className:`text-sm font-semibold ${h?`text-foreground`:`text-foreground-subtle`}`,children:h??(y?`No press recorded`:`Awaiting state…`)}),u(`div`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:a?fa(a.timestamp,p):`Waiting for the first event`})]}),g.length>0&&u(`div`,{className:`flex max-w-full flex-wrap justify-center gap-1`,children:g.map(e=>u(`span`,{"data-testid":`event-emitter-chip`,className:`rounded-full border px-2 py-0.5 text-[10px] font-medium ${e===a?.eventType?`border-primary bg-primary/15 text-primary`:`border-border bg-surface text-foreground-subtle`}`,children:e},e))}),u(`div`,{className:`text-[10px] text-foreground-subtle`,children:`${String(_)} ${_===1?`event`:`events`} since start`})]})}function _a({deviceName:e,deviceType:t,provider:n,isOnline:i,features:a}){return r(`div`,{className:`flex h-full w-full flex-col items-center justify-center gap-3 rounded-lg border border-dashed border-border bg-surface p-6 text-center`,children:[u(Ir,{type:n,size:`lg`}),r(`div`,{children:[u(`div`,{className:`text-sm font-semibold text-foreground`,children:e}),u(`div`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wider mt-0.5`,children:t})]}),r(`div`,{className:`flex items-center gap-2 flex-wrap justify-center`,children:[u(Ot,{status:i?`online`:`offline`}),a.length>0&&u(Rr,{capabilities:a})]}),u(`div`,{className:`text-[10px] text-foreground-subtle italic max-w-xs mt-1`,children:`No live view for this device type. Use the Config tab or the shortcut row to interact.`})]})}n();function va({deviceId:e}){let t=s(),n=Ar({deviceId:e},{refetchInterval:1e4,retry:!1}),a=st({onSuccess:()=>{t.invalidateQueries({queryKey:[[`deviceDiscovery`,`listDiscovered`]]}),t.invalidateQueries({queryKey:[[`deviceDiscovery`,`getStatus`]]})}}),o=i(()=>ya(n.data??[]),[n.data]);return r(`div`,{className:`flex h-full w-full flex-col gap-3 p-3 sm:p-4`,children:[r(`div`,{className:`flex flex-wrap items-stretch gap-2 sm:gap-3`,children:[u(ba,{label:`Discovered`,value:o.total,icon:u(O,{className:`h-3.5 w-3.5`})}),u(ba,{label:`Adopted`,value:o.adopted,accent:`success`}),u(ba,{label:`Available`,value:o.available,accent:o.available>0?`primary`:void 0}),r(`button`,{type:`button`,onClick:()=>{a.mutateAsync({deviceId:e}).catch(()=>{})},disabled:a.isPending,className:`inline-flex items-center justify-center gap-1.5 rounded-lg border border-border px-3 py-2 text-xs font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors disabled:opacity-50 self-stretch shrink-0`,children:[a.isPending?u(B,{className:`h-3.5 w-3.5 animate-spin`}):u(me,{className:`h-3.5 w-3.5`}),u(`span`,{className:`hidden sm:inline`,children:`Discover`})]})]}),r(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-foreground-subtle border-t border-border-subtle pt-2`,children:[u(xa,{icon:u(U,{className:`h-3 w-3 text-emerald-500`}),label:`${o.online} online`}),u(xa,{icon:u(g,{className:`h-3 w-3 text-amber-500`}),label:`${o.sleeping} sleeping`}),u(xa,{icon:u(ee,{className:`h-3 w-3 text-destructive`}),label:`${o.offline} offline`}),o.unknown>0?u(xa,{icon:u(G,{className:`h-3 w-3 text-foreground-subtle`}),label:`${o.unknown} unknown`}):null]})]})}function ya(e){let t={total:e.length,adopted:0,available:0,online:0,sleeping:0,offline:0,unknown:0};for(let n of e)n.alreadyAdopted?t.adopted+=1:t.available+=1,t[n.status]+=1;return t}function ba({label:e,value:t,icon:n,accent:i}){return r(`div`,{className:`flex flex-1 basis-[140px] min-w-0 flex-col gap-1 rounded-lg border px-2 py-1.5 sm:px-3 sm:py-2 ${i===`success`?`bg-emerald-500/10 border-emerald-500/30 text-emerald-500`:i===`primary`?`bg-primary/10 border-primary/30 text-primary`:`bg-surface-hover border-border text-foreground`}`,children:[r(`div`,{className:`flex items-center gap-1.5 text-[10px] uppercase tracking-wider opacity-70 truncate`,children:[n,u(`span`,{className:`truncate`,children:e})]}),u(`div`,{className:`text-xl sm:text-2xl font-semibold tabular-nums leading-none`,children:t})]})}function xa({icon:e,label:t}){return r(`span`,{className:`inline-flex items-center gap-1`,children:[e,u(`span`,{children:t})]})}var Sa={[Y.Switch]:Q,[Y.Siren]:Q,[Y.Light]:Q,[Y.Sensor]:Q,[Y.Button]:Q,[Y.Hub]:va,[Y.Cover]:ia,[Y.Valve]:Q,[Y.Humidifier]:Q,[Y.WaterHeater]:Q,[Y.Container]:na,[Y.Lock]:Q,[Y.Fan]:Q,[Y.Thermostat]:Q,[Y.Climate]:Q,[Y.MediaPlayer]:Q,[Y.Control]:Q,[Y.AlarmPanel]:Q,[Y.EventEmitter]:ga,[Y.Notifier]:aa,[Y.Script]:Q,[Y.Automation]:Q,[Y.Presence]:Q,[Y.Update]:Q,[Y.Vacuum]:Q,[Y.LawnMower]:Q,[Y.Weather]:Q,[Y.Image]:Q,[Y.PetFeeder]:Q};function Ca(e){return Sa[e]??_a}function wa(e){return u(Ca(e.deviceType),{...e})}function Ta(e){return $n(W().trpcClient,e)}n();function Ea(n){let[r,i]=c(`idle`),[a,o]=c(null),s=t(null),l=t(null),u=t(null),f=t(!0),p=ir(),m=En(),h=Jn(),g=e(()=>{if(s.current){try{s.current.close()}catch{}s.current=null}if(l.current){for(let e of l.current.getTracks())try{e.stop()}catch{}l.current=null}u.current=null},[]),_=e(async()=>{if(r===`idle`)return;i(`stopping`);let e=u.current;if(e&&n!==null)try{await Promise.race([h.mutateAsync({deviceId:n,sessionId:e}),new Promise((e,t)=>setTimeout(()=>t(Error(`server stopSession timeout`)),2e3))])}catch(e){console.warn(`[intercom] server stopSession failed (continuing teardown)`,e)}g(),f.current&&(i(`idle`),o(null))},[r,n,h,g]),v=e(async()=>{if(n===null||r!==`idle`&&r!==`error`)return;o(null);let e=null,t=null,a=null;try{i(`requesting-mic`),e=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),l.current=e,i(`starting`);let r=await p.mutateAsync({deviceId:n});a=r.sessionId,u.current=a,i(`connecting`),t=new RTCPeerConnection,s.current=t,t.oniceconnectionstatechange=()=>{if(!f.current)return;let e=t.iceConnectionState;e===`connected`||e===`completed`?i(`talking`):(e===`failed`||e===`closed`||e===`disconnected`)&&f.current&&(o(e===`failed`?`WebRTC connection failed`:null),_())};for(let n of e.getAudioTracks())t.addTrack(n,e);await t.setRemoteDescription({type:`offer`,sdp:r.sdpOffer});let c=await t.createAnswer();await t.setLocalDescription(c);let d=t.localDescription?.sdp??c.sdp??``;await m.mutateAsync({deviceId:n,sessionId:a,sdpAnswer:d})}catch(r){let c=r instanceof Error?r.message:String(r);if(console.warn(`[intercom] start failed`,r),t)try{t.close()}catch{}if(e)for(let t of e.getTracks())try{t.stop()}catch{}if(s.current=null,l.current=null,a!==null)try{await h.mutateAsync({deviceId:n,sessionId:a})}catch{}u.current=null,f.current&&(o(c),i(`error`))}},[n,r,p,m,h,_]);return d(()=>(f.current=!0,()=>{f.current=!1;let e=u.current;if(e!==null&&n!==null&&h.mutate({deviceId:n,sessionId:e}),s.current){try{s.current.close()}catch{}s.current=null}if(l.current){for(let e of l.current.getTracks())try{e.stop()}catch{}l.current=null}u.current=null}),[n]),{state:r,error:a,start:v,stop:_,isTalking:r===`talking`}}n();var Da=0;function $(){return++Da}function Oa(e){switch(e.type){case`system`:return`system`;case`device`:return`#${e.deviceId}`;case`provider`:return e.providerId;case`addon`:return e.addonId}}function ka(e){return[``,`Commands`,` help Show this help`,` examples Show usage examples for the current scope`,` context Show every available variable + full API surface`,` clear Clear terminal (also Ctrl+L)`,``,`Shortcuts`,` Enter Execute expression`,` Arrow Up/Down Navigate command history`,` Ctrl+L Clear terminal`,``,`Try: ${{system:` sm.summary() // fleet overview`,device:` device.state.battery.value?.sleeping // sync read`,provider:` devices.map(d => d.name)`,addon:` manifest.version`}[e.type]}`,``,`Top-level objects: sm (SystemMirror), DeviceType, Math, JSON, Date, …`]}function Aa(e){switch(e.type){case`device`:return[``,`── State (sync, zero round-trip) ─────────────────────────`,` device.state.battery.value`,` device.state.battery.value?.percentage`,` device.state.motion.value?.detected`,``,`── Actions (async, through wrapper chain) ────────────────`,` await device.snapshot.getSnapshot({})`,` await device.ptz.move({ direction: 'left', steps: 1 })`,` await device.switch.setState({ on: true })`,``,`── Wait for condition ───────────────────────────────────`,` await sm.waitForState(deviceId, 'battery', s => !s.sleeping, 30_000)`,``,`── Subscribe to changes ─────────────────────────────────`,` const off = device.state.battery.subscribe(s => console.log(s))`,``,`── Quick info ───────────────────────────────────────────`,` info.name device name`,` info.addonId owning addon`,` sm.dump(deviceId) full debug dump`];case`system`:return[``,`── Lookups ──────────────────────────────────────────────`,` sm.getDeviceById(8)`,` sm.getDeviceByName('Sala da pranzo')`,` sm.getDevicesByAddon('reolink')`,` sm.getDevicesByType(DeviceType.Camera)`,``,`── Filters (typed query) ────────────────────────────────`,` sm.query({ addonId: 'reolink', online: true })`,` sm.query({ caps: ['battery', 'snapshot'] })`,` sm.query({ name: /^Cam-/ })`,``,`── Cross-device ─────────────────────────────────────────`,` sm.whereState('battery', s => s.percentage < 20).length`,` sm.mapState('battery', s => s.percentage)`,` sm.countByCap('snapshot')`,``,`── Batch action ─────────────────────────────────────────`,` await sm.invokeCap('snapshot', 'getSnapshot', {}, { parallelism: 4 })`,``,`── Listen ───────────────────────────────────────────────`,` sm.listenCap('motion', (id, s) => console.log(id, s))`,` sm.onDeviceAdded((id, info) => console.log('+', info.name))`,``,`── Diagnostics ──────────────────────────────────────────`,` sm.summary()`,` sm.dump(8)`];case`provider`:return[``,` devices.map(d => d.name)`,` await getIntegration()`,` sm.getDevicesByAddon('<this-addon-id>').length`];case`addon`:return[``,` manifest.name`,` manifest.version`,` declaration`]}}function ja(e){let t=[``,`Scope: ${e.type}`,``];switch(e.type){case`system`:return[...t,`Primary API — sm (SystemMirror):`,` sm.getDeviceById(id) DeviceProxy | null (sync)`,` sm.getDeviceByName(name) DeviceProxy | null`,` sm.getDeviceByStableId(sid) DeviceProxy | null`,` sm.getAllDevices() readonly DeviceProxy[]`,` sm.getDeviceInfo(id) DeviceInfo | null`,` sm.summary() fleet stats`,``,`Filters — sm.query({...}):`,` sm.query({ addonId: 'reolink', online: true })`,` sm.query({ caps: ['battery', 'snapshot'] }) // ALL caps required`,` sm.query({ anyCap: ['ptz', 'motion'] }) // ANY cap`,` sm.query({ name: { contains: 'sala' } }) // case-insensitive`,` sm.query({ name: /^Cam-\\d+$/ })`,` sm.query({ type: DeviceType.Camera })`,` sm.query({ parentDeviceId: 8 }) // accessories of cam 8`,` sm.query({ where: (info, dev) => dev.state.battery.value?.sleeping })`,``,`State queries:`,` sm.whereState('battery', s => s.percentage < 20)`,` sm.mapState('battery', s => s.percentage)`,` sm.findState('motion', s => s.detected)`,` sm.countByCap('snapshot')`,``,`Listeners (return unsubscribe fn):`,` sm.listen((id, cap, slice) => …) // every state change`,` sm.listenCap('motion', (id, slice) => …)`,` sm.listenDevice(8, (id, cap, slice) => …)`,` sm.onDeviceAdded((id, info) => …)`,` sm.onDeviceRemoved((id, info) => …)`,``,`Wait primitives:`,` await sm.waitForState(8, 'battery', s => !s.sleeping, 30_000)`,` await sm.waitForDevice(99, 30_000)`,``,`Batch:`,` await sm.invokeCap('snapshot', 'getSnapshot', {}, { parallelism: 4 })`,` await sm.forEachCap('reboot', d => d.reboot.reboot({}))`,``,`Diagnostics:`,` sm.dump(8) debug dump (one device)`,` sm.dump() full fleet dump`,` sm.summary() breakdown by cap/addon/type`,``,`Legacy: deviceRegistry, addonRegistry, eventBus, devices(), addons()`];case`device`:return[...t,`Pre-bound variables:`,` device DeviceProxy for this device (sync state + async methods)`,` deviceId number`,` info DeviceInfo metadata (name, addonId, type, online, …)`,` sm SystemMirror (full cluster view)`,` rawDevice legacy IDevice instance (escape hatch)`,``,`Reactive state (sync, zero round-trip):`,` device.state.battery.value BatteryStatus | undefined`,` device.state.battery.value?.sleeping`,` device.state.battery.value?.percentage`,` device.state.motion.value?.detected`,` device.state.switch.value?.on`,` device.state.brightness.value?.percentage`,` device.state.doorbell.value?.lastPressedAt`,``,`Cap actions (async, through wrapper chain):`,` await device.snapshot.getSnapshot({})`,` await device.snapshot.getSnapshot({ streamId: 'high' })`,` await device.ptz.move({ direction: 'left', steps: 1 })`,` await device.ptz.goToPreset({ presetId: 'home' })`,` await device.switch.setState({ on: true })`,` await device.brightness.setBrightness({ percentage: 60 })`,` await device.reboot.reboot({})`,``,`Subscribe to slice changes:`,` const off = device.state.battery.subscribe(s => console.log(s))`,` // off() to unsubscribe`,``,`Wait for a state condition:`,` await sm.waitForState(deviceId, 'battery', s => !s.sleeping, 30_000)`,``,`Diagnostics:`,` info.name device name`,` info.addonId which addon owns it`,` info.online transport health`,` sm.dump(deviceId) full debug dump (binding + state + info)`];case`provider`:return[...t,`Pre-bound variables:`,` devices Devices belonging to this provider (raw IDevice[])`,` getIntegration() Integration metadata`,``,`For typed device access use the SystemMirror:`,` await getSystemMirror()`,` sm.getDevicesByAddon('this-addon-id')`];case`addon`:return[...t,`Pre-bound variables:`,` manifest { name, version, ... }`,` declaration addon declaration`,` source addon source location`,``,`Examples:`,` manifest.name`,` manifest.version`]}}function Ma({scope:n,greeting:i,className:a}){let o=W(),[s,f]=c(()=>{let e=[];return i&&e.push({id:$(),kind:`info`,text:i}),e.push({id:$(),kind:`info`,text:`scope: ${Oa(n)} — type help or context for available commands`}),e}),[p,m]=c(``),[h,g]=c([]),[_,v]=c(-1),y=t(null),b=t(null);d(()=>{let e=b.current;e&&(e.scrollTop=e.scrollHeight)},[s]);let x=e(()=>{y.current?.focus()},[]),S=l({mutationFn:e=>o.trpcClient.repl.execute.mutate({code:e,scope:n}),onSuccess:e=>{let t=e??{},n=typeof t.output==`string`?t.output:e==null?`undefined`:typeof e==`string`?e:JSON.stringify(e,null,2),r=t.type===`error`;f(e=>[...e,{id:$(),kind:r?`error`:`result`,text:n}])},onError:e=>{let t=e instanceof Error?e.message:String(e);f(e=>[...e,{id:$(),kind:`error`,text:t}])}});function C(e){let t=e.trim();if(t){if(t===`clear`){f([{id:$(),kind:`info`,text:`scope: ${Oa(n)}`}]),m(``);return}if(t===`help`){f(e=>[...e,{id:$(),kind:`input`,text:`> ${t}`},...ka(n).map(e=>({id:$(),kind:`info`,text:e}))]),m(``);return}if(t===`context`){f(e=>[...e,{id:$(),kind:`input`,text:`> ${t}`},...ja(n).map(e=>({id:$(),kind:`info`,text:e}))]),m(``);return}if(t===`examples`){f(e=>[...e,{id:$(),kind:`input`,text:`> ${t}`},...Aa(n).map(e=>({id:$(),kind:`info`,text:e}))]),m(``);return}g(e=>[...e,t]),v(-1),f(e=>[...e,{id:$(),kind:`input`,text:`> ${t}`}]),m(``),S.mutate(t)}}function w(e){if(e.key===`Enter`){e.preventDefault(),C(p);return}if(e.key===`ArrowUp`){if(e.preventDefault(),h.length===0)return;let t=_===-1?h.length-1:Math.max(0,_-1);v(t),m(h[t]??``);return}if(e.key===`ArrowDown`){if(e.preventDefault(),_===-1)return;let t=_+1;t>=h.length?(v(-1),m(``)):(v(t),m(h[t]??``));return}e.ctrlKey&&e.key===`l`&&(e.preventDefault(),f([{id:$(),kind:`info`,text:`scope: ${Oa(n)}`}]))}let T={input:`text-zinc-300`,result:`text-emerald-300`,error:`text-red-300`,info:`text-zinc-400`};return r(`div`,{className:`flex flex-col bg-[#0c0a09] rounded-lg border border-border overflow-hidden font-mono text-xs ${a??``}`,onClick:x,children:[r(`div`,{ref:b,className:`flex-1 overflow-y-auto p-3 space-y-1 min-h-[120px]`,children:[s.map(e=>u(`pre`,{className:`whitespace-pre-wrap break-words leading-relaxed ${T[e.kind]}`,children:e.text},e.id)),S.isPending&&u(`span`,{className:`text-zinc-500 animate-pulse`,children:`…thinking`})]}),r(`div`,{className:`flex items-center gap-2 border-t border-zinc-800 px-3 py-2 bg-[#0c0a09]`,children:[u(`span`,{className:`text-emerald-400 flex-shrink-0 select-none font-bold`,children:`>`}),u(`input`,{ref:y,value:p,onChange:e=>m(e.target.value),onKeyDown:w,disabled:S.isPending,placeholder:`device.state.battery.value`,autoFocus:!0,className:`flex-1 bg-transparent text-zinc-100 placeholder:text-zinc-600 focus:outline-none caret-emerald-400 disabled:opacity-50`,spellCheck:!1,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`off`})]})]})}function Na(e,t){return e===null?null:{playbackUrl:e.url,...e.format===void 0?{}:{playbackFormat:e.format},playbackAuthToken:t,...e.label===void 0?{}:{playbackLabel:e.label}}}n();function Pa({deviceId:e,intercomAvailable:t=!1}){let n=W(),r=typeof window<`u`?R():``,a=Number.isFinite(e),s=Ta(a?e:null),c=Wi(a?[e]:[]),l=i(()=>{if(!a)return;let e=[];for(let t of c.rows){let n=rn(t);n!==null&&e.push(n)}return e},[a,c.rows]),{streams:d,pipelineMetrics:f,createSession:p,sendAnswer:m,handleOffer:g,getIceServers:_,addIceCandidate:v,getIceCandidates:y,closeSession:b,getSessionState:x,applyDownlinkProbe:S}=jr(n.trpcClient,a?e:null),C=h(a?e:null,{width:za}),w=Ea(a&&t?e:null),T=w.state===`requesting-mic`||w.state===`starting`||w.state===`connecting`||w.state===`stopping`,E=w.isTalking||T,D=()=>{w.state===`idle`||w.state===`error`?w.start():w.state!==`stopping`&&w.stop()},O=ce(),k=xt(),A=typeof window<`u`?window.localStorage.getItem(`camstack_admin_token`):null,j=Na(k.request,A),M=O.length>0?u(o,{children:O.map(e=>u(`div`,{className:`absolute inset-0`,children:e.node},e.id))}):null;return u(Tr,{serverUrl:r,createSession:p,sendAnswer:m,handleOffer:g,getIceServers:_,addIceCandidate:v,getIceCandidates:y,closeSession:b,getSessionState:x,applyDownlinkProbe:S,...j===null?{}:{...j,onExitPlayback:()=>k.clear()},streams:d,pipelineMetrics:f,phase:s.phase,detections:s,...l===void 0?{}:{stationaryObjects:l},defaultShowDetections:!0,defaultShowMotion:!0,showPlayStop:!0,snapshotSrc:C.src,...C.src?{posterUrl:C.src}:{},snapshotLoading:C.loading,onRefreshSnapshot:C.refresh,intercomAvailable:t,intercomShown:E,onIntercomToggle:D,extraOverlay:M,chromeless:!0,className:`h-full`})}function Fa({deviceId:e,containerDeviceId:t}){return Number.isFinite(e)?u(`div`,{className:`flex flex-col h-full`,children:u(Ut,{...t===void 0?{deviceId:e}:{containerDeviceId:t},limit:50,maxHeight:`max-h-full`,showScope:!1,showFilters:!1})}):r(`div`,{className:`flex items-center justify-center h-full text-[11px] text-foreground-subtle italic`,children:[`Device #`,e,` not loaded.`]})}function Ia({deviceId:e}){if(!Number.isFinite(e))return r(`div`,{className:`flex items-center justify-center h-full text-[11px] text-foreground-subtle italic`,children:[`Device #`,e,` not loaded.`]});let t=[`CamStack REPL — device #${e}`,``,` device.state.battery.value sync state read`,` await device.snapshot.getSnapshot({}) cap action`,``,` type 'examples' for more, 'context' for the full API`].join(`
2
- `);return u(Ma,{scope:{type:`device`,deviceId:e},greeting:t,className:`h-full border-0 rounded-none`})}function La({deviceId:e}){return Number.isFinite(e)?u(`div`,{className:`flex flex-col h-full overflow-y-auto`,children:u(wr,{deviceId:e,limit:50,maxHeight:`max-h-full`})}):r(`div`,{className:`flex items-center justify-center h-full text-[11px] text-foreground-subtle italic`,children:[`Device #`,e,` not loaded.`]})}function Ra({deviceId:e}){return Number.isFinite(e)?u(`div`,{className:`flex flex-col h-full overflow-y-auto`,children:u(lt,{deviceId:e,limit:50,maxHeight:`max-h-full`})}):r(`div`,{className:`flex items-center justify-center h-full text-[11px] text-foreground-subtle italic`,children:[`Device #`,e,` not loaded.`]})}var za=960;function Ba(e){return new Set(e.filter(e=>{let t=e.nativeAddonId?.trim()??``;return t!==``&&t!==`composer`}).map(e=>e.capName))}function Va(e){return e.kind===`known`?null:e}function Ha(e,t){return e.composable.kind===`known`?e.composable.value.has(t)?{kind:`present`,mode:`add`}:{kind:`absent`}:e.composable}function Ua(e){if(e.deviceType!==Y.Camera)return{kind:`absent`};switch(e.cameraSensors){case`pending`:return{kind:`pending`};case`unknown`:return{kind:`unknown`,reason:`camera sensors could not be checked`};case`absent`:return{kind:`absent`};case`present`:return{kind:`present`,mode:`add`}}}function Wa(e,t){if(e===`motion`)return Ua(t);let n=Va(t.nativeCaps);if(n!==null)return n;let r=t.nativeCaps.kind===`known`?t.nativeCaps.value:new Set;switch(e){case`doorbell`:return r.has(`doorbell`)?{kind:`absent`}:Ha(t,`doorbell`);case`battery`:return r.has(`battery`)?{kind:`present`,mode:`replace`}:Ha(t,`battery`);case`consumables`:return r.has(`consumables`)?{kind:`absent`}:Ha(t,`consumables`)}}function Ga({onAdvanced:e}){let{t}=Z();return e===void 0?null:u(`button`,{type:`button`,className:`rounded text-left text-[11px] text-primary hover:underline focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary`,onClick:e,children:t(`customize.advancedLink`)})}function Ka(e){if(e.status===`pending`)return{kind:`pending`};if(e.status===`error`)return{kind:`unknown`,reason:e.error?.message??`the request failed`};let t=e.data;if(t===void 0)return{kind:`pending`};if(t.state===`not-loaded`)return{kind:`not-loaded`,reason:t.reason};if(t.view===null)return{kind:`none`};let n=Re(t.view.block);return n===null?{kind:`unknown`,reason:`block ${t.view.block.id} is not a composition`}:{kind:`present`,view:t.view,composition:n}}function qa(e){return e.kind===`present`?e.composition:null}function Ja(e,t){let{hidden:n,...r}=e??{},i=t?{...r,hidden:!0}:r;return Object.keys(i).length===0?null:i}function Ya(e){return typeof e.linkDeviceId==`number`}var Xa=new Set(Object.values(q));function Za(e){return Xa.has(e)}var Qa={[Y.Switch]:[q.Siren,q.Floodlight,q.Spotlight,q.PirSensor,q.Chime,q.Autotrack,q.Nightvision,q.PrivacyMask,q.BinaryHelper],[Y.Light]:[q.Floodlight,q.Spotlight,q.Nightvision],[Y.Siren]:[q.Siren],[Y.Button]:[q.Doorbell],[Y.Sensor]:[q.MotionSensor,q.ContactSensor,q.LeakSensor,q.SmokeSensor,q.COSensor,q.GasSensor,q.TamperSensor,q.VibrationSensor,q.ConnectivitySensor,q.SoundSensor,q.BinarySensor,q.TemperatureSensor,q.HumiditySensor,q.AmbientLightSensor,q.PressureSensor,q.WindSensor,q.RainSensor,q.UvSensor,q.SolarRadiationSensor,q.SoilMoistureSensor,q.PowerSensor,q.EnergySensor,q.VoltageSensor,q.CurrentSensor,q.AirQualitySensor,q.BatterySensor,q.NumericSensor,q.EnumSensor,q.DateTimeSensor,q.GenericSensor],[Y.Control]:[q.NumericControl,q.SelectControl,q.TextControl,q.DateTimeControl],[Y.Notifier]:[q.MobilePushNotifier,q.MessagingNotifier,q.EmailNotifier,q.GenericNotifier]};function $a(e){for(let t of Object.values(Y))if(t===e)return!0;return!1}function eo(e){return $a(e)?Qa[e]??[]:[]}function to(e,t){let n=eo(t);return e==null||e===``||n.includes(e)?n:[...n,e]}n();function no({device:e}){let{t}=Z(),n=s(),[i,a]=c(null),o=()=>a(null),l={onSuccess:()=>{o(),n.invalidateQueries({queryKey:[[`deviceManager`]]})},onError:e=>a(e.message)},d=yt(),f=Vn(),m=e.display?.hidden===!0;return r(`section`,{"aria-label":t(`customize.identity.title`),className:`${w} ${p}`,children:[r(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4`,children:[u(Ur,{deviceId:e.id,initialName:e.name,label:t(`customize.identity.name`),layout:`stacked`,onError:a,onSaved:o,onCancel:o}),u(Lr,{deviceId:e.id,initialLocation:e.location,label:t(`customize.identity.room`),layout:`stacked`,onError:a,onSaved:o,onCancel:o}),u(Wr,{label:t(`customize.identity.hidden`),layout:`stacked`,value:u(an,{"aria-label":t(`deviceDisplay.hideFromLists`),checked:m,disabled:f.isPending,onChange:t=>f.mutate({deviceId:e.id,display:Ja(e.display,t.target.checked)},l)})}),u(Wr,{label:t(`customize.identity.role`),layout:`stacked`,value:Ya(e)?u(`span`,{children:ro(e.role,t(`customize.identity.noRole`))}):u(ht,{"aria-label":t(`customize.identity.role`),value:e.role??``,disabled:d.isPending,options:[{value:``,label:t(`customize.identity.noRole`)},...to(e.role,e.type).map(e=>({value:e,label:ro(e,t(`customize.identity.noRole`))}))],onChange:t=>d.mutate({deviceId:e.id,role:t.target.value===``?null:t.target.value},l)})})]}),i!==null&&u(`p`,{role:`alert`,className:`mt-2 text-xs text-danger break-words`,children:i})]})}function ro(e,t){return e==null||e===``?t:Za(e)?gn(e).label:e}function io(e,t){if(e.kind!==`known`||typeof t!=`string`||t.length===0)return null;let n=pr(e.value,t),r=new Map(e.value.map(e=>[e.id,e])),i=new Map;for(let e of n){let t=r.get(e)?.parentDeviceId,n=t==null?void 0:r.get(t);n!==void 0&&n.type===`container`&&i.set(e,n.name)}return{location:t,ids:n,containers:i}}function ao(e,t,n){return tr(e,t?.ids??new Set,n)}function oo(e,t){return e?.containers.get(t)??null}function so(e,t){return e===null||t.length===0?e:{...e,ids:new Set([...e.ids].filter(e=>!t.includes(e)))}}function co(e,t,n){return e.kind===`known`?ao(e.value,t,n).suggested.length:0}function lo(e,t){let n=[t,e.detail].filter(e=>e!==null&&e!==``);return n.length===0?null:n.join(` · `)}function uo({location:e,devices:t,action:n,onPick:i,onPickAll:a}){let{t:o}=Z();if(t.length===0)return null;let s=o(`customize.suggest.heading`,{location:e});return r(`section`,{"aria-label":s,className:`flex flex-col gap-1`,children:[r(`div`,{className:`flex min-h-7 items-center gap-2`,children:[u(`h3`,{className:`${N} min-w-0 flex-1`,children:s}),a!==void 0&&t.length>1&&u(X,{variant:`ghost`,size:`sm`,onClick:a,children:o(`customize.suggest.addAll`,{count:t.length})})]}),u(`ul`,{className:`flex flex-col divide-y divide-border rounded-md border border-border`,children:t.map(e=>{let t=lo(e,e.container===null||e.name.includes(e.container)?null:o(`customize.suggest.in`,{container:e.container}));return r(`li`,{className:`${j} flex items-center gap-3`,children:[r(`div`,{className:`min-w-0 flex-1`,children:[u(`div`,{className:`text-xs text-foreground break-words`,children:e.name}),t!==null&&u(`div`,{className:`text-[11px] text-foreground-subtle break-words`,children:t})]}),u(X,{variant:`outline`,size:`sm`,"aria-label":o(n===`add`?`customize.suggest.addNamed`:`customize.suggest.useNamed`,{name:e.name}),onClick:()=>i(e.id),children:o(n===`add`?`customize.suggest.add`:`customize.suggest.use`)})]},e.id)})})]})}n();function fo(e){return e===`pending`?`pending`:e===`error`?`failed`:`answered`}function po({excludeDeviceIds:e,room:t,onSelect:n}){let{t:a}=Z(),s=qn({projection:`slim`}),c=s.status===`success`?s.data:null,l=i(()=>{if(c===null)return[];let t=new Set(e);return ci(c).filter(e=>!t.has(e.id))},[c,e]),d=i(()=>new Map(l.map(e=>[e.id,e])),[l]),f=i(()=>ao(l,t,e=>e.id),[l,t]),p=i(()=>f.others.map(e=>({id:e.id,name:e.name,type:e.type,...e.location===null?{}:{location:e.location}})),[f.others]);if(s.status===`error`)return u(Dt,{title:a(`customize.picker.devicesFailed`),message:s.error?.message??``});let m=e=>{let t=d.get(e);t!==void 0&&n(t)};return r(o,{children:[t!==null&&u(uo,{location:t.location,devices:f.suggested.map(e=>({id:e.id,name:e.name,container:oo(t,e.id),detail:e.type})),action:`use`,onPick:m}),p.length===0&&f.suggested.length>0?null:u(_n,{devices:p,listState:fo(s.status),value:[],onChange:e=>{let t=e.at(-1);t!==void 0&&m(t)},noun:`device`,emptyLabel:a(`customize.assign.none`),showAll:!0,testId:`customize-field-device-picker`})]})}function mo({open:e,title:t,targetKind:n,excludeDeviceIds:i,room:a=null,confirmLabel:s,extra:l,extraComplete:d=!0,onConfirm:f,onClose:p}){let{t:m}=Z(),[h,g]=c(null),[_,v]=c(null),y=()=>{g(null),v(null),p()};return u(Ht,{open:e,onOpenChange:e=>e?void 0:y(),children:r(ut,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"aria-label":t,children:[u(ot,{children:u(Rn,{children:t})}),u(pt,{className:`flex flex-col gap-3 p-2 sm:p-4`,children:e&&r(o,{children:[r(`section`,{"aria-label":m(`customize.assign.stepDevice`),className:`flex flex-col gap-1`,children:[u(`h3`,{className:`text-[10px] sm:text-[11px] font-semibold text-foreground uppercase tracking-wider`,children:m(`customize.assign.stepDevice`)}),h===null?u(po,{excludeDeviceIds:i,room:a,onSelect:g}):r(`p`,{className:`flex items-center gap-2 text-xs text-foreground`,children:[h.name,u(X,{variant:`ghost`,size:`sm`,onClick:()=>{g(null),v(null)},children:m(`customize.assign.change`)})]})]}),h!==null&&r(`section`,{"aria-label":m(`customize.assign.stepField`),className:`flex flex-col gap-1`,children:[u(`h3`,{className:`text-[10px] sm:text-[11px] font-semibold text-foreground uppercase tracking-wider`,children:m(`customize.assign.stepField`)}),u(oi,{device:h,targetKind:n,selected:_===null?null:{cap:_.cap,path:_.path},onPick:v,onBack:()=>{g(null),v(null)}})]}),h!==null&&l!==void 0&&r(`section`,{"aria-label":m(`customize.assign.stepDetails`),className:`flex flex-col gap-1`,children:[u(`h3`,{className:`text-[10px] sm:text-[11px] font-semibold text-foreground uppercase tracking-wider`,children:m(`customize.assign.stepDetails`)}),l]})]})}),r(Hn,{children:[u(X,{variant:`ghost`,onClick:y,children:m(`customize.assign.cancel`)}),u(X,{disabled:_===null||!d,onClick:()=>{_!==null&&(f(_),g(null),v(null))},children:s})]})]})})}function ho(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function go(e,t){let n=bi(e,t);return n===void 0?{kind:`absent`}:{kind:`value`,value:n}}function _o(e,t,n){return ho(t)?go(t,n):e.status===`error`?{kind:`unknown`,reason:e.error?.message??`the value could not be read`}:e.status===`pending`||e.data===void 0?{kind:`pending`}:e.data===null?{kind:`absent`}:go(e.data,n)}function vo(e,t,n){let r=e?`active`:`muted`;return t.cap===`contact`&&t.path===`entryOpen`?{text:e?n.open:n.closed,tone:r}:Te[t.cap]===t.path?{text:e?n.active:n.inactive,tone:r}:{text:String(e),tone:`normal`}}function yo(e,t,n){switch(e.kind){case`pending`:return{text:`…`,tone:`muted`};case`unknown`:return{text:`?`,title:e.reason,tone:`warning`};case`absent`:return{text:`—`,tone:`muted`};case`value`:{let r=e.value;return r===null?{text:`—`,tone:`muted`}:typeof r==`boolean`?vo(r,t,n):typeof r==`number`?{text:t.path===`percentage`?`${Math.round(r)} %`:String(r),tone:`normal`}:typeof r==`string`?{text:r,tone:`normal`}:{text:JSON.stringify(r),tone:`normal`}}}}var bo=0;function xo(e){let t=W(),n=gt({deviceId:e?.deviceId??bo,capName:e?.cap??``},{enabled:e!==null}),r=ur(t.trpcClient,e?.deviceId??null,e?.cap??``);return e===null?{kind:`absent`}:_o({status:n.status,data:n.data,error:n.error===null||n.error===void 0?null:{message:n.error.message}},r,e.path)}var So={muted:`text-foreground-subtle`,active:`text-success`,normal:`text-foreground`,warning:`text-warning`};function Co({target:e}){let{t}=Z(),n=xo(e);return e===null?null:u(wo,{display:yo(n,e,{active:t(`customize.assign.value.active`),inactive:t(`customize.assign.value.inactive`),open:t(`customize.assign.value.open`),closed:t(`customize.assign.value.closed`)})})}function wo({display:e}){return u(`span`,{className:`text-xs ${So[e.tone]}`,title:e.title,children:e.text})}function To({name:e,detail:t,meta:n,value:i,shown:a,problem:o,onRemove:s,removeLabel:c,busy:l=!1}){return r(`li`,{className:`${j} grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 gap-y-1 sm:grid-cols-[minmax(0,2fr)_minmax(0,1fr)_minmax(0,1fr)_1.75rem]`,children:[r(`div`,{className:`min-w-0`,children:[u(`div`,{className:`text-xs text-foreground break-words`,children:e}),t!==null&&u(`div`,{className:`text-[11px] text-foreground-subtle break-words`,children:t}),o!==void 0&&u(`div`,{role:`alert`,className:`text-[11px] text-warning break-words`,children:o})]}),u(`div`,{className:`row-start-2 col-start-1 text-[11px] text-foreground-subtle empty:hidden sm:row-start-auto sm:col-start-auto sm:empty:block`,children:n}),u(`div`,{className:`row-start-3 col-start-1 empty:hidden sm:row-start-auto sm:col-start-auto sm:empty:block`,children:a===void 0?u(Co,{target:i}):a!==null&&u(wo,{display:a})}),u(`div`,{className:`row-start-1 col-start-2 flex justify-end sm:row-start-auto sm:col-start-auto`,children:s!==void 0&&u(Qt,{icon:ie,variant:`ghost`,size:`sm`,"aria-label":c,disabled:l,onClick:s})})]})}function Eo({id:e,...t}){return u(qt,{headingId:`customize-${e}`,...t})}function Do({id:e,icon:t,title:n,headerControl:i,addLabel:a,onAdd:s,addDisabled:c=!1,notices:l,suggestion:d,children:f}){let{t:p}=Z(),m=s!==void 0&&a!==void 0;return r(Eo,{id:e,icon:t,title:n,actions:r(o,{children:[i,m&&!c&&d!==void 0&&d.count>0&&r(X,{variant:`ghost`,size:`sm`,onClick:d.onOpen,children:[u(I,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),p(`customize.suggest.hint`,{count:d.count,location:d.location})]}),m&&u(X,{variant:`outline`,size:`sm`,disabled:c,onClick:s,children:a})]}),children:[l!==void 0&&u(`div`,{className:`flex flex-col gap-1 px-3 pt-2 empty:hidden sm:px-4`,children:l}),u(`ul`,{className:`flex flex-col divide-y divide-border`,children:f})]})}function Oo({availability:e}){let{t}=Z();return e.kind===`pending`?u(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:t(`customize.assign.checking`)}):e.kind===`unknown`?u(`p`,{role:`alert`,className:`text-xs text-warning`,children:t(`customize.assign.unknown`,{reason:e.reason})}):null}function ko(e,t){if(e.status===`error`)return{kind:`unknown`,reason:e.error?.message??`the request failed`};let n=e.data;return e.status===`pending`||n===void 0?{kind:`pending`}:{kind:`known`,value:t(n)}}var Ao=[{id:`motion`,labelKey:`customize.assign.filters.motion`,caps:[`motion`]},{id:`contact`,labelKey:`customize.assign.filters.contact`,caps:[`contact`]},{id:`all`,labelKey:`customize.assign.filters.all`,caps:tt}];function jo(e,t){return t!==null&&e.includes(t)?t:tt.find(t=>e.includes(t))??null}function Mo(e,t){let n=[e,t].filter(e=>e!==null&&e!==``);return n.length===0?null:n.join(` · `)}function No(e,t){if(e.id===t.hostId||e.type===Y.Container||t.excludeCameras&&e.isCamera)return!1;let n=J({addonId:e.addonId,stableId:e.stableId});return!t.assigned.has(n)}function Po(e){return e.devices.flatMap(t=>{if(!No(t,e))return[];let n=e.capIndex.get(t.id)??[],r=jo(n,e.preferredCap);if(r===null)return[];let i=Te[r];return[{deviceId:t.id,ref:{addonId:t.addonId,stableId:t.stableId},name:t.name,detail:Mo(t.integration,t.location),meta:r,caps:n,value:i===void 0?null:{deviceId:t.id,cap:r,path:i}}]}).toSorted((e,t)=>e.name.localeCompare(t.name))}function Fo(e,t,n){let r=Dr(t);return e.filter(e=>{if(n!==null&&!e.caps.some(e=>n.caps.includes(e)))return!1;if(r.length===0)return!0;let t=ln({id:e.deviceId,name:e.name,...e.detail===null?{}:{detail:e.detail},...e.meta===null?{}:{type:e.meta}});return r.every(e=>t.includes(e))})}function Io(e){let t=e.find(e=>e.query.status===`error`);if(t!==void 0)return{kind:`unknown`,reason:t.query.error?.message??`the request failed`};if(e.some(e=>e.query.status!==`success`||e.query.data===void 0))return{kind:`pending`};let n=new Map;for(let t of e)for(let e of t.query.data??[])n.set(e,[...n.get(e)??[],t.cap]);return{kind:`known`,value:n}}function Lo(e,t){let n=kn.useQueries(n=>e.map(e=>n.deviceManager.listDeviceIdsByCaps({capNames:[e]},{enabled:t})));return Io(e.map((e,t)=>{let r=n[t];return{cap:e,query:r===void 0?{status:`pending`}:{status:r.status,data:r.data,error:r.error===null?null:{message:r.error.message}}}}))}n();function Ro(e,t){let n=Qn(e,t);return n.kind===`resolved`?n.integration.name:null}function zo(e){let t=qn({projection:`slim`},{enabled:e}),{data:n}=mn(void 0,{enabled:e}),r=t.error===null||t.error===void 0?null:t.error.message;return i(()=>ko({status:t.status,data:t.data,error:r===null?null:{message:r}},e=>e.map(e=>({id:e.id,name:e.name,addonId:e.addonId,stableId:e.stableId,type:e.type,location:e.location,isCamera:e.isCamera,integration:Ro(e,n),parentDeviceId:e.parentDeviceId,primaryChildEntityId:e.primaryChildEntityId??null,role:e.role??null}))),[t.status,t.data,r,n])}function Bo(e){let t=zo(e.enabled),n=Lo(tt,e.enabled);return t.kind===`unknown`?t:n.kind===`unknown`?n:t.kind===`pending`||n.kind===`pending`?{kind:`pending`}:{kind:`known`,value:Po({devices:t.value,capIndex:n.value,hostId:e.hostId,excludeCameras:e.excludeCameras,assigned:e.assigned,preferredCap:e.preferredCap})}}n();function Vo(e,t){let n=typeof e==`string`&&e.length>0,r=zo(t&&n);return i(()=>t?io(r,e):null,[t,r,e])}function Ho(){let{t:e}=Z(),t=$t();return(n,r)=>t({title:e(`customize.assign.removeConfirm.title`),message:r?`${e(`customize.assign.removeConfirm.message`,{what:n})} ${e(`customize.assign.removeConfirm.last`)}`:e(`customize.assign.removeConfirm.message`,{what:n}),confirmLabel:e(`customize.assign.removeConfirm.confirm`),variant:`danger`})}n();function Uo(e){return e===null?null:fi(e,`replace`)?`replace`:fi(e,`add`)?`add`:null}function Wo({device:e,handle:t,availability:n,onAdvanced:i}){let{t:a}=Z(),s=Ho(),[l,d]=c(!1),[f,p]=c(null),m=qa(t.state),h=Ti(m,`battery`),g=Uo(h),_=g===null?null:ai(h?.fields.percentage),v=zo(_!==null),y=so(Vo(e.location,n.kind===`present`&&h===null),[e.id]);if(n.kind===`absent`)return null;let b=n.kind===`present`?n.mode:null,x=t.state.kind===`none`||t.state.kind===`present`,S=_===null||v.kind!==`known`?null:v.value.find(e=>J({addonId:e.addonId,stableId:e.stableId})===J(_.source))??null,C=_===null?``:S?.name??J(_.source),w=async e=>{let n=await t.save(e);p(n.kind===`refused`?n.reason:null)},T=async()=>{if(m===null)return;let e=ti(m,`battery`);await s(a(`customize.battery.removeWhat`,{name:C}),e===null)&&await w(e)},E=b!==null&&x&&h===null&&!t.saving;return r(o,{children:[r(Do,{id:`battery`,icon:D,title:a(`customize.battery.title`),addLabel:a(b===`replace`?`customize.battery.replace`:`customize.battery.add`),onAdd:E?()=>d(!0):void 0,...y===null?{}:{suggestion:{count:y.ids.size,location:y.location,onOpen:()=>d(!0)}},notices:r(o,{children:[u(Oo,{availability:n}),_!==null&&v.kind===`unknown`&&u(`p`,{role:`alert`,className:`text-xs text-warning break-words`,children:a(`customize.assign.devicesUnreadable`,{reason:v.reason})}),f!==null&&u(`p`,{role:`alert`,className:`text-xs text-danger break-words`,children:f})]}),children:[b===`replace`&&x&&u(To,{name:a(`customize.battery.native`),detail:null,meta:a(h===null?`customize.assign.native`:`customize.battery.nativeReplaced`),value:h===null?{deviceId:e.id,cap:`battery`,path:`percentage`}:null,removeLabel:``}),h===null&&b===`add`&&x&&u(`li`,{className:`px-3 sm:px-4 py-1.5 sm:py-2 text-[11px] text-foreground-subtle`,children:a(`customize.assign.none`)}),_!==null&&u(To,{name:C,detail:`${_.cap}.${_.fieldPath}`,meta:a(g===`replace`?`customize.assign.replaces`:`customize.assign.adds`),value:S===null?null:{deviceId:S.id,cap:_.cap,path:_.fieldPath},problem:S===null&&v.kind===`known`?a(`customize.assign.missingKept`):void 0,onRemove:x?()=>void T():void 0,removeLabel:a(`customize.assign.removeNamed`,{name:C}),busy:t.saving}),h!==null&&_===null&&u(To,{name:a(`customize.battery.otherFormula`),detail:null,meta:u(Ga,{onAdvanced:i}),value:{deviceId:e.id,cap:`battery`,path:`percentage`},removeLabel:``})]}),u(mo,{open:l,title:a(b===`replace`?`customize.battery.replace`:`customize.battery.add`),targetKind:`number`,excludeDeviceIds:[e.id],room:y,confirmLabel:a(`customize.assign.add`),onConfirm:e=>{d(!1);let n=b===null?null:Si({percentage:{source:e.ref,cap:e.cap,fieldPath:e.path,kind:e.kind},mode:b});n===null?p(a(`customize.assign.pickUnusable`)):w(ii(m,t.target,n))},onClose:()=>d(!1)})]})}n();function Go(e,t){let n=e.source;if(n===null||t.kind!==`known`)return null;let r=J(n.source);return t.value.find(e=>J({addonId:e.addonId,stableId:e.stableId})===r)??null}function Ko(e){let t=typeof e==`number`?e:typeof e==`string`?Number(e):NaN;return Number.isFinite(t)?t:null}function qo({device:e,handle:t,availability:n,onAdvanced:i}){let{t:a}=Z(),s=Ho(),[l,d]=c(!1),[f,p]=c(``),[m,h]=c(`percent`),[g,_]=c(null),v=qa(t.state),y=Ti(v,`consumables`),b=ui(y),x=zo(b.some(e=>e.source!==null)),C=b.flatMap(e=>{let t=Go(e,x);return t===null?[]:[t.id]}),w=so(Vo(e.location,n.kind===`present`),[e.id,...C]);if(n.kind===`absent`)return null;let T=t.state.kind===`none`||t.state.kind===`present`,E=n.kind===`present`&&T&&!t.saving,D=di(f),O=b.find(e=>e.key===D)??null,k=O!==null,A=f.trim()!==``&&D===``,j=async e=>{let n=await t.save(e);_(n.kind===`refused`?n.reason:null)},M=()=>{d(!1),p(``),h(`percent`)},N=async e=>{if(y===null||v===null)return;let n=Ci(y,e.key),r=n===null?ti(v,`consumables`):ii(v,t.target,n);await s(a(`customize.consumables.removeWhat`,{name:e.label}),r===null)&&await j(r)},P=r(`div`,{className:`flex flex-wrap items-end gap-2`,children:[r(`label`,{className:`flex w-full flex-col gap-1 text-[11px] text-foreground-subtle sm:w-56`,children:[a(`customize.consumables.name`),u(Xt,{"aria-label":a(`customize.consumables.name`),value:f,onChange:e=>p(e.target.value)})]}),r(`label`,{className:`flex w-full flex-col gap-1 text-[11px] text-foreground-subtle sm:w-40`,children:[a(`customize.consumables.unit`),u(ht,{"aria-label":a(`customize.consumables.unit`),value:m,options:mi.map(e=>({value:e,label:a(`customize.consumables.units.${e}`)})),onChange:e=>{let t=mi.find(t=>t===e.target.value);t!==void 0&&h(t)}})]}),k&&u(`p`,{role:`alert`,className:`basis-full text-xs text-warning`,children:a(`customize.consumables.takenBy`,{name:O.label})}),A&&u(`p`,{role:`alert`,className:`basis-full text-xs text-warning`,children:a(`customize.consumables.keyless`)})]});return r(o,{children:[r(Do,{id:`consumables`,icon:S,title:a(`customize.consumables.title`),addLabel:a(`customize.consumables.add`),onAdd:E?()=>d(!0):void 0,...w===null?{}:{suggestion:{count:w.ids.size,location:w.location,onOpen:()=>d(!0)}},notices:r(o,{children:[u(Oo,{availability:n}),x.kind===`unknown`&&b.some(e=>e.source!==null)&&u(`p`,{role:`alert`,className:`text-xs text-warning break-words`,children:a(`customize.assign.devicesUnreadable`,{reason:x.reason})}),g!==null&&u(`p`,{role:`alert`,className:`text-xs text-danger break-words`,children:g})]}),children:[b.map(e=>{let n=e.source;if(e.unit===null||n===null)return u(To,{name:e.label,detail:a(`customize.consumables.otherFormula`),meta:u(Ga,{onAdvanced:i}),value:null,removeLabel:``},e.key);let r=Go(e,x),o=r?.name??J(n.source);return u(To,{name:e.label,detail:`${a(`customize.consumables.units.${e.unit}`)} · ${o}`,meta:`${n.cap}.${n.fieldPath}`,value:r===null?null:{deviceId:r.id,cap:n.cap,path:n.fieldPath},problem:r===null&&x.kind===`known`?a(`customize.assign.missingKept`):void 0,onRemove:T?()=>void N(e):void 0,removeLabel:a(`customize.assign.removeNamed`,{name:e.label}),busy:t.saving},e.key)}),b.length===0&&n.kind===`present`&&T&&u(`li`,{className:`px-3 sm:px-4 py-1.5 sm:py-2 text-[11px] text-foreground-subtle`,children:a(`customize.assign.none`)})]}),u(mo,{open:l,title:a(`customize.consumables.pickTitle`),targetKind:`number`,excludeDeviceIds:[e.id],room:w,confirmLabel:a(`customize.assign.add`),extra:P,extraComplete:D!==``&&!k,onConfirm:e=>{let n=Ko(e.value);if(n!==null&&(n<0||m===`percent`&&n>100)){M(),_(a(`customize.consumables.outOfRange`,{value:n}));return}let r=li(y,{key:D,label:f,remaining:{source:e.ref,cap:e.cap,fieldPath:e.path,kind:e.kind},unit:m});M(),r===null?_(a(`customize.assign.pickUnusable`)):j(ii(v,t.target,r))},onClose:M})]})}n();function Jo(e){return e.kind===`pending`?`pending`:e.kind===`unknown`?`failed`:`answered`}function Yo(e){return e.map(e=>({id:e.deviceId,name:e.name,...e.meta===null?{}:{type:e.meta},...e.detail===null?{}:{location:e.detail.includes(` · `)?e.detail.split(` · `).at(-1)??null:e.detail},...e.detail===null?{}:{detail:e.detail}}))}function Xo({open:e,title:t,selection:n,candidates:a,filters:o,room:s=null,confirmLabel:l,onConfirm:f,onClose:p}){let{t:m}=Z(),[h,g]=c(null),[_,v]=c([]),y=o?.find(e=>e.id===h)??o?.[0]??null,b=a.kind===`known`?a.value:[],x=a.kind===`known`?Fo(a.value,``,y):[],S=ao(b,s,e=>e.deviceId).suggested,C=ao(x,s,e=>e.deviceId).others,w=i(()=>Yo(C),[C]),T=Jo(a),E=b.filter(e=>_.includes(e.deviceId));d(()=>{e||(v([]),g(null))},[e]);let D=()=>{v([]),g(null),p()},O=e=>{e.length!==0&&(f(e),v([]),g(null))},k=()=>O(E);return u(Ht,{open:e,onOpenChange:e=>e?void 0:D(),children:r(ut,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,"aria-label":t,children:[u(ot,{children:u(Rn,{children:t})}),r(pt,{className:`flex flex-col gap-2 p-2 sm:p-4`,children:[o!==void 0&&o.length>0&&u(`div`,{className:`flex flex-wrap gap-1`,role:`tablist`,"aria-label":m(`customize.assign.filtersLabel`),children:o.map(e=>u(`button`,{type:`button`,role:`tab`,"aria-selected":(y?.id??null)===e.id,className:`inline-flex items-center gap-1 rounded-full border px-1.5 py-0.5 text-[10px] font-medium transition-colors ${(y?.id??null)===e.id?`border-primary/50 bg-primary/15 text-primary`:`border-border bg-surface text-foreground-subtle hover:bg-surface-hover`}`,onClick:()=>g(e.id),children:m(e.labelKey)},e.id))}),s!==null&&u(uo,{location:s.location,devices:S.map(e=>({id:e.deviceId,name:e.name,container:oo(s,e.deviceId),detail:e.detail})),action:`add`,onPick:e=>O(S.filter(t=>t.deviceId===e)),...n===`multi`?{onPickAll:()=>O(S)}:{}}),a.kind===`unknown`?u(`p`,{role:`alert`,className:`text-xs text-warning`,children:m(`customize.assign.unknown`,{reason:a.reason})}):w.length===0&&S.length>0?null:u(_n,{devices:w,listState:T,value:_,onChange:e=>v(n===`single`?e.length>0?[e[e.length-1]]:[]:e),noun:`device`,emptyLabel:m(`customize.assign.none`),showAll:!0,testId:`customize-device-picker`})]}),r(Hn,{children:[u(X,{variant:`ghost`,onClick:D,children:m(`customize.picker.cancel`)}),u(X,{disabled:E.length===0,onClick:k,children:l(E.length)})]})]})})}function Zo(e){if(e===null)return[];let t=hi(e);return vi(e).map(e=>{let n=J(e);return{key:n,ref:e,caps:t.filter(e=>J(e.source)===n).map(e=>e.cap)}})}function Qo(e,t){let n=hi(e);if(n.length===0)return!1;let{enabled:r,...i}=e,{enabled:a,...o}=Xe({camera:t,sources:n,enabled:!0});return wi(i,o)}function $o(e){return e?.enabled!==!1}function es(e,t,n){let r=[...e===null?[]:hi(e),...n.flatMap(e=>Ue(e.ref,e.caps))];return r.length===0?null:Xe({camera:t,sources:r,enabled:$o(e)})}function ts(e,t,n){let r=hi(e).filter(e=>J(e.source)!==n);return r.length===0?null:Xe({camera:t,sources:r,enabled:$o(e)})}function ns(e,t){return{...e,enabled:t}}n();function rs({device:e,handle:t,availability:n,onAdvanced:i}){let{t:a}=Z(),s=Ho(),[l,d]=c(!1),[f,p]=c(null),h=qa(t.state),g=Ti(h,`doorbell`),_=g===null||Qo(g,t.target),v=_?Zo(g):[],y=zo(v.length>0),b=n.kind===`present`&&_,x=Vo(e.location,b),S=Bo({hostId:e.id,excludeCameras:!1,assigned:new Set(v.map(e=>e.key)),preferredCap:null,enabled:l||x!==null});if(n.kind===`absent`)return null;let C=t.state.kind===`none`||t.state.kind===`present`,w=C&&!t.saving,T=n.kind===`present`&&w&&_,E=async e=>{let n=e===null?h===null?null:ti(h,`doorbell`):ii(h,t.target,e),r=await t.save(n);p(r.kind===`refused`?r.reason:null)},D=async(e,n)=>{if(g===null||h===null)return;let r=ts(g,t.target,e.key),i=r===null&&ti(h,`doorbell`)===null;await s(a(`customize.doorbell.removeWhat`,{name:n}),i)&&await E(r)},O=e=>y.kind===`known`?y.value.find(t=>J({addonId:t.addonId,stableId:t.stableId})===e.key)??null:null;return r(o,{children:[r(Do,{id:`doorbell`,icon:m,title:a(`customize.doorbell.title`),headerControl:g===null?void 0:r(`label`,{className:`flex items-center gap-1.5 text-[11px] text-foreground`,children:[u(an,{"aria-label":a(`customize.doorbell.active`),checked:g.enabled!==!1,disabled:!w,onChange:e=>void E(ns(g,e.target.checked))}),a(`customize.doorbell.active`)]}),addLabel:a(`customize.doorbell.add`),onAdd:T?()=>d(!0):void 0,...x===null?{}:{suggestion:{count:co(S,x,e=>e.deviceId),location:x.location,onOpen:()=>d(!0)}},notices:r(o,{children:[u(Oo,{availability:n}),y.kind===`unknown`&&u(`p`,{role:`alert`,className:`text-xs text-warning break-words`,children:a(`customize.assign.devicesUnreadable`,{reason:y.reason})}),f!==null&&u(`p`,{role:`alert`,className:`text-xs text-danger break-words`,children:f})]}),children:[v.map(e=>{let n=O(e),r=n?.name??e.key,i=jo(e.caps,null),o=i===null?void 0:Te[i];return u(To,{name:r,detail:n===null?null:Mo(n.integration,n.location),meta:e.caps.join(`, `),value:n!==null&&i!==null&&o!==void 0?{deviceId:n.id,cap:i,path:o}:null,problem:n===null&&y.kind===`known`?a(`customize.assign.missingKept`):void 0,onRemove:C?()=>void D(e,r):void 0,removeLabel:a(`customize.assign.removeNamed`,{name:r}),busy:t.saving},e.key)}),!_&&u(To,{name:a(`customize.doorbell.otherFormula`),detail:null,meta:u(Ga,{onAdvanced:i}),value:null,removeLabel:``}),g===null&&n.kind===`present`&&C&&u(`li`,{className:`px-3 sm:px-4 py-1.5 sm:py-2 text-[11px] text-foreground-subtle`,children:a(`customize.assign.none`)})]}),u(Xo,{open:l,title:a(`customize.doorbell.pickTitle`),selection:`multi`,candidates:S,room:x,confirmLabel:e=>a(`customize.assign.addCount`,{count:e}),onConfirm:e=>{d(!1),E(es(g,t.target,e.map(e=>({ref:e.ref,caps:e.caps}))))},onClose:()=>d(!1)})]})}function is(e){return e.slot===`linked-devices`}function as(e){if(e.status===`error`)return{kind:`unknown`,reason:e.error?.message??`the request failed`};if(e.status===`pending`||e.data===void 0)return{kind:`pending`};for(let t of e.data)if(t.state===`ok`&&t.slot===`linked-devices`&&is(t.value))return{kind:`present`,slot:t,value:t.value};let t=e.data.find(e=>e.state===`unreachable`);return t!==void 0&&t.state===`unreachable`?{kind:`unknown`,reason:t.reason}:{kind:`absent`}}function os(e,t){let n=t.trackedDeviceIds??[],r=e=>t=>({deviceId:t.deviceId,name:t.name,health:t.health,implied:e,tracked:n.includes(t.deviceId)});return[...e.sources.map(r(!1)),...(e.impliedSources??[]).map(r(!0))]}function ss(e,t){let n=new Set([...e.sources,...e.impliedSources??[]].map(e=>e.deviceId));return(t.trackedDeviceIds??[]).filter(e=>!n.has(e))}function cs(e,t){return{...e,deviceIds:[...e.deviceIds,...t.filter(t=>!e.deviceIds.includes(t))]}}function ls(e,t){return{...e,deviceIds:e.deviceIds.filter(e=>e!==t),...e.trackedDeviceIds===void 0?{}:{trackedDeviceIds:e.trackedDeviceIds.filter(e=>e!==t)}}}function us(e,t,n){let r=e.trackedDeviceIds??[],i=n?[...r.filter(e=>e!==t),t]:r.filter(e=>e!==t);return{...e,trackedDeviceIds:i}}function ds(e,t,n){return e.flatMap(e=>{let r=t.get(e.deviceId);return n.has(e.deviceId)||r===void 0?[]:[{deviceId:e.deviceId,ref:{addonId:r.addonId,stableId:r.stableId},name:e.parentName===null?e.name:`${e.parentName} · ${e.name}`,detail:Mo(r.integration,e.location),meta:e.type,caps:[],value:null}]})}n();function fs(e){return e==null?null:e.message}function ps({device:e}){let{t}=Z(),n=s(),i=Ho(),a=je.includes(e.type),[l,d]=c(!1),[f,p]=c(!1),[m,h]=c(null),g=Wt({deviceId:e.id},{enabled:a}),_=as({status:g.status,data:g.data,error:fs(g.error)===null?null:{message:fs(g.error)??``}}),v=_.kind===`present`?_.slot.slotRef:``,y=_.kind===`present`?[...os(_.slot,_.value).map(e=>e.deviceId),...ss(_.slot,_.value)]:[],b=Yt(),x=zo(a&&_.kind===`present`&&(l||y.length>0)),S=Vo(e.location,a&&_.kind===`present`),C=_t({deviceId:e.id,slotRef:v},{enabled:(l||S!==null)&&_.kind===`present`});if(!a||_.kind===`absent`)return null;if(_.kind!==`present`)return u(Do,{id:`linked`,icon:ne,title:t(`customize.linked.title`),notices:_.kind===`pending`?u(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:t(`customize.assign.checking`)}):u(`p`,{role:`alert`,className:`text-xs text-warning break-words`,children:t(`customize.assign.unknown`,{reason:_.reason})}),children:null});let w=_.value,T=new Map(x.kind===`known`?x.value.map(e=>[e.id,e]):[]),E=w.trackedDeviceIds!==void 0,D=(e,t)=>{let n=T.get(e.deviceId);return{...e,name:e.name??n?.name??null,type:n?.type??null,detail:n===void 0?null:Mo(n.integration,n.location),orphan:t}},O=[...os(_.slot,w).map(e=>D(e,!1)),...ss(_.slot,w).map(e=>D({deviceId:e,name:null,health:`ok`,implied:!1,tracked:!0},!0))],k=new Set(y),A=x.kind===`unknown`?x:C.status===`error`?{kind:`unknown`,reason:fs(C.error)??`the request failed`}:x.kind===`pending`||C.status===`pending`||C.data===void 0?{kind:`pending`}:{kind:`known`,value:ds(C.data.candidates,T,k)},j=async r=>{if(f){h(t(`customize.saveInFlight`));return}p(!0),h(null);try{await b.mutateAsync({deviceId:e.id,slotRef:_.slot.slotRef,value:r}),await g.refetch(),await n.invalidateQueries({queryKey:[[`deviceManager`]]})}catch(e){h(e instanceof Error?e.message:String(e))}finally{p(!1)}},M=async e=>{await i(t(`customize.linked.removeWhat`,{name:e.name??`#${e.deviceId}`}),!1)&&await j(ls(w,e.deviceId))},N=[{key:`device`,header:t(`customize.linked.device`),cell:e=>r(`div`,{className:`flex flex-col min-w-0`,children:[u(`span`,{className:`truncate text-xs text-foreground`,children:e.name??`#${e.deviceId}`}),e.detail!==null&&u(`span`,{className:`truncate text-[11px] text-foreground-subtle`,children:e.detail}),e.orphan&&u(`span`,{className:`text-[11px] text-foreground-subtle`,children:t(`customize.linked.notLinked`)}),e.health!==`ok`&&u(`span`,{role:`alert`,className:`text-[11px] text-warning`,children:t(`customize.linked.health.${e.health}`)})]})},{key:`type`,header:t(`customize.linked.type`),headerClassName:`hidden sm:table-cell`,cellClassName:`hidden sm:table-cell text-xs text-foreground-subtle`,cell:e=>e.type===null?`—`:xr(e.type).label},{key:`controls`,header:t(`customize.linked.controls`),headerClassName:`hidden md:table-cell`,cellClassName:`hidden md:table-cell text-xs text-foreground-subtle`,cell:e=>e.orphan?`—`:t(`customize.linked.yes`)},...E?[{key:`tracked`,header:t(`customize.linked.tracked`),cellClassName:`text-right`,headerClassName:`text-right`,cell:e=>u(Pn,{checked:e.tracked,disabled:f,"aria-label":t(`customize.linked.trackFor`,{name:e.name??e.deviceId}),onCheckedChange:t=>void j(us(w,e.deviceId,t))})}]:[],{key:`remove`,header:``,cellClassName:`text-right w-10`,cell:e=>e.implied||e.orphan?null:u(Qt,{icon:ie,variant:`ghost`,size:`sm`,"aria-label":t(`customize.assign.removeNamed`,{name:e.name??e.deviceId}),disabled:f,onClick:t=>{t.stopPropagation(),M(e)}})}];return r(o,{children:[u(Do,{id:`linked`,icon:ne,title:t(`customize.linked.title`),addLabel:t(`customize.linked.add`),onAdd:f?void 0:()=>d(!0),...S===null?{}:{suggestion:{count:co(A,S,e=>e.deviceId),location:S.location,onOpen:()=>d(!0)}},notices:r(o,{children:[x.kind===`unknown`&&u(`p`,{role:`alert`,className:`text-xs text-warning break-words`,children:t(`customize.assign.devicesUnreadable`,{reason:x.reason})}),m!==null&&u(`p`,{role:`alert`,className:`text-xs text-danger break-words`,children:m})]}),children:r(`li`,{className:`list-none px-3 py-2 sm:px-4`,children:[O.length===0?u(`p`,{className:`text-[11px] text-foreground-subtle`,children:t(`customize.assign.none`)}):u(wn,{mode:`generic`,items:O,getKey:e=>String(e.deviceId),getSearchText:e=>[e.name??``,e.detail??``,e.type??``,String(e.deviceId)].join(` `),getFilterType:e=>e.type===null?null:xr(e.type).label,columns:N,searchPlaceholder:t(`customize.assign.search`),emptyLabel:t(`customize.assign.none`)}),O.some(e=>!e.orphan)&&u(`p`,{className:`mt-2 text-[10px] text-foreground-subtle`,children:t(`customize.linked.controlsAlways`)}),E&&u(`p`,{className:`mt-0.5 text-[10px] text-foreground-subtle`,children:t(`customize.linked.trackedHint`)})]})}),u(Xo,{open:l,title:t(`customize.linked.pickTitle`),selection:`multi`,candidates:A,room:S,confirmLabel:e=>t(`customize.assign.addCount`,{count:e}),onConfirm:e=>{d(!1),j(cs(w,e.map(e=>e.deviceId)))},onClose:()=>d(!1)})]})}function ms(e){return e===null||e.state===`unreadable`?null:e.state===`configured`?e.sensors:[]}function hs(e){return{addonId:e.addonId,stableId:e.stableId,mode:e.mode}}function gs(e){return e.length===0?null:{sensors:[...e]}}function _s(e,t){let n=new Set(e.map(ke));return gs([...e.map(hs),...t.filter(e=>!n.has(ke(e))).map(e=>({...e,mode:Oe}))])}function vs(e,t,n){return gs(e.map(e=>ke(e)===t?{...hs(e),mode:n}:hs(e)))}function ys(e,t){return gs(e.filter(e=>ke(e)!==t).map(hs))}function bs(e){return e?.state===`configured`&&e.cameraMotion!==void 0}function xs(e){return e===null||e.state===`unreadable`?null:e.state===`configured`?e.cameraMotion??`always`:`always`}function Ss(e){return e===null||e.state===`unreadable`?!1:e.state===`not-configured`||bs(e)}function Cs(e){return e?.state===`configured`&&(e.notForwarded!==void 0||e.notEnforced!==void 0)}function ws(e,t,n){if(e!==`present`||t===null||n)return{kind:`none`};let r=t.cameraLevel;return r===void 0?{kind:`unknown`}:{kind:`level`,detected:r.detected,atMs:r.atMs}}n();var Ts=5e3;function Es(e){return e.state===`missing`||e.state===`unreadable`?e.stableId:e.name}function Ds({device:e,availability:n,sensors:i}){let{t:a}=Z(),s=Ho(),l=It(),[f,p]=c(!1),[m,h]=c(null),g=t(!1),[_,v]=c(!1),[y,b]=c(!1),x=i.status,S=t(i.refetch);S.current=i.refetch,d(()=>{let e=setInterval(()=>{g.current||S.current()},Ts);return()=>clearInterval(e)},[]);let C=ms(x);d(()=>{x!==null&&b(!1)},[x]);let w=i.presence===`present`&&Ss(x)&&!y?C:null,T=zo(C!==null&&C.length>0),D=Vo(e.location,w!==null&&n.kind===`present`),O=Bo({hostId:e.id,excludeCameras:!0,assigned:new Set((C??[]).map(ke)),preferredCap:`motion`,enabled:f||D!==null});if(n.kind===`absent`)return null;let k=bs(x),A=Cs(x)?`passes`:xs(x),j=ws(i.presence,x,y),M=j.kind===`none`?null:j.kind===`unknown`?{text:`?`,tone:`warning`,title:a(`customize.motion.cameraLevelUnknown`)}:{text:a(j.detected?`customize.assign.value.active`:`customize.assign.value.inactive`),tone:j.detected?`active`:`muted`,title:a(`customize.motion.cameraLevelOwn`,{at:new Date(j.atMs).toLocaleTimeString()})},N=_||l.isPending,P=async t=>{if(g.current){h(a(`customize.saveInFlight`));return}g.current=!0,v(!0);try{await l.mutateAsync({deviceId:e.id,config:t}),h(null),await i.refetch()===`failed`&&b(!0)}catch(e){h(e instanceof Error?e.message:String(e))}finally{g.current=!1,v(!1)}},F=async e=>{w!==null&&await s(a(`customize.motion.removeWhat`,{name:Es(e)}),!1)&&await P(ys(w,ke(e)))},I=e=>{if(T.kind!==`known`||!(`deviceId`in e))return null;let t=T.value.find(t=>t.id===e.deviceId);return t===void 0?null:Mo(t.integration,t.location)};return r(o,{children:[r(Do,{id:`motion`,icon:E,title:a(`customize.motion.title`),addLabel:a(`customize.motion.add`),onAdd:w!==null&&n.kind===`present`?()=>p(!0):void 0,addDisabled:N,...D===null?{}:{suggestion:{count:co(O,D,e=>e.deviceId),location:D.location,onOpen:()=>p(!0)}},notices:r(o,{children:[u(Oo,{availability:n}),i.presence===`pending`&&n.kind!==`pending`&&u(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:a(`customize.motion.reading`)}),x?.state===`unreadable`&&u(`p`,{role:`alert`,className:`text-xs text-warning break-words`,children:a(`customize.motion.unreadable`,{reason:x.reason})}),x?.state===`configured`&&!Ss(x)&&u(`p`,{role:`alert`,className:`text-xs text-warning`,children:a(`customize.motion.olderOrchestrator`)}),y&&u(`p`,{role:`alert`,className:`text-xs text-warning`,children:a(`customize.motion.refetchFailed`)}),x?.state===`configured`&&x.notForwarded!==void 0&&u(`p`,{role:`alert`,className:`text-xs text-warning`,children:a(`customize.motion.notForwarded.${x.notForwarded}`)}),x?.state===`configured`&&x.notEnforced!==void 0&&u(`p`,{role:`alert`,className:`text-xs text-warning`,children:a(`customize.motion.notEnforced`)}),T.kind===`unknown`&&u(`p`,{role:`alert`,className:`text-xs text-warning break-words`,children:a(`customize.assign.devicesUnreadable`,{reason:T.reason})}),m!==null&&u(`p`,{role:`alert`,className:`text-xs text-danger break-words`,children:m})]}),children:[u(To,{name:a(`customize.motion.camera`),detail:null,meta:A===null?a(`customize.assign.native`):`${a(`customize.motion.cameraState.${A}`)} · ${a(`customize.assign.native`)}`,value:null,shown:M,removeLabel:``}),(C??[]).map(e=>{let t=ke(e),n=Es(e),r=e.state===`ready`?jo(e.caps,`motion`):null,i=r===null?void 0:Te[r];return u(To,{name:n,detail:I(e),meta:k&&w!==null?u(ht,{"aria-label":a(`customize.motion.modeFor`,{name:n}),value:e.mode,disabled:N,options:De.options.map(e=>({value:e,label:a(`customize.motion.mode.${e}`)})),onChange:e=>{let n=De.safeParse(e.target.value);n.success&&w!==null&&P(vs(w,t,n.data))}}):a(`customize.motion.mode.${e.mode}`),value:r!==null&&i!==void 0&&`deviceId`in e?{deviceId:e.deviceId,cap:r,path:i}:null,problem:e.state===`ready`?void 0:e.reason===e.state?a(`customize.motion.state.${e.state}`):`${a(`customize.motion.state.${e.state}`)}: ${e.reason}`,onRemove:w===null?void 0:()=>void F(e),removeLabel:a(`customize.assign.removeNamed`,{name:n}),busy:N},t)})]}),u(Xo,{open:f,title:a(`customize.motion.pickTitle`),selection:`multi`,candidates:O,room:D,filters:Ao,confirmLabel:e=>a(`customize.assign.addCount`,{count:e}),onConfirm:e=>{if(p(!1),w===null)return;let t=_s(w,e.map(e=>e.ref));if(t!==null&&t.sensors.length>8){h(a(`customize.motion.tooMany`,{max:8}));return}P(t)},onClose:()=>p(!1)})]})}var Os={"numeric-sensor":{fieldPath:`value`,unitField:`unit`},"temperature-sensor":{fieldPath:`celsius`,unitField:`unit`},"humidity-sensor":{fieldPath:`percent`,unitField:`unit`},"pressure-sensor":{fieldPath:`hpa`,unitField:`unit`},"ambient-light-sensor":{fieldPath:`lux`,unitField:`unit`}},ks=new Set([Y.Camera]);function As(e){return e.unitField===null?[e.fieldPath]:[e.fieldPath,e.unitField]}function js(e,t){if(ks.has(e))return{kind:`absent`};let n=null;for(let[e,r]of Object.entries(Os))if(t.has(e)){n={cap:e,fieldPath:r.fieldPath,unitField:r.unitField};break}let r=null;for(let e of Fe)if(t.has(e)){let t=Te[e];if(t!==void 0){r={cap:e,fieldPath:t};break}}return n===null&&r===null?{kind:`absent`}:{kind:`present`,convert:n,invert:r}}function Ms(e){return $e(e.from,e.to)?Ze(e):null}function Ns(e){return Je(e)}var Ps=/^convert\(v,\s*"[^"]*",\s*"[^"]*"\)$/;function Fs(e){return e!==void 0&&Ps.test(e.expr)}function Is(e){return e===void 0||e.expr===`!v`||Ps.test(e.expr)?!1:e.bindings.v!==void 0}function Ls(e){let t=e.expr.trim();if(t===``)return{kind:`refused`,reason:`expression is empty`};let n={kind:`expression`,expr:t,bindings:{v:{kind:`from`,source:e.self,cap:e.cap,fieldPath:e.fieldPath}}},r=Ke({source:n,now:Date.now(),read:()=>({state:`fresh`,value:e.probe})});return r.state===`unavailable`?{kind:`refused`,reason:r.reason}:{kind:`ok`,feature:{kind:`fields`,cap:e.cap,fields:{[e.fieldPath]:n}}}}function Rs(e,t,n){if(e===null)return null;let r=Ti(e,n.cap);if(r===null)return e;let i=new Set(As(n)),a=Object.fromEntries(Object.entries(r.fields).filter(([e])=>!i.has(e)));return Object.keys(a).length===0?ti(e,n.cap):ii(e,t,{kind:`fields`,cap:n.cap,...r.enabled===void 0?{}:{enabled:r.enabled},fields:a,...r.items===void 0?{}:{items:r.items}})}n();function zs(e){if(typeof e!=`object`||!e)return;let t=Reflect.get(e,`unit`);return typeof t==`string`?t:void 0}function Bs(e,t){if(typeof e!=`object`||!e)return;let n=Reflect.get(e,t);return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Vs(e,t){let n=Ti(e,t.cap);if(n===null)return;let r=n.fields[t.fieldPath];return r!==void 0&&r.kind===`expression`?r:void 0}function Hs(e,t){let n=Vs(e,t);return n===void 0||!Fs(n)?null:/^convert\(v,\s*"[^"]*",\s*"([^"]*)"\)$/.exec(n.expr)?.[1]??null}function Us(e,t){let n=Vs(e,t);return n===void 0||!Is(n)?null:n.expr}function Ws(e,t,n){let r=Ti(e,t);if(r===null)return!1;let i=r.fields[n];return i!==void 0&&i.kind===`expression`&&i.expr===`!v`}function Gs(e){return typeof e==`number`||typeof e==`boolean`||typeof e==`string`?String(e):e===null?`null`:JSON.stringify(e)}function Ks({device:e,target:t,handle:n,facts:i}){let{t:a}=Z(),o=W(),[s,l]=c(null),[d,f]=c(``),[m,h]=c(null),g=i.nativeCaps.kind===`known`?i.nativeCaps.value:null,_=g===null?null:js(e.type,g),v=_?.kind===`present`?_.convert?.cap??``:``,y=ur(o.trpcClient,e.id,v);if(i.nativeCaps.kind===`pending`)return u(`section`,{className:`${w} ${p}`,children:u(Oo,{availability:{kind:`pending`}})});if(i.nativeCaps.kind===`unknown`)return u(`section`,{className:`${w} ${p}`,children:u(Oo,{availability:{kind:`unknown`,reason:i.nativeCaps.reason}})});if(_===null||_.kind===`absent`)return null;let b=qa(n.state),x=_.convert,S=_.invert,C=x===null?void 0:zs(y),T=C===void 0?void 0:Pe(C)??C,E=T===void 0?void 0:Le(T),D=x===null?null:Hs(b,x),O=x===null?null:Us(b,x),k=m??O??``,A=S===null?!1:Ws(b,S.cap,S.fieldPath),j=n.state.kind===`none`||n.state.kind===`present`,M=x===null?0:Bs(y,x.fieldPath)??0,N=x!==null&&k.trim()!==``?{kind:`expression`,expr:k.trim(),bindings:{v:{kind:`from`,source:t,cap:x.cap,fieldPath:x.fieldPath}}}:null,P=N===null||x===null?null:gi(N,new Map([[Ae(t,x.cap),y===void 0?{kind:`pending`}:{kind:`value`,slice:y}]]),Date.now()),F=async e=>{let t=await n.save(e);l(t.kind===`refused`?t.reason:null)},I=async()=>{if(x===null||T===void 0||d===``)return;let e=Ms({self:t,cap:x.cap,fieldPath:x.fieldPath,from:T,to:d,unitField:x.unitField});if(e===null){l(a(`customize.numericTransforms.convertRefused`));return}h(null),await F(ii(b,t,e))},L=async()=>{x!==null&&(await F(Rs(b,t,x)),f(``))},R=async()=>{if(x===null)return;let e=Ls({self:t,cap:x.cap,fieldPath:x.fieldPath,expr:k,probe:M});if(e.kind===`refused`){l(e.reason);return}f(``),await F(ii(b,t,e.feature))},z=async()=>{x!==null&&(await F(Rs(b,t,x)),h(``))},ee=async()=>{if(S===null)return;let e=Ns({self:t,cap:S.cap});if(e===null){l(a(`customize.numericTransforms.invertRefused`));return}await F(ii(b,t,e))},B=async()=>{S===null||b===null||await F(ti(b,S.cap))};return u(Eo,{id:`numeric-transforms`,icon:_e,title:a(`customize.numericTransforms.title`),testId:`numeric-transforms-card`,children:r(`div`,{className:`${p} flex flex-col gap-3`,children:[u(`p`,{className:`text-[11px] text-foreground-subtle`,children:a(`customize.numericTransforms.blurb`)}),s!==null&&u(`p`,{role:`alert`,className:`text-[11px] text-danger break-words`,children:s}),x!==null&&r(`div`,{className:`flex flex-col gap-2`,"data-testid":`numeric-convert`,children:[u(`label`,{className:`text-[11px] font-medium text-foreground`,children:a(`customize.numericTransforms.publishUnit`)}),u(`p`,{className:`text-[11px] text-foreground-subtle`,children:T===void 0?a(`customize.numericTransforms.fromUnknown`):a(`customize.numericTransforms.fromUnit`,{unit:T})}),u(`div`,{className:`w-full sm:max-w-xs`,children:u(Wn,{dimension:E,value:d===``?D??``:d,onChange:e=>{f(e),e!==``&&h(``)},disabled:!j||n.saving||T===void 0,"aria-label":a(`customize.numericTransforms.toUnit`),inheritLabel:a(`customize.numericTransforms.pickUnit`),emptyReason:a(`customize.numericTransforms.fromUnknown`)})}),r(`div`,{className:`flex flex-wrap gap-2`,children:[u(X,{size:`sm`,disabled:!j||n.saving||T===void 0||d===``||d===T,onClick:()=>void I(),children:a(`customize.numericTransforms.applyConvert`)}),D!==null&&u(X,{size:`sm`,variant:`outline`,disabled:!j||n.saving,onClick:()=>void L(),children:a(`customize.numericTransforms.clearConvert`)})]})]}),x!==null&&r(`div`,{className:`flex flex-col gap-2`,"data-testid":`numeric-script`,children:[u(yi,{label:a(`customize.numericTransforms.script`),value:k,bindings:[`v`],onChange:e=>{h(e),e.trim()!==``&&f(``)}}),u(`p`,{className:`text-[11px] text-foreground-subtle`,children:a(`customize.numericTransforms.scriptBlurb`)}),P!==null&&u(`p`,{role:`status`,className:`text-[11px] font-mono text-foreground`,"data-testid":`numeric-script-preview`,children:P.kind===`value`?a(`customize.numericTransforms.preview`,{source:Gs(M),result:Gs(P.value)}):P.kind===`waiting`?a(`customize.numericTransforms.previewWaiting`):P.kind===`unavailable`?a(`customize.numericTransforms.previewError`,{reason:P.reason}):a(`customize.numericTransforms.previewRuntimeOnly`)}),r(`div`,{className:`flex flex-wrap gap-2`,children:[u(X,{size:`sm`,disabled:!j||n.saving||k.trim()===``,onClick:()=>void R(),children:a(`customize.numericTransforms.applyScript`)}),O!==null&&u(X,{size:`sm`,variant:`outline`,disabled:!j||n.saving,onClick:()=>void z(),children:a(`customize.numericTransforms.clearScript`)})]})]}),S!==null&&r(`div`,{className:`flex flex-col gap-2`,"data-testid":`numeric-invert`,children:[u(`label`,{className:`text-[11px] font-medium text-foreground`,children:a(`customize.numericTransforms.invert`)}),u(`p`,{className:`text-[11px] text-foreground-subtle`,children:a(`customize.numericTransforms.invertBlurb`)}),u(`div`,{className:`flex flex-wrap gap-2`,children:A?u(X,{size:`sm`,variant:`outline`,disabled:!j||n.saving,onClick:()=>void B(),children:a(`customize.numericTransforms.clearInvert`)}):u(X,{size:`sm`,disabled:!j||n.saving,onClick:()=>void ee(),children:a(`customize.numericTransforms.applyInvert`)})})]})]})})}n();function qs(e){return e instanceof Error?e.message:String(e)}function Js(e){let n=at({addonId:e.addonId,stableId:e.stableId}),r=Vt(),i=bt(),a=ft(),o=Ka({status:n.status,data:n.data,error:n.error===null||n.error===void 0?null:{message:n.error.message}}),{t:s}=Z(),l=t(!1),[u,d]=c(!1),f=async e=>{let t=si(o,e);try{switch(t.kind){case`refused`:return{kind:`refused`,reason:t.reason};case`noop`:return{kind:`saved`};case`create`:await r.mutateAsync({block:t.input});break;case`update`:await i.mutateAsync({blockId:t.blockId,expectedUpdatedAt:t.expectedUpdatedAt,block:{composition:t.composition}});break;case`delete`:await a.mutateAsync({blockId:t.blockId});break}return await n.refetch(),{kind:`saved`}}catch(e){return{kind:`refused`,reason:qs(e)}}};return{target:e,state:o,saving:u||r.isPending||i.isPending||a.isPending,save:async e=>{if(l.current)return{kind:`refused`,reason:s(`customize.saveInFlight`)};l.current=!0,d(!0);try{return await f(e)}finally{l.current=!1,d(!1)}}}}var Ys=`pipeline-orchestrator`;function Xs(e){return e.status===`pending`?`pending`:e.status===`error`?`unknown`:e.data===void 0?`pending`:e.data.cameraSensors===void 0?`absent`:`present`}function Zs(e,t){return e===`absent`?`absent`:Xs(t)}async function Qs(e){try{return(await e()).isError?`failed`:`answered`}catch{return`failed`}}function $s(e,t){let n=Gt(Ys),r=Un({deviceId:e},{enabled:t&&n!==`absent`}),i=()=>Qs(r.refetch);return t?{presence:Zs(n,{status:r.status,data:r.data}),status:r.data?.cameraSensors??null,refetch:i}:{presence:`absent`,status:null,refetch:i}}function ec(e,t){let n=Ln({deviceType:e.type}),r=dr({deviceId:e.id}),i=rr({deviceId:e.id}),a=ko(n,e=>new Set(e.caps.map(e=>e.cap))),o=ko(r,e=>Ba(e.entries)),s=ko(i,e=>e);return{deviceType:e.type,composable:a,nativeCaps:o,wireable:s,composed:new Set((t?.features??[]).map(e=>e.cap))}}var tc={kind:`unknown`,reason:`the composer reports no value for this field`};function nc(e,t){let n=J(e);return t.get(n)??n}function rc(e,t,n){let r=n.nativeCaps.has(e.cap)?`replaced`:`added`,i=t.filter(t=>t.cap===e.cap&&t.origin===`composed`);if(e.cap===`doorbell`){let t=vi(e).map(e=>nc(e,n.sourceNames)).join(` + `),a=i.find(e=>e.field===`lastPressedAt`);return[{key:`doorbell`,label:`doorbell`,origin:{kind:r,from:t},value:a?.value??tc}]}return e.cap===`consumables`?ui(e).map(e=>{let t=t=>Ee(et,e.key,t),a=i.find(e=>e.field===t(`level`)||e.field===t(`remaining.value`)),o=e.source===null?``:nc(e.source.source,n.sourceNames);return{key:`consumables.${e.key}`,label:`consumables · ${e.label}`,origin:{kind:r,from:o},value:a?.value??tc}}):i.map(e=>({key:e.key,label:`${e.cap}.${e.field}`,origin:{kind:r,from:e.from},value:e.value}))}function ic(e){let t=pi({composition:e.composition,nativeCaps:e.nativeCaps,state:e.state,nativeFields:new Map,snapshot:null,sourceNames:e.sourceNames});return e.composition.features.flatMap(n=>n.kind===`fields`?rc(n,t,e):[])}function ac(e,t){if(e?.state!==`configured`||e.sensors.length===0)return null;let n=e.cameraMotion===`never`?[]:[t.camera],r=e.sensors.map(e=>t.sensor(e.state===`missing`||e.state===`unreadable`?e.stableId:e.name,e.mode));return[...n,...r].join(` + `)}var oc=`${j} grid grid-cols-1 gap-x-3 gap-y-0.5 items-baseline sm:grid-cols-[minmax(0,1fr)_minmax(0,2fr)_minmax(0,1.5fr)]`,sc=`font-mono text-[11px] text-foreground break-words`,cc=`text-[11px] text-foreground-subtle break-words`,lc=`text-[11px] break-words sm:text-right`;function uc({device:e,composition:t,state:n,nativeCaps:i,cameraSensors:a}){let{t:o}=Z(),s=t!==null&&n!==null,c=zo(s),l=new Map(c.kind===`known`?c.value.map(e=>[J({addonId:e.addonId,stableId:e.stableId}),e.name]):[]),d=s&&i.kind===`known`?ic({composition:t,nativeCaps:i.value,state:n,sourceNames:l}):[],f=s&&i.kind===`known`&&d.length===0&&t.features.length>0,p=ac(a,{camera:o(`customize.changes.motion.camera`),sensor:(e,t)=>o(`customize.changes.motion.${t}`,{name:e})}),m=s&&i.kind!==`known`;return d.length===0&&p===null&&!m&&!f?null:r(Eo,{id:`changes`,icon:le,title:o(`customize.changes.title`),children:[m&&u(`p`,{role:i.kind===`unknown`?`alert`:`status`,className:`px-3 sm:px-4 py-1.5 sm:py-2 text-[11px] text-foreground-subtle`,children:i.kind===`unknown`?o(`customize.changes.unknown`,{reason:i.reason}):o(`customize.changes.reading`)}),f&&u(`p`,{className:`px-3 sm:px-4 py-1.5 sm:py-2 text-[11px] text-foreground-subtle`,children:o(`customize.changes.noRows`)}),r(`ul`,{className:`divide-y divide-border`,children:[d.map(e=>r(`li`,{className:oc,children:[u(`span`,{className:sc,children:e.label}),u(`span`,{className:cc,children:c.kind===`known`?o(`customize.changes.origin.${e.origin.kind}`,{from:e.origin.from}):o(`customize.changes.originUnread.${c.kind}`,{kind:o(`customize.changes.kind.${e.origin.kind}`),reason:c.kind===`unknown`?c.reason:``})}),u(`span`,{className:lc,children:u(dc,{value:e.value})})]},e.key)),p!==null&&r(`li`,{className:oc,children:[u(`span`,{className:sc,children:`motion`}),u(`span`,{className:cc,children:p}),u(`span`,{className:lc,children:u(Co,{target:{deviceId:e.id,cap:`motion`,path:`detected`}})})]})]})]})}function dc({value:e}){let{t}=Z();switch(e.kind){case`value`:return r(`span`,{children:[_i(e.value,!0),e.staleReason!==null&&r(`span`,{className:`text-warning`,children:[` `,`·`,` `,t(`customize.changes.value.stale`,{reason:e.staleReason})]})]});case`unavailable`:return u(`span`,{className:`text-warning`,children:t(`customize.changes.value.unavailable`,{reason:e.reason})});case`unknown`:return u(`span`,{className:`text-foreground-subtle`,children:t(`customize.changes.value.unknown`,{reason:e.reason})});case`off`:return u(`span`,{className:`text-foreground-subtle`,children:t(`customize.status.off`)})}}n();function fc({deviceId:e,activeSubTab:t,onSubTabChange:n}){let{t:r}=Z(),i=vr({deviceId:e}),a=i.data;return a==null?i.status===`error`?u(Dt,{title:r(`customize.deviceUnreadable`),message:i.error?.message??``,onRetry:()=>void i.refetch()}):a===null?u(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:r(`customize.noSuchDevice`,{deviceId:e})}):u(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:r(`customize.loadingDevice`)}):a.addonId===`composer`?u(pc,{device:a}):u(mc,{device:a,target:{addonId:a.addonId,stableId:a.stableId},activeSubTab:t,onSubTabChange:n})}function pc({device:e}){let{t}=Z(),n=e.stableId.startsWith(`composed-`)?e.stableId.slice(Ve.length):null;return r(`section`,{className:`${w} ${p} flex flex-col gap-2`,children:[u(`p`,{className:`text-xs text-foreground`,children:t(`customize.composed.body`)}),n!==null&&u(Zr,{className:`text-[11px] text-primary hover:underline`,to:$r(n),children:t(`customize.composed.edit`)})]})}function mc({device:e,target:t,activeSubTab:n,onSubTabChange:i}){let a=Js(t),o=Gt(`composer`),{t:s}=Z(),c=$s(e.id,e.type===Y.Camera),l=ec(e,qa(a.state)),d={deviceType:e.type,composable:l.composable,nativeCaps:l.nativeCaps,cameraSensors:c.presence},f=()=>i(Jr),p=a.state.kind===`none`||a.state.kind===`present`;return n===`advanced`?r(`div`,{className:`flex flex-col gap-3`,children:[u(gc,{state:a.state}),p&&u(hc,{device:e,target:t,handle:a,facts:l,onDone:()=>i(`main`)})]}):r(`div`,{className:`flex flex-col gap-3`,children:[u(no,{device:e}),o===`absent`&&u(`p`,{role:`alert`,className:`text-xs text-warning`,children:s(`customize.composerAbsent`)}),a.state.kind!==`none`&&u(gc,{state:a.state}),u(rs,{device:e,handle:a,availability:Wa(`doorbell`,d),onAdvanced:f}),u(Ds,{device:e,handle:a,availability:Wa(`motion`,d),sensors:c}),u(Wo,{device:e,handle:a,availability:Wa(`battery`,d),onAdvanced:f}),u(qo,{device:e,handle:a,availability:Wa(`consumables`,d),onAdvanced:f}),u(Ks,{device:e,target:t,handle:a,facts:l}),u(ps,{device:e}),u(uc,{device:e,composition:qa(a.state),state:a.state.kind===`present`?a.state.view.state:null,nativeCaps:l.nativeCaps,cameraSensors:c.status}),r(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[p?u(Ga,{onAdvanced:f}):u(`span`,{}),u(_c,{handle:a})]})]})}function hc({device:e,target:t,handle:n,facts:r,onDone:i}){let a=n.state.kind===`present`?n.state:null;return u(xi,{initial:a===null?ni(t):ri(a.composition,``),blockId:a===null?null:a.view.block.id,deviceType:e.type,targetName:e.name,nativeCaps:r.nativeCaps,targetFields:r.wireable,onCancel:i,save:async e=>{let t=await n.save(e);return t.kind===`saved`&&i(),t}})}function gc({state:e}){let{t}=Z();switch(e.kind){case`pending`:return u(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:t(`customize.status.pending`)});case`unknown`:return u(Dt,{title:t(`customize.status.unknownTitle`),message:e.reason});case`not-loaded`:return u(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:t(`customize.status.notLoaded`,{reason:e.reason})});case`none`:return null;case`present`:{let n=e.view.block;return r(`div`,{className:`flex flex-wrap items-center gap-2`,children:[u(on,{variant:n.status===`running`?`success`:n.status===`failed`?`danger`:`warning`,children:t(`customize.blockStatus.${n.status}`)}),!n.enabled&&u(on,{variant:`default`,children:t(`customize.status.off`)}),n.lastError!==void 0&&u(`span`,{className:`text-[11px] text-foreground-muted break-words`,children:n.lastError}),e.view.state.kind===`unreachable`&&u(`span`,{className:`text-[11px] text-warning`,children:t(`customize.status.composerUnreachable`,{reason:e.view.state.error})})]})}}}function _c({handle:e}){let{t}=Z(),n=$t(),[i,a]=c(null);if(e.state.kind!==`present`)return null;let o=async()=>{if(!await n({title:t(`customize.remove.title`),message:t(`customize.remove.message`),confirmLabel:t(`customize.remove.confirm`),variant:`danger`}))return;let r=await e.save(null);a(r.kind===`refused`?r.reason:null)};return r(`div`,{className:`flex flex-col items-start gap-1`,children:[u(X,{variant:`danger`,size:`sm`,disabled:e.saving,onClick:()=>void o(),children:t(`customize.remove.button`)}),i!==null&&u(`p`,{role:`alert`,className:`text-[11px] text-danger break-words`,children:i})]})}var vc=`overview`;function yc(e,t){return e.some(e=>e.id===t)?t:vc}function bc({deviceId:e}){let t=s(),n=Number.isFinite(e),{data:i}=vr({deviceId:e},{enabled:n}),a=typeof i?.type==`string`?i.type:`camera`;or([`deviceManager`,`getBindings`],[`capability.binding-changed`]);let{data:o,isLoading:c,isError:l,error:d}=dr({deviceId:e},{enabled:n}),{data:f}=An({deviceType:a},{enabled:!!a}),p=kr({onSuccess:()=>{t.invalidateQueries({queryKey:[[`deviceManager`,`getBindings`]]})}});if(c)return u(`div`,{className:`p-4`,children:u(`div`,{className:`h-20 rounded-lg border border-border bg-surface animate-pulse`})});if(l)return r(`div`,{className:`p-4 text-xs text-red-400`,children:[`Failed to load bindings: `,d instanceof Error?d.message:String(d)]});let m=new Map,h={};for(let e of f??[])h[e.capName]=e.wrappers;for(let e of o?.entries??[])m.set(e.capName,{...e,wrappers:h[e.capName]??[]});for(let e of f??[])m.has(e.capName)||m.set(e.capName,{capName:e.capName,kind:`unbound`,providerAddonId:``,providerNodeId:``,nativeAddonId:``,wrappers:e.wrappers});let g=[...m.values()].toSorted((e,t)=>e.capName.localeCompare(t.capName));if(g.length===0)return r(`div`,{className:`flex flex-col items-center justify-center gap-2 p-8 text-foreground-subtle`,children:[u(K,{className:`h-8 w-8 opacity-40`}),u(`p`,{className:`text-xs`,children:`No capability providers applicable to this device yet.`}),u(`p`,{className:`text-[10px] opacity-60`,children:`Native providers show up here as soon as the owning addon registers them.`})]});let _=g.filter(e=>e.kind!==`unbound`).length;return r(`div`,{className:`flex flex-col gap-3 p-1`,children:[r(`div`,{className:`text-[11px] text-foreground-subtle`,children:[u(`span`,{className:`font-medium text-foreground`,children:_}),` of `,g.length,` capabilit`,g.length===1?`y`:`ies`,` bound — rows marked `,u(`em`,{children:`unbound`}),` have a wrapper available you can activate.`]}),u(vt,{columns:[{key:`capability`,header:`Capability`,render:e=>u(`span`,{className:`font-mono text-foreground`,children:e.capName})},{key:`kind`,header:`Kind`,render:e=>u(xc,{kind:e.kind})},{key:`provider`,header:`Active Provider`,render:e=>u(`span`,{className:`font-mono text-foreground-subtle`,children:e.providerAddonId||u(`span`,{className:`opacity-40`,children:`—`})})},{key:`node`,header:`Node`,render:e=>e.providerNodeId?u(Sc,{nodeId:e.providerNodeId}):u(`span`,{className:`text-[10px] opacity-40`,children:`—`})},{key:`native`,header:`Native`,render:e=>u(`span`,{className:`font-mono text-foreground-subtle`,children:e.nativeAddonId||u(`span`,{className:`opacity-40`,children:`—`})})},{key:`wrapper`,header:`Wrapper`,render:t=>{let n=t.kind===`wrapped`?t.providerAddonId:null;return u(Cc,{wrappers:t.wrappers,activeWrapperId:n,disabled:p.isPending,onPick:r=>{let i=n===r;p.mutate({deviceId:e,capName:t.capName,wrapperAddonId:r,active:!i})}})}}],rows:g,rowKey:e=>e.capName,minWidthPx:720})]})}function xc({kind:e}){return e===`native`?r(`span`,{className:`inline-flex items-center gap-1 rounded-md border border-success/30 text-success bg-success/5 px-1.5 py-0.5 text-[10px] font-medium`,children:[u(de,{className:`h-3 w-3`}),`native`]}):e===`wrapped`?r(`span`,{className:`inline-flex items-center gap-1 rounded-md border border-primary/30 text-primary bg-primary/5 px-1.5 py-0.5 text-[10px] font-medium`,children:[u(we,{className:`h-3 w-3`}),`wrapped`]}):e===`linked`?r(`span`,{className:`inline-flex items-center gap-1 rounded-md border border-warning/30 text-warning bg-warning/5 px-1.5 py-0.5 text-[10px] font-medium`,children:[u(ne,{className:`h-3 w-3`}),`linked`]}):r(`span`,{className:`inline-flex items-center gap-1 rounded-md border border-border text-foreground-subtle/70 px-1.5 py-0.5 text-[10px] font-medium`,children:[u(se,{className:`h-3 w-3`}),`unbound`]})}function Sc({nodeId:e}){return u(`span`,{className:`inline-flex items-center rounded-md border border-border px-1.5 py-0.5 font-mono text-[10px] ${e===`hub`?`text-foreground-subtle`:`text-foreground`}`,children:e})}function Cc({wrappers:e,activeWrapperId:t,disabled:n,onPick:i}){return e.length===0?u(`span`,{className:`text-[10px] opacity-40`,children:`none available`}):u(`div`,{className:`flex flex-wrap gap-1`,children:e.map(e=>{let a=e===t;return r(`button`,{disabled:n,onClick:()=>i(e),title:a?`Click to deactivate (revert to native)`:`Activate wrapper ${e}`,className:`inline-flex items-center gap-1 rounded-md border px-1.5 py-0.5 font-mono text-[10px] transition-colors disabled:opacity-50 ${a?`border-primary/40 bg-primary/10 text-primary`:`border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover`}`,children:[u(a?V:fe,{className:`h-3 w-3`}),e]},e)})})}function wc({deviceId:e,activeSubTab:t,onSubTabChange:n,deviceType:i,isAdmin:a}){return r(`div`,{className:`flex flex-col gap-3`,children:[Xr(i,a)&&u(Nt,{deviceId:e,readOnly:!0}),u(Pr,{deviceId:e,activeSubTab:t,onSubTabChange:n})]})}n();var Tc=[[`pipelineOrchestrator`,`getCameraDetectionSource`]];function Ec(t){let n=s(),r=dt({deviceId:t},{refetchOnMount:`always`}),i=en(),[a,o]=c(null),[l,u]=c(null),d=e(async e=>{u(null),o(e);try{await i.mutateAsync({deviceId:t,source:e}),await n.invalidateQueries({queryKey:Tc})}catch(e){u(e instanceof Error?e.message:`Could not change the root detector`),await n.invalidateQueries({queryKey:Tc})}finally{o(null)}},[t,i,n]),f=r.data??null;return{view:f,isLoading:r.isLoading,source:a??f?.source??null,saving:a!==null,error:l,pick:d}}var Dc=`object-detection`;function Oc(e){return[e.addonId,...e.children.flatMap(Oc)]}function kc(e,t){if(e===`pipeline`)return new Set;let n=Ac(t,Dc);return n===void 0?new Set:new Set(e===`onboard`?[n.addonId]:Oc(n))}function Ac(e,t){for(let n of e){if(n.addonId===t)return n;let e=Ac(n.children,t);if(e!==void 0)return e}}function jc(e,t){return e===`onboard`?`Camera AI`:t===`object-detection`?`No root`:`Idle`}function Mc(e){switch(e){case`pipeline`:return`This node detects: the root step runs on decoded frames and every step below it applies.`;case`onboard`:return`The camera detects: its own boxes replace the root step, so the accelerator is not asked. The steps below it still run on crops from this node's frames.`;case`none`:return`No root detector: nothing is detected on this camera, so every video step below the root is idle.`}}function Nc(e){switch(e){case`boxed`:return``;case`while-streaming`:return`Its boxes ride the stream that is already open, so they exist only while the camera is awake; between wake-ups it reports nothing.`;case`flag-only`:return`Its onboard AI reports a class with no bounding box, so it cannot be the root detector.`;case`unknown`:return`This camera has not said whether its detections carry a bounding box; without one it cannot be the root detector.`}}function Pc(e,t){return e===`onboard`?`Not running here: this camera's own detector is the root, so this node's root step is never asked. These settings apply again if you switch the root detector back to this node.`:t===`object-detection`?`Not running here: this camera has no root detector.`:`Idle: this camera has no root detector, so there is nothing for this step to work on.`}function Fc({source:e,geometry:t,saving:n,error:i,onPick:a}){let o=t===`flag-only`,s=Nc(t);return r(`section`,{"aria-label":`Root detector`,"aria-busy":n,className:`space-y-1.5 rounded-md border border-border bg-surface px-3 py-2`,children:[r(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1.5`,children:[u(`h3`,{className:N,children:`Root detector`}),u(Bn,{label:`Root detector`,value:e,onChange:t=>{!n&&t!==e&&a(t)},options:[{value:`pipeline`,label:`This node`},{value:`onboard`,label:`Camera onboard AI`,disabled:o&&e!==`onboard`,reason:s},{value:`none`,label:`None`}]}),n&&u(`span`,{className:`text-[10px] text-foreground-subtle`,children:`Saving…`})]}),r(`p`,{className:he,children:[Mc(e),` A camera runs one root detector at a time.`]}),s!==``&&u(`p`,{className:`text-[10px] text-foreground-subtle`,children:s}),i!==null&&u(`p`,{role:`alert`,className:`text-[11px] text-danger`,children:i})]})}n();var Ic=new Set([`package-detection`]);function Lc(e){return e?.settings!==void 0&&Object.keys(e.settings).length>0?`accelerator`:`camera`}function Rc(e){return e===`camera`?`this camera`:e===`node`?`node pin`:`hardware default`}function zc(e){let{stored:t,draft:n,below:r,boundKeys:i}=e,a=n?.modelId===void 0?t?.modelId:n.modelId??void 0,o=Qe(n?.settings??t?.settings,r,i),s={...a===void 0?{}:{modelId:a},...o===void 0?{}:{settings:o}};return Object.keys(s).length>0?s:null}function Bc(e,t){return(e?.modelId??null)===(t?.modelId??null)&&qe(e?.settings??{},t?.settings??{})}function Vc({deviceId:e}){let t=s(),n=W().trpcClient,l=Pt({deviceId:e},{refetchOnMount:`always`}),d=zn({deviceId:e},{refetchOnMount:`always`}),f=Kt(void 0,{refetchOnMount:`always`}),p=We(Yn({addonId:`pipeline-orchestrator`}).data??null);or([`nodes`,`topology`],[`agent.online`,`agent.offline`,`agent.unregistered`,`addon.installed`,`addon.uninstalled`]);let{nodes:m}=xn(),h=i(()=>{let e=new Set((f.data??[]).map(e=>e.nodeId));return m.filter(t=>t.isOnline&&e.has(t.id)).map(e=>({id:e.id,name:e.name}))},[f.data,m]),g=h.map(e=>e.id).join(`,`),_=a({enabled:h.length>0,queryKey:[[`pipelineExecutor`,`getSchema`],`camera-step-schemas`,g],queryFn:async()=>{let e={};for(let t of h)try{e[t.id]=await n.pipelineExecutor.getSchema.query({nodeId:t.id})}catch{}return e}}),v=a({enabled:h.length>0,queryKey:[[`pipelineOrchestrator`,`getNodeInferenceDevices`],`camera-step`,g],queryFn:async()=>{let e={};for(let t of h)try{e[t.id]=(await n.pipelineOrchestrator.getNodeInferenceDevices.query({nodeId:t.id})).devices}catch{e[t.id]=[]}return e}}),y=()=>{t.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getCameraSettings`]]}),t.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getCameraStepOverrides`]]})},b=hr({onSuccess:y}),x=rt(),S=Sn(),[C,w]=c(null),[T,E]=c(null),[D,O]=c(null),[k,A]=c(!1),[j,M]=c(null),P=_.data??{},F=v.data??{},I=d.data??{},L=l.data??null,R=h.map(e=>P[e.id]).find(e=>e!==void 0)??null,z=i(()=>R?Rt(R):[],[R]),ee=i(()=>Pi(z),[z]),B=Ec(e),V=i(()=>B.source===null?new Set:kc(B.source,z),[B.source,z]),[H,te]=c(!1),ne=i(()=>Li(h,F,H),[h,F,H]),re=i(()=>Li(h,F,!0),[h,F]),ie=i(()=>Li(h,F).length,[h,F]),ae=(e,t)=>Oi(P[e.nodeId],t),U=(e,t)=>I[e.nodeId]?.[e.deviceKey]?.[t],oe=(e,t)=>Hi(F[e.nodeId]??[],e.deviceKey,t)??{},se=e=>{if(Ic.has(e))return{kind:`zone-driven`};let t=Oi(R,e)?.enabledByDefault??!0,n=L?.stepToggles?.[e];return{kind:`gate`,effectiveOn:n??t,defaultOn:t,explicit:n!==void 0}},ce=(e,t,n)=>{let r=n?.stepId===t?n:null;return{node:oe(e,t),camera:r?.camera??L?.stepSettings?.[t],accelerator:r?.perAccelerator[e.id]?.settings??U(e,t)?.settings}},G=(e,t,n)=>{let r=n?.stepId===t?n.perAccelerator[e.id]?.modelId:void 0;return r===void 0?U(e,t)?.modelId:r??void 0},le=(e,t)=>{if(V.has(e))return{kind:`disabled`};let n=ae(t,e),r=se(e),i=Ii(e),a=ki(P[t.nodeId],t,U(t,`object-detection`)?.modelId),o=ce(t,e,null),s=Ye(o.node,o.camera,o.accelerator);return zi({addon:n,acc:t,gatedOn:r.kind===`gate`?r.effectiveOn:!0,model:n?Fi(n,t,{nodePin:t.device.steps?.[e]?.modelId,cameraPin:U(t,e)?.modelId}):{modelId:void 0,source:`default`},...Mi(e,s,a)&&a?{rootName:a.name}:{},...i?{clusterModelId:p[e]??i.defaultModelId}:{}})},ue=ee.map(({node:e})=>({addonId:e.addonId,name:e.addonName,fieldLabels:Ri(Oi(R,e.addonId))}));return f.isLoading||h.length>0&&(_.isLoading||v.isLoading)?u(`div`,{className:`animate-pulse p-4 text-xs text-foreground-subtle`,children:`Loading pipeline…`}):h.length===0?u(`div`,{className:`p-4 text-xs text-foreground-subtle`,children:`No pipeline node is online.`}):R===null?u(`div`,{className:`p-4 text-xs text-foreground-subtle`,children:`Catalog unavailable.`}):r(`div`,{className:`space-y-2`,children:[B.view?.onboard.available===!0&&B.source!==null&&u(Fc,{source:B.source,geometry:B.view.onboard.geometry,saving:B.saving,error:B.error,onPick:e=>void B.pick(e)}),u(Di,{tree:z,searchRows:ue,accelerators:ne,cellState:le,stepBadge:e=>V.has(e)&&B.source!==null?u(on,{variant:`warning`,title:Pc(B.source,e),children:jc(B.source,e)}):u(it,{gate:se(e)}),disabledCount:Vi(Object.fromEntries(h.map(e=>[e.id,F[e.id]??[]]))),showDisabled:H,onShowDisabledChange:te,dirty:C!==null,onDiscard:()=>w(null),summary:r(`span`,{className:he,children:[`This camera is balanced across `,ie,` accelerator`,ie===1?``:`s`,` at every session start · ovr = this camera overrides the node`]}),label:`Detection steps of this camera`,renderDetail:({stepId:t,accelerator:n,matchedField:i,closeButton:a,onEscape:s,headingRef:c})=>{let l=n??ne[0],d=l?ae(l,t)??Oi(R,t):null;if(d===null||l===void 0)return u(`div`,{className:`p-4 text-xs text-foreground-subtle`,children:`No step selected.`});let f=C?.stepId===t?C:null,p=Gn(d),m=Ne(p),h=ce(l,t,f),g=Ye(h.node,h.camera,h.accelerator),_=ki(P[l.nodeId],l,U(l,`object-detection`)?.modelId),v=Fi(d,l,{nodePin:l.device.steps?.[t]?.modelId,cameraPin:G(l,t,f)}).modelId,F=Ye(h.node,h.camera),I=Ie(h.accelerator,F,m),z=Ii(t),ee=se(t),H=p.find(e=>`label`in e&&e.label===i)?.key??null,te=n===null?null:`${t}|${n.id}`,ie=n===null?`camera`:T?.key===te?T.scope:Lc(U(n,t)),W=e=>{M(null),w(n=>e(n?.stepId===t?n:{stepId:t,perAccelerator:{}}))},le=(e,t)=>W(n=>({...n,perAccelerator:{...n.perAccelerator,[e.id]:{...n.perAccelerator[e.id],...t}}})),ue=e=>W(n=>{let r=h.accelerator??{},i=ze(n.camera??L?.stepSettings?.[t],e,r,m),a={...n.perAccelerator};for(let r of re){let i=n.perAccelerator[r.id]?.settings??U(r,t)?.settings;i!==void 0&&(a[r.id]={...a[r.id],settings:Me(i,e,m)})}return{...n,camera:i,perAccelerator:a}}),de=async()=>{if(f!==null){A(!0);try{let n=L?.stepSettings?.[t];f.camera!==void 0&&!qe(f.camera,n??{})&&await S.mutateAsync({deviceId:e,addonId:t,settings:Object.keys(f.camera).length>0?{...f.camera}:null});let r=f.camera??n;for(let n of re){let i=f.perAccelerator[n.id];if(i===void 0)continue;let a=U(n,t),o=zc({stored:a,draft:i,below:Ye(oe(n,t),r),boundKeys:m});Bc(o,a)||await x.mutateAsync({deviceId:e,agentNodeId:n.nodeId,deviceKey:n.deviceKey,addonId:t,patch:o})}w(null),M({kind:`saved`})}catch(e){M({kind:`error`,error:e instanceof Error?e.message:`Save failed`})}finally{A(!1),y()}}},fe=f===null?0:+(f.camera!==void 0&&!qe(f.camera,L?.stepSettings?.[t]??{}))+Object.values(f.perAccelerator).length,pe=e=>{let n=ae(e,t)??d,i=G(e,t,f),a=e.device.steps?.[t]?.modelId,s=Fi(n,e,{nodePin:a,cameraPin:i}),c=ce(e,t,f),l=ki(P[e.nodeId],e,U(e,`object-detection`)?.modelId),p=Mi(t,Ye(c.node,c.camera,c.accelerator),l),m=Ai(n,e)?p&&l?u(fr,{rootModel:l,stepModelId:s.modelId}):void 0:r(o,{children:[`No `,e.device.format,` build of this step — it does not run on this accelerator.`]});return{label:e.label,format:e.device.format,modelId:s.modelId,source:s.source,sourceLabel:Rc(s.source),models:jn(n.models??[],e.device.format),defaultModelId:n.defaultModelIdByFormat?.[e.device.format]??n.defaultModelId,expanded:D===e.id,onToggle:()=>O(t=>t===e.id?null:e.id),onChangeModel:t=>le(e,{modelId:t}),...i===void 0?{}:{onReset:()=>le(e,{modelId:null}),resetLabel:a===void 0?`Reset to hardware default`:`Reset to node pin`},...m===void 0?{}:{note:m},changed:f?.perAccelerator[e.id]?.modelId!==void 0}},me=z===null&&p.length>0?n===null?u(`p`,{className:he,children:`Applies to: all accelerators of this camera.`}):r(`div`,{className:`flex flex-wrap items-center gap-2`,children:[u(`span`,{className:`text-[11px] font-medium text-foreground`,children:`Applies to`}),u(Bn,{label:`Settings apply to`,options:[{value:`accelerator`,label:`This accelerator`},{value:`camera`,label:`All accelerators of this camera`}],value:ie,onChange:e=>te!==null&&E({key:te,scope:e})})]}):void 0;return u(zt,{ref:c,title:n===null?`${d.name} · this camera`:`${d.name} · ${n.label}`,subtitle:n===null?`${d.slot} · every accelerator this camera runs on`:`${d.slot} · ${n.device.format}`,leading:a,onEscape:s,headerActions:u(In,{gate:ee,busy:b.isPending,onSet:n=>b.mutate({deviceId:e,addonId:t,enabled:n})}),saveBar:{dirtyCount:fe,saving:k,status:j?.kind??null,...j?.error===void 0?{}:{error:j.error},onSave:()=>void de(),onDiscard:()=>w(null),...me===void 0?{}:{scope:me}},children:r(`div`,{className:`space-y-3`,children:[V.has(t)&&B.source!==null&&u(`p`,{role:`note`,className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-1.5 text-[11px] text-warning`,children:Pc(B.source,t)}),r(`section`,{className:`space-y-2`,"aria-label":`Model`,children:[u(`h3`,{className:N,children:`Model`}),z===null?n===null?u(ji,{rows:ne.map(e=>{let n=Fi(ae(e,t)??d,e,{nodePin:e.device.steps?.[t]?.modelId,cameraPin:G(e,t,f)});return{id:e.id,label:e.label,modelId:n.modelId,sourceLabel:Rc(n.source)}})}):u(Sr,{...pe(n)},n.id):u(Bi,{step:z,engineFormat:l.device.format,runnableModelIds:jn(d.models??[],l.device.format).map(e=>e.id)})]}),z===null&&(p.length>0||_!==void 0)&&u(`section`,{"aria-label":`Settings`,className:`border-t border-border/60 pt-2`,children:u(Hc,{addon:d,fields:p,layers:h,scope:ie,viewed:n,modelId:pn(d,v,g,_),root:_,pinned:n===null?[]:I,highlightKey:H,onChangeCamera:e=>W(t=>({...t,camera:e})),onChangeAccelerator:e=>le(l,{settings:e}),onApplyToAll:ue,onFollowNode:()=>le(l,{settings:I.reduce((e,t)=>Me(e,t,m),{...h.accelerator})})})}),u(Ei,{addonId:t,highlightLabel:i})]})})}})]})}function Hc({addon:e,fields:t,layers:n,scope:i,viewed:a,modelId:o,root:s,pinned:c,highlightKey:l,onChangeCamera:d,onChangeAccelerator:f,onApplyToAll:p,onFollowNode:m}){Ni(l===null?null:yn(l));let h=a!==null&&n.accelerator!==void 0;return u(br,{addon:e,fields:t,layers:{node:n.node,...n.camera===void 0?{}:{camera:n.camera},...h?{accelerator:n.accelerator}:{}},target:i,labels:{...a===null?{}:{accelerator:`This accelerator`},camera:`All accelerators`,node:`Node`},modelId:o,...s===void 0?{}:{rootModel:s},pinnedKeys:c,highlightKey:l,onChangeLayer:i===`camera`?d:f,...c.length>0?{headerActions:r(`button`,{type:`button`,className:oe,onClick:m,children:[`Follow the node for `,c.length,` pinned field`,c.length===1?``:`s`]})}:{},fieldActions:(e,t)=>a!==null&&t===`accelerator`?u(`button`,{type:`button`,className:oe,onClick:()=>p(e),children:`Apply to all accelerators`}):null})}var Uc=[{id:`object-detection`,label:`Object detection`,icon:`scan-search`},{id:`tracking`,label:`Tracking`,icon:`route`},{id:`motion`,label:`Motion`,icon:`activity`},{id:`stationary`,label:`Stationary`,icon:`square-parking`},{id:`zones`,label:`Zones`,icon:`shapes`},{id:`audio`,label:`Audio`,icon:`volume-2`},{id:`cluster`,label:`Cluster`,icon:`server`}],Wc={"pipeline-object-detection":`object-detection`,"detection-sensitivity":`object-detection`,"onboard-object-detection":`object-detection`,tracking:`tracking`,"tracking-core":`tracking`,"motion-tuning":`motion`,"stationary-objects":`stationary`,occupancy:`stationary`,zones:`zones`,"pipeline-audio":`audio`,"cluster-assignment":`cluster`,"orchestrator-live":`cluster`};function Gc(e){return Wc[e]??`object-detection`}n();var Kc=`steps`,qc=`settings`,Jc=new Set([Kc,qc]);function Yc(e){return e.location===`top-tab`&&(e.tab===`detection-pipeline`||e.tab===`zones`)}function Xc({deviceId:t,activeSubTab:n,onSubTabChange:i}){return r(Cn,{value:n&&Jc.has(n)?n:Kc,onValueChange:e(e=>{i?.(e)},[i]),className:`flex flex-col`,children:[r(Zn,{className:`flex-shrink-0`,children:[u(sr,{value:Kc,children:`Steps`}),u(sr,{value:qc,children:`Settings`})]}),u(gr,{value:Kc,children:u(Vc,{deviceId:t})}),u(gr,{value:qc,children:u(Pr,{deviceId:t,sectionFilter:Yc,subTabGrouping:{groupOf:e=>Gc(e.id),tabs:Uc}})})]})}var Zc=`Notifications`,Qc=`This camera never notifies — no rule, no target, no alarm. Existing events, tracks and recordings are unaffected.`;function $c(e){let{mutedDeviceIds:t,deviceId:n}=e,r=t===null?null:!t.includes(n),i=e.pendingOn??null;return{label:Zc,on:r===null?null:i??r,available:r!==null,costWhenOff:Qc}}function el(e,t){return!e.available||e.on===null?null:{deviceId:t,muted:e.on}}n();function tl(e){if(typeof e!=`object`||!e)return null;let t={...e}.mutedDeviceIds;return Array.isArray(t)?t.filter(e=>typeof e==`number`):null}function nl({deviceId:t}){let n=s(),i=Number.isFinite(t),[a,o]=c(null),[l,d]=c(null),f=$c({mutedDeviceIds:tl(cr({},{enabled:i}).data),deviceId:t,pendingOn:l}),p=sn({onError:e=>{console.error(`[DeviceNotificationMute] mute write failed — reverting`,{tags:{deviceId:t},meta:{error:e instanceof Error?e.message:String(e)}}),d(null),o(e instanceof Error?e.message:String(e)),n.invalidateQueries({queryKey:[[`notificationRules`,`listDeviceMutes`]]})},onSuccess:()=>{o(null),d(null),n.invalidateQueries({queryKey:[[`notificationRules`]]})}}),h=e(()=>{let e=el(f,t);e!==null&&(d(!e.muted),p.mutate(e))},[t,p,f]),g=f.on===null,_=f.on===!1,v=_?xe:m;return r(`div`,{className:`rounded-lg border border-border bg-surface overflow-hidden`,children:[r(`div`,{className:`border-b border-border px-4 py-2 flex items-center justify-between gap-2`,children:[u(`h2`,{className:`text-xs font-semibold text-foreground uppercase tracking-wider`,children:`Notifications`}),_&&u(`span`,{className:`rounded bg-warning/20 px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-wide text-warning`,children:`muted`})]}),r(`div`,{className:`px-4 py-3 flex items-start gap-3`,children:[r(`button`,{type:`button`,role:`switch`,"aria-label":f.label,"aria-checked":f.on===!0,disabled:!f.available||p.isPending,onClick:h,title:g?`Notification mute — state unknown; the notification centre did not answer.`:_?`Muted. ${f.costWhenOff}`:`Notifying. Muting it: ${f.costWhenOff}`,className:`inline-flex items-center gap-1.5 rounded-lg border px-2 py-1.5 text-[11px] font-medium transition-colors disabled:cursor-not-allowed ${a===null?g?`border-dashed border-border text-foreground-subtle/50`:_?`border-warning/40 text-warning hover:bg-warning/10`:`border-success/30 text-success hover:bg-success/10`:`border-danger/50 text-danger bg-danger/5`}`,children:[u(v,{className:`h-3.5 w-3.5`}),u(`span`,{children:g?`Unknown`:_?`Muted`:`Notifying`})]}),u(`p`,{className:`flex-1 text-[11px] leading-relaxed text-foreground-subtle`,children:a===null?g?`The notification centre did not answer, so this device’s mute state is unknown.`:f.costWhenOff:`Write failed: ${a}`})]})]})}function rl(e,t){return{switchId:e,label:He[e].label,detail:t===void 0||t.length===0?null:t}}function il(e){let t=new Map;for(let n of e.switches)n.deviceId===e.sourceId&&(t.has(n.switchId)||t.set(n.switchId,n));return t}function al(e){let t=il(e),n=new Set(e.sourceStillLive),r=e.sourceStillLive.map(e=>rl(e,t.get(e)?.detail)),i=[...t.values()].filter(e=>e.outcome===`not-offered`&&!n.has(e.switchId)).map(e=>rl(e.switchId,e.detail));return{inheritedId:e.sourceId,retiredId:e.targetId,swapped:e.swapped,verdict:r.length===0?`quiet`:`still-live`,stillLive:r,neverOffered:i}}n();function ol(e,t){return e.filter(e=>e.isCamera&&e.id!==t).map(e=>({id:e.id,name:e.name})).toSorted((e,t)=>e.name.localeCompare(t.name))}function sl({deviceId:e,deviceName:t}){let{t:n}=Z(),a=$t(),[o,s]=c(null),l=qn({isCamera:!0,projection:`slim`}),d=un(),f=l.data!==void 0,p=i(()=>l.data===void 0?[]:ol(l.data,e),[l.data,e]),m=p.find(e=>e.id===o)??null,h=d.data===void 0?null:al(d.data),g=d.error===null?null:d.error.message,_=async()=>{m===null||m.id===e||await a({title:n(`deviceMigrate.confirmTitle`,`Replace “{{source}}” with “{{target}}”?`,{source:t,target:m.name}),message:n(`deviceMigrate.confirmMessage`,`“{{target}}” takes over number {{sourceId}}. That number is what every recording, event, rule, zone and home-automation export of “{{source}}” is filed under, so all of it follows the number to the new hardware and keeps working. “{{source}}” is switched off and handed number {{targetId}} in exchange. This swaps two device identities and cannot be undone from here.`,{source:t,target:m.name,sourceId:e,targetId:m.id}),confirmLabel:n(`deviceMigrate.confirmAction`,`Migrate`),variant:`danger`})&&d.mutate({sourceId:e,targetId:m.id})};return r(`div`,{className:`rounded-lg border border-border bg-surface px-4 py-3`,children:[r(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[r(`div`,{className:`min-w-0`,children:[u(`h2`,{className:`text-xs font-semibold uppercase tracking-wider text-foreground`,children:n(`deviceMigrate.title`,`Migrate to…`)}),u(`p`,{className:`mt-0.5 text-[11px] text-foreground-subtle`,children:n(`deviceMigrate.subtitle`,`Replace this camera with other hardware you have already adopted. The new camera inherits number {{deviceId}}, so recordings, rules and integrations follow it.`,{deviceId:e})})]}),r(`div`,{className:`flex shrink-0 items-center gap-2`,children:[r(`select`,{"aria-label":n(`deviceMigrate.pickerLabel`,`Replacement camera`),className:`rounded-md border border-border bg-background px-2 py-1.5 text-xs text-foreground disabled:opacity-50`,disabled:!f||p.length===0||d.isPending,value:o===null?``:String(o),onChange:e=>{let t=e.target.value;s(t===``?null:Number(t))},children:[u(`option`,{value:``,children:f?n(`deviceMigrate.pickerPlaceholder`,`Select a camera…`):n(`deviceMigrate.pickerPending`,`Reading the fleet…`)}),p.map(e=>r(`option`,{value:String(e.id),children:[e.name,` (#`,e.id,`)`]},e.id))]}),r(`button`,{type:`button`,disabled:m===null||d.isPending,onClick:()=>{_()},className:`inline-flex shrink-0 items-center gap-1.5 rounded-md border border-border bg-background px-3 py-1.5 text-xs font-medium text-foreground hover:bg-surface disabled:opacity-50`,children:[u(_e,{className:`h-3 w-3`}),d.isPending?n(`deviceMigrate.running`,`Migrating…`):n(`deviceMigrate.action`,`Migrate`)]})]})]}),f&&p.length===0&&u(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:n(`deviceMigrate.noTargets`,`No other camera is adopted, so there is nothing to migrate to.`)}),g!==null&&u(`p`,{className:`mt-2 text-[11px] text-danger`,children:n(`deviceMigrate.failed`,`Migration failed: {{error}}`,{error:g})}),h!==null&&u(cl,{report:h})]})}function cl({report:e}){let{t}=Z(),n=e.verdict===`quiet`;return r(`div`,{className:`mt-3 space-y-2 border-t border-border pt-3`,children:[u(`p`,{className:`text-[11px] text-foreground-subtle`,children:t(`deviceMigrate.swapped`,`The replacement now answers on number {{inheritedId}}; the old camera was handed number {{retiredId}}.`,{inheritedId:e.inheritedId,retiredId:e.retiredId})}),n?r(`div`,{className:`flex items-start gap-2 rounded-md border border-success/30 bg-success/5 px-3 py-2`,children:[u(re,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-success`}),u(`p`,{className:`text-[11px] leading-relaxed text-foreground`,children:t(`deviceMigrate.quiet`,`Every function on the replaced camera was switched off — the old hardware is quiet.`)})]}):r(`div`,{className:`rounded-md border border-warning/40 bg-warning/5 px-3 py-2`,children:[r(`div`,{className:`flex items-start gap-2`,children:[u(H,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`}),u(`p`,{className:`text-[11px] leading-relaxed text-foreground`,children:t(`deviceMigrate.stillLive`,`The replaced camera could not be reached, so these functions are STILL RUNNING on the old hardware. Nothing here failed to migrate — but until you unplug it or reach it physically, it can still produce data.`)})]}),u(`ul`,{className:`mt-2 space-y-1 pl-5`,children:e.stillLive.map(e=>r(`li`,{className:`text-[11px] text-foreground`,children:[u(`span`,{className:`font-medium`,children:e.label}),e.detail!==null&&r(`span`,{className:`text-foreground-subtle`,children:[` — `,e.detail]})]},e.switchId))})]}),e.neverOffered.length>0&&r(`div`,{className:`rounded-md border border-border px-3 py-2`,children:[r(`div`,{className:`flex items-start gap-2`,children:[u(Ce,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),u(`p`,{className:`text-[11px] leading-relaxed text-foreground-subtle`,children:t(`deviceMigrate.neverOffered`,`The replaced camera never offered these, so there was nothing to switch off. They are not running.`)})]}),u(`ul`,{className:`mt-2 space-y-1 pl-5`,children:e.neverOffered.map(e=>u(`li`,{className:`text-[11px] text-foreground-subtle`,children:e.label},e.switchId))})]})]})}n();function ll({deviceId:e}){let[t,n]=c(null),i=Ft({onSuccess:e=>{n(e.changed?`Re-aligned with source — ${e.rebuiltChildren} child${e.rebuiltChildren===1?``:`ren`} rebuilt.`:`Already up to date.`)},onError:e=>n(`Re-sync failed: ${e.message}`)});return r(`div`,{className:`rounded-lg border border-border bg-surface px-4 py-3`,children:[r(`div`,{className:`flex items-center justify-between gap-3`,children:[r(`div`,{children:[u(`h2`,{className:`text-xs font-semibold uppercase tracking-wider text-foreground`,children:`Re-sync`}),u(`p`,{className:`mt-0.5 text-[11px] text-foreground-subtle`,children:`Re-align this device's type, role, capabilities and units with its source.`})]}),r(`button`,{type:`button`,disabled:i.isPending,onClick:()=>{n(null),i.mutate({camDeviceId:e})},className:`inline-flex shrink-0 items-center gap-1.5 rounded-md border border-border bg-background px-3 py-1.5 text-xs font-medium text-foreground hover:bg-surface disabled:opacity-50`,children:[u(me,{className:`h-3 w-3 ${i.isPending?`animate-spin`:``}`}),i.isPending?`Re-syncing…`:`Re-sync`]})]}),t!==null&&u(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:t})]})}function ul(e){return e<1e3?`${e.toFixed(0)} kbps`:`${(e/1e3).toFixed(1)} Mbps`}function dl({device:e}){let t=Kr(),n=typeof e.id==`number`?e.id:null,i=String(e.type??``),a=i===Y.Camera,o=i===Y.Hub,s=e.features??[],c=s.includes(Ge.Resyncable),{data:l}=Zt({deviceId:n??0},{enabled:n!==null&&a,refetchInterval:5e3}),d=l?.streams??{},f=Object.entries(d),p=s.includes(Ge.DoorbellButton),m=Nn(p?{deviceId:n??void 0,historyLimit:10}:void 0),h=m.latest?Date.now()-m.latest.timestamp<3e4:!1;return r(`div`,{className:`space-y-5`,children:[o&&n!==null&&u(ar,{deviceId:n,onOpenChild:e=>t(`/devices/${e}`)}),c&&n!==null&&u(ll,{deviceId:n}),a&&n!==null&&u(sl,{deviceId:n,deviceName:String(e.name??``)}),n!==null&&u(nl,{deviceId:n}),a&&n!==null&&u(Cr,{widgetId:`pipeline-orchestrator/pipeline-quick-stats`,host:`device-tab`,deviceId:n}),p&&u(wt,{history:m.history,latestIsFresh:h}),a&&n!==null&&u(Cr,{widgetId:`stream-broker/stream-broker-panel`,host:`device-tab`,deviceId:n}),a&&f.length>0&&r(`div`,{className:`@container rounded-lg border border-border bg-surface overflow-hidden`,style:{containerType:`inline-size`},children:[u(`div`,{className:`border-b border-border px-4 py-2`,children:u(`h2`,{className:`text-xs font-semibold text-foreground uppercase tracking-wider`,children:`Stream Network`})}),u(`div`,{className:`divide-y divide-border`,children:f.map(([e,t])=>r(`div`,{className:`px-4 py-2.5`,children:[r(`div`,{className:`flex items-center gap-2 mb-2`,children:[u(U,{className:`h-3 w-3 text-foreground-subtle`}),u(`span`,{className:`text-[11px] font-medium text-foreground`,children:e})]}),r(`div`,{className:`grid grid-cols-2 @[640px]:grid-cols-4 gap-2`,children:[u(fl,{label:`Nominal`,value:ul(t.nominalBitrateKbps??0)}),u(fl,{label:`Observed`,value:ul(t.observedBitrateKbps??0)}),u(fl,{label:`Peak`,value:ul(t.peakBitrateKbps??0)}),u(fl,{label:`Packet Loss`,value:`${(t.packetLossPercent??0).toFixed(2)}%`,warning:(t.packetLossPercent??0)>1})]})]},e))})]}),u(Hr,{}),n!==null&&u(Fr,{deviceId:n})]})}function fl({label:e,value:t,warning:n}){return r(`div`,{children:[u(`p`,{className:`text-[10px] text-foreground-subtle`,children:e}),u(`p`,{className:`text-xs font-medium ${n?`text-warning`:`text-foreground`}`,children:t})]})}var pl=[{id:`overview`,label:`Overview`,cameraOnly:!1,adminOnly:!1},{id:`config`,label:`Config`,cameraOnly:!1,adminOnly:!1},{id:Qr,label:`Customize`,cameraOnly:!1,adminOnly:!0},{id:`detection-pipeline`,label:`Detection pipeline`,cameraOnly:!0,adminOnly:!1},{id:`bindings`,label:`Bindings`,cameraOnly:!0,adminOnly:!1}];function ml(e,t){let n=e===Y.Camera;return pl.filter(e=>(n||!e.cameraOnly)&&(t||!e.adminOnly)).map(({id:e,label:t})=>({id:e,label:t}))}function hl({provider:e,integrationId:t,name:n}){let r=Kr(),i=t===null?`/integrations`:`/integrations/${t}`,a=n===null?`Open integrations`:`Open integration ${n}`;return u(`button`,{type:`button`,onClick:()=>r(i),className:`shrink-0 rounded-md transition-opacity hover:opacity-80 focus:outline-none focus-visible:ring-1 focus-visible:ring-primary/50`,title:a,"aria-label":a,children:u(Ir,{type:e,size:`lg`})})}n();var gl=[{id:`logs`,icon:ae,label:`Logs`},{id:`repl`,icon:Se,label:`REPL`},{id:`events`,icon:T,label:`Events`},{id:`state`,icon:x,label:`State`}];function _l(){let n=Gr(),a=Number(n.deviceId),l=Number.isFinite(a),d=Kr(),f=s(),p=$t(),m=W(),{user:h}=zr(),g=h?.isAdmin===!0,[v,y]=qr(),b=v.get(`tab`)??`overview`,x=v.get(`sub`),[S,C]=c(`logs`),w=`device-detail.left-col-width-px`,[T,E]=c(()=>{if(typeof window>`u`)return null;let e=window.localStorage.getItem(w),t=e?Number(e):NaN;return Number.isFinite(t)&&t>0?t:null}),D=t(T);D.current=T;function O(e){e.preventDefault();let t=e.clientX,n=e.currentTarget.previousElementSibling?.getBoundingClientRect().width??T??0,r=Math.max(330,Math.floor(window.innerWidth*.7)),i=e=>{E(Math.max(280,Math.min(r,n+(e.clientX-t))))},a=()=>{document.removeEventListener(`mousemove`,i),document.removeEventListener(`mouseup`,a);let e=D.current;if(e!==null)try{window.localStorage.setItem(w,String(Math.round(e)))}catch{}document.body.style.userSelect=``,document.body.style.cursor=``};document.body.style.userSelect=`none`,document.body.style.cursor=`col-resize`,document.addEventListener(`mousemove`,i),document.addEventListener(`mouseup`,a)}let{data:k,isLoading:A,isError:j}=vr({deviceId:a},{enabled:l,refetchInterval:5e3,retry:1}),{data:N}=vn({deviceId:a},{enabled:l}),F=i(()=>{let e=N?.settings?.sections??[],t=N?.live?.sections??[],n=[...e,...t],r=new Set;for(let e of n)e.location===`top-tab`&&e.tab&&r.add(e.tab===`zones`?`detection-pipeline`:e.tab);return n.some(Br)&&r.add(Mr),[...r].map(e=>e===`export`?{id:e,label:Yr,isAddonContrib:!0}:{id:e,label:Be[e]?.label??e,isAddonContrib:!0})},[N]),I=k,L=String(I?.name??n.deviceId??`Device`),R=I?.online===!0,ee=R?`online`:`offline`,B=String(I?.addonId??`rtsp`),V=I?.features??[],H=I?.type,te=H===Y.Camera,{data:ne}=Nr(l?a:0),re=H===Y.Container,ie=i(()=>(ne??[]).map(e=>({id:e.id,stableId:e.stableId,type:e.type,...e.sourceInfo?{sourceInfo:{id:e.sourceInfo.id}}:{}})),[ne]),ae=i(()=>re?On(ie,typeof I?.linkDeviceId==`number`?I.linkDeviceId:null,typeof I?.primaryChildEntityId==`string`?I.primaryChildEntityId:null)?.id??null:null,[re,ie,I?.linkDeviceId,I?.primaryChildEntityId]),{data:U}=vn({deviceId:ae??0},{enabled:ae!==null}),oe=i(()=>{if(ae===null)return[];let e=U?.settings?.sections??[],t=U?.live?.sections??[],n=new Set;for(let r of[...e,...t])r.location===`top-tab`&&r.tab&&n.add(r.tab);return[...n].map(e=>({id:e,label:Be[e]?.label??e,isAddonContrib:!0,childDeviceId:ae}))},[ae,U]),se=typeof I?.parentDeviceId==`number`?I.parentDeviceId:null,{data:ce}=vr({deviceId:se??0},{enabled:se!==null}),G=lr(),le=I?.disabled!==!0,de=i(()=>{let e=N?.settings?.sections??[],t=N?.live?.sections??[];return Vr([...e,...t],H,g,N!==void 0)},[N,H,g]),fe=i(()=>{let e=new Set,t=[];for(let n of[...ml(H,g),...F,...oe])n.id===`config`&&!de||e.has(n.id)||(e.add(n.id),t.push(n));return t},[H,g,F,oe,de]),he=i(()=>yc(fe,b),[fe,b]),ge=e(e=>{y(t=>{let n=new URLSearchParams(t);e===`overview`?n.delete(`tab`):n.set(`tab`,e),n.delete(`sub`);for(let e of Ui)n.delete(e);return n},{replace:!0})},[y]),_e=e(e=>{y(t=>{let n=new URLSearchParams(t);return n.set(`sub`,e),n},{replace:!0})},[y]),ve=(ne??[]).length>0,ye=i(()=>gl.filter(({featureGate:e})=>!e||V.includes(e)),[V]),{data:be}=mn(void 0),xe=i(()=>I?Qn(I,be):null,[I,be]),K=xe?.kind===`resolved`?xe.integration:null,Se=K===null?xe?.kind===`unknown`?`Loading integration…`:xe?.kind===`orphan`?`Missing integration`:`No integration`:K.name,Ce=K!==null&&K.addonId===B?K.name:B,we=ct({onSuccess:()=>{f.invalidateQueries({queryKey:[[`deviceManager`]]}),d(K?.id?`/integrations/${K.id}`:`/integrations`)}}),q=er({onSuccess:()=>{f.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Te=mr({onSuccess:()=>{f.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Ee=Bt(),J=At({onSuccess:()=>{f.invalidateQueries({queryKey:[[`deviceManager`]]})}}),De=V.includes(Ge.Rebootable),Oe=V.includes(Ge.BatteryOperated),ke=Kn(m.trpcClient,Oe&&l?a:null),Ae=hn(m.trpcClient,l?a:null),[je,Me]=c(!1),Ne=async()=>{if(!je){Me(!0);try{let e=L.replace(/[^a-zA-Z0-9_.-]+/g,`_`),t=new Date().toISOString().replace(/[:.]/g,`-`);await Gi(`${P}/${String(a)}.jpg?force=1`,`${e}-${t}.jpg`)}finally{Me(!1)}}},Pe=q.isPending||Te.isPending,{data:Fe}=St({deviceId:a},{enabled:l,refetchInterval:1e4}),Ie=Fe?.agentNodeId??null,Le=typeof Ie==`string`&&Ie.length>0&&!Ie.startsWith(`addon:`)?Ie:void 0,{data:Re}=yr({deviceId:a,...Le?{nodeId:Le}:{}},{enabled:l,refetchInterval:3e3,retry:!1}),{data:ze}=Ct({deviceId:a},{enabled:l,refetchInterval:3e3,retry:!1}),Ve=ze?.level?.dbfs??null;function He(){if(!l)return null;switch(he){case`overview`:return u(dl,{device:I??{}});case`config`:return u(wc,{deviceId:a,activeSubTab:x,onSubTabChange:_e,deviceType:H,isAdmin:g});case`detection-pipeline`:return u(Xc,{deviceId:a,activeSubTab:x,onSubTabChange:_e});case`bindings`:return u(bc,{deviceId:a});case Qr:return u(fc,{deviceId:a,activeSubTab:x,onSubTabChange:_e});default:{let e=he,t=F.some(t=>t.id===e),n=oe.find(t=>t.id===e);if(!t&&n===void 0)return null;let r=n?.childDeviceId??a;if(e===`export`)return u(Pr,{deviceId:a,sectionFilter:Br,activeSubTab:x,onSubTabChange:_e});let i=u(Pr,{deviceId:r,sectionFilter:t=>t.location===`top-tab`&&(t.tab===e||e===`detection-pipeline`&&t.tab===`zones`),flattenSubTabs:e===`detection-pipeline`,activeSubTab:x,onSubTabChange:_e});return n!==void 0&&r!==a?u(Tt,{deviceId:r,children:i}):i}}}return l?A?r(`div`,{className:`flex flex-col h-full`,children:[r(`div`,{className:`border-b border-border bg-surface px-6 py-4`,children:[u(`div`,{className:`h-4 w-48 rounded bg-surface-hover animate-pulse mb-3`}),u(`div`,{className:`h-8 w-64 rounded bg-surface-hover animate-pulse`})]}),u(`div`,{className:`flex-1 p-6`,children:u(`div`,{className:`h-40 rounded-lg border border-border bg-surface animate-pulse`})})]}):j||!k?r(`div`,{className:`flex flex-col items-center justify-center h-full gap-3 text-foreground-subtle`,children:[u(`p`,{className:`text-lg font-semibold text-foreground`,children:`Device not found`}),r(`p`,{className:`text-xs`,children:[`No device with ID`,` `,r(`code`,{className:`font-mono bg-surface px-1.5 py-0.5 rounded text-[11px]`,children:[`#`,a]})]}),u(`button`,{onClick:()=>d(`/integrations`),className:`mt-2 rounded-lg bg-primary px-4 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 transition-colors`,children:`Back to Integrations`})]}):r(`div`,{className:`absolute inset-0 flex flex-col overflow-clip`,children:[r(`div`,{className:`border-b border-border bg-surface px-6 py-3 flex-shrink-0`,children:[u(`div`,{className:`mb-2`,children:u(Et,{items:[{label:`Integrations`,onClick:()=>d(`/integrations`)},K===null?{label:Se}:{label:Se,onClick:()=>d(`/integrations/${K.id}`)},{label:L}]})}),r(`div`,{className:`flex items-center gap-2 sm:gap-3`,children:[K!==null&&u(hl,{provider:K.addonId,integrationId:K.id,name:K.name}),r(`div`,{className:`min-w-0 flex-1`,children:[r(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[u(`h1`,{className:`text-sm sm:text-base font-semibold text-foreground truncate`,children:L}),u(Ot,{status:ee}),Oe&&u(Lt,{status:ke,variant:`full`}),u(tn,{status:Ae})]}),se!==null&&ce&&r(`button`,{type:`button`,onClick:()=>d(`/devices/${se}`),className:`text-[10px] text-foreground-subtle hover:text-primary transition-colors mt-0.5 inline-flex items-center gap-1`,title:`Open parent device ${ce.name}`,children:[u(`span`,{children:`↑`}),u(`span`,{className:`truncate`,children:String(ce.name??`Device #${se}`)})]}),u(`div`,{className:`hidden md:flex items-center gap-3 mt-0.5 text-[10px] text-foreground-subtle`,children:V.length>0&&u(Rr,{capabilities:V})})]}),Re&&u(`div`,{className:`hidden lg:flex`,children:u(vl,{metrics:Re,dbfs:Ve})}),r(`div`,{className:`flex items-center gap-1 shrink-0`,children:[r(`button`,{onClick:async()=>{le?await p({title:`Disable "${L}"?`,message:`The device will stop processing streams and events. You can re-enable it later.`,confirmLabel:`Disable`,variant:`danger`})&&Te.mutate({deviceId:a}):q.mutate({deviceId:a})},disabled:Pe,title:le?`Disable device`:`Enable device`,className:`inline-flex items-center gap-1.5 rounded-lg px-2 sm:px-2.5 py-1.5 text-[11px] font-medium border transition-colors disabled:opacity-50 ${le?`border-success/30 text-success hover:bg-success/10`:`border-border text-foreground-subtle/50 hover:text-foreground hover:bg-surface-hover`}`,children:[u(M,{className:`h-3.5 w-3.5`}),u(`span`,{className:`hidden sm:inline`,children:Pe?`Updating…`:le?`Enabled`:`Disabled`})]}),u(`div`,{className:`hidden sm:block h-5 w-px bg-border mx-1`}),te&&r(o,{children:[u(Qi,{deviceId:a}),u(`div`,{className:`hidden sm:block h-5 w-px bg-border mx-1`})]}),u(ea,{deviceId:a}),u(Jt,{triggerClassName:`ml-1`,items:[{id:`snapshot`,label:`Take snapshot`,description:`Fetch a fresh frame and download it.`,icon:pe,disabled:je,onClick:()=>{Ne()}},{id:`reboot`,label:`Reboot device`,description:`Camera goes offline for ~30 seconds.`,icon:z,hidden:!De,disabled:Ee.isPending,danger:!0,onClick:async()=>{await p({title:`Reboot "${L}"?`,message:`The camera will go offline for around 30 seconds while the firmware reboots.`,confirmLabel:`Reboot`,variant:`danger`})&&Ee.mutate({deviceId:a})}},{id:`restart-addon`,label:`Restart addon`,description:`Bounces every device served by ${Ce}.`,icon:me,disabled:J.isPending,danger:!0,onClick:async()=>{await p({title:`Restart "${Ce}"?`,message:`Restarting the addon will briefly disconnect every device served by it (not just "${L}"). Streams will reconnect automatically.`,confirmLabel:`Restart`,variant:`danger`})&&J.mutate({addonId:B})}},{id:`delete`,label:`Delete device`,description:`Remove the device and all its settings.`,icon:_,separatorBefore:!0,disabled:we.isPending,danger:!0,onClick:async()=>{await p({title:`Delete "${L}"?`,message:`This will remove the device and all its settings. This action cannot be undone.`,confirmLabel:`Delete`,variant:`danger`})&&we.mutate({deviceId:a})}}]})]})]})]}),u(Tt,{deviceId:a,device:I??void 0,children:u(mt,{children:u(kt,{children:u(ue,{children:u(fn,{children:r(`main`,{className:G?`flex-1 overflow-y-auto flex flex-col`:`flex-1 min-h-0 overflow-hidden flex flex-row`,children:[r(`div`,{className:G?`flex flex-col bg-surface`:`${T===null?`w-1/2 lg:w-1/3`:``} flex-shrink-0 flex flex-col bg-surface min-h-0 overflow-hidden`,style:!G&&T!==null?{width:`${String(T)}px`}:void 0,children:[u(`div`,{className:te?`flex-shrink-0 border-b border-border-subtle bg-black`:G?`flex-shrink-0 border-b border-border-subtle bg-surface`:`max-h-[55%] shrink-0 overflow-y-auto border-b border-border-subtle bg-surface`,children:te?u(Pa,{deviceId:a,intercomAvailable:V.includes(Ge.TwoWayAudio)}):u(wa,{deviceId:a,deviceName:L,deviceType:H??`unknown`,provider:B,isOnline:R,features:V})}),r(`div`,{className:G?`flex flex-col border-b border-border`:`flex-1 min-h-0 flex flex-col overflow-hidden`,children:[u(`div`,{className:`flex-shrink-0 border-b border-border-subtle px-2 py-1.5`,children:u(`div`,{className:`flex gap-1 overflow-x-auto -mx-1 px-1 pb-0.5`,children:ye.map(({id:e,label:t,icon:n})=>r(`button`,{onClick:()=>C(e),title:t,className:`flex items-center gap-1 rounded px-2 py-1 text-[10px] font-medium transition-colors flex-shrink-0 ${S===e?`bg-primary/15 text-primary`:`text-foreground-subtle hover:text-foreground hover:bg-surface-hover`}`,children:[u(n,{className:`h-3 w-3`}),t]},e))})}),r(`div`,{className:G?`h-72 overflow-hidden`:`flex-1 min-h-0 overflow-hidden`,children:[S===`logs`&&u(Fa,{deviceId:a,containerDeviceId:H===`container`?a:void 0}),S===`repl`&&u(Ia,{deviceId:a}),S===`events`&&u(La,{deviceId:a}),S===`state`&&u(Ra,{deviceId:a})]})]})]}),!G&&u(`div`,{role:`separator`,"aria-orientation":`vertical`,title:`Drag to resize`,onMouseDown:O,className:`flex-shrink-0 w-1 cursor-col-resize bg-border hover:bg-primary/40 transition-colors group relative z-10`,children:u(`span`,{className:`absolute inset-y-0 -left-1 -right-1`})}),r(`div`,{className:G?`flex flex-col`:`flex-1 min-w-0 min-h-0 flex flex-col overflow-hidden`,children:[u(`div`,{className:`flex-shrink-0 border-b border-border bg-surface px-4`,children:u(`div`,{className:`flex flex-nowrap overflow-x-auto md:flex-wrap md:overflow-x-visible items-center gap-0`,children:fe.map(e=>{let t=he===e.id;return r(`button`,{onClick:()=>ge(e.id),className:`relative flex-shrink-0 px-3 py-2 text-xs font-medium transition-colors ${t?`text-primary`:`text-foreground-subtle hover:text-foreground`}`,children:[e.label,t&&u(`span`,{className:`absolute bottom-0 left-0 right-0 h-0.5 rounded-full bg-primary`})]},e.id)})})}),r(`div`,{className:G?`p-3 flex flex-col gap-3`:`flex-1 min-h-0 overflow-y-auto p-4 flex flex-col gap-3`,children:[he===`overview`&&ve&&u(ta,{parentDeviceId:a}),He()]})]})]})})})})})})]}):r(`div`,{className:`flex flex-col items-center justify-center h-full gap-3 text-foreground-subtle`,children:[u(`p`,{className:`text-lg font-semibold text-foreground`,children:`Invalid device id`}),r(`p`,{className:`text-xs`,children:[`The URL segment`,` `,u(`code`,{className:`font-mono bg-surface px-1.5 py-0.5 rounded text-[11px]`,children:n.deviceId}),` `,`is not a number.`]}),u(`button`,{onClick:()=>d(`/integrations`),className:`mt-2 rounded-lg bg-primary px-4 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 transition-colors`,children:`Back to Integrations`})]})}function vl({metrics:e,dbfs:t}){let n=Mt(e.phase??`idle`);return r(`div`,{className:`flex items-center gap-3 flex-shrink-0`,children:[r(`div`,{className:`flex items-center gap-1.5`,children:[u(`span`,{className:`h-1.5 w-1.5 rounded-full ${n.dotClass}`}),u(`span`,{className:`text-[10px] font-medium ${n.textColor}`,children:n.label})]}),u(`div`,{className:`h-3 w-px bg-border`}),r(`div`,{className:`flex items-center gap-1 text-[10px] text-foreground-subtle`,children:[u(E,{className:`h-3 w-3`}),u(`span`,{className:`text-foreground tabular-nums`,children:(e.actualFps??0).toFixed(1)}),u(`span`,{children:`fps`})]}),r(`div`,{className:`flex items-center gap-1 text-[10px] text-foreground-subtle`,children:[u(y,{className:`h-3 w-3`}),u(`span`,{className:`text-foreground tabular-nums`,children:(e.avgInferenceTimeMs??0).toFixed(0)}),u(`span`,{children:`ms`})]}),r(`div`,{className:`flex items-center gap-1 text-[10px] text-foreground-subtle`,title:`Current audio level (dBFS)`,children:[u(A,{className:`h-3 w-3`}),u(`span`,{className:`text-foreground tabular-nums`,children:t==null?`—`:t.toFixed(0)}),u(`span`,{children:`dB`})]}),(e.queueDepth??0)>0&&r(`span`,{className:`text-[10px] text-warning tabular-nums`,children:[`q:`,e.queueDepth]})]})}export{_l as DeviceDetailPage};
@@ -1 +0,0 @@
1
- import{Q as e,S as t,W as n,a as r,x as i}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{ot as a}from"./player-overlays-DWMIy1MJ.js";import{Bt as o,Gt as s,Ht as c,Kt as l,Ut as u,Vt as d,Wt as f,zt as p}from"./client-CjyKfSu1.js";import{d as m}from"./src-BLkInT8U.js";import"./notification-schedule-field-D8dd67dT.js";e();var h=6e4;function g(e){let t=a();return r({queryKey:[`device-do-action`,`bound-caps`,e],enabled:e>0,staleTime:h,queryFn:async()=>{let n=await t.trpcClient.deviceManager.getBindings.query({deviceId:e});return[...new Set(n.entries.map(e=>e.capName))].sort((e,t)=>e.localeCompare(t))}})}function _(e){let t=a(),n=[...new Set(e.filter(e=>e>0))].sort((e,t)=>e-t);return r({queryKey:[`device-do-action`,`bound-caps-batch`,n],enabled:n.length>0,staleTime:h,queryFn:async()=>{let e=await t.trpcClient.deviceManager.getBindingsBatch.query({deviceIds:n}),r=new Map;for(let t of e)r.set(t.deviceId,[...new Set(t.entries.map(e=>e.capName))].sort((e,t)=>e.localeCompare(t)));return r}})}var v=`mt-1 w-full rounded border border-border bg-background px-2 py-1 text-xs`,y=`block text-[11px] font-medium text-foreground`,b=`deviceId`;function x(e,t){return t.length===0?0:t.length===1?t[0]:t.find(t=>!e.includes(t))??t[t.length-1]}function S(e,t,n){if(t.length===0)return[];if(t.length===1)return t;let r=t.find(t=>!e.includes(t));if(r===void 0)return t;let i=n(r);if(i===void 0)return[r];let a=e[0]??t.find(e=>e!==r);if(a===void 0)return[r];let o=n(a);return o===void 0||!l(o,i)?[r]:t.filter(e=>{let t=n(e);return t!==void 0&&l(o,t)})}function C(e){return e.length===0?0:e.length===1?e[0]:[...e]}function w(e){return typeof e==`number`?e>0?[e]:[]:Array.isArray(e)?e.filter(e=>e>0):[]}function T(e,t){return{deviceId:e,cap:t.cap,method:t.method,...t.args===void 0?{}:{args:{...t.args}}}}function E(e,t){return`Custom: ${e}.${t}`}function D({value:e,onChange:r,devices:a,listState:h,fleet:D,allowTriggerDevice:O=!1,allowMultiSameFamily:k=!1,testId:A=`device-do-action`}){let j=typeof e.deviceId!=`number`&&!Array.isArray(e.deviceId),M=w(e.deviceId),N=n(()=>a.filter(e=>f(String(e.type??``))),[a]),P=n(()=>{let e=new Map;for(let t of N)t.type!==void 0&&t.type!==null&&e.set(t.id,String(t.type));return e},[N]),F=n(()=>{if(!k||M.length===0)return N;let e=P.get(M[0]);return e===void 0?N:N.filter(t=>{if(M.includes(t.id))return!0;let n=t.type!==void 0&&t.type!==null?String(t.type):void 0;return n!==void 0&&l(e,n)})},[k,M,N,P]),I=g(!k&&M.length===1?M[0]:0),L=_(k?M:[]),R=n(()=>j?c():M.length===0?[]:k?L.isLoading&&L.data===void 0?[]:d(M.map(e=>({boundCaps:L.data?.get(e),deviceType:P.get(e)}))):I.data===void 0&&I.isLoading?[]:o({boundCaps:I.data,deviceType:P.get(M[0])}),[j,M,k,L.data,L.isLoading,I.data,I.isLoading,P]),z=u(e.cap,e.method,e.args),B=s(e.cap,e.method,e.args),V=e.cap!==``&&e.method!==``&&B===null&&(j||M.length>0),H=k?L.isLoading:I.isLoading,U=k?L.isError:I.isError,W=t=>{if(t.startsWith(`custom:`))return;let n=p.find(e=>e.id===t);n!==void 0&&r(T(j?e.deviceId:M.length>0?C(M):N[0]?.id??0,n))};return t(`div`,{className:`flex min-w-0 flex-1 flex-col gap-2`,"data-testid":A,children:[O&&t(`div`,{className:`w-full max-w-xs`,children:[i(`label`,{className:y,children:`Target`}),t(`select`,{className:v,"data-testid":`${A}-target`,value:j?`trigger`:`device`,onChange:e=>{if(e.target.value===`trigger`){r({deviceId:{$var:b},cap:``,method:``});return}r({deviceId:N[0]?.id??0,cap:``,method:``})},children:[i(`option`,{value:`device`,children:`Specific device`}),i(`option`,{value:`trigger`,children:`The device that triggered this run`})]})]}),!j&&t(`div`,{"data-testid":`${A}-device`,children:[t(`label`,{className:y,children:[`Device`,k?`s`:``]}),i(m,{devices:F,listState:h,...D===void 0?{}:{fleet:D},value:[...M],onChange:e=>{r({deviceId:C(k?S(M,e,e=>P.get(e)):(()=>{let t=x(M,e);return t>0?[t]:[]})()),cap:``,method:``})},emptyLabel:k?`No devices selected`:`No device selected`,noun:`device`,testId:`${A}-device-picker`}),k&&M.length>1&&i(`p`,{className:`mt-1 text-[11px] text-foreground-subtle`,children:`Same family only — the action runs on each selected device.`})]}),t(`div`,{className:`w-full max-w-sm`,children:[i(`label`,{className:y,children:`Action`}),t(`select`,{className:v,"data-testid":`${A}-action`,value:z===`custom:${e.cap}.${e.method}`?z:B?.id??``,disabled:!j&&(M.length===0||H),onChange:e=>W(e.target.value),children:[i(`option`,{value:``,children:!j&&M.length===0?`Pick a device first`:H?`Loading actions…`:R.length===0?`No actions for this device`:`Select an action…`}),V&&i(`option`,{value:z,children:E(e.cap,e.method)}),R.map(e=>i(`option`,{value:e.id,children:e.label},e.id))]}),U&&i(`p`,{className:`mt-1 text-[11px] text-warning`,children:`Could not read this device’s capabilities.`})]}),B?.openArgs!==void 0&&B.openArgs.length>0&&i(`div`,{className:`flex flex-col gap-2`,children:B.openArgs.map(n=>{let a=e.args?.[n.key],o=typeof a==`string`||typeof a==`number`?String(a):``;return t(`div`,{className:`w-full max-w-sm`,children:[i(`label`,{className:y,htmlFor:`${A}-${n.key}`,children:n.label}),i(`input`,{id:`${A}-${n.key}`,className:v,"data-testid":`${A}-${n.key}`,type:n.kind===`number`?`number`:`text`,value:o,onChange:t=>{let i=t.target.value,a=e.args===void 0?{}:{...e.args};if(i===``)delete a[n.key];else if(n.kind===`number`){let e=Number(i);Number.isNaN(e)?delete a[n.key]:a[n.key]=e}else a[n.key]=i;r(Object.keys(a).length>0?{...e,args:a}:{deviceId:e.deviceId,cap:e.cap,method:e.method})}})]},n.key)})})]})}export{D as t};
@@ -1 +0,0 @@
1
- import{I as e,Q as t,S as n,W as r,o as i,x as a}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{Nt as o,ot as s,wi as c}from"./player-overlays-DWMIy1MJ.js";import{Ca as l,co as u,et as d,ma as f,oa as p,r as m,ta as h,tt as g}from"./src-BLkInT8U.js";import{t as _}from"./useTranslation-Bc5yH9V9.js";import{G as v,Y as y}from"./index-D66JvELZ.js";import{t as b}from"./AdminPage-C0Zxs_ot.js";import"./useEventInvalidation-1Z6p3UkP.js";import{t as x}from"./device-integration-icon-CCoHGEQZ.js";t();var S=32;function C(e,t){let n=e=>t(e).kind===`orphan`,r=new Set;for(let t of e)n(t)&&r.add(t.id);let i=new Map;for(let t of e)i.set(t.id,t);let a=(e,t=0)=>{if(t>S)return!1;if(r.has(e.id))return!0;if(e.parentDeviceId==null)return!1;let n=i.get(e.parentDeviceId);return n?a(n,t+1):!1},o=[],s=[];for(let t of e)a(t)?s.push(t):o.push(t);return{activeDevices:o,orphanDevices:s}}function w(){let{t}=_(),S=y(),w=s(),T=i();m([`deviceManager`],[`device.registered`,`device.unregistered`,`device.online`,`device.offline`,`device.disabled`,`device.enabled`]),m([`integrations`],[`integration.enabled`,`integration.disabled`,`integration.deleted`,`provider.started`,`provider.stopped`,`addon.installed`,`addon.uninstalled`,`addon.started`,`addon.stopped`]);let{data:E}=f({projection:`slim`}),{data:D}=u(void 0),O=l({onSuccess:()=>{T.invalidateQueries({queryKey:[[`deviceManager`]]})}}),k=h({onSuccess:()=>{T.invalidateQueries({queryKey:[[`deviceManager`]]})}}),A=p({onSuccess:()=>{T.invalidateQueries({queryKey:[[`deviceManager`]]})}}),j=r(()=>E??[],[E]),M=r(()=>g(D),[D]),{activeDevices:N,orphanDevices:P}=r(()=>C(j,M),[j,M]),F=r(()=>{let e=new Map;for(let t of j)e.set(t.id,{id:t.id,name:t.name??t.stableId??`#${String(t.id)}`});return e},[j]),I=e(e=>F.get(e)??null,[F]),L=r(()=>(D??[]).map(e=>({id:e.id,name:e.name??e.addonId,icon:a(v,{type:e.addonId,size:`sm`})})),[D]),R=e(e=>S(`/devices/${String(e)}`),[S]);return n(b,{icon:c,title:t(`nav.devices`,`Devices`),children:[a(d,{context:`devices`,devices:N,trpc:w.trpcClient,filters:{integrations:L},integrationOf:M,resolveIntegrationIcon:x,resolveParent:I,onNavigate:R,batchActions:{remove:O.mutate,disable:k.mutate,enable:A.mutate}}),P.length>0&&n(`div`,{className:`mt-6 space-y-2`,children:[n(`div`,{className:`flex items-baseline gap-2`,children:[a(o,{className:`h-3.5 w-3.5 text-warning shrink-0`}),a(`h2`,{className:`text-sm font-semibold text-foreground`,children:`Orphan devices`}),n(`span`,{className:`text-[10px] text-foreground-subtle`,children:[P.length,` device`,P.length===1?``:`s`,` pointing at integrations no longer registered`]})]}),n(`div`,{className:`rounded-lg border border-warning/30 bg-warning/5 p-2`,children:[a(`p`,{className:`text-[11px] text-foreground-subtle px-2 pb-2`,children:"These devices reference an integration that is no longer registered (their `integrationId`, or — for older devices without one — their `addonId`). Delete them, or re-install the missing integration to bring them back online. The provider badge beside each row is the addon that serves it."}),a(d,{context:`devices`,devices:P,trpc:w.trpcClient,integrationOf:M,urlScope:`nested`,lsKey:`devices:orphan`,resolveIntegrationIcon:x,resolveParent:I,onNavigate:R})]})]})]})}export{w as DevicesPage};
@@ -1 +0,0 @@
1
- import{Q as e,S as t,W as n,d as r,q as i,u as a,x as o,z as s}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{it as c}from"./player-overlays-DWMIy1MJ.js";import{fi as l}from"./client-CjyKfSu1.js";import{D as u,M as d,O as f,P as p,T as m,y as h}from"./__vite-browser-external-DF8Eb0aa.js";import{Et as g,Gt as _,gu as v,jt as y,zt as b}from"./src-BLkInT8U.js";e();var x=p([f({kind:m(`adaptive`)}),f({kind:m(`profile`),profile:l})]),S=f({serverUrl:d().min(1),token:d().min(1),deviceId:u().int().nonnegative(),target:x,muted:h()});function C(e,t){let n=t===void 0?{type:`state`,state:e}:{type:`state`,state:e,message:t};window.ReactNativeWebView?.postMessage(JSON.stringify(n))}function w(e){switch(e){case`playing`:return`playing`;case`error`:return`error`;case`connecting`:case`disconnected`:case`idle`:return`connecting`}}function T(e){return e.kind===`adaptive`?{kind:`adaptive`}:{kind:`profile`,profile:e.profile}}function E(e){return e.kind===`adaptive`?`embed:adaptive`:`embed:profile:${e.profile}`}function D(){let e=window.__CAMSTACK_EMBED__;if(e==null)return{ok:!1,error:`window.__CAMSTACK_EMBED__ is not set`};let t=S.safeParse(e);return t.success?{ok:!0,config:t.data}:{ok:!1,error:t.error.issues.map(e=>`${e.path.join(`.`)||`(root)`}: ${e.message}`).join(`; `)}}function O({message:e}){return s(()=>{C(`error`,e)},[e]),t(`div`,{style:{position:`fixed`,inset:0,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#000`,color:`#f87171`,fontFamily:`system-ui, sans-serif`,fontSize:13,padding:16,textAlign:`center`},children:[`Embed config error: `,e]})}function k({system:e,deviceId:t,initialTarget:r,initialMuted:a}){let[c,l]=i(r),[u,d]=i(a),{handleOffer:f,getIceServers:p,addIceCandidate:m,getIceCandidates:h,closeSession:g,getSessionState:v,getSessionDebug:y,applyDownlinkProbe:S}=b(e.trpcClient,t),D=n(()=>T(c),[c]),O=n(()=>(e,t)=>f(D,e,t),[f,D]),k=n(()=>(e,t,n)=>f(n,t,e),[f]);s(()=>(window.__camstackEmbed={setMuted:e=>d(e),setTarget:e=>{let t=x.safeParse(e);t.success&&l(t.data)}},()=>{window.__camstackEmbed&&delete window.__camstackEmbed}),[]);let A=E(c);return o(`div`,{style:{position:`fixed`,inset:0,width:`100vw`,height:`100vh`,background:`#000`},children:o(_,{serverUrl:e.serverUrl,streamKey:A,autoPlay:!0,muted:u,showControls:!1,className:`w-full h-full`,getSessionDebug:y,applyDownlinkProbe:S,handleOffer:O,reoffer:k,getSessionState:v,getIceServers:p,addIceCandidate:m,getIceCandidates:h,closeSession:g,onStateChange:e=>C(w(e)),onError:e=>C(`error`,e)},A)})}function A(){let e=n(()=>D(),[]),t=n(()=>{if(!e.ok)return null;let t=y({serverUrl:e.config.serverUrl,token:e.config.token}),n=new r({defaultOptions:{queries:{retry:!1,refetchOnWindowFocus:!1}}});return g(n),{system:t,queryClient:n}},[e]);return s(()=>{if(t)return()=>{t.system.close()}},[t]),e.ok?t?o(c,{system:t.system,children:o(a,{client:t.queryClient,children:o(v.Provider,{client:t.system.trpcClient,queryClient:t.queryClient,children:o(k,{system:t.system,deviceId:e.config.deviceId,initialTarget:e.config.target,initialMuted:e.config.muted})})})}):o(O,{message:`Failed to initialise the embed player`}):o(O,{message:e.error})}export{A as EmbedPlayerPage};
@@ -1 +0,0 @@
1
- import{I as e,K as t,Q as n,S as r,W as i,a,b as o,o as s,q as c,t as l,x as u,z as d}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{Hi as f,Hr as p,Ir as m,It as h,Nt as g,On as _,Pn as v,Qt as y,Tt as b,_i as x,ar as S,cn as C,cr as w,dt as T,fi as E,fn as D,nr as O,on as k,ot as A,pr as j,sn as M,un as N,yi as P,yn as F}from"./player-overlays-DWMIy1MJ.js";import{n as I,r as L,t as ee}from"./key-Bj5-ZBrb.js";import{c as R,o as z,u as B}from"./video--MLJeLNU.js";import{t as V}from"./history-V8RQKQAb.js";import{t as H}from"./key-round-B2I1YisX.js";import{t as te}from"./monitor-smartphone-iBd_3nPv.js";import{t as U}from"./unlink-DeNvF8r-.js";import{a as ne,bi as re,i as ie,o as W,s as ae,xi as oe,yi as se}from"./client-CjyKfSu1.js";import{Al as ce,An as le,Ao as ue,Bl as de,Bn as G,Cn as fe,Dl as pe,Dn as me,Dr as he,El as ge,En as _e,Er as ve,Fl as ye,Ft as be,G as xe,Gl as Se,Ht as Ce,Il as we,Kl as Te,L as Ee,Ll as De,Ln as Oe,Ml as ke,N as Ae,Nl as je,Ol as Me,P as Ne,Pl as Pe,Qn as Fe,Rl as Ie,Rn as Le,Tl as Re,Tn as ze,Ut as Be,Wt as K,X as Ve,Xl as He,Z as Ue,Zn as q,ar as J,bn as We,en as Ge,gu as Y,in as Ke,jl as qe,jn as Je,kl as Ye,kn as Xe,ma as Ze,nn as Qe,on as $e,rn as et,z as tt,zl as nt,zn as rt}from"./src-BLkInT8U.js";import{t as it}from"./useTranslation-Bc5yH9V9.js";import{J as at,L as ot,S as st,Y as ct,Z as lt,c as ut,f as dt,m as ft,q as pt,s as mt}from"./index-D66JvELZ.js";import{t as ht}from"./AdminSectionedPage-D2kYQhvu.js";import{t as gt}from"./AdminPage-C0Zxs_ot.js";import{A as _t,C as vt,D as yt,E as bt,F as xt,M as St,N as X,O as Ct,P as Z,S as wt,T as Tt,_ as Et,a as Dt,b as Ot,c as kt,d as At,f as jt,h as Mt,i as Nt,j as Pt,k as Ft,l as It,m as Lt,n as Rt,o as zt,p as Bt,s as Vt,t as Ht,u as Ut,v as Wt,w as Gt,x as Kt,y as qt}from"./SessionsList-DQ7kj8fX.js";import{i as Jt,n as Yt,r as Xt,t as Zt}from"./IntegrationHub-CuW7-WRy.js";import{n as Qt,t as $t}from"./addon-display-names-BkwMrExv.js";n();function en(){let e=q(),t=Y.useUtils(),n=xt(),{data:r,isLoading:a}=je(),o=i(()=>r??[],[r]),s=Y.useQueries(e=>o.map(t=>e.userManagement.listExternalIdentities({userId:t.id}))),l=Y.auth.listLoginMethods.useQuery(),[d,f]=c(null),p=nt({onSuccess:()=>void t.userManagement.listExternalIdentities.invalidate(),onError:e=>f(`Remove failed: ${e.message}`)}),m=i(()=>new Map((l.data??[]).flatMap(e=>e.kind===`redirect`?[[e.id,e.label]]:[])),[l.data]),h=o.flatMap((e,t)=>s[t]?.data??[]),g=h.map(e=>({...Tt(e,n),kind:m.get(e.provider)??e.provider})),_=async t=>{let n=h.find(e=>Gt(e)===t.id);n!==void 0&&await e({title:`Remove sign-in link`,message:`"${t.ownerName}" will no longer be able to sign in with this ${t.kind} account.`,confirmLabel:`Remove`,variant:`danger`})&&(f(null),p.mutate({userId:n.userId,provider:n.provider,subject:n.subject}))};return u(X,{notice:Z(d),onDismissNotice:()=>{f(null)},id:`external-identities`,title:`Sign-in links`,icon:B,description:`External accounts (single sign-on) each user linked to their CamStack account. Only the owner can link one, from their profile; an admin can remove it.`,children:u(Ft,{rows:g,label:`sign-in links`,isLoading:a||s.some(e=>e.isLoading),loadError:s.find(e=>e.isError)?.error?.message??null,emptyText:`No user has linked a sign-in account.`,expiresNone:`—`,action:{label:`Remove`,icon:U,isAvailable:()=>!0,onRun:e=>void _(e),busyId:null,disabled:p.isPending}})})}n();function tn(){let e=q(),t=s(),n=xt(),r=ce(),[a,o]=c(null),l=ye({onSuccess:()=>void t.invalidateQueries({queryKey:[[`userManagement`,`listApiKeys`]]}),onError:e=>o(`Revoke failed: ${e.message}`)}),d=i(()=>(r.data??[]).map(e=>vt(e,n)),[r.data,n]),f=async t=>{await e({title:`Revoke "${t.name}"?`,message:`Any client using this key loses access immediately. This cannot be undone.`,confirmLabel:`Revoke`,variant:`danger`})&&(o(null),l.mutate({id:t.id}))};return u(X,{notice:Z(a),onDismissNotice:()=>{o(null)},id:`legacy-api-keys`,title:`Legacy API keys`,icon:V,description:`Keys from before scoped tokens. Nothing creates them any more; revoke them and issue a scoped token instead.`,children:u(Ft,{rows:d,label:`legacy API keys`,isLoading:r.isLoading,loadError:r.isError?r.error?.message??`Request failed`:null,emptyText:`No legacy API keys.`,action:{label:`Revoke`,icon:h,isAvailable:()=>!0,onRun:e=>void f(e),busyId:l.isPending?l.variables?.id??null:null,disabled:l.isPending}})})}n();var nn={one:`linked app`,many:`linked apps`};function rn(e){if(e.type===`category`){let t=e.target??``;return t===`device`?`all devices`:`all ${t}`}if(e.type===`device`)return`device:[${(e.targets??[]).join(`,`)}]`;let t=e;return`${t.type}:${t.target??``}`}function an(){let e=q(),t=s(),n=ke(),[r,a]=c(null),o=()=>void t.invalidateQueries({queryKey:[[`userManagement`,`listOauthSessions`]]}),l=we({onSuccess:o,onError:e=>a(`Revoke failed: ${e.message}`)}),d=_t(`oauth-session`,nn,o),f=i(()=>(n.data??[]).map(e=>bt(e,e.scopes.map(rn).join(`, `))),[n.data]),p=async t=>{await e({title:`Revoke the "${t.name}" link?`,message:`${t.name} loses access for ${t.ownerName} on its next call. Linking it again needs the account-link flow from the start.`,confirmLabel:`Revoke`,variant:`danger`})&&(a(null),l.mutate({id:t.id}))},m=l.isPending?l.variables?.id??null:null;return u(X,{notice:Z(r,d.outcome),onDismissNotice:()=>{a(null),d.dismiss()},id:`linked-apps`,title:`Linked apps`,icon:w,description:`External integrations (Alexa, …) linked to this hub through OAuth. Revoking one stops that integration on its next call. Already-revoked rows can be selected and removed from the list.`,children:u(Ft,{rows:f,label:`linked apps`,isLoading:n.isLoading,loadError:n.isError?n.error?.message??`Request failed`:null,emptyText:`No linked apps — an integration appears here once it completes the account-link flow.`,expiresNone:`—`,action:{label:`Revoke`,icon:h,isAvailable:e=>e.status===`active`||e.status===`revoked`,onRun:e=>void p(e),busyId:m,disabled:l.isPending||d.busy},bulk:{revoke:d,noun:nn,isSelectable:e=>e.status===`active`||e.status===`revoked`,quickSelect:[{label:`Select revoked`,match:e=>e.status===`revoked`}]}})})}n();var on={one:`session`,many:`sessions`};function sn(){let e=q(),t=Y.useUtils(),n=xt(),r=Y.auth.listSessions.useQuery(),[a,o]=c(null),s=()=>void t.auth.listSessions.invalidate(),l=Y.auth.revokeSessions.useMutation({onSuccess:s,onError:e=>o(`Sign out failed: ${e.message}`)}),d=_t(`login-session`,on,s),f=i(()=>(r.data??[]).map(e=>yt(e,n,{client:e=>Wt(e).label,method:qt})),[r.data,n]),p=async t=>{await e({title:`Sign out this session`,message:`${t.ownerName} on ${t.name} will have to sign in again.`,confirmLabel:`Sign out`,variant:`danger`})&&(o(null),l.mutate({id:t.id}))};return u(X,{notice:Z(a,d.outcome),onDismissNotice:()=>{o(null),d.dismiss()},id:`login-sessions`,title:`Login sessions`,icon:te,description:`Every browser and app signed in to this hub, for every user. Signing one out ends it at once; it has to sign in again. Your own current session is marked and never included in a bulk sign-out.`,children:u(Ft,{rows:f,label:`sessions`,isLoading:r.isLoading,loadError:r.isError?r.error?.message??`Request failed`:null,emptyText:`No active sessions.`,action:{label:`Sign out`,icon:z,isAvailable:e=>e.status===`active`,onRun:e=>void p(e),busyId:l.isPending&&l.variables!==void 0&&`id`in l.variables?l.variables.id:null,disabled:l.isPending||d.busy},bulk:{revoke:d,noun:on,isSelectable:e=>e.status===`active`}})})}function cn({token:e,label:t,onClose:n}){return u(ze,{open:!0,onOpenChange:e=>!e&&n(),children:r(me,{width:`md`,scroll:`body`,children:[u(le,{children:u(Je,{children:`Token: ${t}`})}),r(_e,{className:`space-y-3`,children:[u(`div`,{className:`rounded-md border border-warning/30 bg-warning/10 px-3 py-2 text-xs text-warning`,children:`Copy this token now. Once you close this dialog the secret cannot be displayed again.`}),u(`div`,{className:`select-all break-all rounded-md border border-border bg-background p-2 font-mono text-[11px] text-foreground`,children:e})]}),r(Xe,{children:[u(be,{value:e,label:`Copy`,srLabel:`token`}),u(G,{type:`button`,variant:`primary`,size:`sm`,onClick:n,children:`Done`})]})]})})}var ln={token:`newToken`,scoped:`newScoped`,admin:`newAdmin`};n();var un=7,dn=90,fn=80;function pn(e){let t=Number(e);return Number.isInteger(t)&&t>=1&&t<=dn?t:null}function mn({open:e,users:t,onClose:n,onSubmitScoped:i,onSubmitAdmin:a,submitting:s,formError:l,awaitingProof:f}){let{user:p}=ot(),m=p?.isAdmin===!0,h=m?null:p?.scopes??[],[g,_]=c(!1),[v,y]=c(t[0]?.id??``),[b,x]=c(``),[C,w]=c([{type:`capability`,target:``,access:[`view`,`create`]}]),[T,E]=c(``),[D,O]=c(String(un));d(()=>{e||(_(!1),y(t[0]?.id??``),x(``),w([{type:`capability`,target:``,access:[`view`,`create`]}]),E(``),O(String(un)))},[e,t]);let A=b.trim(),j=Ne(C),N=pn(D),P=!g&&v!==``&&A.length>0&&C.length>0&&j===null&&!s,F=g&&m&&A.length>0&&A.length<=fn&&N!==null&&!s&&!f;return u(tt,{open:e,onClose:n,title:g?`Create admin token`:`Create token`,icon:g?M:H,error:l,width:`md`,testId:`create-token-dialog`,footer:r(G,{type:`button`,variant:g?`danger`:`primary`,size:`sm`,onClick:()=>{if(g){if(!F||N===null)return;a({name:A,expiresInDays:N});return}if(!P)return;let e=parseInt(T,10),t=Number.isFinite(e)&&e>0?Date.now()+e*864e5:void 0;i({userId:v,name:A,scopes:C,...t===void 0?{}:{expiresAt:t}})},disabled:g?!F:!P,children:[s||f?u(S,{className:`h-3.5 w-3.5 animate-spin`,"aria-hidden":!0}):u(g?M:k,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),g?`Create admin token`:`Issue token`]}),children:r(`div`,{className:`space-y-3`,children:[m?r(`label`,{className:`flex items-start gap-2 text-sm text-foreground`,children:[u(`input`,{type:`checkbox`,className:`mt-0.5`,checked:g,onChange:e=>_(e.target.checked),"data-testid":`token-as-admin`}),r(`span`,{children:[u(`span`,{className:`font-medium`,children:`Administrator`}),u(`span`,{className:`block text-[11px] text-foreground-subtle`,children:`Off = scoped to a surface. On = full admin for scripts (audited, max 90 days).`})]})]}):null,g?u(`div`,{className:`space-y-1 rounded-md border border-danger/30 bg-danger/5 px-3 py-2 text-[11px] leading-relaxed text-foreground`,"data-testid":`admin-token-warning`,children:r(`p`,{children:[`An admin token acts as a `,u(`strong`,{children:`full administrator`}),`. Anyone holding it can do anything an admin can. Creating one asks you to confirm it is you.`]})}):null,g?null:r(`div`,{className:`space-y-1`,children:[u($e,{htmlFor:`token-user`,children:`On behalf of user`}),u(Se,{id:`token-user`,value:v,onChange:e=>y(e.target.value),options:t.map(e=>({value:e.id,label:e.username}))})]}),u(xe,{label:`Name`,required:!0,children:u(He,{id:`token-name`,value:b,maxLength:fn,onChange:e=>x(e.target.value),placeholder:g?`nightly-backup`:`cloudflare-tunnel-route`,autoFocus:!0})}),g?r(`div`,{className:`space-y-1`,children:[u($e,{htmlFor:`token-admin-days`,children:`Expires in (days)`}),u(He,{id:`token-admin-days`,type:`number`,min:1,max:dn,value:D,onChange:e=>O(e.target.value),state:N===null?`error`:`default`}),N===null?r(`p`,{className:`text-[11px] text-danger`,children:[`Expiry must be a whole number of days, 1 to `,dn,`.`]}):r(`p`,{className:`text-[11px] text-foreground-subtle`,children:[`Whole number of days, 1 to `,dn,`.`]})]}):r(o,{children:[r(`div`,{className:`space-y-1`,children:[u($e,{children:`Scopes`}),u(Ae,{value:C,onChange:w,clampToParent:h}),j&&u(`p`,{className:`text-[10px] text-danger`,children:j}),u(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Each scope picks a (cap or addon) target + one or more access flavours. The token can access ONLY what's listed.`})]}),r(`div`,{className:`space-y-1`,children:[u($e,{htmlFor:`token-scoped-days`,children:`Expires in (days)`}),u(He,{id:`token-scoped-days`,type:`number`,min:1,value:T,onChange:e=>E(e.target.value),placeholder:`30`}),u(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Leave blank for non-expiring.`})]})]})]})})}n();var hn={one:`token`,many:`tokens`};function gn(e){return e.type===`device`?`device:[${Ue(e.selector)}]`:`${e.type}:${e.target??``}`}function _n({createRequested:e=!1,onCreateConsumed:t}){let{user:n}=ot(),a=q(),o=s(),l=Y.useUtils(),f=xt(),{data:p,isLoading:m}=je(),g=i(()=>p??[],[p]),_=Y.useQueries(e=>g.map(t=>e.userManagement.listScopedTokens({userId:t.id}))),v=Y.auth.listAdminTokens.useQuery(void 0,{enabled:n?.isAdmin===!0}),{requestProof:y,dialog:b}=Et(`Creating an admin token`),{state:x,openNew:S,close:C}=Ee({newKey:ln.token}),[w,T]=c(null),[E,D]=c(null),[O,k]=c(!1),[A,j]=c(null),[M,N]=c(null);d(()=>{e&&(S(),t?.())},[e,S,t]);let P=()=>{o.invalidateQueries({queryKey:[[`userManagement`,`listScopedTokens`]]}),l.auth.listAdminTokens.invalidate(),l.auth.listAuthAudit.invalidate()},F=Re({onSuccess:({token:e,record:t})=>{P(),C(),D(null),j({token:e,label:t.name})},onError:e=>{T(`Create failed: ${e.message}`),D(`Create failed: ${e.message}`)}}),I=Y.auth.createAdminToken.useMutation({onSuccess:({token:e,record:t})=>{P(),C(),D(null),k(!1),j({token:e,label:t.name})},onError:e=>{T(`Create failed: ${e.message}`),D(`Create failed: ${e.message}`),k(!1)}}),L=De({onSuccess:()=>{N(null),P()},onError:e=>{N(null),T(`Revoke failed: ${e.message}`)}}),ee=Y.auth.revokeAdminToken.useMutation({onSuccess:()=>{N(null),P()},onError:e=>{N(null),T(`Revoke failed: ${e.message}`)}}),R=St(hn,P),z=Date.now(),B=g.flatMap((e,t)=>(_[t]?.data??[]).map(t=>Ct(t,e.id,f,t.scopes.map(gn).join(`, `),z))),V=n?.isAdmin===!0?(v.data??[]).map(e=>wt(e,f,z)):[],te=[...B,...V],U=_.find(e=>e.isError)?.error?.message??(v.isError?v.error?.message??`Request failed`:null),ne=async e=>{let t=e.kind===Kt;await a({title:`Revoke "${e.name}"?`,message:t?`Every script using it loses access immediately. This cannot be undone.`:`${e.ownerName}'s scoped token stops working on its next use. This cannot be undone.`,confirmLabel:`Revoke`,variant:`danger`})&&(T(null),N(e.id),t?ee.mutate({id:e.id}):L.mutate({id:e.id}))},re=F.isPending||I.isPending;return r(`div`,{"data-testid":`tokens`,children:[b,u(X,{notice:Z(w,R.outcome),onDismissNotice:()=>{T(null),R.dismiss()},id:`tokens`,title:`Tokens`,icon:H,description:`Scoped tokens for a narrow surface, and admin tokens for full-administrator scripts. Revoking one stops it on its next use.`,children:u(Ft,{rows:te,label:`tokens`,isLoading:m||_.some(e=>e.isLoading)||n?.isAdmin===!0&&v.isLoading,loadError:U,emptyText:`No tokens.`,action:{label:`Revoke`,icon:h,isAvailable:e=>e.status===`active`,onRun:e=>void ne(e),busyId:M,disabled:R.busy||M!==null},bulk:{revoke:R,noun:hn,isSelectable:e=>e.status===`active`}})}),u(mn,{open:x.mode===`new`,users:g.map(e=>({id:e.id,username:e.username})),onClose:()=>{C(),D(null),k(!1)},submitting:re,formError:E,awaitingProof:O,onSubmitScoped:e=>F.mutate({userId:e.userId,name:e.name,scopes:e.scopes,expiresAt:e.expiresAt}),onSubmitAdmin:e=>{(async()=>{T(null),D(null),k(!0);let t=await y();k(!1),t!==null&&I.mutate({...e,reauthToken:t})})()}}),A&&u(cn,{token:A.token,label:A.label,onClose:()=>j(null)})]})}var vn={"share-link":`share links`,"admin-token":`admin tokens`,"login-session":`login sessions`};function Q(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:null}function yn(e,t){let n=Q(e,`tokenId`);return Q(e,`name`)??(n===null?void 0:t.get(n))??n??`?`}function bn(e){return e.filter(e=>e!==null)}function xn(e){let t=Q(e,`prefix`);return t===null?null:`Prefix ${t}…`}function Sn(e,t){let n=e.detail??{};switch(e.action){case`admin-token-created`:{let e=n.expiresAt;return{title:`Admin token "${yn(n,t)}" created`,details:bn([xn(n),typeof e==`number`?`Expires ${Ot(e)}`:null])}}case`admin-token-used`:{let e=Q(n,`path`);return{title:`Admin token "${yn(n,t)}" used`,details:bn([xn(n),e===null?null:`Call ${e}`])}}case`admin-token-revoked`:return{title:`Admin token "${yn(n,t)}" revoked`,details:bn([xn(n)])};case`credentials-revoked`:{let e=Q(n,`kind`)??`credential`,t=n.revoked,r=n.skipped,i=vn[e]??`${e}s`;return{title:`${typeof t==`number`?String(t):`?`} ${i} revoked in bulk`,details:bn([typeof r==`number`&&r>0?`${String(r)} skipped`:null,Q(n,`ids`)===null?null:`Ids ${Q(n,`ids`)??``}`])}}case`second-factor-skipped`:{let e=Q(n,`method`),t=Q(n,`factors`);return{title:`Second factor skipped on a trusted network`,details:bn([e===null?null:`Signed in with ${qt(e)}`,t===null?null:`Skipped: ${t.split(`,`).join(`, `)}`])}}default:return{title:e.action,details:Object.entries(n).map(([e,t])=>`${e}: ${String(t)}`)}}}n();var Cn=100;function wn(){let{user:e}=ot();return e?.isAdmin?u(En,{}):null}function Tn(){let{data:e}=je(),{data:t}=Y.auth.listAdminTokens.useQuery();return i(()=>{let n=new Map;for(let t of e??[])n.set(t.id,t.username);let r=new Map;for(let e of t??[])r.set(e.id,e.name);return{userNameById:n,tokenNameById:r}},[e,t])}function En(){let e=Y.auth.listAuthAudit.useQuery({limit:Cn}),{userNameById:t,tokenNameById:n}=Tn(),i=e.data??[];return r(`div`,{"data-testid":`auth-audit`,className:`rounded-lg border border-border bg-surface overflow-hidden`,children:[r(`div`,{className:`px-4 py-2.5 border-b border-border flex items-center gap-2`,children:[u(D,{className:`h-3.5 w-3.5 text-foreground-subtle`}),u(`div`,{className:`text-xs font-semibold text-foreground`,children:`Authentication audit`}),r(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:[`Latest `,Cn,`, newest first`]})]}),u(`div`,{className:`p-4`,children:e.isLoading?r(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[u(S,{className:`h-3.5 w-3.5 animate-spin`}),`Loading audit trail…`]}):e.isError?r(`div`,{className:`text-[11px] text-danger`,children:[`Could not load the audit trail: `,e.error?.message??`Request failed`]}):i.length===0?r(`div`,{className:`rounded border border-dashed border-border px-3 py-4 text-xs text-foreground-subtle text-center space-y-1`,children:[u(`div`,{children:`No authentication events recorded yet.`}),u(`div`,{className:`text-[11px] text-foreground-subtle/90`,children:`This trail records admin-token create/use/revoke, trusted-network 2FA skips, and credential revokes (including single share-link revoke). Browser password logins are not listed here.`})]}):u(`ul`,{className:`divide-y divide-border rounded-md border border-border max-h-[420px] overflow-y-auto`,children:i.map(e=>u(Dn,{record:e,userName:e.userId===void 0?null:t.get(e.userId)??e.userId,tokenNameById:n},e.id))})})]})}function Dn({record:e,userName:t,tokenNameById:n}){let i=Sn(e,n);return r(`li`,{"data-testid":`auth-audit-row`,className:`px-3 py-2 text-xs space-y-0.5`,children:[r(`div`,{className:`flex flex-wrap items-baseline gap-x-2`,children:[u(`span`,{className:`font-medium text-foreground`,children:i.title}),u(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:Ot(e.at)})]}),r(`div`,{className:`flex flex-wrap gap-x-3 text-[11px] text-foreground-subtle`,children:[t!==null&&u(`span`,{className:`text-foreground`,children:t}),e.ip!==void 0&&u(`span`,{className:`font-mono`,children:e.ip}),i.details.map(e=>u(`span`,{className:`font-mono`,children:e},e))]})]})}n();var $={loginSessions:`login-sessions`,linkedApps:`linked-apps`,tokens:`tokens`,scopedTokens:`scoped-tokens`,adminTokens:`admin-tokens`,shareLinks:`share-links`,legacyApiKeys:`legacy-api-keys`,externalIdentities:`external-identities`,audit:`auth-audit`},On={[$.scopedTokens]:$.tokens,[$.adminTokens]:$.tokens};function kn(e){return[{id:$.loginSessions,label:`Login sessions`,icon:te,render:()=>u(sn,{})},{id:$.linkedApps,label:`Linked apps`,icon:w,render:()=>u(an,{})},{id:$.tokens,label:`Tokens`,icon:H,render:({createRequested:e,onCreateConsumed:t})=>u(_n,{headerOwnsCreate:!0,createRequested:e,onCreateConsumed:t})},{id:$.shareLinks,label:`Share links`,icon:C,render:()=>u(Mt,{})},...e?[{id:$.legacyApiKeys,label:`Legacy API keys`,icon:V,render:()=>u(tn,{})}]:[],{id:$.externalIdentities,label:`Sign-in links`,icon:B,render:()=>u(en,{})},{id:$.audit,label:`Audit`,icon:D,render:()=>u(wn,{})}]}function An({createRequested:e=!1,onCreateConsumed:t}){let n=ce(),a=(n.data??[]).length>0,o=i(()=>kn(a),[a]),s=Jt({ids:i(()=>o.map(e=>e.id),[o]),answered:!n.isLoading}),c=ct(),[l]=lt(),d=l.get(`integration`),f=d===null?void 0:On[d];if(f!==void 0){let e=new URLSearchParams(l);return e.set(`integration`,f),u(at,{to:`?${e.toString()}`,replace:!0})}let p=o.find(e=>e.id===s.selectedId)??o[0],m=p?.id??$.loginSessions;return n.isLoading?u(`div`,{className:`text-sm text-foreground-subtle`,"data-testid":`access-page`,children:`Loading…`}):r(`div`,{className:`flex flex-col gap-3`,"data-testid":`access-page`,children:[u(Ge,{appearance:`pills`,value:m,onValueChange:e=>{c(`?${ft(l,e,null,null).toString()}`)},children:u(Qe,{"aria-label":`Credential kinds`,children:o.map(e=>r(et,{value:e.id,"data-testid":`access-kind-${e.id}`,children:[u(e.icon,{className:`h-3.5 w-3.5 shrink-0`,"aria-hidden":!0}),e.label]},e.id))})}),p===void 0?null:u(`div`,{role:`region`,"aria-label":p.label,"data-testid":`access-kind-body`,children:p.render({createRequested:e&&p.id===$.tokens,onCreateConsumed:t??(()=>void 0)})},p.id)]})}function jn(e,t){if(e===$.tokens)return r(G,{size:`sm`,type:`button`,"data-testid":`access-new-token`,onClick:t,children:[u(H,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),`New token`]})}function Mn(){let[e,t]=c(!1);return{createRequested:e,requestCreate:()=>t(!0),clearCreate:()=>t(!1)}}n();var Nn=[`oidcConnections`,`listConnections`],Pn=[`oidcConnections`,`connectionFormSchema`],Fn={displayName:`OpenID Connect`,icon:`shield-check`,issuerUrl:``,clientId:``,clientSecret:``,redirectUri:``,scopes:`openid profile email`,usernameClaim:`preferred_username`},In=/^[a-z0-9][a-z0-9-]{0,63}$/;function Ln(e){return e instanceof Error?e.message:String(e)}function Rn(e,t){if(t)return typeof e==`string`&&e.length>0?e:void 0;if(re(e))return se;if(typeof e==`string`&&e.length>0)return e;oe(e)}function zn(e){return typeof e!=`object`||!e?!1:Array.isArray(Reflect.get(e,`sections`))}function Bn({addonId:n}){let f=A(),p=s(),m=q(),g=Ee({editKey:`oidcEdit`,newKey:`oidcNew`}),[v,y]=c(!1),[b,x]=c(null),[S,C]=c(``),[w,T]=c({...Fn}),E=t(null),D=a({queryKey:[...Nn,n],queryFn:async()=>f.trpcClient.oidcConnections.listConnections.query({})}),O=a({queryKey:Pn,queryFn:async()=>f.trpcClient.oidcConnections.connectionFormSchema.query({})}),j=D.data??[],M=zn(O.data)?O.data:void 0,N=g.state,P=N.mode===`edit`?j.find(e=>e.id===N.id)??null:null;d(()=>{if(g.state.mode===`edit`&&P!==null){let e=`edit:${P.id}`;if(E.current===e)return;E.current=e,x(null),C(P.id),T(P.formValues===void 0?{...Fn}:{...P.formValues});return}if(g.state.mode===`new`){if(E.current===`new`)return;E.current=`new`,x(null),C(``),T({...Fn})}},[P,g.state]);let F=e(async()=>{await p.invalidateQueries({queryKey:Nn})},[p]),I=l({mutationFn:async e=>f.trpcClient.oidcConnections.deleteConnection.mutate({id:e}),onSuccess:async()=>F()}),L=e(async e=>{await m({title:`Delete OIDC connection?`,message:`Remove “${e.displayName}” (${e.id}). The login button and IdP credentials for this id are dropped.`,confirmLabel:`Delete`,cancelLabel:`Cancel`,variant:`danger`})&&(await I.mutateAsync(e.id),g.state.mode===`edit`&&g.state.id===e.id&&(g.close(),E.current=null))},[m,I,g]),ee=e(async()=>{let e=w.displayName,t=typeof e==`string`&&e.trim()!==``?e.trim():``;if(t===``){x(`Display name is required.`);return}let n=g.state.mode===`new`,r=n?S.trim():P?.id??``;if(n&&!In.test(r)){x(`Instance id must be a lowercase slug (e.g. authentik, google).`);return}if(r===``){x(`That connection is no longer available.`);return}let i=Rn(w.clientSecret,n),a=w.icon,o=w.issuerUrl,s=w.clientId,c=w.redirectUri,l=w.scopes,u=w.usernameClaim,d=u===`email`||u===`sub`?u:`preferred_username`;y(!0),x(null);try{n&&await f.trpcClient.oidcConnections.createConnection.mutate({id:r,displayName:t}),await f.trpcClient.oidcConnections.updateConnection.mutate({id:r,displayName:t,icon:typeof a==`string`?a:`shield-check`,issuerUrl:typeof o==`string`?o:``,clientId:typeof s==`string`?s:``,...i===void 0?{}:{clientSecret:i},redirectUri:typeof c==`string`?c:``,scopes:typeof l==`string`?l:`openid profile email`,usernameClaim:d}),await F(),g.close(),E.current=null}catch(e){x(Ln(e))}finally{y(!1)}},[S,P?.id,g,w,F,f]),R=i(()=>[{key:`id`,header:`Id`,sortValue:e=>e.id,render:e=>u(`span`,{className:`font-mono text-xs text-foreground`,children:e.id})},{key:`name`,header:`Name`,sortValue:e=>e.displayName,render:e=>u(`span`,{className:`truncate font-medium text-foreground`,children:e.displayName})},{key:`issuer`,header:`Issuer`,sortValue:e=>e.issuerUrl,render:e=>u(`span`,{className:`truncate text-xs text-foreground-muted`,children:e.issuerUrl===``?`—`:e.issuerUrl})},{key:`status`,header:`Status`,notSortableReason:`Badge`,render:e=>u(J,{variant:e.configured?`success`:`warning`,children:e.configured?`Configured`:`Not configured`})},{key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,nowrap:!0,render:e=>r(`div`,{className:`flex justify-end gap-1`,children:[u(G,{type:`button`,size:`sm`,variant:`secondary`,onClick:t=>{t.stopPropagation(),g.openEdit(e.id)},children:`Edit`}),u(G,{type:`button`,size:`sm`,variant:`ghost`,"aria-label":`Delete ${e.displayName}`,title:`Delete`,onClick:t=>{t.stopPropagation(),L(e)},children:u(h,{className:`h-3.5 w-3.5 text-danger`})})]})}],[g,L]),z=g.state.mode===`new`,B=z||P!==null,V=z?`new`:P===null?`closed`:`edit:${P.id}:${P.configured?`cfg`:`empty`}`;return r(`div`,{className:`flex min-h-0 flex-col gap-3`,"data-testid":`oidc-settings-connections`,children:[r(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[r(`p`,{className:`text-sm text-foreground-muted`,children:[`Each row is one IdP. Redirect URI:`,` `,u(`span`,{className:`font-mono text-xs`,children:`/addon/${n}/<id>/callback`})]}),r(G,{type:`button`,size:`sm`,"data-testid":`oidc-connections-add`,onClick:()=>g.openNew(),children:[u(_,{className:`h-3.5 w-3.5`}),`Add connection`]})]}),D.isError?u(`p`,{className:`text-sm text-danger`,children:`Could not load connections.`}):null,D.isPending?u(rt,{className:`h-32 w-full`}):u(Ce,{columns:R,rows:j,rowKey:e=>e.id,pageSize:25,mobileMode:`scroll`,emptyMessage:`No OIDC connections yet. Add one to register an IdP.`,onRowClick:e=>g.openEdit(e.id),defaultSort:{columnKey:`name`,dir:`asc`}}),u(tt,{open:B,onClose:()=>{g.close(),x(null),E.current=null},title:z?`Add OIDC connection`:`Edit ${P?.displayName??`connection`}`,icon:k,width:`xl`,testId:`oidc-connection-editor`,error:b,footer:u(G,{type:`button`,size:`sm`,disabled:v||z&&S.trim()===``,onClick:()=>void ee(),children:v?`Saving…`:`Save`}),children:B?r(o,{children:[z?r(`div`,{children:[u($e,{htmlFor:`oidc-connection-id`,children:`Instance id`}),u(He,{id:`oidc-connection-id`,value:S,onChange:e=>C(e.target.value),placeholder:`authentik`,autoComplete:`off`}),u(`p`,{className:`mt-1 text-xs text-foreground-muted`,children:`URL slug — appears in /addon/${n}/<id>/callback. Stable; renaming is not supported after save.`})]}):r(`p`,{className:`text-sm text-foreground-muted`,children:[`Instance id: `,u(`span`,{className:`font-mono`,children:P?.id})]}),M===void 0?u(`p`,{className:`text-sm text-foreground-muted`,children:`Loading form…`}):u(We,{schema:M,values:w,onChange:T,bare:!0},V)]}):null})]})}n();var Vn=3e4,Hn=[{capName:`auth-provider`,stageBadge:null},{capName:`user-passkeys`,stageBadge:`Second factor`}],Un={title:`Authentication`,subtitle:`Login providers (local password, OIDC, SAML) and second-factor providers (passkeys / WebAuthn). They run in parallel — enable or disable each independently; disabling one only removes that method, local password login is unaffected.`,emptyTitle:`No authentication providers registered`,emptyDescription:`Local auth should always be available — if this list is empty the local-auth builtin failed to register. Check the Addons page for load errors.`,installLabel:`Add provider`};function Wn(e){return e===`local-auth`?{headline:`Username + password (local).`,icon:I,bullets:[`Users live in the hub’s SQLite database — no IdP roundtrip.`,`TOTP / 2FA is self-enrolled: each user enables it from their own profile page (My access → Two-factor authentication).`,`Scoped tokens, admin tokens and sessions are managed from Identity → Tokens & sessions.`],setupSteps:[`A fresh hub has one account, admin / changeme — the first sign-in asks for a new password. Add users from Users → New user.`,`Hand out either passwords or scoped tokens — both validate through this provider.`]}:e.startsWith(`auth-oidc`)?{headline:`OpenID Connect (Google, Microsoft, Okta, Keycloak, …).`,icon:R,bullets:[`Three-leg redirect flow with PKCE S256 + nonce.`,`id_token is signature-verified against the IdP’s JWKS — no implicit trust.`,`Explicit linking only: an IdP account signs in only the CamStack user who linked it from their profile (My access → Linked sign-in accounts). No auto-created users, no email matching.`,`The linked user’s role, scopes and two-factor authentication apply.`],setupSteps:[`Register a web app at your IdP and copy the client_id + client_secret.`,"Choose a stable instance id (slug). Set the IdP redirect URI to `https://<this-hub>/addon/auth-oidc/<id>/callback`.",`In Settings below, Add connection — enter the id, issuer, and credentials; Save.`,`Each user then links their IdP account from My access → Linked sign-in accounts.`]}:e.startsWith(`auth-saml`)?{headline:`SAML 2.0 — enterprise SSO (Azure AD, Okta, OneLogin).`,icon:R,bullets:[`Heavier handshake than OIDC — exchange metadata XML with your IdP.`,`Group → role mapping via SAML assertions.`]}:e.startsWith(`auth-webauthn`)||e.startsWith(`auth-passkey`)?{headline:`Passkeys / WebAuthn — passwordless second factor.`,icon:y,bullets:[`Enroll a YubiKey, Touch ID, or platform passkey per user.`,`Resistant to phishing — the browser binds the credential to your hub origin.`]}:e.startsWith(`auth-totp`)?{headline:`TOTP — second factor.`,icon:y,bullets:[`Time-based codes from an authenticator app (RFC 6238).`,`Compatible with Google Authenticator, Aegis, 1Password, Bitwarden, etc.`]}:{headline:`Authentication provider.`,icon:k,bullets:[`Generic authentication provider. No additional hints registered.`]}}function Gn(){let e=he({capName:Hn[0].capName},{refetchInterval:Vn}),t=he({capName:Hn[1].capName},{refetchInterval:Vn}),n=ve(void 0,{refetchInterval:Vn}),r=i(()=>$t(n.data??[]),[n.data]),a=i(()=>{let n=[],i=[e.data??[],t.data??[]];for(let[e,t]of Hn.entries())for(let a of i[e]??[])n.push({addonId:a.addonId,displayName:r.get(a.addonId)??a.addonId,isActive:a.isActive,capName:t.capName,stageBadge:t.stageBadge});return n},[e.data,t.data,r]),o=[{id:`authentication`,label:`Authentication providers`,install:{capability:Hn[0].capName,label:Un.installLabel},entries:a.map(e=>({id:e.addonId,name:e.displayName,fallbackIcon:k,...Qt(e.isActive),render:()=>u(Yt,{addonId:e.addonId,displayName:e.displayName,capName:e.capName,isActive:e.isActive,badges:e.stageBadge===null?null:u(J,{variant:`info`,className:Xt,children:e.stageBadge}),settingsContent:e.addonId.startsWith(`auth-oidc`)?u(Bn,{addonId:e.addonId}):void 0,panels:[{id:`about`,title:`About`,icon:Wn(e.addonId).icon,content:u(Kn,{addonId:e.addonId})}]})}))}];return u(Zt,{embedded:!0,icon:k,title:Un.title,subtitle:Un.subtitle,groups:o,isLoading:e.isLoading||t.isLoading,emptyTitle:Un.emptyTitle,emptyDescription:Un.emptyDescription})}function Kn({addonId:e}){let t=Wn(e),n=t.icon;return r(`div`,{className:`space-y-3 rounded-lg border border-border bg-surface p-2 sm:p-4`,children:[r(`div`,{className:`flex items-start gap-2.5`,children:[u(n,{className:`h-4 w-4 mt-0.5 text-primary shrink-0`}),u(`div`,{className:`text-xs text-foreground font-medium`,children:t.headline})]}),u(`ul`,{className:`text-xs text-foreground-subtle space-y-1.5 pl-6 list-disc`,children:t.bullets.map((e,t)=>u(`li`,{children:e},t))}),t.setupSteps&&t.setupSteps.length>0&&r(`div`,{className:`rounded-md border border-border bg-surface-hover/40 px-3 py-2.5 space-y-1.5`,children:[r(`div`,{className:`flex items-center gap-1.5 text-[10px] font-semibold text-foreground-subtle uppercase tracking-wide`,children:[u(L,{className:`h-3 w-3`}),`Setup steps`]}),u(`ol`,{className:`text-xs text-foreground space-y-0.5 pl-4 list-decimal`,children:t.setupSteps.map((e,t)=>u(`li`,{children:e},t))})]}),e===`local-auth`&&r(`div`,{className:`rounded-md border border-info/30 bg-info/5 px-3 py-2 flex items-start gap-2 text-[11px] text-foreground`,children:[u(j,{className:`h-3.5 w-3.5 mt-0.5 text-info shrink-0`}),r(`span`,{children:[`TOTP / 2FA is self-service: each user enrols from their own profile page —`,` `,u(pt,{to:`/system/my-access`,className:`underline text-primary`,children:`My access`}),` `,`→ “Two-factor authentication” → Enable 2FA. Admins can only remove a user’s active enrollment (lost device) from the`,` `,u(pt,{to:`/system/identity?tab=users`,className:`underline text-primary`,children:`Users`}),` `,`page via Actions → “Remove 2FA”.`]})]})]})}function qn({isPending:e,error:t,what:n,onRetry:i,children:a}){return e?r(`div`,{className:`flex items-center gap-2 py-3 text-xs text-foreground-subtle`,role:`status`,"data-testid":`query-pending`,children:[u(S,{className:`h-3.5 w-3.5 animate-spin`,"aria-hidden":!0}),`Reading `,n,`…`]}):t===null?a:u(Oe,{title:`Could not read ${n}`,message:t.message.length>0?t.message:`Request failed`,onRetry:i})}function Jn(){let e=Y.deviceCredentials.getDeviceCaStatus.useQuery({}),t=e.data;return u(X,{id:`device-ca`,title:`Device certificate authority`,icon:k,description:`Signs the certificate each paired device holds. It is created the first time a device is paired.`,children:u(qn,{isPending:e.isPending,error:e.error,what:`the device CA`,onRetry:()=>void e.refetch(),children:t!==void 0&&r(`div`,{className:`space-y-1`,"data-testid":`device-ca-status`,children:[r(K,{label:`State`,children:[t.state===`ready`&&u(J,{variant:`success`,children:`Ready`}),t.state===`absent`&&u(J,{variant:`default`,children:`Not created yet`}),t.state===`unavailable`&&u(J,{variant:`danger`,children:`Unavailable`})]}),t.state===`ready`&&r(o,{children:[u(K,{label:`Subject`,valueClassName:`font-mono`,children:t.subject}),u(K,{label:`Fingerprint (SHA-256)`,valueClassName:`font-mono`,children:t.fingerprintSha256}),u(K,{label:`Valid until`,children:t.validTo})]}),t.state===`unavailable`&&u(K,{label:`Reason`,children:u(`span`,{className:`text-danger`,children:t.reason})})]})})})}n();function Yn(){let e=Y.useUtils(),t=Y.deviceCredentials.getDeviceCertificateSettings.useQuery({}),[n,i]=c(null),a=Y.deviceCredentials.setDeviceCertificateSettings.useMutation({onSuccess:()=>{i(null),e.deviceCredentials.getDeviceCertificateSettings.invalidate()},onError:e=>i(`Could not save: ${e.message}`)});return u(qn,{isPending:t.isPending,error:t.error,what:`the enrollment setting`,onRetry:()=>void t.refetch(),children:t.data!==void 0&&r(K,{label:`Users can enroll their own devices`,actions:u(Ke,{checked:t.data.selfEnrollment===`allowed`,disabled:a.isPending,"aria-label":`Users can enroll their own devices`,onCheckedChange:e=>a.mutate({selfEnrollment:e?`allowed`:`disabled`})}),children:[u(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.data.selfEnrollment===`allowed`?`Allowed - a user signed in on a phone can keep it signed in. Pairing by QR works either way.`:`Disabled - only an admin can pair a device, with a QR code.`}),n!==null&&u(`span`,{className:`block text-[11px] text-danger`,children:n})]})})}n();function Xn(e){let[t,n]=c(()=>Date.now());return d(()=>{let t=setInterval(()=>n(Date.now()),e);return()=>clearInterval(t)},[e]),t}n();var Zn=80,Qn=208;function $n({open:e,users:t,onClose:n,onPaired:i}){let a=Y.deviceCredentials.startEnrollment.useMutation({onSuccess:i}),[o,s]=c(``),[l,d]=c(``),f=o===``?t[0]?.id??``:o,p=a.data,m=()=>{a.reset(),d(``),n()};return u(tt,{open:e,onClose:m,title:`Pair a device`,icon:y,width:`md`,testId:`pair-device-dialog`,error:a.isError?a.error.message:null,footer:p===void 0?r(G,{type:`button`,onClick:()=>{let e=l.trim();f===``||e===``||a.mutate({userId:f,deviceName:e})},disabled:a.isPending||f===``||l.trim()===``,children:[a.isPending&&u(S,{className:`h-3.5 w-3.5 animate-spin`,"aria-hidden":!0}),`Create pairing code`]}):u(G,{type:`button`,variant:`outline`,onClick:m,children:`Done`}),children:p===void 0?r(`div`,{className:`space-y-3`,children:[u(`p`,{className:`text-[11px] text-foreground-subtle`,children:`Creates a one-time code for a phone you hold. Scan it with the CamStack app on that phone; the phone then stays signed in as the chosen user until you revoke it.`}),u(xe,{label:`User`,required:!0,children:u(Se,{value:f,onChange:e=>s(e.target.value),options:t.map(e=>({value:e.id,label:e.username}))})}),u(xe,{label:`Device name`,required:!0,description:`How this phone is listed, e.g. Anna's iPhone.`,children:u(He,{value:l,maxLength:Zn,onChange:e=>d(e.target.value),placeholder:`Anna's iPhone`,autoFocus:!0})})]}):u(er,{enrollUrl:p.enrollUrl,expiresAt:p.expiresAt,hubKnown:p.hubOrigin!==null,onRestart:()=>a.reset()})})}function er({enrollUrl:e,expiresAt:t,hubKnown:n,onRestart:i}){let a=zt(t,Xn(1e3));return u(`div`,{className:`space-y-3`,"data-testid":`pair-issued`,children:r(`div`,{className:`flex flex-col items-center gap-3 sm:flex-row sm:items-start`,children:[u(`div`,{className:a.expired?`opacity-30`:void 0,children:u(fe,{value:e,size:Qn,alt:`Enrollment QR code`})}),r(`div`,{className:`min-w-0 flex-1 space-y-2`,children:[u(`p`,{className:`text-[11px] text-foreground-subtle`,children:`Open the CamStack app on the phone and scan this code. It works once.`}),u(`div`,{className:`text-sm font-semibold tabular-nums text-foreground`,role:`timer`,"data-testid":`pair-countdown`,children:a.expired?`Expired - create a new code`:`Expires in ${a.label}`}),r(`div`,{className:`flex items-center gap-1 rounded-md border border-border bg-background px-2 py-1`,children:[u(`code`,{className:`min-w-0 flex-1 select-all break-all font-mono text-[11px] text-foreground`,children:e}),u(be,{value:e,srLabel:`Enrollment link`})]}),!n&&r(`div`,{className:`flex items-start gap-2 rounded-md border border-warning/30 bg-warning/5 px-2.5 py-1.5 text-[11px] text-foreground`,children:[u(g,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`,"aria-hidden":!0}),u(`span`,{children:`The hub could not name an address for this link, so the app must already know it.`})]}),a.expired&&u(G,{type:`button`,variant:`outline`,size:`sm`,onClick:i,children:`New code`})]})]})})}n();var tr={one:`device`,many:`devices`};function nr({pairOpen:e,onPairClose:t}){let n=q(),a=Fe(),o=Y.useUtils(),s=Y.deviceCredentials.listDeviceCredentials.useQuery({includeRevoked:!0}),l=je(),[d,p]=c(null),[m,g]=c(null),_=()=>void o.deviceCredentials.listDeviceCredentials.invalidate(),b=e=>t=>{g(null),p(`${e} failed: ${t.message}`)},x=()=>{g(null),_()},S=Y.deviceCredentials.revokeDeviceCredential.useMutation({onSuccess:x,onError:b(`Revoke`)}),C=Y.deviceCredentials.deleteDeviceCredential.useMutation({onSuccess:e=>{e.result!==`deleted`&&p(e.result===`live`?`Only a revoked device can be deleted: revoke it first.`:`That device no longer exists.`),x()},onError:b(`Delete`)}),w=Y.deviceCredentials.renameDeviceCredential.useMutation({onSuccess:x,onError:b(`Rename`)}),T=Pt(tr,e=>S.mutateAsync({id:e}),_),E=T.busy||m!==null,D=i(()=>(s.data??[]).map(Rt),[s.data]),O=async e=>{await n({title:`Revoke "${e.name}"?`,message:`${e.ownerName}'s device stops signing in at once and its open sessions end. To use it again it has to be paired anew. This cannot be undone.`,confirmLabel:`Revoke`,variant:`danger`})&&(p(null),g(e.id),S.mutate({id:e.id}))},k=async e=>{await n({title:`Delete "${e.name}"?`,message:`${e.name} is removed from the list. The audit trail keeps the revocation.`,confirmLabel:`Delete`,variant:`danger`})&&(p(null),g(e.id),C.mutate({id:e.id}))},A=async e=>{let t=(await a({title:`Rename device`,label:`Device name`,defaultValue:e.name,confirmLabel:`Rename`}))?.trim()??``;t===``||t===e.name||(p(null),g(e.id),w.mutate({id:e.id,deviceName:t}))},j={label:`Revoke`,icon:f,isAvailable:Dt,onRun:e=>void O(e),busyId:S.isPending?m:null,disabled:E},M=[{label:`Rename`,icon:v,tone:`neutral`,isAvailable:()=>!0,onRun:e=>void A(e),busyId:w.isPending?m:null,disabled:E},{label:`Delete`,icon:h,isAvailable:Nt,onRun:e=>void k(e),busyId:C.isPending?m:null,disabled:E}];return r(X,{id:`devices`,title:`Devices`,icon:y,description:`Phones that stay signed in with a certificate instead of a login. Revoking one signs it out at once; it has to be paired again.`,notice:Z(d,T.outcome),onDismissNotice:()=>{p(null),T.dismiss()},children:[u(Yn,{}),u(Ft,{rows:D,label:`devices`,isLoading:s.isPending,loadError:s.error===null?null:s.error.message||`Request failed`,emptyText:`No devices paired yet.`,expiresNone:`—`,action:j,extraActions:M,bulk:{revoke:T,noun:tr,isSelectable:Dt}}),u($n,{open:e,users:l.data??[],onClose:t,onPaired:_})]})}var rr={ok:`text-foreground-subtle`,soon:`text-warning`,expired:`text-danger`,unknown:`text-foreground-subtle`};function ir(e){let t=e.find(e=>e.isHub);return t?.https.kind===`served`?t.https.status.caFingerprintSha256:null}function ar({https:e,mesh:t,now:n}){let i=ue().data?.caCertPem??``,a=()=>{if(i===``)return;let e=URL.createObjectURL(new Blob([i],{type:`application/x-pem-file`})),t=document.createElement(`a`);t.href=e,t.download=`camstack-ca.crt`,t.click(),URL.revokeObjectURL(e)},o=t?.ca,s=o?.state===`ready`?Date.parse(o.validTo):null,c=t?.listener;return r(`div`,{className:`space-y-1`,"data-testid":`ca-strip`,children:[u(K,{label:`Local HTTPS CA (SHA-256)`,valueClassName:`font-mono`,children:r(`span`,{className:`flex flex-wrap items-center gap-2`,children:[ir(e)??`—`,i!==``&&r(G,{type:`button`,variant:`ghost`,size:`sm`,onClick:a,children:[u(p,{className:`h-3 w-3`,"aria-hidden":!0}),`Download CA`]})]})}),u(K,{label:`Cluster CA (SHA-256)`,valueClassName:`font-mono`,children:o===void 0?`—`:o.state===`ready`?o.fingerprintSha256:r(`span`,{className:`text-danger`,children:[`Unavailable - `,o.reason]})}),o?.state===`ready`&&r(K,{label:`Cluster CA valid until`,children:[o.validTo,s!==null&&!Number.isNaN(s)&&r(`span`,{className:`ml-2 text-[10px] ${rr[Ut(s,n)]}`,children:[`(`,kt(s,n),`)`]})]}),c!==void 0&&r(K,{label:`Node listener`,children:[c.state===`open`&&u(J,{variant:`success`,children:`Open`}),c.state===`not-started`&&u(J,{variant:`default`,children:`Not started`}),c.state===`closed`&&r(`span`,{className:`text-danger`,children:[`Closed since `,At(c.since),` - every node is refused.`,` `,c.reason]})]}),t!==void 0&&!t.registryAvailable&&r(`div`,{className:`flex items-start gap-2 rounded-md border border-warning/30 bg-warning/5 px-2.5 py-1.5 text-[11px] text-foreground`,children:[u(g,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`,"aria-hidden":!0}),u(`span`,{children:`The certificate registry is not up, so the node list below is incomplete.`})]})]})}function or(e,t){let n=new Set;for(let t of e)n.add(t.nodeId);for(let e of t?.nodes??[])n.add(e.nodeId);return[...n].map(n=>{let r=e.find(e=>e.nodeId===n)??null,i=t?.nodes.find(e=>e.nodeId===n)??null;return{nodeId:n,isHub:r?.isHub??n===`hub`,online:r?.online??i?.online??!1,https:r,mesh:i}}).toSorted((e,t)=>Number(t.isHub)-Number(e.isHub)||e.nodeId.localeCompare(t.nodeId))}function sr(e){return e.isHub?`The hub's own cluster certificate is re-issued at every boot; there is nothing to renew or revoke.`:e.mesh===null?`No cluster certificate is recorded for this node.`:e.online?null:`The node is offline - it cannot be renewed now.`}function cr(e){return e.isHub||e.mesh===null?sr(e):null}var lr={ok:`text-foreground-subtle`,soon:`text-warning`,expired:`text-danger`,unknown:`text-foreground-subtle`},ur={enroll:`Issued at enrollment`,renewal:`Issued by a renewal`,boot:`Issued at boot`,pairing:`Issued at pairing`,observed:`Observed on its connection`},dr={uploaded:`Uploaded`,generated:`Generated`,disabled:`Disabled`};function fr(e){let t=e.https?.https;return t?.kind===`served`?Vt(t.status.validTo):null}function pr({ms:e,now:t}){return e===null?u(`span`,{className:`text-foreground-subtle`,children:`—`}):r(`div`,{children:[u(`div`,{children:At(e)}),u(`div`,{className:`text-[10px] ${lr[Ut(e,t)]}`,children:kt(e,t)})]})}function mr({row:e}){let t=e.https?.https;return t===void 0?u(`span`,{className:`text-foreground-subtle`,children:`—`}):t.kind===`served`?r(`div`,{title:t.status.leafFingerprintSha256??``,children:[u(J,{variant:`success`,className:`text-[10px]`,children:`Served`}),u(`span`,{className:`ml-1.5 text-[10px] text-foreground-subtle`,children:dr[t.status.mode]}),u(`div`,{className:`mt-1 font-mono text-[10px] text-foreground-subtle`,children:Bt(t.status.leafFingerprintSha256)}),t.status.sans.length>0&&u(`div`,{className:`mt-0.5 max-w-[14rem] truncate font-mono text-[10px] text-foreground-subtle`,title:t.status.sans.join(`, `),children:t.status.sans.join(`, `)})]}):r(`div`,{className:`max-w-[16rem]`,children:[u(J,{variant:t.kind===`unreadable`?`danger`:`warning`,className:`text-[10px]`,children:t.kind===`unreadable`?`Unreadable`:`Not served`}),u(`div`,{className:`mt-1 whitespace-normal text-[10px] text-foreground-subtle`,children:t.reason})]})}function hr({row:e}){let t=e.mesh?.current??null;if(t===null)return u(`span`,{className:`text-foreground-subtle`,children:`None recorded`});let n=e.mesh?.history.length??0;return r(`div`,{children:[u(`div`,{className:`font-mono text-[11px]`,title:t.serial,children:Lt(t.serial)}),u(`div`,{className:`font-mono text-[10px] text-foreground-subtle`,title:t.fingerprintSha256,children:Bt(t.fingerprintSha256)}),r(`div`,{className:`text-[10px] text-foreground-subtle`,children:[ur[t.issuedVia],n>0?` · ${String(n)} earlier`:``]})]})}function gr({row:e}){let t=e.mesh?.presentingCurrent??null;return t===null?u(`span`,{className:`text-foreground-subtle`,children:e.online?`—`:`Offline`}):t?u(J,{variant:`success`,className:`text-[10px]`,children:`Yes`}):u(J,{variant:`warning`,className:`text-[10px]`,children:`No - presents another`})}function _r(e){let t=e.icon;return r(G,{type:`button`,variant:`ghost`,size:`sm`,className:e.danger?`text-danger hover:bg-danger/10`:void 0,disabled:e.reason!==null||e.busy,title:e.reason??void 0,"aria-label":e.ariaLabel,onClick:e.onClick,children:[e.spinning?u(S,{className:`h-3 w-3 animate-spin`,"aria-hidden":!0}):u(t,{className:`h-3 w-3`,"aria-hidden":!0}),e.label]})}function vr({row:e,o:t}){let n=e.https===null?`No HTTPS inventory for this node.`:jt(e.https).reason,i=sr(e),a=cr(e),o=n=>t.running?.nodeId===e.nodeId&&t.running.action===n;return r(`div`,{className:`flex w-44 flex-col items-end gap-1`,children:[r(`div`,{className:`flex flex-col items-end gap-0.5`,children:[u(_r,{label:`Renew HTTPS`,ariaLabel:`Renew the certificate on ${e.nodeId}`,icon:F,reason:n,busy:t.busy,spinning:o(`renew-https`),danger:!1,onClick:()=>t.onRenewHttps(e)}),u(_r,{label:o(`renew-identity`)?`Renewing…`:`Renew identity`,ariaLabel:`Renew the cluster certificate of ${e.nodeId}`,icon:F,reason:i,busy:t.busy,spinning:o(`renew-identity`),danger:!1,onClick:()=>t.onRenewIdentity(e)}),u(_r,{label:`Revoke identity`,ariaLabel:`Revoke the cluster certificate of ${e.nodeId}`,icon:f,reason:a,busy:t.busy,spinning:o(`revoke-identity`),danger:!0,onClick:()=>t.onRevokeIdentity(e)})]}),n!==null&&e.https!==null&&u(`div`,{className:`w-full whitespace-normal text-right text-[10px] text-foreground-subtle`,"data-testid":`renew-reason-${e.nodeId}`,children:n}),i!==null&&u(`div`,{className:`w-full whitespace-normal text-right text-[10px] text-foreground-subtle`,"data-testid":`mesh-reason-${e.nodeId}`,children:i})]})}function yr(e){return[{key:`node`,header:`Node`,sortValue:e=>e.isHub?``:e.nodeId.toLowerCase(),render:e=>r(`div`,{className:`flex items-center gap-1.5`,children:[u(`span`,{className:`font-medium text-foreground`,children:e.nodeId}),e.nodeId===`hub`&&u(J,{variant:`info`,className:`text-[10px]`,children:`hub`}),!e.online&&u(J,{variant:`default`,className:`text-[10px]`,children:`offline`})]})},{key:`https-state`,header:`HTTPS`,notSortableReason:`A state with a reason has no single order.`,render:e=>u(mr,{row:e})},{key:`https-expires`,header:`HTTPS expires`,sortValue:e=>fr(e),render:t=>u(pr,{ms:fr(t),now:e.now})},{key:`identity`,header:`Identity`,sortValue:e=>e.mesh?.current?.serial??null,render:e=>u(hr,{row:e})},{key:`identity-expires`,header:`Identity expires`,sortValue:e=>e.mesh?.current?.notAfter??null,render:t=>u(pr,{ms:t.mesh?.current?.notAfter??null,now:e.now})},{key:`presenting`,header:`In use`,notSortableReason:`Offline nodes have no answer to order by.`,render:e=>u(gr,{row:e})},{key:`actions`,header:`Actions`,align:`right`,notSortableReason:`Actions have no order.`,render:t=>u(vr,{row:t,o:e})}]}n();function br(){let e=q(),t=Y.useUtils(),n=Xn(6e4),a=Y.certificates.listHttpsCertificates.useQuery(),o=Y.certificates.getMeshCertificates.useQuery(),[s,l]=c(null),[d,f]=c(null),[p,m]=c(null),h=()=>{m(null),t.certificates.listHttpsCertificates.invalidate(),t.certificates.getMeshCertificates.invalidate()},g=e=>(t,n)=>{m(null),l(`${n.nodeId}: ${e} - ${t.message}`)},_=Y.certificates.renewHttpsOnNode.useMutation({onSuccess:(e,t)=>{f({tone:`success`,message:e.restartRequired?`${t.nodeId}: new certificate issued. Restart the node to serve it.`:`${t.nodeId}: new certificate issued and served.`}),h()},onError:g(`renewal failed`)}),v=Y.certificates.renewMeshOnNode.useMutation({onSuccess:e=>{f(It(e)),h()},onError:g(`renewal could not start`)}),y=Y.certificates.revokeMeshOnNode.useMutation({onSuccess:e=>{f({tone:`success`,message:`${e.nodeId}: ${e.next}`}),h()},onError:g(`revoke failed`)}),b=_.isPending||v.isPending||y.isPending,x=(e,t)=>{l(null),f(null),m({nodeId:e,action:t})},S=async t=>{await e({title:`Renew HTTPS on "${t.nodeId}"?`,message:t.isHub?`A new certificate is issued from the local CA. Clients that trust the CA keep working.`:`The node makes a new key, the hub signs it and the node switches over without a restart. It keeps serving what it had if anything fails.`,confirmLabel:`Renew`})&&(x(t.nodeId,`renew-https`),_.mutate({nodeId:t.nodeId}))},C=e=>{x(e.nodeId,`renew-identity`),v.mutate({nodeId:e.nodeId})},w=async t=>{await e({title:`Revoke the identity of "${t.nodeId}"?`,message:`${t.nodeId} is disconnected at once and can no longer connect. To bring it back it must be paired again from System → Cluster → Agents. It stays in the node list until you forget it on the Cluster page. This cannot be undone.`,confirmLabel:`Revoke and disconnect`,variant:`danger`})&&(x(t.nodeId,`revoke-identity`),y.mutate({nodeId:t.nodeId}))},T=yr({now:n,busy:b,running:p,onRenewHttps:e=>void S(e),onRenewIdentity:C,onRevokeIdentity:e=>void w(e)}),E=i(()=>or(a.data??[],o.data),[a.data,o.data]),D=o.data?.registryAvailable??!0;return u(X,{id:`nodes`,title:`Nodes`,icon:N,description:`Each node holds two certificates: one it serves over HTTPS, one that proves its identity to the hub. Renewing replaces a certificate without a gap; revoking an identity cuts the node off until it re-joins.`,notice:Z(s,d),onDismissNotice:()=>{l(null),f(null)},children:u(qn,{isPending:a.isPending||o.isPending,error:a.error??o.error,what:`node certificates`,onRetry:()=>{a.refetch(),o.refetch()},children:r(`div`,{className:`space-y-3`,children:[u(ar,{https:a.data??[],mesh:o.data,now:n}),u(Ce,{columns:T,rows:E,rowKey:e=>e.nodeId,minWidthPx:960,mobileMode:`cards`,maxBodyHeight:Be,defaultSort:{columnKey:`node`,dir:`asc`},emptyMessage:D?`No nodes reported.`:`The certificate registry is not available yet, so nodes cannot be listed.`})]})})})}function xr({pairOpen:e,onPairClose:t}){return r(`div`,{className:`space-y-4`,"data-testid":`certificates-page`,children:[u(nr,{pairOpen:e,onPairClose:t}),u(Jn,{}),u(br,{})]})}function Sr({userId:e,username:t,onClose:n}){let i=q(),a=Y.useUtils(),o=qe({userId:e}),s=Y.auth.listLoginMethods.useQuery(),c=nt({onSuccess:()=>void a.userManagement.listExternalIdentities.invalidate()}),l=new Map((s.data??[]).flatMap(e=>e.kind===`redirect`?[[e.id,e.label]]:[])),d=o.data??[],f=async(n,r)=>{await i({title:`Remove sign-in link`,message:`"${t}" will no longer be able to sign in with this ${r} account.`,confirmLabel:`Remove`,variant:`danger`})&&c.mutate({userId:e,provider:n.provider,subject:n.subject})};return u(ze,{open:!0,onOpenChange:e=>!e&&n(),children:r(me,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`external-identities-modal`,children:[u(le,{children:r(Je,{className:`flex items-center gap-2`,children:[u(w,{className:`h-4 w-4 text-primary`}),r(`span`,{children:[`Linked sign-in accounts`,r(`span`,{className:`mt-0.5 block text-[11px] font-normal text-foreground-subtle`,children:[`User: `,u(`span`,{className:`font-mono`,children:t})]})]})]})}),u(_e,{className:`space-y-3`,children:o.isLoading?r(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[u(S,{className:`h-3.5 w-3.5 animate-spin`}),`Loading…`]}):d.length===0?u(`p`,{className:`text-xs text-foreground-subtle`,children:`No linked accounts. Only the user can link one, from their own profile page.`}):u(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:d.map(e=>{let t=l.get(e.provider),n=t??e.provider;return r(`li`,{className:`flex items-center gap-3 px-3 py-2 text-xs`,children:[r(`div`,{className:`flex-1 min-w-0`,children:[r(`div`,{className:`font-medium text-foreground truncate`,children:[n,t===void 0&&u(`span`,{className:`ml-2 rounded bg-foreground-subtle/15 px-1.5 py-0.5 text-[10px] font-normal text-foreground-subtle`,children:`provider unavailable`})]}),r(`div`,{className:`text-[11px] text-foreground-subtle truncate`,children:[e.label??e.subject,` ·`,` `,new Date(e.linkedAt).toLocaleDateString()]})]}),r(`button`,{onClick:()=>void f(e,n),disabled:c.isPending,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-danger hover:bg-danger/10 disabled:opacity-50`,children:[u(U,{className:`h-3 w-3`}),`Remove`]})]},`${e.provider}|${e.subject}`)})})}),u(Xe,{children:u(G,{onClick:n,variant:`secondary`,children:`Close`})})]})})}function Cr({userId:e,username:t,onClose:n}){let i=s(),a=q(),c=Ye({userId:e}),l=c.data,d=()=>i.invalidateQueries({queryKey:[[`userManagement`,`getTotpStatus`]]}),f=Me({onSuccess:()=>{d(),n()}}),p=c.isLoading?`loading`:l?.enabled?`enrolled`:`not_enrolled`;return u(ze,{open:!0,onOpenChange:e=>!e&&n(),children:r(me,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,children:[u(le,{children:r(Je,{className:`flex items-center gap-2`,children:[u(y,{className:`h-4 w-4 text-primary`}),r(`span`,{children:[`Two-factor authentication`,r(`span`,{className:`mt-0.5 block text-[11px] font-normal text-foreground-subtle`,children:[`User: `,u(`span`,{className:`font-mono`,children:t})]})]})]})}),r(_e,{className:`space-y-4`,children:[p===`loading`&&r(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[u(S,{className:`h-3.5 w-3.5 animate-spin`}),`Checking status…`]}),p===`not_enrolled`&&r(`div`,{className:`rounded-md border border-border bg-surface-hover/30 px-3 py-2.5 flex items-start gap-2.5 text-xs text-foreground-subtle`,children:[u(j,{className:`h-4 w-4 mt-0.5 shrink-0`}),r(`div`,{children:[u(`div`,{className:`font-medium text-foreground`,children:`2FA not enrolled`}),u(`p`,{className:`mt-0.5`,children:`Only the user themselves can enable 2FA, from their own profile page.`})]})]}),p===`enrolled`&&l&&r(o,{children:[r(`div`,{className:`rounded-md border border-emerald-500/30 bg-emerald-500/5 px-3 py-2.5 flex items-start gap-2.5`,children:[u(E,{className:`h-4 w-4 mt-0.5 text-emerald-500 shrink-0`}),r(`div`,{className:`text-xs text-foreground space-y-0.5`,children:[u(`div`,{className:`font-medium`,children:`2FA is active`}),r(`div`,{className:`text-foreground-subtle`,children:[`Enrolled on`,` `,l.confirmedAt?new Date(l.confirmedAt).toLocaleString():`—`]})]})]}),u(`div`,{className:`text-[11px] text-foreground-subtle`,children:`Removing here clears the server-side secret. Use this only when the user has lost access — they'll have to re-enroll from their profile page afterwards.`}),r(`div`,{className:`flex justify-end gap-2`,children:[u(G,{onClick:n,variant:`secondary`,children:`Close`}),r(`button`,{onClick:async()=>{await a({title:`Remove 2FA`,message:`Remove two-factor authentication for "${t}"? They'll be able to log in with just their password until they re-enroll from their own profile page.`,confirmLabel:`Remove`,variant:`danger`})&&f.mutate({userId:e})},disabled:f.isPending,className:`rounded bg-danger px-3 py-1.5 text-xs font-medium text-white hover:bg-danger/90 disabled:opacity-50 inline-flex items-center gap-1`,children:[f.isPending?u(S,{className:`h-3 w-3 animate-spin`}):u(T,{className:`h-3 w-3`}),`Remove 2FA`]})]})]})]})]})})}n();function wr({userId:e,username:t,onClose:n}){let{user:i,logout:a}=ot(),o=i?.id===e,s=q(),l=Y.useUtils(),d=Y.auth.listSessions.useQuery({userId:e}),[f,p]=c(null),m=Y.auth.revokeSessions.useMutation({onSuccess:(e,t)=>{if(o&&`userId`in t){a();return}l.auth.listSessions.invalidate()},onError:e=>p(`Sign out failed: ${e.message}`)}),h=async e=>{await s({title:`Sign out this session`,message:`"${t}" on ${Wt(e.client).label} will have to sign in again.`,confirmLabel:`Sign out`,variant:`danger`})&&(p(null),m.mutate({id:e.id}))},g=async()=>{await s({title:`Sign out everywhere`,message:o?`Every session of your own account ends, this browser included: you will be signed out here too.`:`Every session of "${t}" ends at once; each device has to sign in again.`,confirmLabel:`Sign out everywhere`,variant:`danger`})&&(p(null),m.mutate({userId:e}))},_=m.isPending&&m.variables!==void 0&&`id`in m.variables?m.variables.id:null;return u(ze,{open:!0,onOpenChange:e=>!e&&n(),children:r(me,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`user-sessions-modal`,children:[u(le,{children:r(Je,{className:`flex items-center gap-2`,children:[u(te,{className:`h-4 w-4 text-primary`}),r(`span`,{children:[`Active sessions`,r(`span`,{className:`mt-0.5 block text-[11px] font-normal text-foreground-subtle`,children:[`User: `,u(`span`,{className:`font-mono`,children:t})]})]})]})}),r(_e,{className:`space-y-3`,children:[f!==null&&u(`div`,{className:`text-[11px] text-danger`,children:f}),u(Ht,{sessions:d.data??[],isLoading:d.isLoading,loadError:d.isError?d.error?.message??`Request failed`:null,emptyText:`No active sessions.`,onRevoke:e=>void h(e),revokingId:_})]}),r(Xe,{className:`justify-between`,children:[r(`button`,{onClick:()=>void g(),disabled:m.isPending||(d.data??[]).length===0,className:`inline-flex items-center gap-1.5 rounded border border-danger/40 px-2.5 py-1 text-[11px] font-medium text-danger hover:bg-danger/10 disabled:opacity-50`,children:[m.isPending&&_===null?u(S,{className:`h-3 w-3 animate-spin`}):u(z,{className:`h-3 w-3`}),`Sign out everywhere`]}),u(G,{onClick:n,variant:`secondary`,children:`Close`})]})]})})}function Tr({icon:e,label:t,count:n,all:i,total:a}){return r(`div`,{className:`flex items-center gap-2 text-[11px]`,children:[u(e,{className:`h-3 w-3 shrink-0 text-foreground-subtle`}),u(`span`,{className:`min-w-0 flex-1 text-foreground-subtle`,children:t}),u(`span`,{className:n===0?`text-foreground-subtle`:`font-medium text-foreground`,children:n===0?`none`:i?`all ${a}`:`${n} of ${a}`})]})}function Er({scopes:e,isAdmin:t,invalidReason:n}){let i=A(),s=a({queryKey:[`auth`,`previewScope`,e,t],enabled:n===null,queryFn:()=>i.trpcClient.auth.previewScope.query({scopes:[...e],isAdmin:t})}),{data:c}=Ze({projection:`slim`}),l=c?.length??0;if(n!==null)return u(`div`,{className:`rounded-lg border border-border bg-surface p-3`,children:r(`p`,{className:`flex items-center gap-1.5 text-[11px] text-warning`,children:[u(M,{className:`h-3 w-3 shrink-0`}),n]})});if(s.isLoading)return r(`div`,{className:`flex items-center gap-2 rounded-lg border border-border bg-surface p-3 text-[11px] text-foreground-subtle`,children:[u(S,{className:`h-3 w-3 animate-spin`}),`Resolving…`]});if(s.isError||!s.data)return u(`div`,{className:`rounded-lg border border-border bg-surface p-3`,children:u(`p`,{className:`text-[11px] text-danger`,children:`Could not resolve this grant set. Saving is still allowed — the server enforces the same rules either way.`})});let d=s.data;return u(`div`,{className:`space-y-2 rounded-lg border border-border bg-surface p-3`,children:d.isAdmin?r(`p`,{className:`text-[11px] text-foreground`,children:[u(`span`,{className:`font-medium`,children:`Administrator`}),` — unrestricted. Grants are ignored for an admin.`]}):r(o,{children:[u(Tr,{icon:m,label:`Devices they can see`,count:d.device.view.deviceCount,all:d.device.view.all,total:l}),u(Tr,{icon:v,label:`Devices they can operate`,count:d.device.create.deviceCount,all:d.device.create.all,total:l}),u(Tr,{icon:h,label:`Devices they can delete`,count:d.device.delete.deviceCount,all:d.device.delete.all,total:l}),r(`div`,{className:`border-t border-border pt-2 text-[10px] text-foreground-subtle`,children:[`System access: `,d.system.length===0?`none`:d.system.join(`, `),d.capabilities.length>0&&r(o,{children:[` · Extra capabilities: `,d.capabilities.map(e=>e.name).join(`, `)]}),d.addons.length>0&&r(o,{children:[` · Addons: `,d.addons.map(e=>e.name).join(`, `)]})]}),d.device.view.deviceCount===0&&u(`p`,{className:`text-[10px] text-warning`,children:`This user will not be able to see any device.`})]})})}n();function Dr(e){let t=W(e);return t===null?{mode:e.length===0?`role`:`advanced`,roleId:null,selector:{kind:`all`},includeLinked:!0,advancedScopes:e}:{mode:`role`,roleId:t.roleId,selector:t.selector,includeLinked:t.includeLinked,advancedScopes:e}}function Or(e){return e.mode===`advanced`?e.advancedScopes:e.roleId===null?[]:ne({roleId:e.roleId,selector:e.selector,includeLinked:e.includeLinked})}function kr({user:e,onClose:t,onSubmit:n,submitting:a,callerScopes:s}){let l=i(()=>Dr(e.scopes??[]),[e.scopes]),[d,f]=c(l),[p,m]=c(l.mode===`advanced`),h=i(()=>Or(d),[d]),g=!e.isAdmin&&d.mode===`role`&&d.roleId===null,_=i(()=>e.isAdmin?null:d.mode===`role`&&d.roleId===null?`Pick what this user can do to see the result.`:Ne(h),[e.isAdmin,d.mode,d.roleId,h]),v=e=>f({...d,...e});return u(ze,{open:!0,onOpenChange:e=>!e&&t(),children:r(me,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,className:`md:max-w-2xl`,children:[r(le,{children:[r(Je,{children:[`Access — `,e.username]}),u(`p`,{className:`text-[10px] text-foreground-subtle`,children:e.isAdmin?`This user is an administrator — they can do everything, and the settings below are ignored.`:`Choose what they can do, then which devices it applies to.`})]}),r(_e,{className:`space-y-4`,children:[g&&r(`div`,{className:`flex items-start gap-2 rounded-lg border border-warning/40 bg-warning/10 p-3`,children:[u(M,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`}),r(`p`,{className:`text-[11px] text-foreground`,children:[u(`span`,{className:`font-medium`,children:`No access.`}),` `,r(`span`,{className:`text-foreground-subtle`,children:[e.username,` cannot see or do anything yet. Configure it below.`]})]})]}),r(`section`,{className:`space-y-2`,children:[u(`h3`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:`1 · What can they do`}),u(`div`,{className:`space-y-1.5`,children:ie.map(e=>{let t=d.mode===`role`&&d.roleId===e.id;return r(`label`,{className:`flex cursor-pointer items-start gap-2 rounded-lg border p-2.5 transition-colors ${t?`border-primary bg-primary/5`:`border-border hover:bg-foreground-subtle/5`}`,children:[u(`input`,{type:`radio`,name:`access-role`,checked:t,onChange:()=>v({mode:`role`,roleId:e.id}),className:`mt-0.5 border-border focus:ring-primary`}),r(`span`,{className:`min-w-0`,children:[u(`span`,{className:`block text-[12px] font-medium text-foreground`,children:e.label}),u(`span`,{className:`mt-0.5 block text-[10px] text-foreground-subtle`,children:e.description})]})]},e.id)})}),r(`button`,{type:`button`,onClick:()=>{if(!p){f({...d,mode:`advanced`,advancedScopes:h}),m(!0);return}m(!1),f(Dr(d.advancedScopes))},className:`inline-flex items-center gap-1 rounded px-1.5 py-1 text-[10px] text-foreground-subtle transition-colors hover:bg-foreground-subtle/10 hover:text-foreground`,children:[u(p?P:x,{className:`h-3 w-3`}),`Advanced — edit raw grants`]}),p&&r(`div`,{className:`rounded-lg border border-border p-2`,children:[u(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:`One row per grant. Anything expressible here overrides the three roles above; close this section to go back to them.`}),u(Ae,{value:d.advancedScopes,onChange:e=>v({mode:`advanced`,advancedScopes:e}),clampToParent:s,emptyHint:r(o,{children:[`No grants.`,` `,u(`span`,{className:`font-medium text-foreground`,children:e.username}),` cannot call any protected endpoint until one is added.`]})})]})]}),d.mode===`role`&&r(`section`,{className:`space-y-2`,children:[u(`h3`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:`2 · On which devices`}),u(Ve,{value:d.selector,onChange:e=>v({selector:e}),includeLinked:d.includeLinked,onIncludeLinkedChange:e=>v({includeLinked:e}),clampToDeviceIds:null})]}),r(`section`,{className:`space-y-2`,children:[u(`h3`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:d.mode===`role`?`3 · Result`:`2 · Result`}),u(Er,{scopes:h,isAdmin:e.isAdmin,invalidReason:_})]})]}),r(Xe,{children:[u(G,{variant:`outline`,size:`sm`,onClick:t,children:`Cancel`}),u(G,{size:`sm`,onClick:()=>n([...h]),disabled:a||_!==null,children:a?u(S,{className:`h-3 w-3 animate-spin`}):`Save access`})]})]})})}n();var Ar=8;function jr(){return{username:``,password:``,isAdmin:!1}}function Mr(e){return{id:e.id,username:e.username,password:``,isAdmin:e.isAdmin}}function Nr(e){return e instanceof Error?e.message:`Something went wrong`}function Pr(){let e=s(),{user:t}=ot(),{state:n,openNew:i,openEdit:a,close:l}=Ee(),[f,p]=c(null),[m,g]=c(null),[x,C]=c(!1),{data:T,isLoading:E,isError:D,error:O,refetch:A}=je(),j=q(),M=Fe(),N=()=>e.invalidateQueries({queryKey:[[`userManagement`,`listUsers`]]}),P=ge(),F=pe({onSuccess:N}),I=de({onSuccess:N}),L=Pe({onSuccess:N}),R=Ie({onSuccess:()=>{N(),B(null)}}),[z,B]=c(null),[V,H]=c(null),[U,ne]=c(null),[re,ie]=c(null),W=T??[],ae=n.mode===`edit`?W.find(e=>e.id===n.id)??null:null,oe=()=>{p(null),g(null),C(!1),P.reset(),I.reset(),l()};d(()=>{if(n.mode===`closed`){p(null),g(null),C(!1);return}if(n.mode===`new`){p(e=>e!==null&&e.id===void 0?e:jr());return}if(ae===null){E||l();return}p(e=>e?.id===ae.id?e:Mr(ae))},[n,ae,E,l]);let se=n.mode===`new`&&f!==null&&f.id===void 0||n.mode===`edit`&&f!==null&&ae!==null;async function ce(e){await j({title:`Delete user`,message:`Permanently delete user "${e.username}"? This cannot be undone — any active sessions will be revoked on next request.`,confirmLabel:`Delete`,variant:`danger`})&&(F.mutate({id:e.id}),n.mode===`edit`&&n.id===e.id&&oe())}async function le(e){let t=await M({title:`Reset password`,message:`Set a new password for "${e.username}".`,label:`New password`,inputType:`password`,placeholder:`At least 8 characters`,confirmLabel:`Continue`,validate:e=>e.length<Ar?`Password must be at least ${String(Ar)} characters.`:null});t===null||t.length===0||await j({title:`Reset password`,message:`Reset the password for "${e.username}"? They will need to use the new password on their next login.`,confirmLabel:`Reset`})&&L.mutate({id:e.id,newPassword:t})}function ue(e,t){t!==e.isAdmin&&I.mutate({id:e.id,isAdmin:t})}async function fe(){if(f!==null){g(null);try{if(f.id===void 0){let e=f.username.trim();if(e===``||f.password.length<Ar)return;await P.mutateAsync({username:e,password:f.password,isAdmin:f.isAdmin})}else await I.mutateAsync({id:f.id,isAdmin:f.isAdmin});N(),oe()}catch(e){g(Nr(e))}}}function me(e){return e?new Date(typeof e==`number`?e:String(e)).toLocaleDateString(`en-GB`,{day:`2-digit`,month:`short`,year:`numeric`}):`—`}let he=P.isPending||I.isPending,_e=f!==null&&f.id===void 0&&f.username.trim()!==``&&f.password.length>=Ar,ve=f!==null&&f.id!==void 0,ye=he||(f?.id===void 0?!_e:!ve),be=e=>F.isPending&&F.variables?.id===e.id||I.isPending&&I.variables?.id===e.id||L.isPending&&L.variables?.id===e.id;return r(gt,{embedded:!0,icon:b,title:`Users`,subtitle:`Hub accounts, admin flag, access scopes, sessions and sign-in links.`,actions:r(G,{size:`sm`,type:`button`,onClick:()=>{g(null),i()},children:[u(_,{className:`h-3.5 w-3.5`}),`Create User`]}),children:[D&&u(Oe,{title:`Could not load users`,message:Nr(O),onRetry:()=>void A()}),E&&r(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[u(S,{className:`h-3.5 w-3.5 animate-spin`}),`Loading…`]}),!E&&!D&&W.length===0&&u(Le,{icon:b,title:`No users yet`,description:`Create a user to grant hub access.`}),!E&&!D&&W.length>0&&u(Ce,{columns:[{key:`username`,header:`Username`,sortValue:e=>e.username,render:e=>u(`span`,{className:`font-medium text-foreground`,"data-testid":`user-open-${e.id}`,children:e.username})},{key:`isAdmin`,header:`Admin`,nowrap:!0,sortValue:e=>+!!e.isAdmin,render:e=>u(`span`,{onClick:e=>e.stopPropagation(),children:r(`label`,{className:`inline-flex items-center gap-1.5 text-xs cursor-pointer`,children:[u(`input`,{type:`checkbox`,checked:e.isAdmin,onChange:t=>ue(e,t.target.checked),disabled:be(e),className:`rounded border-border focus:ring-primary disabled:opacity-50`}),u(`span`,{className:e.isAdmin?`text-primary font-medium`:`text-foreground-subtle`,children:e.isAdmin?`Admin`:`Regular`})]})})},{key:`scopes`,header:`Access`,render:e=>e.isAdmin?u(`span`,{className:`text-[10px] italic text-foreground-subtle`,children:`everything (admin)`}):u(`span`,{onClick:e=>e.stopPropagation(),children:r(G,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>B(e),title:`Configure access`,children:[u(k,{className:`h-3 w-3 shrink-0 text-foreground-subtle`}),u(Fr,{scopes:e.scopes??[]})]})})},{key:`createdAt`,header:`Created`,nowrap:!0,sortValue:e=>e.createdAt,render:e=>u(`span`,{className:`text-foreground-subtle`,children:me(e.createdAt)})},{key:`actions`,header:`Actions`,align:`right`,nowrap:!0,notSortableReason:`Row actions`,render:e=>{let n=be(e),i=e.id!==t?.id&&e.totpEnabled;return r(`div`,{className:`flex items-center justify-end gap-1`,onClick:e=>e.stopPropagation(),children:[r(G,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>a(e.id),disabled:n,title:`Edit user`,children:[u(v,{className:`h-3 w-3`}),`Edit`]}),i&&r(G,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>H(e),disabled:n,title:`Remove two-factor authentication`,children:[u(y,{className:`h-3 w-3`}),`Remove 2FA`]}),r(G,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>ne(e),disabled:n,title:`Linked sign-in accounts`,children:[u(w,{className:`h-3 w-3`}),`Sign-in links`]}),r(G,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>ie(e),disabled:n,title:`Active sessions`,children:[u(te,{className:`h-3 w-3`}),`Sessions`]}),r(G,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>void le(e),disabled:n,title:`Reset password`,children:[u(ee,{className:`h-3 w-3`}),`Reset password`]}),r(G,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>void ce(e),disabled:n,title:`Delete user`,className:`text-danger hover:bg-danger/10`,children:[n?u(S,{className:`h-3 w-3 animate-spin`}):u(h,{className:`h-3 w-3`}),`Delete`]})]})}}],rows:W,rowKey:e=>e.id,minWidthPx:560,maxBodyHeight:`max-h-[60vh]`,mobileMode:`scroll`,onRowClick:e=>a(e.id)}),u(tt,{open:se,onClose:oe,title:f?.id===void 0?`Create User`:`Edit ${f.username||`user`}`,icon:b,error:m,testId:`user-form-dialog`,footer:u(G,{size:`sm`,type:`button`,disabled:ye,onClick:()=>void fe(),children:he?r(o,{children:[u(S,{className:`h-3.5 w-3.5 animate-spin`}),`Saving…`]}):f?.id===void 0?`Create`:`Save`}),children:f!==null&&r(`div`,{className:`space-y-3`,children:[u(xe,{label:`Username`,required:f.id===void 0,children:u(He,{value:f.username,onChange:e=>p({...f,username:e.target.value}),placeholder:`john`,autoFocus:f.id===void 0,disabled:f.id!==void 0,"data-testid":`user-form-username`})}),f.id===void 0&&u(xe,{label:`Password`,required:!0,description:`At least ${String(Ar)} characters.`,children:u(Te,{value:f.password,onValueChange:e=>p({...f,password:e}),shown:x,onToggleShown:()=>C(e=>!e),placeholder:`••••••••`,"data-testid":`user-form-password`})}),u(xe,{label:`Admin`,description:`Unrestricted access to every capability and device.`,children:r(`label`,{className:`inline-flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[u(`input`,{type:`checkbox`,checked:f.isAdmin,onChange:e=>p({...f,isAdmin:e.target.checked}),className:`rounded border-border focus:ring-primary`,"data-testid":`user-form-admin`}),u(`span`,{children:`Admin`})]})}),f.id!==void 0&&u(`p`,{className:`text-[11px] text-foreground-subtle`,children:`To change the password, use Reset password on the user's row. Access scopes are configured from the Access column.`})]})}),V&&u(Cr,{userId:V.id,username:V.username,onClose:()=>H(null)}),U&&u(Sr,{userId:U.id,username:U.username,onClose:()=>ne(null)}),re&&u(wr,{userId:re.id,username:re.username,onClose:()=>ie(null)}),z&&u(Ir,{user:z,onClose:()=>B(null),onSubmit:e=>R.mutate({userId:z.id,scopes:e}),submitting:R.isPending})]})}function Fr({scopes:e}){if(e.length===0)return u(`span`,{className:`font-medium text-warning`,children:`No access`});let t=W(e);return t===null?r(`span`,{className:`text-foreground-subtle`,children:[`Custom · `,e.length,` grant`,e.length===1?``:`s`]}):r(`span`,{className:`text-foreground-subtle`,children:[u(`span`,{className:`font-medium text-foreground`,children:ae(t.roleId).label}),` ·`,` `,Ue(t.selector)]})}function Ir(e){let{user:t}=ot(),n=t?.isAdmin===!0;return u(kr,{...e,callerScopes:n?null:t?.scopes??[]})}n();var Lr={"api-keys":$.tokens,"linked-sessions":$.linkedApps},Rr=`certificates`;function zr(e){return r(G,{size:`sm`,type:`button`,"data-testid":`certificates-pair-device`,onClick:e,children:[u(y,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),`Pair a device`]})}function Br(){let{t:e}=it(),[t]=lt(),n=Mn(),[r,i]=c(!1),a=Lr[t.get(`tab`)??``];if(a!==void 0)return u(at,{to:dt(`access`,{integration:a}),replace:!0});let o=st(`/system/identity`,{t:e,isAdmin:!0})??{icon:O,title:e(`system.identity`,`Identity & Access`)},s=t.get(`tab`)??`users`,l=t.get(`integration`),d=s===ut.access.tab?jn(l,n.requestCreate):s===`certificates`?zr(()=>i(!0)):void 0;return u(ht,{icon:o.icon,title:o.title,defaultSection:`users`,sectionsLabel:`${o.title} sections`,actions:d,sections:[{id:`users`,label:`Users`,content:u(Pr,{})},{id:ut.access.tab,label:`Tokens & sessions`,content:u(An,{createRequested:n.createRequested,onCreateConsumed:n.clearCreate}),ownedParams:mt.concat([ln.token,ln.scoped,ln.admin])},{id:Rr,label:`Certificates`,content:u(xr,{pairOpen:r,onPairClose:()=>i(!1)})},{id:ut.authentication.tab,label:`Authentication`,content:u(Gn,{}),ownedParams:mt}]})}export{Br as IdentityPage};